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