Server/MainForm.cs
author sl
Sun, 26 Oct 2014 16:16:57 +0100
changeset 75 2549a8055bd1
parent 72 fd0bb39a7818
child 76 906d88eb53fb
permissions -rw-r--r--
Removing specific functions for setting text and bitmap.
Now having a generic functions for setting any kind of fields.
Thus bitmaps can now be set together with text fields in a single server call.
     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 SharpDisplayClient;
    18 using SharpDisplay;
    19 
    20 namespace SharpDisplayManager
    21 {
    22     //Types declarations
    23     public delegate uint ColorProcessingDelegate(int aX, int aY, uint aPixel);
    24     public delegate int CoordinateTranslationDelegate(System.Drawing.Bitmap aBmp, int aInt);
    25     //Delegates are used for our thread safe method
    26     public delegate void AddClientDelegate(string aSessionId, ICallback aCallback);
    27     public delegate void RemoveClientDelegate(string aSessionId);
    28     public delegate void SetTextDelegate(string SessionId, DataField aField);
    29     public delegate void SetLayoutDelegate(string SessionId, TableLayout aLayout);
    30     public delegate void SetFieldsDelegate(string SessionId, System.Collections.Generic.IList<DataField> aFields);
    31     public delegate void SetClientNameDelegate(string aSessionId, string aName);
    32 
    33 
    34     /// <summary>
    35     /// Our Display manager main form
    36     /// </summary>
    37     public partial class MainForm : Form
    38     {
    39 
    40         DateTime LastTickTime;
    41         Display iDisplay;
    42         System.Drawing.Bitmap iBmp;
    43         bool iCreateBitmap; //Workaround render to bitmap issues when minimized
    44         ServiceHost iServiceHost;
    45         // Our collection of clients sorted by session id.
    46         public Dictionary<string, ClientData> iClients;
    47         // The name of the client which informations are currently displayed.
    48         public string iCurrentClientSessionId;
    49         ClientData iCurrentClientData;
    50         //
    51         public bool iClosing;
    52         //Function pointer for pixel color filtering
    53         ColorProcessingDelegate iColorFx;
    54         //Function pointer for pixel X coordinate intercept
    55         CoordinateTranslationDelegate iScreenX;
    56         //Function pointer for pixel Y coordinate intercept
    57         CoordinateTranslationDelegate iScreenY;
    58 
    59         public MainForm()
    60         {
    61             iCurrentClientSessionId = "";
    62             iCurrentClientData = null;
    63             LastTickTime = DateTime.Now;
    64             iDisplay = new Display();
    65             iClients = new Dictionary<string, ClientData>();
    66 
    67             InitializeComponent();
    68             UpdateStatus();
    69             //We have a bug when drawing minimized and reusing our bitmap
    70             iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
    71             iCreateBitmap = false;
    72         }
    73 
    74         private void MainForm_Load(object sender, EventArgs e)
    75         {
    76             StartServer();
    77 
    78             if (Properties.Settings.Default.DisplayConnectOnStartup)
    79             {
    80                 OpenDisplayConnection();
    81             }
    82         }
    83 
    84         /// <summary>
    85         /// Set our current client.
    86         /// This will take care of applying our client layout and set data fields.
    87         /// </summary>
    88         /// <param name="aSessionId"></param>
    89         void SetCurrentClient(string aSessionId)
    90         {
    91             if (aSessionId == iCurrentClientSessionId)
    92             {
    93                 //Given client is already the current one.
    94                 //Don't bother changing anything then.
    95                 return;
    96             }
    97 
    98             //Set current client ID.
    99             iCurrentClientSessionId = aSessionId;
   100             //Fetch and set current client data.
   101             iCurrentClientData = iClients[aSessionId];
   102             //Apply layout and set data fields.
   103             UpdateTableLayoutPanel(iCurrentClientData);
   104         }
   105 
   106         private void buttonFont_Click(object sender, EventArgs e)
   107         {
   108             //fontDialog.ShowColor = true;
   109             //fontDialog.ShowApply = true;
   110             fontDialog.ShowEffects = true;
   111             MarqueeLabel label = (MarqueeLabel)tableLayoutPanel.Controls[0];
   112             fontDialog.Font = label.Font;
   113 
   114             fontDialog.FixedPitchOnly = checkBoxFixedPitchFontOnly.Checked;
   115 
   116             //fontDialog.ShowHelp = true;
   117 
   118             //fontDlg.MaxSize = 40;
   119             //fontDlg.MinSize = 22;
   120 
   121             //fontDialog.Parent = this;
   122             //fontDialog.StartPosition = FormStartPosition.CenterParent;
   123 
   124             //DlgBox.ShowDialog(fontDialog);
   125 
   126             //if (fontDialog.ShowDialog(this) != DialogResult.Cancel)
   127             if (DlgBox.ShowDialog(fontDialog) != DialogResult.Cancel)
   128             {
   129 
   130                 //MsgBox.Show("MessageBox MsgBox", "MsgBox caption");
   131 
   132                 //MessageBox.Show("Ok");
   133                 foreach (MarqueeLabel ctrl in tableLayoutPanel.Controls)
   134                 {
   135                     ctrl.Font = fontDialog.Font;
   136                 }
   137                 cds.Font = fontDialog.Font;
   138                 Properties.Settings.Default.Save();
   139                 //
   140                 CheckFontHeight();
   141             }
   142         }
   143 
   144         /// <summary>
   145         ///
   146         /// </summary>
   147         void CheckFontHeight()
   148         {
   149             //Show font height and width
   150             labelFontHeight.Text = "Font height: " + cds.Font.Height;
   151             float charWidth = IsFixedWidth(cds.Font);
   152             if (charWidth == 0.0f)
   153             {
   154                 labelFontWidth.Visible = false;
   155             }
   156             else
   157             {
   158                 labelFontWidth.Visible = true;
   159                 labelFontWidth.Text = "Font width: " + charWidth;
   160             }
   161 
   162             MarqueeLabel label = null;
   163             //Get the first label control we can find
   164             foreach (Control ctrl in tableLayoutPanel.Controls)
   165             {
   166                 if (ctrl is MarqueeLabel)
   167                 {
   168                     label = (MarqueeLabel)ctrl;
   169                     break;
   170                 }
   171             }
   172 
   173             //Now check font height and show a warning if needed.
   174             if (label != null && label.Font.Height > label.Height)
   175             {
   176                 labelWarning.Text = "WARNING: Selected font is too height by " + (label.Font.Height - label.Height) + " pixels!";
   177                 labelWarning.Visible = true;
   178             }
   179             else
   180             {
   181                 labelWarning.Visible = false;
   182             }
   183 
   184         }
   185 
   186         private void buttonCapture_Click(object sender, EventArgs e)
   187         {
   188             System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height);
   189             tableLayoutPanel.DrawToBitmap(bmp, tableLayoutPanel.ClientRectangle);
   190             //Bitmap bmpToSave = new Bitmap(bmp);
   191             bmp.Save("D:\\capture.png");
   192 
   193             ((MarqueeLabel)tableLayoutPanel.Controls[0]).Text = "Captured";
   194 
   195             /*
   196             string outputFileName = "d:\\capture.png";
   197             using (MemoryStream memory = new MemoryStream())
   198             {
   199                 using (FileStream fs = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
   200                 {
   201                     bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
   202                     byte[] bytes = memory.ToArray();
   203                     fs.Write(bytes, 0, bytes.Length);
   204                 }
   205             }
   206              */
   207 
   208         }
   209 
   210         private void CheckForRequestResults()
   211         {
   212             if (iDisplay.IsRequestPending())
   213             {
   214                 switch (iDisplay.AttemptRequestCompletion())
   215                 {
   216                     case Display.TMiniDisplayRequest.EMiniDisplayRequestFirmwareRevision:
   217                         toolStripStatusLabelConnect.Text += " v" + iDisplay.FirmwareRevision();
   218                         //Issue next request then
   219                         iDisplay.RequestPowerSupplyStatus();
   220                         break;
   221 
   222                     case Display.TMiniDisplayRequest.EMiniDisplayRequestPowerSupplyStatus:
   223                         if (iDisplay.PowerSupplyStatus())
   224                         {
   225                             toolStripStatusLabelPower.Text = "ON";
   226                         }
   227                         else
   228                         {
   229                             toolStripStatusLabelPower.Text = "OFF";
   230                         }
   231                         //Issue next request then
   232                         iDisplay.RequestDeviceId();
   233                         break;
   234 
   235                     case Display.TMiniDisplayRequest.EMiniDisplayRequestDeviceId:
   236                         toolStripStatusLabelConnect.Text += " - " + iDisplay.DeviceId();
   237                         //No more request to issue
   238                         break;
   239                 }
   240             }
   241         }
   242 
   243         public static uint ColorWhiteIsOn(int aX, int aY, uint aPixel)
   244         {
   245             if ((aPixel & 0x00FFFFFF) == 0x00FFFFFF)
   246             {
   247                 return 0xFFFFFFFF;
   248             }
   249             return 0x00000000;
   250         }
   251 
   252         public static uint ColorUntouched(int aX, int aY, uint aPixel)
   253         {
   254             return aPixel;
   255         }
   256 
   257         public static uint ColorInversed(int aX, int aY, uint aPixel)
   258         {
   259             return ~aPixel;
   260         }
   261 
   262         public static uint ColorChessboard(int aX, int aY, uint aPixel)
   263         {
   264             if ((aX % 2 == 0) && (aY % 2 == 0))
   265             {
   266                 return ~aPixel;
   267             }
   268             else if ((aX % 2 != 0) && (aY % 2 != 0))
   269             {
   270                 return ~aPixel;
   271             }
   272             return 0x00000000;
   273         }
   274 
   275 
   276         public static int ScreenReversedX(System.Drawing.Bitmap aBmp, int aX)
   277         {
   278             return aBmp.Width - aX - 1;
   279         }
   280 
   281         public int ScreenReversedY(System.Drawing.Bitmap aBmp, int aY)
   282         {
   283             return iBmp.Height - aY - 1;
   284         }
   285 
   286         public int ScreenX(System.Drawing.Bitmap aBmp, int aX)
   287         {
   288             return aX;
   289         }
   290 
   291         public int ScreenY(System.Drawing.Bitmap aBmp, int aY)
   292         {
   293             return aY;
   294         }
   295 
   296         /// <summary>
   297         /// Select proper pixel delegates according to our current settings.
   298         /// </summary>
   299         private void SetupPixelDelegates()
   300         {
   301             //Select our pixel processing routine
   302             if (cds.InverseColors)
   303             {
   304                 //iColorFx = ColorChessboard;
   305                 iColorFx = ColorInversed;
   306             }
   307             else
   308             {
   309                 iColorFx = ColorWhiteIsOn;
   310             }
   311 
   312             //Select proper coordinate translation functions
   313             //We used delegate/function pointer to support reverse screen without doing an extra test on each pixels
   314             if (cds.ReverseScreen)
   315             {
   316                 iScreenX = ScreenReversedX;
   317                 iScreenY = ScreenReversedY;
   318             }
   319             else
   320             {
   321                 iScreenX = ScreenX;
   322                 iScreenY = ScreenY;
   323             }
   324 
   325         }
   326 
   327         //This is our timer tick responsible to perform our render
   328         private void timer_Tick(object sender, EventArgs e)
   329         {
   330             //Update our animations
   331             DateTime NewTickTime = DateTime.Now;
   332 
   333             //Update animation for all our marquees
   334             foreach (Control ctrl in tableLayoutPanel.Controls)
   335             {
   336                 if (ctrl is MarqueeLabel)
   337                 {
   338                     ((MarqueeLabel)ctrl).UpdateAnimation(LastTickTime, NewTickTime);
   339                 }
   340             }
   341 
   342 
   343             //Update our display
   344             if (iDisplay.IsOpen())
   345             {
   346                 CheckForRequestResults();
   347 
   348                 //Draw to bitmap
   349                 if (iCreateBitmap)
   350                 {
   351                     iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
   352                 }
   353                 tableLayoutPanel.DrawToBitmap(iBmp, tableLayoutPanel.ClientRectangle);
   354                 //iBmp.Save("D:\\capture.png");
   355 
   356                 //Send it to our display
   357                 for (int i = 0; i < iBmp.Width; i++)
   358                 {
   359                     for (int j = 0; j < iBmp.Height; j++)
   360                     {
   361                         unchecked
   362                         {
   363                             //Get our processed pixel coordinates
   364                             int x = iScreenX(iBmp, i);
   365                             int y = iScreenY(iBmp, j);
   366                             //Get pixel color
   367                             uint color = (uint)iBmp.GetPixel(i, j).ToArgb();
   368                             //Apply color effects
   369                             color = iColorFx(x,y,color);
   370                             //Now set our pixel
   371                             iDisplay.SetPixel(x, y, color);
   372                         }
   373                     }
   374                 }
   375 
   376                 iDisplay.SwapBuffers();
   377 
   378             }
   379 
   380             //Compute instant FPS
   381             toolStripStatusLabelFps.Text = (1.0/NewTickTime.Subtract(LastTickTime).TotalSeconds).ToString("F0") + " / " + (1000/timer.Interval).ToString() + " FPS";
   382 
   383             LastTickTime = NewTickTime;
   384 
   385         }
   386 
   387         private void OpenDisplayConnection()
   388         {
   389             CloseDisplayConnection();
   390 
   391             if (iDisplay.Open((Display.TMiniDisplayType)cds.DisplayType))
   392             {
   393                 UpdateStatus();
   394                 iDisplay.RequestFirmwareRevision();
   395             }
   396             else
   397             {
   398                 UpdateStatus();
   399                 toolStripStatusLabelConnect.Text = "Connection error";
   400             }
   401         }
   402 
   403         private void CloseDisplayConnection()
   404         {
   405             iDisplay.Close();
   406             UpdateStatus();
   407         }
   408 
   409         private void buttonOpen_Click(object sender, EventArgs e)
   410         {
   411             OpenDisplayConnection();
   412         }
   413 
   414         private void buttonClose_Click(object sender, EventArgs e)
   415         {
   416             CloseDisplayConnection();
   417         }
   418 
   419         private void buttonClear_Click(object sender, EventArgs e)
   420         {
   421             iDisplay.Clear();
   422             iDisplay.SwapBuffers();
   423         }
   424 
   425         private void buttonFill_Click(object sender, EventArgs e)
   426         {
   427             iDisplay.Fill();
   428             iDisplay.SwapBuffers();
   429         }
   430 
   431         private void trackBarBrightness_Scroll(object sender, EventArgs e)
   432         {
   433             cds.Brightness = trackBarBrightness.Value;
   434             Properties.Settings.Default.Save();
   435             iDisplay.SetBrightness(trackBarBrightness.Value);
   436 
   437         }
   438 
   439 
   440         /// <summary>
   441         /// CDS stands for Current Display Settings
   442         /// </summary>
   443         private DisplaySettings cds
   444         {
   445             get
   446             {
   447                 DisplaysSettings settings = Properties.Settings.Default.DisplaysSettings;
   448                 if (settings == null)
   449                 {
   450                     settings = new DisplaysSettings();
   451                     settings.Init();
   452                     Properties.Settings.Default.DisplaysSettings = settings;
   453                 }
   454 
   455                 //Make sure all our settings have been created
   456                 while (settings.Displays.Count <= Properties.Settings.Default.CurrentDisplayIndex)
   457                 {
   458                     settings.Displays.Add(new DisplaySettings());
   459                 }
   460 
   461                 DisplaySettings displaySettings = settings.Displays[Properties.Settings.Default.CurrentDisplayIndex];
   462                 return displaySettings;
   463             }
   464         }
   465 
   466         /// <summary>
   467         /// Check if the given font has a fixed character pitch.
   468         /// </summary>
   469         /// <param name="ft"></param>
   470         /// <returns>0.0f if this is not a monospace font, otherwise returns the character width.</returns>
   471         public float IsFixedWidth(Font ft)
   472         {
   473             Graphics g = CreateGraphics();
   474             char[] charSizes = new char[] { 'i', 'a', 'Z', '%', '#', 'a', 'B', 'l', 'm', ',', '.' };
   475             float charWidth = g.MeasureString("I", ft, Int32.MaxValue, StringFormat.GenericTypographic).Width;
   476 
   477             bool fixedWidth = true;
   478 
   479             foreach (char c in charSizes)
   480                 if (g.MeasureString(c.ToString(), ft, Int32.MaxValue, StringFormat.GenericTypographic).Width != charWidth)
   481                     fixedWidth = false;
   482 
   483             if (fixedWidth)
   484             {
   485                 return charWidth;
   486             }
   487 
   488             return 0.0f;
   489         }
   490 
   491         private void UpdateStatus()
   492         {
   493             //Synchronize UI with settings
   494             //Load settings
   495             checkBoxShowBorders.Checked = cds.ShowBorders;
   496             tableLayoutPanel.CellBorderStyle = (cds.ShowBorders ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
   497 
   498             //Set the proper font to each of our labels
   499             foreach (MarqueeLabel ctrl in tableLayoutPanel.Controls)
   500             {
   501                 ctrl.Font = cds.Font;
   502             }
   503 
   504             CheckFontHeight();
   505             checkBoxConnectOnStartup.Checked = Properties.Settings.Default.DisplayConnectOnStartup;
   506             checkBoxReverseScreen.Checked = cds.ReverseScreen;
   507             checkBoxInverseColors.Checked = cds.InverseColors;
   508             comboBoxDisplayType.SelectedIndex = cds.DisplayType;
   509             timer.Interval = cds.TimerInterval;
   510             maskedTextBoxTimerInterval.Text = cds.TimerInterval.ToString();
   511             //
   512             SetupPixelDelegates();
   513 
   514             if (iDisplay.IsOpen())
   515             {
   516                 //Only setup brightness if display is open
   517                 trackBarBrightness.Minimum = iDisplay.MinBrightness();
   518                 trackBarBrightness.Maximum = iDisplay.MaxBrightness();
   519                 trackBarBrightness.Value = cds.Brightness;
   520                 trackBarBrightness.LargeChange = Math.Max(1, (iDisplay.MaxBrightness() - iDisplay.MinBrightness()) / 5);
   521                 trackBarBrightness.SmallChange = 1;
   522                 iDisplay.SetBrightness(cds.Brightness);
   523                 //
   524                 buttonFill.Enabled = true;
   525                 buttonClear.Enabled = true;
   526                 buttonOpen.Enabled = false;
   527                 buttonClose.Enabled = true;
   528                 trackBarBrightness.Enabled = true;
   529                 toolStripStatusLabelConnect.Text = "Connected - " + iDisplay.Vendor() + " - " + iDisplay.Product();
   530                 //+ " - " + iDisplay.SerialNumber();
   531 
   532                 if (iDisplay.SupportPowerOnOff())
   533                 {
   534                     buttonPowerOn.Enabled = true;
   535                     buttonPowerOff.Enabled = true;
   536                 }
   537                 else
   538                 {
   539                     buttonPowerOn.Enabled = false;
   540                     buttonPowerOff.Enabled = false;
   541                 }
   542 
   543                 if (iDisplay.SupportClock())
   544                 {
   545                     buttonShowClock.Enabled = true;
   546                     buttonHideClock.Enabled = true;
   547                 }
   548                 else
   549                 {
   550                     buttonShowClock.Enabled = false;
   551                     buttonHideClock.Enabled = false;
   552                 }
   553             }
   554             else
   555             {
   556                 buttonFill.Enabled = false;
   557                 buttonClear.Enabled = false;
   558                 buttonOpen.Enabled = true;
   559                 buttonClose.Enabled = false;
   560                 trackBarBrightness.Enabled = false;
   561                 buttonPowerOn.Enabled = false;
   562                 buttonPowerOff.Enabled = false;
   563                 buttonShowClock.Enabled = false;
   564                 buttonHideClock.Enabled = false;
   565                 toolStripStatusLabelConnect.Text = "Disconnected";
   566                 toolStripStatusLabelPower.Text = "N/A";
   567             }
   568         }
   569 
   570 
   571 
   572         private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
   573         {
   574             //Save our show borders setting
   575             tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
   576             cds.ShowBorders = checkBoxShowBorders.Checked;
   577             Properties.Settings.Default.Save();
   578             CheckFontHeight();
   579         }
   580 
   581         private void checkBoxConnectOnStartup_CheckedChanged(object sender, EventArgs e)
   582         {
   583             //Save our connect on startup setting
   584             Properties.Settings.Default.DisplayConnectOnStartup = checkBoxConnectOnStartup.Checked;
   585             Properties.Settings.Default.Save();
   586         }
   587 
   588         private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
   589         {
   590             //Save our reverse screen setting
   591             cds.ReverseScreen = checkBoxReverseScreen.Checked;
   592             Properties.Settings.Default.Save();
   593             SetupPixelDelegates();
   594         }
   595 
   596         private void checkBoxInverseColors_CheckedChanged(object sender, EventArgs e)
   597         {
   598             //Save our inverse colors setting
   599             cds.InverseColors = checkBoxInverseColors.Checked;
   600             Properties.Settings.Default.Save();
   601             SetupPixelDelegates();
   602         }
   603 
   604         private void MainForm_Resize(object sender, EventArgs e)
   605         {
   606             if (WindowState == FormWindowState.Minimized)
   607             {
   608                 // Do some stuff
   609                 //iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
   610                 iCreateBitmap = true;
   611             }
   612         }
   613 
   614         private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
   615         {
   616             StopServer();
   617             e.Cancel = iClosing;
   618         }
   619 
   620         public void StartServer()
   621         {
   622             iServiceHost = new ServiceHost
   623                 (
   624                     typeof(Session),
   625                     new Uri[] { new Uri("net.tcp://localhost:8001/") }
   626                 );
   627 
   628             iServiceHost.AddServiceEndpoint(typeof(IService), new NetTcpBinding(SecurityMode.None, true), "DisplayService");
   629             iServiceHost.Open();
   630         }
   631 
   632         public void StopServer()
   633         {
   634             if (iClients.Count > 0 && !iClosing)
   635             {
   636                 //Tell our clients
   637                 iClosing = true;
   638                 BroadcastCloseEvent();
   639             }
   640             else if (iClosing)
   641             {
   642                 if (MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
   643                 {
   644                     iClosing = false; //We make sure we force close if asked twice
   645                 }
   646             }
   647             else
   648             {
   649                 //We removed that as it often lags for some reason
   650                 //iServiceHost.Close();
   651             }
   652         }
   653 
   654         public void BroadcastCloseEvent()
   655         {
   656             Trace.TraceInformation("BroadcastCloseEvent - start");
   657 
   658             var inactiveClients = new List<string>();
   659             foreach (var client in iClients)
   660             {
   661                 //if (client.Key != eventData.ClientName)
   662                 {
   663                     try
   664                     {
   665                         Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
   666                         client.Value.Callback.OnCloseOrder(/*eventData*/);
   667                     }
   668                     catch (Exception ex)
   669                     {
   670                         inactiveClients.Add(client.Key);
   671                     }
   672                 }
   673             }
   674 
   675             if (inactiveClients.Count > 0)
   676             {
   677                 foreach (var client in inactiveClients)
   678                 {
   679                     iClients.Remove(client);
   680                     Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(client, false)[0]);
   681                 }
   682             }
   683         }
   684 
   685         private void buttonStartClient_Click(object sender, EventArgs e)
   686         {
   687             Thread clientThread = new Thread(SharpDisplayClient.Program.Main);
   688             clientThread.Start();
   689             BringToFront();
   690         }
   691 
   692         private void buttonSuspend_Click(object sender, EventArgs e)
   693         {
   694             LastTickTime = DateTime.Now; //Reset timer to prevent jump
   695             timer.Enabled = !timer.Enabled;
   696             if (!timer.Enabled)
   697             {
   698                 buttonSuspend.Text = "Run";
   699             }
   700             else
   701             {
   702                 buttonSuspend.Text = "Pause";
   703             }
   704         }
   705 
   706         private void buttonCloseClients_Click(object sender, EventArgs e)
   707         {
   708             BroadcastCloseEvent();
   709         }
   710 
   711         private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
   712         {
   713 
   714         }
   715 
   716 
   717         /// <summary>
   718         ///
   719         /// </summary>
   720         /// <param name="aSessionId"></param>
   721         /// <param name="aCallback"></param>
   722         public void AddClientThreadSafe(string aSessionId, ICallback aCallback)
   723         {
   724             if (this.InvokeRequired)
   725             {
   726                 //Not in the proper thread, invoke ourselves
   727                 AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
   728                 this.Invoke(d, new object[] { aSessionId, aCallback });
   729             }
   730             else
   731             {
   732                 //We are in the proper thread
   733                 //Add this session to our collection of clients
   734                 ClientData newClient = new ClientData(aSessionId, aCallback);
   735                 Program.iMainForm.iClients.Add(aSessionId, newClient);
   736                 //Add this session to our UI
   737                 UpdateClientTreeViewNode(newClient);
   738             }
   739         }
   740 
   741         /// <summary>
   742         ///
   743         /// </summary>
   744         /// <param name="aSessionId"></param>
   745         public void RemoveClientThreadSafe(string aSessionId)
   746         {
   747             if (this.InvokeRequired)
   748             {
   749                 //Not in the proper thread, invoke ourselves
   750                 RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
   751                 this.Invoke(d, new object[] { aSessionId });
   752             }
   753             else
   754             {
   755                 //We are in the proper thread
   756                 //Remove this session from both client collection and UI tree view
   757                 if (Program.iMainForm.iClients.Keys.Contains(aSessionId))
   758                 {
   759                     Program.iMainForm.iClients.Remove(aSessionId);
   760                     Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(aSessionId, false)[0]);
   761                 }
   762 
   763                 if (iClosing && iClients.Count == 0)
   764                 {
   765                     //We were closing our form
   766                     //All clients are now closed
   767                     //Just resume our close operation
   768                     iClosing = false;
   769                     Close();
   770                 }
   771             }
   772         }
   773 
   774         /// <summary>
   775         ///
   776         /// </summary>
   777         /// <param name="aSessionId"></param>
   778         /// <param name="aLayout"></param>
   779         public void SetClientLayoutThreadSafe(string aSessionId, TableLayout aLayout)
   780         {
   781             if (this.InvokeRequired)
   782             {
   783                 //Not in the proper thread, invoke ourselves
   784                 SetLayoutDelegate d = new SetLayoutDelegate(SetClientLayoutThreadSafe);
   785                 this.Invoke(d, new object[] { aSessionId, aLayout });
   786             }
   787             else
   788             {
   789                 ClientData client = iClients[aSessionId];
   790                 if (client != null)
   791                 {
   792                     client.Layout = aLayout;
   793                     UpdateTableLayoutPanel(client);
   794                     //
   795                     UpdateClientTreeViewNode(client);
   796                 }
   797             }
   798         }
   799 
   800         /// <summary>
   801         ///
   802         /// </summary>
   803         /// <param name="aSessionId"></param>
   804         /// <param name="aField"></param>
   805         public void SetClientFieldThreadSafe(string aSessionId, DataField aField)
   806         {
   807             if (this.InvokeRequired)
   808             {
   809                 //Not in the proper thread, invoke ourselves
   810                 SetTextDelegate d = new SetTextDelegate(SetClientFieldThreadSafe);
   811                 this.Invoke(d, new object[] { aSessionId, aField });
   812             }
   813             else
   814             {
   815                 //We are in the proper thread
   816                 //Call the non-thread-safe variant
   817                 SetClientField(aSessionId, aField);
   818             }
   819         }
   820 
   821         /// <summary>
   822         /// 
   823         /// </summary>
   824         /// <param name="aSessionId"></param>
   825         /// <param name="aField"></param>
   826         private void SetClientField(string aSessionId, DataField aField)
   827         {            
   828             SetCurrentClient(aSessionId);
   829             ClientData client = iClients[aSessionId];
   830             if (client != null)
   831             {
   832                 //Make sure all our fields are in place
   833                 while (client.Fields.Count < (aField.Index + 1))
   834                 {
   835                     //Add a text field with proper index
   836                     client.Fields.Add(new DataField(client.Fields.Count));
   837                 }
   838 
   839                 if (client.Fields[aField.Index].IsSameLayout(aField))
   840                 {
   841                     //Same layout just update our field
   842                     client.Fields[aField.Index] = aField;
   843                     //
   844                     if (aField.IsText && tableLayoutPanel.Controls[aField.Index] is MarqueeLabel)
   845                     {
   846                         //Text field control already in place, just change the text
   847                         MarqueeLabel label = (MarqueeLabel)tableLayoutPanel.Controls[aField.Index];
   848                         label.Text = aField.Text;
   849                         label.TextAlign = aField.Alignment;
   850                     }
   851                     else if (aField.IsBitmap && tableLayoutPanel.Controls[aField.Index] is PictureBox)
   852                     {
   853                         //Bitmap field control already in place just change the bitmap
   854                         PictureBox pictureBox = (PictureBox)tableLayoutPanel.Controls[aField.Index];
   855                         pictureBox.Image = aField.Bitmap;
   856                     }
   857                     else
   858                     {
   859                         //The requested control in our layout it not of the correct type
   860                         //Wrong control type, re-create them all
   861                         UpdateTableLayoutPanel(iCurrentClientData);
   862                     }
   863                 }
   864                 else
   865                 {
   866                     //Different layout, need to rebuild it
   867                     client.Fields[aField.Index] = aField;
   868                     UpdateTableLayoutPanel(iCurrentClientData);
   869                 }
   870 
   871                 //
   872                 UpdateClientTreeViewNode(client);
   873             }
   874         }
   875 
   876         /// <summary>
   877         ///
   878         /// </summary>
   879         /// <param name="aTexts"></param>
   880         public void SetClientFieldsThreadSafe(string aSessionId, System.Collections.Generic.IList<DataField> aFields)
   881         {
   882             if (this.InvokeRequired)
   883             {
   884                 //Not in the proper thread, invoke ourselves
   885                 SetFieldsDelegate d = new SetFieldsDelegate(SetClientFieldsThreadSafe);
   886                 this.Invoke(d, new object[] { aSessionId, aFields });
   887             }
   888             else
   889             {
   890                 //Put each our text fields in a label control
   891                 foreach (DataField field in aFields)
   892                 {
   893                     SetClientField(aSessionId, field);
   894                 }
   895             }
   896         }
   897 
   898         /// <summary>
   899         ///
   900         /// </summary>
   901         /// <param name="aSessionId"></param>
   902         /// <param name="aName"></param>
   903         public void SetClientNameThreadSafe(string aSessionId, string aName)
   904         {
   905             if (this.InvokeRequired)
   906             {
   907                 //Not in the proper thread, invoke ourselves
   908                 SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
   909                 this.Invoke(d, new object[] { aSessionId, aName });
   910             }
   911             else
   912             {
   913                 //We are in the proper thread
   914                 //Get our client
   915                 ClientData client = iClients[aSessionId];
   916                 if (client != null)
   917                 {
   918                     //Set its name
   919                     client.Name = aName;
   920                     //Update our tree-view
   921                     UpdateClientTreeViewNode(client);
   922                 }
   923             }
   924         }
   925 
   926         /// <summary>
   927         ///
   928         /// </summary>
   929         /// <param name="aClient"></param>
   930         private void UpdateClientTreeViewNode(ClientData aClient)
   931         {
   932             if (aClient == null)
   933             {
   934                 return;
   935             }
   936 
   937             TreeNode node = null;
   938             //Check that our client node already exists
   939             //Get our client root node using its key which is our session ID
   940             TreeNode[] nodes = treeViewClients.Nodes.Find(aClient.SessionId, false);
   941             if (nodes.Count()>0)
   942             {
   943                 //We already have a node for that client
   944                 node = nodes[0];
   945                 //Clear children as we are going to recreate them below
   946                 node.Nodes.Clear();
   947             }
   948             else
   949             {
   950                 //Client node does not exists create a new one
   951                 treeViewClients.Nodes.Add(aClient.SessionId, aClient.SessionId);
   952                 node = treeViewClients.Nodes.Find(aClient.SessionId, false)[0];
   953             }
   954 
   955             if (node != null)
   956             {
   957                 //Change its name
   958                 if (aClient.Name != "")
   959                 {
   960                     //We have a name, us it as text for our root node
   961                     node.Text = aClient.Name;
   962                     //Add a child with SessionId
   963                     node.Nodes.Add(new TreeNode(aClient.SessionId));
   964                 }
   965                 else
   966                 {
   967                     //No name, use session ID instead
   968                     node.Text = aClient.SessionId;
   969                 }
   970 
   971                 if (aClient.Fields.Count > 0)
   972                 {
   973                     //Create root node for our texts
   974                     TreeNode textsRoot = new TreeNode("Fields");
   975                     node.Nodes.Add(textsRoot);
   976                     //For each text add a new entry
   977                     foreach (DataField field in aClient.Fields)
   978                     {
   979                         if (!field.IsBitmap)
   980                         {
   981                             DataField textField = (DataField)field;
   982                             textsRoot.Nodes.Add(new TreeNode("[Text]" + textField.Text));
   983                         }
   984                         else
   985                         {
   986                             textsRoot.Nodes.Add(new TreeNode("[Bitmap]"));
   987                         }
   988                     }
   989                 }
   990 
   991                 node.ExpandAll();
   992             }
   993         }
   994 
   995         private void buttonAddRow_Click(object sender, EventArgs e)
   996         {
   997             if (tableLayoutPanel.RowCount < 6)
   998             {
   999                 UpdateTableLayoutPanel(tableLayoutPanel.ColumnCount, tableLayoutPanel.RowCount + 1);
  1000             }
  1001         }
  1002 
  1003         private void buttonRemoveRow_Click(object sender, EventArgs e)
  1004         {
  1005             if (tableLayoutPanel.RowCount > 1)
  1006             {
  1007                 UpdateTableLayoutPanel(tableLayoutPanel.ColumnCount, tableLayoutPanel.RowCount - 1);
  1008             }
  1009 
  1010             UpdateTableLayoutRowStyles();
  1011         }
  1012 
  1013         private void buttonAddColumn_Click(object sender, EventArgs e)
  1014         {
  1015             if (tableLayoutPanel.ColumnCount < 8)
  1016             {
  1017                 UpdateTableLayoutPanel(tableLayoutPanel.ColumnCount + 1, tableLayoutPanel.RowCount);
  1018             }
  1019         }
  1020 
  1021         private void buttonRemoveColumn_Click(object sender, EventArgs e)
  1022         {
  1023             if (tableLayoutPanel.ColumnCount > 1)
  1024             {
  1025                 UpdateTableLayoutPanel(tableLayoutPanel.ColumnCount - 1, tableLayoutPanel.RowCount);
  1026             }
  1027         }
  1028 
  1029 
  1030         /// <summary>
  1031         /// Update our table layout row styles to make sure each rows have similar height
  1032         /// </summary>
  1033         private void UpdateTableLayoutRowStyles()
  1034         {
  1035             foreach (RowStyle rowStyle in tableLayoutPanel.RowStyles)
  1036             {
  1037                 rowStyle.SizeType = SizeType.Percent;
  1038                 rowStyle.Height = 100 / tableLayoutPanel.RowCount;
  1039             }
  1040         }
  1041 
  1042         /// DEPRECATED
  1043         /// <summary>
  1044         /// Empty and recreate our table layout with the given number of columns and rows.
  1045         /// Sizes of rows and columns are uniform.
  1046         /// </summary>
  1047         /// <param name="aColumn"></param>
  1048         /// <param name="aRow"></param>
  1049         private void UpdateTableLayoutPanel(int aColumn, int aRow)
  1050         {
  1051             tableLayoutPanel.Controls.Clear();
  1052             tableLayoutPanel.RowStyles.Clear();
  1053             tableLayoutPanel.ColumnStyles.Clear();
  1054             tableLayoutPanel.RowCount = 0;
  1055             tableLayoutPanel.ColumnCount = 0;
  1056 
  1057             while (tableLayoutPanel.RowCount < aRow)
  1058             {
  1059                 tableLayoutPanel.RowCount++;
  1060             }
  1061 
  1062             while (tableLayoutPanel.ColumnCount < aColumn)
  1063             {
  1064                 tableLayoutPanel.ColumnCount++;
  1065             }
  1066 
  1067             for (int i = 0; i < tableLayoutPanel.ColumnCount; i++)
  1068             {
  1069                 //Create our column styles
  1070                 this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100 / tableLayoutPanel.ColumnCount));
  1071 
  1072                 for (int j = 0; j < tableLayoutPanel.RowCount; j++)
  1073                 {
  1074                     if (i == 0)
  1075                     {
  1076                         //Create our row styles
  1077                         this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100 / tableLayoutPanel.RowCount));
  1078                     }
  1079 
  1080                     MarqueeLabel control = new SharpDisplayManager.MarqueeLabel();
  1081                     control.AutoEllipsis = true;
  1082                     control.AutoSize = true;
  1083                     control.BackColor = System.Drawing.Color.Transparent;
  1084                     control.Dock = System.Windows.Forms.DockStyle.Fill;
  1085                     control.Location = new System.Drawing.Point(1, 1);
  1086                     control.Margin = new System.Windows.Forms.Padding(0);
  1087                     control.Name = "marqueeLabelCol" + aColumn + "Row" + aRow;
  1088                     control.OwnTimer = false;
  1089                     control.PixelsPerSecond = 64;
  1090                     control.Separator = "|";
  1091                     //control.Size = new System.Drawing.Size(254, 30);
  1092                     //control.TabIndex = 2;
  1093                     control.Font = cds.Font;
  1094                     control.Text = "ABCDEFGHIJKLMNOPQRST-0123456789";
  1095                     control.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
  1096                     control.UseCompatibleTextRendering = true;
  1097                     //
  1098                     tableLayoutPanel.Controls.Add(control, i, j);
  1099                 }
  1100             }
  1101 
  1102             CheckFontHeight();
  1103         }
  1104 
  1105 
  1106         /// <summary>
  1107         /// Update our display table layout.
  1108         /// </summary>
  1109         /// <param name="aLayout"></param>
  1110         private void UpdateTableLayoutPanel(ClientData aClient)
  1111         {
  1112             TableLayout layout = aClient.Layout;
  1113             int fieldCount = 0;
  1114 
  1115             tableLayoutPanel.Controls.Clear();
  1116             tableLayoutPanel.RowStyles.Clear();
  1117             tableLayoutPanel.ColumnStyles.Clear();
  1118             tableLayoutPanel.RowCount = 0;
  1119             tableLayoutPanel.ColumnCount = 0;
  1120 
  1121             while (tableLayoutPanel.RowCount < layout.Rows.Count)
  1122             {
  1123                 tableLayoutPanel.RowCount++;
  1124             }
  1125 
  1126             while (tableLayoutPanel.ColumnCount < layout.Columns.Count)
  1127             {
  1128                 tableLayoutPanel.ColumnCount++;
  1129             }
  1130 
  1131             for (int i = 0; i < tableLayoutPanel.ColumnCount; i++)
  1132             {
  1133                 //Create our column styles
  1134                 this.tableLayoutPanel.ColumnStyles.Add(layout.Columns[i]);
  1135 
  1136                 for (int j = 0; j < tableLayoutPanel.RowCount; j++)
  1137                 {
  1138                     if (i == 0)
  1139                     {
  1140                         //Create our row styles
  1141                         this.tableLayoutPanel.RowStyles.Add(layout.Rows[j]);
  1142                     }
  1143 
  1144                     //Check if we already have a control
  1145                     Control existingControl = tableLayoutPanel.GetControlFromPosition(i,j);
  1146                     if (existingControl!=null)
  1147                     {
  1148                         //We already have a control in that cell as a results of row/col spanning
  1149                         //Move on to next cell then
  1150                         continue;
  1151                     }
  1152 
  1153                     fieldCount++;
  1154 
  1155                     //Check if a client field already exists for that cell
  1156                     if (aClient.Fields.Count <= tableLayoutPanel.Controls.Count)
  1157                     {
  1158                         //No client field specified, create a text field by default
  1159                         aClient.Fields.Add(new DataField(aClient.Fields.Count));
  1160                     }
  1161 
  1162                     //Create a control corresponding to the field specified for that cell
  1163                     DataField field = aClient.Fields[tableLayoutPanel.Controls.Count];
  1164                     Control control = CreateControlForDataField(field);
  1165 
  1166                     //Add newly created control to our table layout at the specified row and column
  1167                     tableLayoutPanel.Controls.Add(control, i, j);
  1168                     //Make sure we specify row and column span for that new control
  1169                     tableLayoutPanel.SetRowSpan(control,field.RowSpan);
  1170                     tableLayoutPanel.SetColumnSpan(control, field.ColumnSpan);
  1171                 }
  1172             }
  1173 
  1174             //
  1175             while (aClient.Fields.Count > fieldCount)
  1176             {
  1177                 //We have too much fields for this layout
  1178                 //Just discard them until we get there
  1179                 aClient.Fields.RemoveAt(aClient.Fields.Count-1);
  1180             }
  1181 
  1182             CheckFontHeight();
  1183         }
  1184 
  1185         /// <summary>
  1186         /// Check our type of data field and create corresponding control
  1187         /// </summary>
  1188         /// <param name="aField"></param>
  1189         private Control CreateControlForDataField(DataField aField)
  1190         {
  1191             Control control=null;
  1192             if (!aField.IsBitmap)
  1193             {
  1194                 MarqueeLabel label = new SharpDisplayManager.MarqueeLabel();
  1195                 label.AutoEllipsis = true;
  1196                 label.AutoSize = true;
  1197                 label.BackColor = System.Drawing.Color.Transparent;
  1198                 label.Dock = System.Windows.Forms.DockStyle.Fill;
  1199                 label.Location = new System.Drawing.Point(1, 1);
  1200                 label.Margin = new System.Windows.Forms.Padding(0);
  1201                 label.Name = "marqueeLabel" + aField.Index;
  1202                 label.OwnTimer = false;
  1203                 label.PixelsPerSecond = 64;
  1204                 label.Separator = "|";
  1205                 //control.Size = new System.Drawing.Size(254, 30);
  1206                 //control.TabIndex = 2;
  1207                 label.Font = cds.Font;
  1208 
  1209                 label.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
  1210                 label.UseCompatibleTextRendering = true;
  1211                 label.Text = aField.Text;
  1212                 //
  1213                 control = label;
  1214             }
  1215             else
  1216             {
  1217                 //Create picture box
  1218                 PictureBox picture = new PictureBox();
  1219                 picture.AutoSize = true;
  1220                 picture.BackColor = System.Drawing.Color.Transparent;
  1221                 picture.Dock = System.Windows.Forms.DockStyle.Fill;
  1222                 picture.Location = new System.Drawing.Point(1, 1);
  1223                 picture.Margin = new System.Windows.Forms.Padding(0);
  1224                 picture.Name = "pictureBox" + aField;
  1225                 //Set our image
  1226                 picture.Image = aField.Bitmap;
  1227                 //
  1228                 control = picture;
  1229             }
  1230 
  1231             return control;
  1232         }
  1233 
  1234 
  1235         private void buttonAlignLeft_Click(object sender, EventArgs e)
  1236         {
  1237             foreach (MarqueeLabel ctrl in tableLayoutPanel.Controls)
  1238             {
  1239                 ctrl.TextAlign = ContentAlignment.MiddleLeft;
  1240             }
  1241         }
  1242 
  1243         private void buttonAlignCenter_Click(object sender, EventArgs e)
  1244         {
  1245             foreach (MarqueeLabel ctrl in tableLayoutPanel.Controls)
  1246             {
  1247                 ctrl.TextAlign = ContentAlignment.MiddleCenter;
  1248             }
  1249         }
  1250 
  1251         private void buttonAlignRight_Click(object sender, EventArgs e)
  1252         {
  1253             foreach (MarqueeLabel ctrl in tableLayoutPanel.Controls)
  1254             {
  1255                 ctrl.TextAlign = ContentAlignment.MiddleRight;
  1256             }
  1257         }
  1258 
  1259         private void comboBoxDisplayType_SelectedIndexChanged(object sender, EventArgs e)
  1260         {
  1261             Properties.Settings.Default.CurrentDisplayIndex = comboBoxDisplayType.SelectedIndex;
  1262             cds.DisplayType = comboBoxDisplayType.SelectedIndex;
  1263             Properties.Settings.Default.Save();
  1264             if (iDisplay.IsOpen())
  1265             {
  1266                 OpenDisplayConnection();
  1267             }
  1268             else
  1269             {
  1270                 UpdateStatus();
  1271             }
  1272         }
  1273 
  1274 
  1275         private void maskedTextBoxTimerInterval_TextChanged(object sender, EventArgs e)
  1276         {
  1277             if (maskedTextBoxTimerInterval.Text != "")
  1278             {
  1279                 int interval = Convert.ToInt32(maskedTextBoxTimerInterval.Text);
  1280 
  1281                 if (interval > 0)
  1282                 {
  1283                     timer.Interval = interval;
  1284                     cds.TimerInterval = timer.Interval;
  1285                     Properties.Settings.Default.Save();
  1286                 }
  1287             }
  1288         }
  1289 
  1290         private void buttonPowerOn_Click(object sender, EventArgs e)
  1291         {
  1292             iDisplay.PowerOn();
  1293         }
  1294 
  1295         private void buttonPowerOff_Click(object sender, EventArgs e)
  1296         {
  1297             iDisplay.PowerOff();
  1298         }
  1299 
  1300         private void buttonShowClock_Click(object sender, EventArgs e)
  1301         {
  1302             iDisplay.ShowClock();
  1303         }
  1304 
  1305         private void buttonHideClock_Click(object sender, EventArgs e)
  1306         {
  1307             iDisplay.HideClock();
  1308         }
  1309     }
  1310 
  1311     /// <summary>
  1312     /// A UI thread copy of a client relevant data.
  1313     /// Keeping this copy in the UI thread helps us deal with threading issues.
  1314     /// </summary>
  1315     public class ClientData
  1316     {
  1317         public ClientData(string aSessionId, ICallback aCallback)
  1318         {
  1319             SessionId = aSessionId;
  1320             Name = "";
  1321             Fields = new List<DataField>();
  1322             Layout = new TableLayout(1, 2); //Default to one column and two rows
  1323             Callback = aCallback;
  1324         }
  1325 
  1326         public string SessionId { get; set; }
  1327         public string Name { get; set; }
  1328         public List<DataField> Fields { get; set; }
  1329         public TableLayout Layout { get; set; }
  1330         public ICallback Callback { get; set; }
  1331     }
  1332 }