Server/MainForm.cs
author sl
Sun, 31 Aug 2014 16:21:50 +0200
changeset 50 ba4cad33db58
parent 48 9039acfde091
child 51 ae2052cc89ef
permissions -rw-r--r--
Renaming some of our new display settings classes.
     1 using System;
     2 using System.Collections.Generic;
     3 using System.ComponentModel;
     4 using System.Data;
     5 using System.Drawing;
     6 using System.Linq;
     7 using System.Text;
     8 using System.Threading.Tasks;
     9 using System.Windows.Forms;
    10 using System.IO;
    11 using CodeProject.Dialog;
    12 using System.Drawing.Imaging;
    13 using System.ServiceModel;
    14 using System.Threading;
    15 using System.Diagnostics;
    16 //
    17 using SharpDisplayInterface;
    18 using SharpDisplayClient;
    19 
    20 
    21 namespace SharpDisplayManager
    22 {
    23     public partial class MainForm : Form
    24     {
    25         DateTime LastTickTime;
    26         Display iDisplay;
    27         System.Drawing.Bitmap iBmp;
    28         bool iCreateBitmap; //Workaround render to bitmap issues when minimized
    29         ServiceHost iServiceHost;
    30         /// <summary>
    31         /// Our collection of clients
    32         /// </summary>
    33         public Dictionary<string, ClientData> iClients;
    34         public bool iClosing;
    35 
    36         public MainForm()
    37         {
    38             LastTickTime = DateTime.Now;
    39             iDisplay = new Display();
    40             iClients = new Dictionary<string, ClientData>();
    41 
    42             InitializeComponent();
    43             UpdateStatus();
    44             
    45             //
    46             tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
    47             //We have a bug when drawing minimized and reusing our bitmap
    48             iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
    49             iCreateBitmap = false;
    50         }
    51 
    52         private void MainForm_Load(object sender, EventArgs e)
    53         {
    54             StartServer();
    55 
    56             //
    57             CheckFontHeight();
    58             //
    59 
    60 
    61             if (Properties.Settings.Default.DisplayConnectOnStartup)
    62             {
    63                 OpenDisplayConnection();
    64             }
    65         }
    66 
    67 
    68         private void buttonFont_Click(object sender, EventArgs e)
    69         {
    70             //fontDialog.ShowColor = true;
    71             //fontDialog.ShowApply = true;
    72             fontDialog.ShowEffects = true;
    73             fontDialog.Font = marqueeLabelTop.Font;
    74 
    75             fontDialog.FixedPitchOnly = checkBoxFixedPitchFontOnly.Checked;
    76 
    77             //fontDialog.ShowHelp = true;
    78 
    79             //fontDlg.MaxSize = 40;
    80             //fontDlg.MinSize = 22;
    81 
    82             //fontDialog.Parent = this;
    83             //fontDialog.StartPosition = FormStartPosition.CenterParent;
    84 
    85             //DlgBox.ShowDialog(fontDialog);
    86 
    87             //if (fontDialog.ShowDialog(this) != DialogResult.Cancel)
    88             if (DlgBox.ShowDialog(fontDialog) != DialogResult.Cancel)
    89             {
    90 
    91                 //MsgBox.Show("MessageBox MsgBox", "MsgBox caption");
    92 
    93                 //MessageBox.Show("Ok");
    94                 marqueeLabelTop.Font = fontDialog.Font;
    95                 marqueeLabelBottom.Font = fontDialog.Font;
    96                 cds.Font = fontDialog.Font;
    97                 Properties.Settings.Default.Save();
    98                 //
    99                 CheckFontHeight();
   100             }
   101         }
   102 
   103         /// <summary>
   104         ///
   105         /// </summary>
   106         void CheckFontHeight()
   107         {
   108             if (marqueeLabelBottom.Font.Height > marqueeLabelBottom.Height)
   109             {
   110                 labelWarning.Text = "WARNING: Selected font is too height by " + (marqueeLabelBottom.Font.Height - marqueeLabelBottom.Height) + " pixels!";
   111                 labelWarning.Visible = true;
   112             }
   113             else
   114             {
   115                 labelWarning.Visible = false;
   116             }
   117 
   118         }
   119 
   120         private void buttonCapture_Click(object sender, EventArgs e)
   121         {
   122             System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height);
   123             tableLayoutPanel.DrawToBitmap(bmp, tableLayoutPanel.ClientRectangle);
   124             //Bitmap bmpToSave = new Bitmap(bmp);
   125             bmp.Save("D:\\capture.png");
   126 
   127             marqueeLabelTop.Text = "Sweet";
   128 
   129             /*
   130             string outputFileName = "d:\\capture.png";
   131             using (MemoryStream memory = new MemoryStream())
   132             {
   133                 using (FileStream fs = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
   134                 {
   135                     bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
   136                     byte[] bytes = memory.ToArray();
   137                     fs.Write(bytes, 0, bytes.Length);
   138                 }
   139             }
   140              */
   141 
   142         }
   143 
   144         private void CheckForRequestResults()
   145         {
   146             if (iDisplay.IsRequestPending())
   147             {
   148                 switch (iDisplay.AttemptRequestCompletion())
   149                 {
   150                     case Display.TMiniDisplayRequest.EMiniDisplayRequestPowerSupplyStatus:
   151                         if (iDisplay.PowerSupplyStatus())
   152                         {
   153                             toolStripStatusLabelPower.Text = "ON";
   154                         }
   155                         else
   156                         {
   157                             toolStripStatusLabelPower.Text = "OFF";
   158                         }
   159                         //Issue next request then
   160                         iDisplay.RequestDeviceId();
   161                         break;
   162 
   163                     case Display.TMiniDisplayRequest.EMiniDisplayRequestDeviceId:
   164                         toolStripStatusLabelConnect.Text += " - " + iDisplay.DeviceId();
   165                         //Issue next request then
   166                         iDisplay.RequestFirmwareRevision();
   167                         break;
   168 
   169                     case Display.TMiniDisplayRequest.EMiniDisplayRequestFirmwareRevision:
   170                         toolStripStatusLabelConnect.Text += " v" + iDisplay.FirmwareRevision();
   171                         //No more request to issue
   172                         break;
   173                 }
   174             }
   175         }
   176 
   177 
   178         public delegate int CoordinateTranslationDelegate(System.Drawing.Bitmap aBmp, int aInt);
   179 
   180 
   181         public static int ScreenReversedX(System.Drawing.Bitmap aBmp, int aX)
   182         {
   183             return aBmp.Width - aX - 1;
   184         }
   185 
   186         public int ScreenReversedY(System.Drawing.Bitmap aBmp, int aY)
   187         {
   188             return iBmp.Height - aY - 1;
   189         }
   190 
   191         public int ScreenX(System.Drawing.Bitmap aBmp, int aX)
   192         {
   193             return aX;
   194         }
   195 
   196         public int ScreenY(System.Drawing.Bitmap aBmp, int aY)
   197         {
   198             return aY;
   199         }
   200 
   201 
   202         //This is our timer tick responsible to perform our render
   203         private void timer_Tick(object sender, EventArgs e)
   204         {
   205             //Update our animations
   206             DateTime NewTickTime = DateTime.Now;
   207 
   208             marqueeLabelTop.UpdateAnimation(LastTickTime, NewTickTime);
   209             marqueeLabelBottom.UpdateAnimation(LastTickTime, NewTickTime);
   210 
   211             //Update our display
   212             if (iDisplay.IsOpen())
   213             {
   214                 CheckForRequestResults();
   215 
   216                 //Draw to bitmap
   217                 if (iCreateBitmap)
   218                 {
   219                     iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
   220                 }
   221                 tableLayoutPanel.DrawToBitmap(iBmp, tableLayoutPanel.ClientRectangle);
   222                 //iBmp.Save("D:\\capture.png");
   223 
   224                 //Select proper coordinate translation functions
   225                 //We used delegate/function pointer to support reverse screen without doing an extra test on each pixels
   226                 CoordinateTranslationDelegate screenX;
   227                 CoordinateTranslationDelegate screenY;
   228 
   229                 if (cds.ReverseScreen)
   230                 {
   231                     screenX = ScreenReversedX;
   232                     screenY = ScreenReversedY;
   233                 }
   234                 else
   235                 {
   236                     screenX = ScreenX;
   237                     screenY = ScreenY;
   238                 }
   239 
   240                 //Send it to our display
   241                 for (int i = 0; i < iBmp.Width; i++)
   242                 {
   243                     for (int j = 0; j < iBmp.Height; j++)
   244                     {
   245                         unchecked
   246                         {
   247                             uint color = (uint)iBmp.GetPixel(i, j).ToArgb();
   248                             //For some reason when the app is minimized in the task bar only the alpha of our color is set.
   249                             //Thus that strange test for rendering to work both when the app is in the task bar and when it isn't.
   250                             iDisplay.SetPixel(screenX(iBmp, i), screenY(iBmp, j), Convert.ToInt32(!(color != 0xFF000000)));
   251                         }
   252                     }
   253                 }
   254 
   255                 iDisplay.SwapBuffers();
   256 
   257             }
   258 
   259             //Compute instant FPS
   260             toolStripStatusLabelFps.Text = (1.0/NewTickTime.Subtract(LastTickTime).TotalSeconds).ToString("F0") + " / " + (1000/timer.Interval).ToString() + " FPS";
   261 
   262             LastTickTime = NewTickTime;
   263 
   264         }
   265 
   266         private void OpenDisplayConnection()
   267         {
   268             CloseDisplayConnection();
   269 
   270             if (iDisplay.Open((Display.TMiniDisplayType)cds.DisplayType))
   271             {
   272                 UpdateStatus();
   273                 iDisplay.RequestPowerSupplyStatus();
   274             }
   275             else
   276             {
   277                 UpdateStatus();
   278                 toolStripStatusLabelConnect.Text = "Connection error";
   279             }
   280         }
   281 
   282         private void CloseDisplayConnection()
   283         {
   284             iDisplay.Close();
   285             UpdateStatus();
   286         }
   287 
   288         private void buttonOpen_Click(object sender, EventArgs e)
   289         {
   290             OpenDisplayConnection();
   291         }
   292 
   293         private void buttonClose_Click(object sender, EventArgs e)
   294         {
   295             CloseDisplayConnection();
   296         }
   297 
   298         private void buttonClear_Click(object sender, EventArgs e)
   299         {
   300             iDisplay.Clear();
   301             iDisplay.SwapBuffers();
   302         }
   303 
   304         private void buttonFill_Click(object sender, EventArgs e)
   305         {
   306             iDisplay.Fill();
   307             iDisplay.SwapBuffers();
   308         }
   309 
   310         private void trackBarBrightness_Scroll(object sender, EventArgs e)
   311         {
   312             cds.Brightness = trackBarBrightness.Value;
   313             Properties.Settings.Default.Save();
   314             iDisplay.SetBrightness(trackBarBrightness.Value);
   315 
   316         }
   317 
   318 
   319         /// <summary>
   320         /// CDS stands for Current Display Settings
   321         /// </summary>
   322         private DisplaySettings cds
   323         {
   324             get
   325             {
   326                 DisplaysSettings settings = Properties.Settings.Default.DisplaySettings;
   327 
   328                 //Make sure all our settings have been created
   329                 while (settings.Displays.Count <= Properties.Settings.Default.CurrentDisplayIndex)
   330                 {
   331                     settings.Displays.Add(new DisplaySettings());
   332                 }
   333 
   334                 DisplaySettings displaySettings = settings.Displays[Properties.Settings.Default.CurrentDisplayIndex];
   335                 return displaySettings;
   336             }
   337         }
   338 
   339         private void UpdateStatus()
   340         {
   341             //Synchronize UI with settings
   342             //Load settings
   343             marqueeLabelTop.Font = cds.Font;
   344             marqueeLabelBottom.Font = cds.Font;
   345             checkBoxShowBorders.Checked = cds.ShowBorders;
   346             checkBoxConnectOnStartup.Checked = Properties.Settings.Default.DisplayConnectOnStartup;
   347             checkBoxReverseScreen.Checked = cds.ReverseScreen;
   348             comboBoxDisplayType.SelectedIndex = cds.DisplayType;
   349             timer.Interval = cds.TimerInterval;
   350             maskedTextBoxTimerInterval.Text = cds.TimerInterval.ToString();
   351 
   352 
   353             if (iDisplay.IsOpen())
   354             {
   355                 //Only setup brightness if display is open
   356                 trackBarBrightness.Minimum = iDisplay.MinBrightness();
   357                 trackBarBrightness.Maximum = iDisplay.MaxBrightness();
   358                 trackBarBrightness.Value = cds.Brightness;
   359                 trackBarBrightness.LargeChange = Math.Max(1, (iDisplay.MaxBrightness() - iDisplay.MinBrightness()) / 5);
   360                 trackBarBrightness.SmallChange = 1;
   361                 iDisplay.SetBrightness(cds.Brightness);
   362                 //
   363                 buttonFill.Enabled = true;
   364                 buttonClear.Enabled = true;
   365                 buttonOpen.Enabled = false;
   366                 buttonClose.Enabled = true;
   367                 trackBarBrightness.Enabled = true;
   368                 toolStripStatusLabelConnect.Text = "Connected - " + iDisplay.Vendor() + " - " + iDisplay.Product();
   369                 //+ " - " + iDisplay.SerialNumber();
   370             }
   371             else
   372             {
   373                 buttonFill.Enabled = false;
   374                 buttonClear.Enabled = false;
   375                 buttonOpen.Enabled = true;
   376                 buttonClose.Enabled = false;
   377                 trackBarBrightness.Enabled = false;
   378                 toolStripStatusLabelConnect.Text = "Disconnected";
   379                 toolStripStatusLabelPower.Text = "N/A";
   380             }
   381         }
   382 
   383 
   384 
   385         private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
   386         {
   387             //Save our show borders setting
   388             tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
   389             cds.ShowBorders = checkBoxShowBorders.Checked;
   390             Properties.Settings.Default.Save();
   391         }
   392 
   393         private void checkBoxConnectOnStartup_CheckedChanged(object sender, EventArgs e)
   394         {
   395             //Save our connect on startup setting
   396             Properties.Settings.Default.DisplayConnectOnStartup = checkBoxConnectOnStartup.Checked;
   397             Properties.Settings.Default.Save();
   398         }
   399 
   400         private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
   401         {
   402             //Save our reverse screen setting
   403             cds.ReverseScreen = checkBoxReverseScreen.Checked;
   404             Properties.Settings.Default.Save();
   405         }
   406 
   407         private void MainForm_Resize(object sender, EventArgs e)
   408         {
   409             if (WindowState == FormWindowState.Minimized)
   410             {
   411                 // Do some stuff
   412                 //iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
   413                 iCreateBitmap = true;
   414             }
   415         }
   416 
   417         private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
   418         {
   419             StopServer();
   420             e.Cancel = iClosing;
   421         }
   422 
   423         public void StartServer()
   424         {
   425             iServiceHost = new ServiceHost
   426                 (
   427                     typeof(DisplayServer),
   428                     new Uri[] { new Uri("net.tcp://localhost:8001/") }
   429                 );
   430 
   431             iServiceHost.AddServiceEndpoint(typeof(IDisplayService), new NetTcpBinding(SecurityMode.None,true), "DisplayService");
   432             iServiceHost.Open();
   433         }
   434 
   435         public void StopServer()
   436         {
   437             if (iClients.Count > 0 && !iClosing)
   438             {
   439                 //Tell our clients
   440                 iClosing = true;
   441                 BroadcastCloseEvent();
   442             }
   443             else if (iClosing)
   444             {
   445                 if (MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
   446                 {
   447                     iClosing = false; //We make sure we force close if asked twice
   448                 }
   449             }
   450             else
   451             {
   452                 //We removed that as it often lags for some reason
   453                 //iServiceHost.Close();
   454             }
   455         }
   456 
   457         public void BroadcastCloseEvent()
   458         {
   459             Trace.TraceInformation("BroadcastCloseEvent - start");
   460 
   461             var inactiveClients = new List<string>();
   462             foreach (var client in iClients)
   463             {
   464                 //if (client.Key != eventData.ClientName)
   465                 {
   466                     try
   467                     {
   468                         Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
   469                         client.Value.Callback.OnCloseOrder(/*eventData*/);
   470                     }
   471                     catch (Exception ex)
   472                     {
   473                         inactiveClients.Add(client.Key);
   474                     }
   475                 }
   476             }
   477 
   478             if (inactiveClients.Count > 0)
   479             {
   480                 foreach (var client in inactiveClients)
   481                 {
   482                     iClients.Remove(client);
   483                     Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(client, false)[0]);
   484                 }
   485             }
   486         }
   487 
   488         private void buttonStartClient_Click(object sender, EventArgs e)
   489         {
   490             Thread clientThread = new Thread(SharpDisplayClient.Program.Main);
   491             clientThread.Start();
   492             BringToFront();
   493         }
   494 
   495         private void buttonSuspend_Click(object sender, EventArgs e)
   496         {
   497             timer.Enabled = !timer.Enabled;
   498             if (!timer.Enabled)
   499             {
   500                 buttonSuspend.Text = "Suspend";
   501             }
   502             else
   503             {
   504                 buttonSuspend.Text = "Pause";
   505             }
   506         }
   507 
   508         private void buttonCloseClients_Click(object sender, EventArgs e)
   509         {
   510             BroadcastCloseEvent();
   511         }
   512 
   513         private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
   514         {
   515 
   516         }
   517 
   518         //Delegates are used for our thread safe method
   519         public delegate void AddClientDelegate(string aSessionId, IDisplayServiceCallback aCallback);
   520         public delegate void RemoveClientDelegate(string aSessionId);
   521         public delegate void SetTextDelegate(string SessionId, TextField aTextField);
   522         public delegate void SetTextsDelegate(string SessionId, System.Collections.Generic.IList<TextField> aTextFields);
   523         public delegate void SetClientNameDelegate(string aSessionId, string aName);
   524 
   525 
   526         /// <summary>
   527         ///
   528         /// </summary>
   529         /// <param name="aSessionId"></param>
   530         /// <param name="aCallback"></param>
   531         public void AddClientThreadSafe(string aSessionId, IDisplayServiceCallback aCallback)
   532         {
   533             if (this.InvokeRequired)
   534             {
   535                 //Not in the proper thread, invoke ourselves
   536                 AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
   537                 this.Invoke(d, new object[] { aSessionId, aCallback });
   538             }
   539             else
   540             {
   541                 //We are in the proper thread
   542                 //Add this session to our collection of clients
   543                 ClientData newClient = new ClientData(aSessionId, aCallback);
   544                 Program.iMainForm.iClients.Add(aSessionId, newClient);
   545                 //Add this session to our UI
   546                 UpdateClientTreeViewNode(newClient);
   547             }
   548         }
   549 
   550         /// <summary>
   551         ///
   552         /// </summary>
   553         /// <param name="aSessionId"></param>
   554         public void RemoveClientThreadSafe(string aSessionId)
   555         {
   556             if (this.InvokeRequired)
   557             {
   558                 //Not in the proper thread, invoke ourselves
   559                 RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
   560                 this.Invoke(d, new object[] { aSessionId });
   561             }
   562             else
   563             {
   564                 //We are in the proper thread
   565                 //Remove this session from both client collection and UI tree view
   566                 if (Program.iMainForm.iClients.Keys.Contains(aSessionId))
   567                 {
   568                     Program.iMainForm.iClients.Remove(aSessionId);
   569                     Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(aSessionId, false)[0]);
   570                 }
   571 
   572                 if (iClosing && iClients.Count == 0)
   573                 {
   574                     //We were closing our form
   575                     //All clients are now closed
   576                     //Just resume our close operation
   577                     iClosing = false;
   578                     Close();
   579                 }
   580             }
   581         }
   582 
   583         /// <summary>
   584         ///
   585         /// </summary>
   586         /// <param name="aLineIndex"></param>
   587         /// <param name="aText"></param>
   588         public void SetTextThreadSafe(string aSessionId, TextField aTextField)
   589         {
   590             if (this.InvokeRequired)
   591             {
   592                 //Not in the proper thread, invoke ourselves
   593                 SetTextDelegate d = new SetTextDelegate(SetTextThreadSafe);
   594                 this.Invoke(d, new object[] { aSessionId, aTextField });
   595             }
   596             else
   597             {
   598                 ClientData client = iClients[aSessionId];
   599                 if (client != null)
   600                 {
   601                     //Make sure all our texts are in place
   602                     while (client.Texts.Count < (aTextField.Index + 1))
   603                     {
   604                         //Add a text field with proper index
   605                         client.Texts.Add(new TextField(client.Texts.Count));
   606                     }
   607                     client.Texts[aTextField.Index] = aTextField;
   608 
   609                     //We are in the proper thread
   610                     //Only support two lines for now
   611                     if (aTextField.Index == 0)
   612                     {
   613                         marqueeLabelTop.Text = aTextField.Text;
   614                         marqueeLabelTop.TextAlign = aTextField.Alignment;
   615                     }
   616                     else if (aTextField.Index == 1)
   617                     {
   618                         marqueeLabelBottom.Text = aTextField.Text;
   619                         marqueeLabelBottom.TextAlign = aTextField.Alignment;
   620                     }
   621 
   622 
   623                     UpdateClientTreeViewNode(client);
   624                 }
   625             }
   626         }
   627 
   628         /// <summary>
   629         ///
   630         /// </summary>
   631         /// <param name="aTexts"></param>
   632         public void SetTextsThreadSafe(string aSessionId, System.Collections.Generic.IList<TextField> aTextFields)
   633         {
   634             if (this.InvokeRequired)
   635             {
   636                 //Not in the proper thread, invoke ourselves
   637                 SetTextsDelegate d = new SetTextsDelegate(SetTextsThreadSafe);
   638                 this.Invoke(d, new object[] { aSessionId, aTextFields });
   639             }
   640             else
   641             {
   642                 //We are in the proper thread
   643                 ClientData client = iClients[aSessionId];
   644                 if (client != null)
   645                 {
   646                     //Populate our client with the given text fields
   647                     int j = 0;
   648                     foreach (TextField textField in aTextFields)
   649                     {
   650                         if (client.Texts.Count < (j + 1))
   651                         {
   652                             client.Texts.Add(textField);
   653                         }
   654                         else
   655                         {
   656                             client.Texts[j] = textField;
   657                         }
   658                         j++;
   659                     }                    
   660                     //Only support two lines for now
   661                     for (int i = 0; i < aTextFields.Count; i++)
   662                     {
   663                         if (aTextFields[i].Index == 0)
   664                         {
   665                             marqueeLabelTop.Text = aTextFields[i].Text;
   666                             marqueeLabelTop.TextAlign = aTextFields[i].Alignment;
   667                         }
   668                         else if (aTextFields[i].Index == 1)
   669                         {
   670                             marqueeLabelBottom.Text = aTextFields[i].Text;
   671                             marqueeLabelBottom.TextAlign = aTextFields[i].Alignment;
   672                         }
   673                     }
   674 
   675 
   676                     UpdateClientTreeViewNode(client);
   677                 }
   678             }
   679         }
   680 
   681 
   682         /// <summary>
   683         ///
   684         /// </summary>
   685         /// <param name="aSessionId"></param>
   686         /// <param name="aName"></param>
   687         public void SetClientNameThreadSafe(string aSessionId, string aName)
   688         {
   689             if (this.InvokeRequired)
   690             {
   691                 //Not in the proper thread, invoke ourselves
   692                 SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
   693                 this.Invoke(d, new object[] { aSessionId, aName });
   694             }
   695             else
   696             {
   697                 //We are in the proper thread
   698                 //Get our client
   699                 ClientData client = iClients[aSessionId];
   700                 if (client != null)
   701                 {
   702                     //Set its name
   703                     client.Name = aName;
   704                     //Update our tree-view
   705                     UpdateClientTreeViewNode(client);
   706                 }
   707             }
   708         }
   709 
   710         /// <summary>
   711         ///
   712         /// </summary>
   713         /// <param name="aClient"></param>
   714         private void UpdateClientTreeViewNode(ClientData aClient)
   715         {
   716             if (aClient == null)
   717             {
   718                 return;
   719             }
   720 
   721             TreeNode node = null;
   722             //Check that our client node already exists
   723             //Get our client root node using its key which is our session ID
   724             TreeNode[] nodes = treeViewClients.Nodes.Find(aClient.SessionId, false);
   725             if (nodes.Count()>0)
   726             {
   727                 //We already have a node for that client
   728                 node = nodes[0];
   729                 //Clear children as we are going to recreate them below
   730                 node.Nodes.Clear();
   731             }
   732             else
   733             {
   734                 //Client node does not exists create a new one
   735                 treeViewClients.Nodes.Add(aClient.SessionId, aClient.SessionId);
   736                 node = treeViewClients.Nodes.Find(aClient.SessionId, false)[0];
   737             }
   738 
   739             if (node != null)
   740             {
   741                 //Change its name
   742                 if (aClient.Name != "")
   743                 {
   744                     //We have a name, us it as text for our root node
   745                     node.Text = aClient.Name;
   746                     //Add a child with SessionId
   747                     node.Nodes.Add(new TreeNode(aClient.SessionId));
   748                 }
   749                 else
   750                 {
   751                     //No name, use session ID instead
   752                     node.Text = aClient.SessionId;
   753                 }
   754 
   755                 if (aClient.Texts.Count > 0)
   756                 {
   757                     //Create root node for our texts
   758                     TreeNode textsRoot = new TreeNode("Text");
   759                     node.Nodes.Add(textsRoot);
   760                     //For each text add a new entry
   761                     foreach (TextField field in aClient.Texts)
   762                     {
   763                         textsRoot.Nodes.Add(new TreeNode(field.Text));
   764                     }
   765                 }
   766 
   767                 node.ExpandAll();
   768             }
   769         }
   770 
   771         private void buttonAddRow_Click(object sender, EventArgs e)
   772         {
   773             if (tableLayoutPanel.RowCount < 6)
   774             {
   775                 tableLayoutPanel.RowCount++;
   776                 CheckFontHeight();
   777             }
   778         }
   779 
   780         private void buttonRemoveRow_Click(object sender, EventArgs e)
   781         {
   782             if (tableLayoutPanel.RowCount > 1)
   783             {
   784                 tableLayoutPanel.RowCount--;
   785                 CheckFontHeight();
   786             }
   787         }
   788 
   789         private void buttonAddColumn_Click(object sender, EventArgs e)
   790         {
   791             if (tableLayoutPanel.ColumnCount < 8)
   792             {
   793                 tableLayoutPanel.ColumnCount++;
   794                 //CheckFontHeight();
   795             }
   796         }
   797 
   798         private void buttonRemoveColumn_Click(object sender, EventArgs e)
   799         {
   800             if (tableLayoutPanel.ColumnCount > 1)
   801             {
   802                 tableLayoutPanel.ColumnCount--;
   803                 //CheckFontHeight();
   804             }
   805         }
   806 
   807         private void buttonAlignLeft_Click(object sender, EventArgs e)
   808         {
   809             marqueeLabelTop.TextAlign = ContentAlignment.MiddleLeft;
   810             marqueeLabelBottom.TextAlign = ContentAlignment.MiddleLeft;
   811         }
   812 
   813         private void buttonAlignCenter_Click(object sender, EventArgs e)
   814         {
   815             marqueeLabelTop.TextAlign = ContentAlignment.MiddleCenter;
   816             marqueeLabelBottom.TextAlign = ContentAlignment.MiddleCenter;
   817         }
   818 
   819         private void buttonAlignRight_Click(object sender, EventArgs e)
   820         {
   821             marqueeLabelTop.TextAlign = ContentAlignment.MiddleRight;
   822             marqueeLabelBottom.TextAlign = ContentAlignment.MiddleRight;
   823         }
   824 
   825         private void comboBoxDisplayType_SelectedIndexChanged(object sender, EventArgs e)
   826         {
   827             Properties.Settings.Default.CurrentDisplayIndex = comboBoxDisplayType.SelectedIndex;
   828             cds.DisplayType = comboBoxDisplayType.SelectedIndex;
   829             Properties.Settings.Default.Save();
   830             OpenDisplayConnection();
   831         }
   832 
   833 
   834         private void maskedTextBoxTimerInterval_TextChanged(object sender, EventArgs e)
   835         {
   836             if (maskedTextBoxTimerInterval.Text != "")
   837             {
   838                 timer.Interval = Convert.ToInt32(maskedTextBoxTimerInterval.Text);
   839                 cds.TimerInterval = timer.Interval;
   840                 Properties.Settings.Default.Save();
   841             }
   842         }
   843 
   844     }
   845 
   846     /// <summary>
   847     /// A UI thread copy of a client relevant data.
   848     /// Keeping this copy in the UI thread helps us deal with threading issues.
   849     /// </summary>
   850     public class ClientData
   851     {
   852         public ClientData(string aSessionId, IDisplayServiceCallback aCallback)
   853         {
   854             SessionId = aSessionId;
   855             Name = "";
   856             Texts = new List<TextField>();
   857             Callback = aCallback;
   858         }
   859 
   860         public string SessionId { get; set; }
   861         public string Name { get; set; }
   862         public List<TextField> Texts { get; set; }
   863         public IDisplayServiceCallback Callback { get; set; }
   864     }
   865 }