GP1212A02: Clock support.
2 using System.Collections.Generic;
3 using System.ComponentModel;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
11 using CodeProject.Dialog;
12 using System.Drawing.Imaging;
13 using System.ServiceModel;
14 using System.Threading;
15 using System.Diagnostics;
17 using SharpDisplayInterface;
18 using SharpDisplayClient;
21 namespace SharpDisplayManager
23 public partial class MainForm : Form
25 DateTime LastTickTime;
27 System.Drawing.Bitmap iBmp;
28 bool iCreateBitmap; //Workaround render to bitmap issues when minimized
29 ServiceHost iServiceHost;
31 /// Our collection of clients
33 public Dictionary<string, ClientData> iClients;
38 LastTickTime = DateTime.Now;
39 iDisplay = new Display();
40 iClients = new Dictionary<string, ClientData>();
42 InitializeComponent();
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;
52 private void MainForm_Load(object sender, EventArgs e)
61 if (Properties.Settings.Default.DisplayConnectOnStartup)
63 OpenDisplayConnection();
68 private void buttonFont_Click(object sender, EventArgs e)
70 //fontDialog.ShowColor = true;
71 //fontDialog.ShowApply = true;
72 fontDialog.ShowEffects = true;
73 fontDialog.Font = marqueeLabelTop.Font;
75 fontDialog.FixedPitchOnly = checkBoxFixedPitchFontOnly.Checked;
77 //fontDialog.ShowHelp = true;
79 //fontDlg.MaxSize = 40;
80 //fontDlg.MinSize = 22;
82 //fontDialog.Parent = this;
83 //fontDialog.StartPosition = FormStartPosition.CenterParent;
85 //DlgBox.ShowDialog(fontDialog);
87 //if (fontDialog.ShowDialog(this) != DialogResult.Cancel)
88 if (DlgBox.ShowDialog(fontDialog) != DialogResult.Cancel)
91 //MsgBox.Show("MessageBox MsgBox", "MsgBox caption");
93 //MessageBox.Show("Ok");
94 marqueeLabelTop.Font = fontDialog.Font;
95 marqueeLabelBottom.Font = fontDialog.Font;
96 cds.Font = fontDialog.Font;
97 Properties.Settings.Default.Save();
106 void CheckFontHeight()
108 if (marqueeLabelBottom.Font.Height > marqueeLabelBottom.Height)
110 labelWarning.Text = "WARNING: Selected font is too height by " + (marqueeLabelBottom.Font.Height - marqueeLabelBottom.Height) + " pixels!";
111 labelWarning.Visible = true;
115 labelWarning.Visible = false;
120 private void buttonCapture_Click(object sender, EventArgs e)
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");
127 marqueeLabelTop.Text = "Sweet";
130 string outputFileName = "d:\\capture.png";
131 using (MemoryStream memory = new MemoryStream())
133 using (FileStream fs = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
135 bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
136 byte[] bytes = memory.ToArray();
137 fs.Write(bytes, 0, bytes.Length);
144 private void CheckForRequestResults()
146 if (iDisplay.IsRequestPending())
148 switch (iDisplay.AttemptRequestCompletion())
150 case Display.TMiniDisplayRequest.EMiniDisplayRequestFirmwareRevision:
151 toolStripStatusLabelConnect.Text += " v" + iDisplay.FirmwareRevision();
152 //Issue next request then
153 iDisplay.RequestPowerSupplyStatus();
156 case Display.TMiniDisplayRequest.EMiniDisplayRequestPowerSupplyStatus:
157 if (iDisplay.PowerSupplyStatus())
159 toolStripStatusLabelPower.Text = "ON";
163 toolStripStatusLabelPower.Text = "OFF";
165 //Issue next request then
166 iDisplay.RequestDeviceId();
169 case Display.TMiniDisplayRequest.EMiniDisplayRequestDeviceId:
170 toolStripStatusLabelConnect.Text += " - " + iDisplay.DeviceId();
171 //No more request to issue
178 public delegate int CoordinateTranslationDelegate(System.Drawing.Bitmap aBmp, int aInt);
181 public static int ScreenReversedX(System.Drawing.Bitmap aBmp, int aX)
183 return aBmp.Width - aX - 1;
186 public int ScreenReversedY(System.Drawing.Bitmap aBmp, int aY)
188 return iBmp.Height - aY - 1;
191 public int ScreenX(System.Drawing.Bitmap aBmp, int aX)
196 public int ScreenY(System.Drawing.Bitmap aBmp, int aY)
202 //This is our timer tick responsible to perform our render
203 private void timer_Tick(object sender, EventArgs e)
205 //Update our animations
206 DateTime NewTickTime = DateTime.Now;
208 marqueeLabelTop.UpdateAnimation(LastTickTime, NewTickTime);
209 marqueeLabelBottom.UpdateAnimation(LastTickTime, NewTickTime);
212 if (iDisplay.IsOpen())
214 CheckForRequestResults();
219 iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
221 tableLayoutPanel.DrawToBitmap(iBmp, tableLayoutPanel.ClientRectangle);
222 //iBmp.Save("D:\\capture.png");
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;
229 if (cds.ReverseScreen)
231 screenX = ScreenReversedX;
232 screenY = ScreenReversedY;
240 //Send it to our display
241 for (int i = 0; i < iBmp.Width; i++)
243 for (int j = 0; j < iBmp.Height; j++)
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)));
255 iDisplay.SwapBuffers();
259 //Compute instant FPS
260 toolStripStatusLabelFps.Text = (1.0/NewTickTime.Subtract(LastTickTime).TotalSeconds).ToString("F0") + " / " + (1000/timer.Interval).ToString() + " FPS";
262 LastTickTime = NewTickTime;
266 private void OpenDisplayConnection()
268 CloseDisplayConnection();
270 if (iDisplay.Open((Display.TMiniDisplayType)cds.DisplayType))
273 iDisplay.RequestFirmwareRevision();
278 toolStripStatusLabelConnect.Text = "Connection error";
282 private void CloseDisplayConnection()
288 private void buttonOpen_Click(object sender, EventArgs e)
290 OpenDisplayConnection();
293 private void buttonClose_Click(object sender, EventArgs e)
295 CloseDisplayConnection();
298 private void buttonClear_Click(object sender, EventArgs e)
301 iDisplay.SwapBuffers();
304 private void buttonFill_Click(object sender, EventArgs e)
307 iDisplay.SwapBuffers();
310 private void trackBarBrightness_Scroll(object sender, EventArgs e)
312 cds.Brightness = trackBarBrightness.Value;
313 Properties.Settings.Default.Save();
314 iDisplay.SetBrightness(trackBarBrightness.Value);
320 /// CDS stands for Current Display Settings
322 private DisplaySettings cds
326 DisplaysSettings settings = Properties.Settings.Default.DisplaySettings;
327 if (settings == null)
329 settings = new DisplaysSettings();
331 Properties.Settings.Default.DisplaySettings = settings;
334 //Make sure all our settings have been created
335 while (settings.Displays.Count <= Properties.Settings.Default.CurrentDisplayIndex)
337 settings.Displays.Add(new DisplaySettings());
340 DisplaySettings displaySettings = settings.Displays[Properties.Settings.Default.CurrentDisplayIndex];
341 return displaySettings;
345 private void UpdateStatus()
347 //Synchronize UI with 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();
359 if (iDisplay.IsOpen())
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);
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();
377 if (iDisplay.SupportPowerOnOff())
379 buttonPowerOn.Enabled = true;
380 buttonPowerOff.Enabled = true;
384 buttonPowerOn.Enabled = false;
385 buttonPowerOff.Enabled = false;
388 if (iDisplay.SupportClock())
390 buttonShowClock.Enabled = true;
391 buttonHideClock.Enabled = true;
395 buttonShowClock.Enabled = false;
396 buttonHideClock.Enabled = false;
401 buttonFill.Enabled = false;
402 buttonClear.Enabled = false;
403 buttonOpen.Enabled = true;
404 buttonClose.Enabled = false;
405 trackBarBrightness.Enabled = false;
406 buttonPowerOn.Enabled = false;
407 buttonPowerOff.Enabled = false;
408 buttonShowClock.Enabled = false;
409 buttonHideClock.Enabled = false;
410 toolStripStatusLabelConnect.Text = "Disconnected";
411 toolStripStatusLabelPower.Text = "N/A";
417 private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
419 //Save our show borders setting
420 tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
421 cds.ShowBorders = checkBoxShowBorders.Checked;
422 Properties.Settings.Default.Save();
425 private void checkBoxConnectOnStartup_CheckedChanged(object sender, EventArgs e)
427 //Save our connect on startup setting
428 Properties.Settings.Default.DisplayConnectOnStartup = checkBoxConnectOnStartup.Checked;
429 Properties.Settings.Default.Save();
432 private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
434 //Save our reverse screen setting
435 cds.ReverseScreen = checkBoxReverseScreen.Checked;
436 Properties.Settings.Default.Save();
439 private void MainForm_Resize(object sender, EventArgs e)
441 if (WindowState == FormWindowState.Minimized)
444 //iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
445 iCreateBitmap = true;
449 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
455 public void StartServer()
457 iServiceHost = new ServiceHost
459 typeof(DisplayServer),
460 new Uri[] { new Uri("net.tcp://localhost:8001/") }
463 iServiceHost.AddServiceEndpoint(typeof(IDisplayService), new NetTcpBinding(SecurityMode.None,true), "DisplayService");
467 public void StopServer()
469 if (iClients.Count > 0 && !iClosing)
473 BroadcastCloseEvent();
477 if (MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
479 iClosing = false; //We make sure we force close if asked twice
484 //We removed that as it often lags for some reason
485 //iServiceHost.Close();
489 public void BroadcastCloseEvent()
491 Trace.TraceInformation("BroadcastCloseEvent - start");
493 var inactiveClients = new List<string>();
494 foreach (var client in iClients)
496 //if (client.Key != eventData.ClientName)
500 Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
501 client.Value.Callback.OnCloseOrder(/*eventData*/);
505 inactiveClients.Add(client.Key);
510 if (inactiveClients.Count > 0)
512 foreach (var client in inactiveClients)
514 iClients.Remove(client);
515 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(client, false)[0]);
520 private void buttonStartClient_Click(object sender, EventArgs e)
522 Thread clientThread = new Thread(SharpDisplayClient.Program.Main);
523 clientThread.Start();
527 private void buttonSuspend_Click(object sender, EventArgs e)
529 LastTickTime = DateTime.Now; //Reset timer to prevent jump
530 timer.Enabled = !timer.Enabled;
533 buttonSuspend.Text = "Run";
537 buttonSuspend.Text = "Pause";
541 private void buttonCloseClients_Click(object sender, EventArgs e)
543 BroadcastCloseEvent();
546 private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
551 //Delegates are used for our thread safe method
552 public delegate void AddClientDelegate(string aSessionId, IDisplayServiceCallback aCallback);
553 public delegate void RemoveClientDelegate(string aSessionId);
554 public delegate void SetTextDelegate(string SessionId, TextField aTextField);
555 public delegate void SetTextsDelegate(string SessionId, System.Collections.Generic.IList<TextField> aTextFields);
556 public delegate void SetClientNameDelegate(string aSessionId, string aName);
562 /// <param name="aSessionId"></param>
563 /// <param name="aCallback"></param>
564 public void AddClientThreadSafe(string aSessionId, IDisplayServiceCallback aCallback)
566 if (this.InvokeRequired)
568 //Not in the proper thread, invoke ourselves
569 AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
570 this.Invoke(d, new object[] { aSessionId, aCallback });
574 //We are in the proper thread
575 //Add this session to our collection of clients
576 ClientData newClient = new ClientData(aSessionId, aCallback);
577 Program.iMainForm.iClients.Add(aSessionId, newClient);
578 //Add this session to our UI
579 UpdateClientTreeViewNode(newClient);
586 /// <param name="aSessionId"></param>
587 public void RemoveClientThreadSafe(string aSessionId)
589 if (this.InvokeRequired)
591 //Not in the proper thread, invoke ourselves
592 RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
593 this.Invoke(d, new object[] { aSessionId });
597 //We are in the proper thread
598 //Remove this session from both client collection and UI tree view
599 if (Program.iMainForm.iClients.Keys.Contains(aSessionId))
601 Program.iMainForm.iClients.Remove(aSessionId);
602 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(aSessionId, false)[0]);
605 if (iClosing && iClients.Count == 0)
607 //We were closing our form
608 //All clients are now closed
609 //Just resume our close operation
619 /// <param name="aLineIndex"></param>
620 /// <param name="aText"></param>
621 public void SetTextThreadSafe(string aSessionId, TextField aTextField)
623 if (this.InvokeRequired)
625 //Not in the proper thread, invoke ourselves
626 SetTextDelegate d = new SetTextDelegate(SetTextThreadSafe);
627 this.Invoke(d, new object[] { aSessionId, aTextField });
631 ClientData client = iClients[aSessionId];
634 //Make sure all our texts are in place
635 while (client.Texts.Count < (aTextField.Index + 1))
637 //Add a text field with proper index
638 client.Texts.Add(new TextField(client.Texts.Count));
640 client.Texts[aTextField.Index] = aTextField;
642 //We are in the proper thread
643 //Only support two lines for now
644 if (aTextField.Index == 0)
646 marqueeLabelTop.Text = aTextField.Text;
647 marqueeLabelTop.TextAlign = aTextField.Alignment;
649 else if (aTextField.Index == 1)
651 marqueeLabelBottom.Text = aTextField.Text;
652 marqueeLabelBottom.TextAlign = aTextField.Alignment;
656 UpdateClientTreeViewNode(client);
664 /// <param name="aTexts"></param>
665 public void SetTextsThreadSafe(string aSessionId, System.Collections.Generic.IList<TextField> aTextFields)
667 if (this.InvokeRequired)
669 //Not in the proper thread, invoke ourselves
670 SetTextsDelegate d = new SetTextsDelegate(SetTextsThreadSafe);
671 this.Invoke(d, new object[] { aSessionId, aTextFields });
675 //We are in the proper thread
676 ClientData client = iClients[aSessionId];
679 //Populate our client with the given text fields
681 foreach (TextField textField in aTextFields)
683 if (client.Texts.Count < (j + 1))
685 client.Texts.Add(textField);
689 client.Texts[j] = textField;
693 //Only support two lines for now
694 for (int i = 0; i < aTextFields.Count; i++)
696 if (aTextFields[i].Index == 0)
698 marqueeLabelTop.Text = aTextFields[i].Text;
699 marqueeLabelTop.TextAlign = aTextFields[i].Alignment;
701 else if (aTextFields[i].Index == 1)
703 marqueeLabelBottom.Text = aTextFields[i].Text;
704 marqueeLabelBottom.TextAlign = aTextFields[i].Alignment;
709 UpdateClientTreeViewNode(client);
718 /// <param name="aSessionId"></param>
719 /// <param name="aName"></param>
720 public void SetClientNameThreadSafe(string aSessionId, string aName)
722 if (this.InvokeRequired)
724 //Not in the proper thread, invoke ourselves
725 SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
726 this.Invoke(d, new object[] { aSessionId, aName });
730 //We are in the proper thread
732 ClientData client = iClients[aSessionId];
737 //Update our tree-view
738 UpdateClientTreeViewNode(client);
746 /// <param name="aClient"></param>
747 private void UpdateClientTreeViewNode(ClientData aClient)
754 TreeNode node = null;
755 //Check that our client node already exists
756 //Get our client root node using its key which is our session ID
757 TreeNode[] nodes = treeViewClients.Nodes.Find(aClient.SessionId, false);
760 //We already have a node for that client
762 //Clear children as we are going to recreate them below
767 //Client node does not exists create a new one
768 treeViewClients.Nodes.Add(aClient.SessionId, aClient.SessionId);
769 node = treeViewClients.Nodes.Find(aClient.SessionId, false)[0];
775 if (aClient.Name != "")
777 //We have a name, us it as text for our root node
778 node.Text = aClient.Name;
779 //Add a child with SessionId
780 node.Nodes.Add(new TreeNode(aClient.SessionId));
784 //No name, use session ID instead
785 node.Text = aClient.SessionId;
788 if (aClient.Texts.Count > 0)
790 //Create root node for our texts
791 TreeNode textsRoot = new TreeNode("Text");
792 node.Nodes.Add(textsRoot);
793 //For each text add a new entry
794 foreach (TextField field in aClient.Texts)
796 textsRoot.Nodes.Add(new TreeNode(field.Text));
804 private void buttonAddRow_Click(object sender, EventArgs e)
806 if (tableLayoutPanel.RowCount < 6)
808 tableLayoutPanel.RowCount++;
813 private void buttonRemoveRow_Click(object sender, EventArgs e)
815 if (tableLayoutPanel.RowCount > 1)
817 tableLayoutPanel.RowCount--;
822 private void buttonAddColumn_Click(object sender, EventArgs e)
824 if (tableLayoutPanel.ColumnCount < 8)
826 tableLayoutPanel.ColumnCount++;
831 private void buttonRemoveColumn_Click(object sender, EventArgs e)
833 if (tableLayoutPanel.ColumnCount > 1)
835 tableLayoutPanel.ColumnCount--;
840 private void buttonAlignLeft_Click(object sender, EventArgs e)
842 marqueeLabelTop.TextAlign = ContentAlignment.MiddleLeft;
843 marqueeLabelBottom.TextAlign = ContentAlignment.MiddleLeft;
846 private void buttonAlignCenter_Click(object sender, EventArgs e)
848 marqueeLabelTop.TextAlign = ContentAlignment.MiddleCenter;
849 marqueeLabelBottom.TextAlign = ContentAlignment.MiddleCenter;
852 private void buttonAlignRight_Click(object sender, EventArgs e)
854 marqueeLabelTop.TextAlign = ContentAlignment.MiddleRight;
855 marqueeLabelBottom.TextAlign = ContentAlignment.MiddleRight;
858 private void comboBoxDisplayType_SelectedIndexChanged(object sender, EventArgs e)
860 Properties.Settings.Default.CurrentDisplayIndex = comboBoxDisplayType.SelectedIndex;
861 cds.DisplayType = comboBoxDisplayType.SelectedIndex;
862 Properties.Settings.Default.Save();
863 if (iDisplay.IsOpen())
865 OpenDisplayConnection();
874 private void maskedTextBoxTimerInterval_TextChanged(object sender, EventArgs e)
876 if (maskedTextBoxTimerInterval.Text != "")
878 int interval = Convert.ToInt32(maskedTextBoxTimerInterval.Text);
882 timer.Interval = interval;
883 cds.TimerInterval = timer.Interval;
884 Properties.Settings.Default.Save();
889 private void buttonPowerOn_Click(object sender, EventArgs e)
894 private void buttonPowerOff_Click(object sender, EventArgs e)
899 private void buttonShowClock_Click(object sender, EventArgs e)
901 iDisplay.ShowClock();
904 private void buttonHideClock_Click(object sender, EventArgs e)
906 iDisplay.HideClock();
912 /// A UI thread copy of a client relevant data.
913 /// Keeping this copy in the UI thread helps us deal with threading issues.
915 public class ClientData
917 public ClientData(string aSessionId, IDisplayServiceCallback aCallback)
919 SessionId = aSessionId;
921 Texts = new List<TextField>();
922 Callback = aCallback;
925 public string SessionId { get; set; }
926 public string Name { get; set; }
927 public List<TextField> Texts { get; set; }
928 public IDisplayServiceCallback Callback { get; set; }