Server/MainForm.cs
author sl
Sun, 31 Aug 2014 18:33:05 +0200
changeset 52 b22b0127afa4
parent 51 ae2052cc89ef
child 53 f7ad2dce46a9
permissions -rw-r--r--
Adding support for power on/off.
     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.EMiniDisplayRequestFirmwareRevision:
   151                         toolStripStatusLabelConnect.Text += " v" + iDisplay.FirmwareRevision();
   152                         //Issue next request then
   153                         iDisplay.RequestPowerSupplyStatus();
   154                         break;
   155 
   156                     case Display.TMiniDisplayRequest.EMiniDisplayRequestPowerSupplyStatus:
   157                         if (iDisplay.PowerSupplyStatus())
   158                         {
   159                             toolStripStatusLabelPower.Text = "ON";
   160                         }
   161                         else
   162                         {
   163                             toolStripStatusLabelPower.Text = "OFF";
   164                         }
   165                         //Issue next request then
   166                         iDisplay.RequestDeviceId();
   167                         break;
   168 
   169                     case Display.TMiniDisplayRequest.EMiniDisplayRequestDeviceId:
   170                         toolStripStatusLabelConnect.Text += " - " + iDisplay.DeviceId();
   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.RequestFirmwareRevision();
   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                 if (settings == null)
   328                 {
   329                     settings = new DisplaysSettings();
   330                     settings.Init();
   331                     Properties.Settings.Default.DisplaySettings = settings;
   332                 }
   333 
   334                 //Make sure all our settings have been created
   335                 while (settings.Displays.Count <= Properties.Settings.Default.CurrentDisplayIndex)
   336                 {
   337                     settings.Displays.Add(new DisplaySettings());
   338                 }
   339 
   340                 DisplaySettings displaySettings = settings.Displays[Properties.Settings.Default.CurrentDisplayIndex];
   341                 return displaySettings;
   342             }
   343         }
   344 
   345         private void UpdateStatus()
   346         {
   347             //Synchronize UI with settings
   348             //Load settings
   349             marqueeLabelTop.Font = cds.Font;
   350             marqueeLabelBottom.Font = cds.Font;
   351             checkBoxShowBorders.Checked = cds.ShowBorders;
   352             checkBoxConnectOnStartup.Checked = Properties.Settings.Default.DisplayConnectOnStartup;
   353             checkBoxReverseScreen.Checked = cds.ReverseScreen;
   354             comboBoxDisplayType.SelectedIndex = cds.DisplayType;
   355             timer.Interval = cds.TimerInterval;
   356             maskedTextBoxTimerInterval.Text = cds.TimerInterval.ToString();
   357 
   358 
   359             if (iDisplay.IsOpen())
   360             {
   361                 //Only setup brightness if display is open
   362                 trackBarBrightness.Minimum = iDisplay.MinBrightness();
   363                 trackBarBrightness.Maximum = iDisplay.MaxBrightness();
   364                 trackBarBrightness.Value = cds.Brightness;
   365                 trackBarBrightness.LargeChange = Math.Max(1, (iDisplay.MaxBrightness() - iDisplay.MinBrightness()) / 5);
   366                 trackBarBrightness.SmallChange = 1;
   367                 iDisplay.SetBrightness(cds.Brightness);
   368                 //
   369                 buttonFill.Enabled = true;
   370                 buttonClear.Enabled = true;
   371                 buttonOpen.Enabled = false;
   372                 buttonClose.Enabled = true;
   373                 trackBarBrightness.Enabled = true;
   374                 toolStripStatusLabelConnect.Text = "Connected - " + iDisplay.Vendor() + " - " + iDisplay.Product();
   375                 //+ " - " + iDisplay.SerialNumber();
   376 
   377                 if (iDisplay.SupportPowerOnOff())
   378                 {
   379                     buttonPowerOn.Enabled = true;
   380                     buttonPowerOff.Enabled = true;
   381                 }
   382                 else
   383                 {
   384                     buttonPowerOn.Enabled = false;
   385                     buttonPowerOff.Enabled = false;
   386                 }
   387             }
   388             else
   389             {
   390                 buttonFill.Enabled = false;
   391                 buttonClear.Enabled = false;
   392                 buttonOpen.Enabled = true;
   393                 buttonClose.Enabled = false;
   394                 trackBarBrightness.Enabled = false;
   395                 buttonPowerOn.Enabled = false;
   396                 buttonPowerOff.Enabled = false;
   397                 toolStripStatusLabelConnect.Text = "Disconnected";
   398                 toolStripStatusLabelPower.Text = "N/A";
   399             }
   400         }
   401 
   402 
   403 
   404         private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
   405         {
   406             //Save our show borders setting
   407             tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
   408             cds.ShowBorders = checkBoxShowBorders.Checked;
   409             Properties.Settings.Default.Save();
   410         }
   411 
   412         private void checkBoxConnectOnStartup_CheckedChanged(object sender, EventArgs e)
   413         {
   414             //Save our connect on startup setting
   415             Properties.Settings.Default.DisplayConnectOnStartup = checkBoxConnectOnStartup.Checked;
   416             Properties.Settings.Default.Save();
   417         }
   418 
   419         private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
   420         {
   421             //Save our reverse screen setting
   422             cds.ReverseScreen = checkBoxReverseScreen.Checked;
   423             Properties.Settings.Default.Save();
   424         }
   425 
   426         private void MainForm_Resize(object sender, EventArgs e)
   427         {
   428             if (WindowState == FormWindowState.Minimized)
   429             {
   430                 // Do some stuff
   431                 //iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
   432                 iCreateBitmap = true;
   433             }
   434         }
   435 
   436         private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
   437         {
   438             StopServer();
   439             e.Cancel = iClosing;
   440         }
   441 
   442         public void StartServer()
   443         {
   444             iServiceHost = new ServiceHost
   445                 (
   446                     typeof(DisplayServer),
   447                     new Uri[] { new Uri("net.tcp://localhost:8001/") }
   448                 );
   449 
   450             iServiceHost.AddServiceEndpoint(typeof(IDisplayService), new NetTcpBinding(SecurityMode.None,true), "DisplayService");
   451             iServiceHost.Open();
   452         }
   453 
   454         public void StopServer()
   455         {
   456             if (iClients.Count > 0 && !iClosing)
   457             {
   458                 //Tell our clients
   459                 iClosing = true;
   460                 BroadcastCloseEvent();
   461             }
   462             else if (iClosing)
   463             {
   464                 if (MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
   465                 {
   466                     iClosing = false; //We make sure we force close if asked twice
   467                 }
   468             }
   469             else
   470             {
   471                 //We removed that as it often lags for some reason
   472                 //iServiceHost.Close();
   473             }
   474         }
   475 
   476         public void BroadcastCloseEvent()
   477         {
   478             Trace.TraceInformation("BroadcastCloseEvent - start");
   479 
   480             var inactiveClients = new List<string>();
   481             foreach (var client in iClients)
   482             {
   483                 //if (client.Key != eventData.ClientName)
   484                 {
   485                     try
   486                     {
   487                         Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
   488                         client.Value.Callback.OnCloseOrder(/*eventData*/);
   489                     }
   490                     catch (Exception ex)
   491                     {
   492                         inactiveClients.Add(client.Key);
   493                     }
   494                 }
   495             }
   496 
   497             if (inactiveClients.Count > 0)
   498             {
   499                 foreach (var client in inactiveClients)
   500                 {
   501                     iClients.Remove(client);
   502                     Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(client, false)[0]);
   503                 }
   504             }
   505         }
   506 
   507         private void buttonStartClient_Click(object sender, EventArgs e)
   508         {
   509             Thread clientThread = new Thread(SharpDisplayClient.Program.Main);
   510             clientThread.Start();
   511             BringToFront();
   512         }
   513 
   514         private void buttonSuspend_Click(object sender, EventArgs e)
   515         {
   516             LastTickTime = DateTime.Now; //Reset timer to prevent jump
   517             timer.Enabled = !timer.Enabled;
   518             if (!timer.Enabled)
   519             {
   520                 buttonSuspend.Text = "Run";
   521             }
   522             else
   523             {
   524                 buttonSuspend.Text = "Pause";
   525             }
   526         }
   527 
   528         private void buttonCloseClients_Click(object sender, EventArgs e)
   529         {
   530             BroadcastCloseEvent();
   531         }
   532 
   533         private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
   534         {
   535 
   536         }
   537 
   538         //Delegates are used for our thread safe method
   539         public delegate void AddClientDelegate(string aSessionId, IDisplayServiceCallback aCallback);
   540         public delegate void RemoveClientDelegate(string aSessionId);
   541         public delegate void SetTextDelegate(string SessionId, TextField aTextField);
   542         public delegate void SetTextsDelegate(string SessionId, System.Collections.Generic.IList<TextField> aTextFields);
   543         public delegate void SetClientNameDelegate(string aSessionId, string aName);
   544 
   545 
   546         /// <summary>
   547         ///
   548         /// </summary>
   549         /// <param name="aSessionId"></param>
   550         /// <param name="aCallback"></param>
   551         public void AddClientThreadSafe(string aSessionId, IDisplayServiceCallback aCallback)
   552         {
   553             if (this.InvokeRequired)
   554             {
   555                 //Not in the proper thread, invoke ourselves
   556                 AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
   557                 this.Invoke(d, new object[] { aSessionId, aCallback });
   558             }
   559             else
   560             {
   561                 //We are in the proper thread
   562                 //Add this session to our collection of clients
   563                 ClientData newClient = new ClientData(aSessionId, aCallback);
   564                 Program.iMainForm.iClients.Add(aSessionId, newClient);
   565                 //Add this session to our UI
   566                 UpdateClientTreeViewNode(newClient);
   567             }
   568         }
   569 
   570         /// <summary>
   571         ///
   572         /// </summary>
   573         /// <param name="aSessionId"></param>
   574         public void RemoveClientThreadSafe(string aSessionId)
   575         {
   576             if (this.InvokeRequired)
   577             {
   578                 //Not in the proper thread, invoke ourselves
   579                 RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
   580                 this.Invoke(d, new object[] { aSessionId });
   581             }
   582             else
   583             {
   584                 //We are in the proper thread
   585                 //Remove this session from both client collection and UI tree view
   586                 if (Program.iMainForm.iClients.Keys.Contains(aSessionId))
   587                 {
   588                     Program.iMainForm.iClients.Remove(aSessionId);
   589                     Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(aSessionId, false)[0]);
   590                 }
   591 
   592                 if (iClosing && iClients.Count == 0)
   593                 {
   594                     //We were closing our form
   595                     //All clients are now closed
   596                     //Just resume our close operation
   597                     iClosing = false;
   598                     Close();
   599                 }
   600             }
   601         }
   602 
   603         /// <summary>
   604         ///
   605         /// </summary>
   606         /// <param name="aLineIndex"></param>
   607         /// <param name="aText"></param>
   608         public void SetTextThreadSafe(string aSessionId, TextField aTextField)
   609         {
   610             if (this.InvokeRequired)
   611             {
   612                 //Not in the proper thread, invoke ourselves
   613                 SetTextDelegate d = new SetTextDelegate(SetTextThreadSafe);
   614                 this.Invoke(d, new object[] { aSessionId, aTextField });
   615             }
   616             else
   617             {
   618                 ClientData client = iClients[aSessionId];
   619                 if (client != null)
   620                 {
   621                     //Make sure all our texts are in place
   622                     while (client.Texts.Count < (aTextField.Index + 1))
   623                     {
   624                         //Add a text field with proper index
   625                         client.Texts.Add(new TextField(client.Texts.Count));
   626                     }
   627                     client.Texts[aTextField.Index] = aTextField;
   628 
   629                     //We are in the proper thread
   630                     //Only support two lines for now
   631                     if (aTextField.Index == 0)
   632                     {
   633                         marqueeLabelTop.Text = aTextField.Text;
   634                         marqueeLabelTop.TextAlign = aTextField.Alignment;
   635                     }
   636                     else if (aTextField.Index == 1)
   637                     {
   638                         marqueeLabelBottom.Text = aTextField.Text;
   639                         marqueeLabelBottom.TextAlign = aTextField.Alignment;
   640                     }
   641 
   642 
   643                     UpdateClientTreeViewNode(client);
   644                 }
   645             }
   646         }
   647 
   648         /// <summary>
   649         ///
   650         /// </summary>
   651         /// <param name="aTexts"></param>
   652         public void SetTextsThreadSafe(string aSessionId, System.Collections.Generic.IList<TextField> aTextFields)
   653         {
   654             if (this.InvokeRequired)
   655             {
   656                 //Not in the proper thread, invoke ourselves
   657                 SetTextsDelegate d = new SetTextsDelegate(SetTextsThreadSafe);
   658                 this.Invoke(d, new object[] { aSessionId, aTextFields });
   659             }
   660             else
   661             {
   662                 //We are in the proper thread
   663                 ClientData client = iClients[aSessionId];
   664                 if (client != null)
   665                 {
   666                     //Populate our client with the given text fields
   667                     int j = 0;
   668                     foreach (TextField textField in aTextFields)
   669                     {
   670                         if (client.Texts.Count < (j + 1))
   671                         {
   672                             client.Texts.Add(textField);
   673                         }
   674                         else
   675                         {
   676                             client.Texts[j] = textField;
   677                         }
   678                         j++;
   679                     }                    
   680                     //Only support two lines for now
   681                     for (int i = 0; i < aTextFields.Count; i++)
   682                     {
   683                         if (aTextFields[i].Index == 0)
   684                         {
   685                             marqueeLabelTop.Text = aTextFields[i].Text;
   686                             marqueeLabelTop.TextAlign = aTextFields[i].Alignment;
   687                         }
   688                         else if (aTextFields[i].Index == 1)
   689                         {
   690                             marqueeLabelBottom.Text = aTextFields[i].Text;
   691                             marqueeLabelBottom.TextAlign = aTextFields[i].Alignment;
   692                         }
   693                     }
   694 
   695 
   696                     UpdateClientTreeViewNode(client);
   697                 }
   698             }
   699         }
   700 
   701 
   702         /// <summary>
   703         ///
   704         /// </summary>
   705         /// <param name="aSessionId"></param>
   706         /// <param name="aName"></param>
   707         public void SetClientNameThreadSafe(string aSessionId, string aName)
   708         {
   709             if (this.InvokeRequired)
   710             {
   711                 //Not in the proper thread, invoke ourselves
   712                 SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
   713                 this.Invoke(d, new object[] { aSessionId, aName });
   714             }
   715             else
   716             {
   717                 //We are in the proper thread
   718                 //Get our client
   719                 ClientData client = iClients[aSessionId];
   720                 if (client != null)
   721                 {
   722                     //Set its name
   723                     client.Name = aName;
   724                     //Update our tree-view
   725                     UpdateClientTreeViewNode(client);
   726                 }
   727             }
   728         }
   729 
   730         /// <summary>
   731         ///
   732         /// </summary>
   733         /// <param name="aClient"></param>
   734         private void UpdateClientTreeViewNode(ClientData aClient)
   735         {
   736             if (aClient == null)
   737             {
   738                 return;
   739             }
   740 
   741             TreeNode node = null;
   742             //Check that our client node already exists
   743             //Get our client root node using its key which is our session ID
   744             TreeNode[] nodes = treeViewClients.Nodes.Find(aClient.SessionId, false);
   745             if (nodes.Count()>0)
   746             {
   747                 //We already have a node for that client
   748                 node = nodes[0];
   749                 //Clear children as we are going to recreate them below
   750                 node.Nodes.Clear();
   751             }
   752             else
   753             {
   754                 //Client node does not exists create a new one
   755                 treeViewClients.Nodes.Add(aClient.SessionId, aClient.SessionId);
   756                 node = treeViewClients.Nodes.Find(aClient.SessionId, false)[0];
   757             }
   758 
   759             if (node != null)
   760             {
   761                 //Change its name
   762                 if (aClient.Name != "")
   763                 {
   764                     //We have a name, us it as text for our root node
   765                     node.Text = aClient.Name;
   766                     //Add a child with SessionId
   767                     node.Nodes.Add(new TreeNode(aClient.SessionId));
   768                 }
   769                 else
   770                 {
   771                     //No name, use session ID instead
   772                     node.Text = aClient.SessionId;
   773                 }
   774 
   775                 if (aClient.Texts.Count > 0)
   776                 {
   777                     //Create root node for our texts
   778                     TreeNode textsRoot = new TreeNode("Text");
   779                     node.Nodes.Add(textsRoot);
   780                     //For each text add a new entry
   781                     foreach (TextField field in aClient.Texts)
   782                     {
   783                         textsRoot.Nodes.Add(new TreeNode(field.Text));
   784                     }
   785                 }
   786 
   787                 node.ExpandAll();
   788             }
   789         }
   790 
   791         private void buttonAddRow_Click(object sender, EventArgs e)
   792         {
   793             if (tableLayoutPanel.RowCount < 6)
   794             {
   795                 tableLayoutPanel.RowCount++;
   796                 CheckFontHeight();
   797             }
   798         }
   799 
   800         private void buttonRemoveRow_Click(object sender, EventArgs e)
   801         {
   802             if (tableLayoutPanel.RowCount > 1)
   803             {
   804                 tableLayoutPanel.RowCount--;
   805                 CheckFontHeight();
   806             }
   807         }
   808 
   809         private void buttonAddColumn_Click(object sender, EventArgs e)
   810         {
   811             if (tableLayoutPanel.ColumnCount < 8)
   812             {
   813                 tableLayoutPanel.ColumnCount++;
   814                 //CheckFontHeight();
   815             }
   816         }
   817 
   818         private void buttonRemoveColumn_Click(object sender, EventArgs e)
   819         {
   820             if (tableLayoutPanel.ColumnCount > 1)
   821             {
   822                 tableLayoutPanel.ColumnCount--;
   823                 //CheckFontHeight();
   824             }
   825         }
   826 
   827         private void buttonAlignLeft_Click(object sender, EventArgs e)
   828         {
   829             marqueeLabelTop.TextAlign = ContentAlignment.MiddleLeft;
   830             marqueeLabelBottom.TextAlign = ContentAlignment.MiddleLeft;
   831         }
   832 
   833         private void buttonAlignCenter_Click(object sender, EventArgs e)
   834         {
   835             marqueeLabelTop.TextAlign = ContentAlignment.MiddleCenter;
   836             marqueeLabelBottom.TextAlign = ContentAlignment.MiddleCenter;
   837         }
   838 
   839         private void buttonAlignRight_Click(object sender, EventArgs e)
   840         {
   841             marqueeLabelTop.TextAlign = ContentAlignment.MiddleRight;
   842             marqueeLabelBottom.TextAlign = ContentAlignment.MiddleRight;
   843         }
   844 
   845         private void comboBoxDisplayType_SelectedIndexChanged(object sender, EventArgs e)
   846         {
   847             Properties.Settings.Default.CurrentDisplayIndex = comboBoxDisplayType.SelectedIndex;
   848             cds.DisplayType = comboBoxDisplayType.SelectedIndex;
   849             Properties.Settings.Default.Save();
   850             if (iDisplay.IsOpen())
   851             {
   852                 OpenDisplayConnection();
   853             }
   854             else
   855             {
   856                 UpdateStatus();
   857             }
   858         }
   859 
   860 
   861         private void maskedTextBoxTimerInterval_TextChanged(object sender, EventArgs e)
   862         {
   863             if (maskedTextBoxTimerInterval.Text != "")
   864             {
   865                 int interval = Convert.ToInt32(maskedTextBoxTimerInterval.Text);
   866 
   867                 if (interval > 0)
   868                 {
   869                     timer.Interval = interval;
   870                     cds.TimerInterval = timer.Interval;
   871                     Properties.Settings.Default.Save();
   872                 }
   873             }
   874         }
   875 
   876         private void buttonPowerOn_Click(object sender, EventArgs e)
   877         {
   878             iDisplay.PowerOn();
   879         }
   880 
   881         private void buttonPowerOff_Click(object sender, EventArgs e)
   882         {
   883             iDisplay.PowerOff();
   884         }
   885 
   886     }
   887 
   888     /// <summary>
   889     /// A UI thread copy of a client relevant data.
   890     /// Keeping this copy in the UI thread helps us deal with threading issues.
   891     /// </summary>
   892     public class ClientData
   893     {
   894         public ClientData(string aSessionId, IDisplayServiceCallback aCallback)
   895         {
   896             SessionId = aSessionId;
   897             Name = "";
   898             Texts = new List<TextField>();
   899             Callback = aCallback;
   900         }
   901 
   902         public string SessionId { get; set; }
   903         public string Name { get; set; }
   904         public List<TextField> Texts { get; set; }
   905         public IDisplayServiceCallback Callback { get; set; }
   906     }
   907 }