Fixing issue with interval zero exception.
Adding support for GP1212A02 firmware revision display.
Fixing issue that would always auto connect on stratup.
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();
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";
391 private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
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();
399 private void checkBoxConnectOnStartup_CheckedChanged(object sender, EventArgs e)
401 //Save our connect on startup setting
402 Properties.Settings.Default.DisplayConnectOnStartup = checkBoxConnectOnStartup.Checked;
403 Properties.Settings.Default.Save();
406 private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
408 //Save our reverse screen setting
409 cds.ReverseScreen = checkBoxReverseScreen.Checked;
410 Properties.Settings.Default.Save();
413 private void MainForm_Resize(object sender, EventArgs e)
415 if (WindowState == FormWindowState.Minimized)
418 //iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
419 iCreateBitmap = true;
423 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
429 public void StartServer()
431 iServiceHost = new ServiceHost
433 typeof(DisplayServer),
434 new Uri[] { new Uri("net.tcp://localhost:8001/") }
437 iServiceHost.AddServiceEndpoint(typeof(IDisplayService), new NetTcpBinding(SecurityMode.None,true), "DisplayService");
441 public void StopServer()
443 if (iClients.Count > 0 && !iClosing)
447 BroadcastCloseEvent();
451 if (MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
453 iClosing = false; //We make sure we force close if asked twice
458 //We removed that as it often lags for some reason
459 //iServiceHost.Close();
463 public void BroadcastCloseEvent()
465 Trace.TraceInformation("BroadcastCloseEvent - start");
467 var inactiveClients = new List<string>();
468 foreach (var client in iClients)
470 //if (client.Key != eventData.ClientName)
474 Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
475 client.Value.Callback.OnCloseOrder(/*eventData*/);
479 inactiveClients.Add(client.Key);
484 if (inactiveClients.Count > 0)
486 foreach (var client in inactiveClients)
488 iClients.Remove(client);
489 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(client, false)[0]);
494 private void buttonStartClient_Click(object sender, EventArgs e)
496 Thread clientThread = new Thread(SharpDisplayClient.Program.Main);
497 clientThread.Start();
501 private void buttonSuspend_Click(object sender, EventArgs e)
503 timer.Enabled = !timer.Enabled;
506 buttonSuspend.Text = "Suspend";
510 buttonSuspend.Text = "Pause";
514 private void buttonCloseClients_Click(object sender, EventArgs e)
516 BroadcastCloseEvent();
519 private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
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);
535 /// <param name="aSessionId"></param>
536 /// <param name="aCallback"></param>
537 public void AddClientThreadSafe(string aSessionId, IDisplayServiceCallback aCallback)
539 if (this.InvokeRequired)
541 //Not in the proper thread, invoke ourselves
542 AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
543 this.Invoke(d, new object[] { aSessionId, aCallback });
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);
559 /// <param name="aSessionId"></param>
560 public void RemoveClientThreadSafe(string aSessionId)
562 if (this.InvokeRequired)
564 //Not in the proper thread, invoke ourselves
565 RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
566 this.Invoke(d, new object[] { aSessionId });
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))
574 Program.iMainForm.iClients.Remove(aSessionId);
575 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(aSessionId, false)[0]);
578 if (iClosing && iClients.Count == 0)
580 //We were closing our form
581 //All clients are now closed
582 //Just resume our close operation
592 /// <param name="aLineIndex"></param>
593 /// <param name="aText"></param>
594 public void SetTextThreadSafe(string aSessionId, TextField aTextField)
596 if (this.InvokeRequired)
598 //Not in the proper thread, invoke ourselves
599 SetTextDelegate d = new SetTextDelegate(SetTextThreadSafe);
600 this.Invoke(d, new object[] { aSessionId, aTextField });
604 ClientData client = iClients[aSessionId];
607 //Make sure all our texts are in place
608 while (client.Texts.Count < (aTextField.Index + 1))
610 //Add a text field with proper index
611 client.Texts.Add(new TextField(client.Texts.Count));
613 client.Texts[aTextField.Index] = aTextField;
615 //We are in the proper thread
616 //Only support two lines for now
617 if (aTextField.Index == 0)
619 marqueeLabelTop.Text = aTextField.Text;
620 marqueeLabelTop.TextAlign = aTextField.Alignment;
622 else if (aTextField.Index == 1)
624 marqueeLabelBottom.Text = aTextField.Text;
625 marqueeLabelBottom.TextAlign = aTextField.Alignment;
629 UpdateClientTreeViewNode(client);
637 /// <param name="aTexts"></param>
638 public void SetTextsThreadSafe(string aSessionId, System.Collections.Generic.IList<TextField> aTextFields)
640 if (this.InvokeRequired)
642 //Not in the proper thread, invoke ourselves
643 SetTextsDelegate d = new SetTextsDelegate(SetTextsThreadSafe);
644 this.Invoke(d, new object[] { aSessionId, aTextFields });
648 //We are in the proper thread
649 ClientData client = iClients[aSessionId];
652 //Populate our client with the given text fields
654 foreach (TextField textField in aTextFields)
656 if (client.Texts.Count < (j + 1))
658 client.Texts.Add(textField);
662 client.Texts[j] = textField;
666 //Only support two lines for now
667 for (int i = 0; i < aTextFields.Count; i++)
669 if (aTextFields[i].Index == 0)
671 marqueeLabelTop.Text = aTextFields[i].Text;
672 marqueeLabelTop.TextAlign = aTextFields[i].Alignment;
674 else if (aTextFields[i].Index == 1)
676 marqueeLabelBottom.Text = aTextFields[i].Text;
677 marqueeLabelBottom.TextAlign = aTextFields[i].Alignment;
682 UpdateClientTreeViewNode(client);
691 /// <param name="aSessionId"></param>
692 /// <param name="aName"></param>
693 public void SetClientNameThreadSafe(string aSessionId, string aName)
695 if (this.InvokeRequired)
697 //Not in the proper thread, invoke ourselves
698 SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
699 this.Invoke(d, new object[] { aSessionId, aName });
703 //We are in the proper thread
705 ClientData client = iClients[aSessionId];
710 //Update our tree-view
711 UpdateClientTreeViewNode(client);
719 /// <param name="aClient"></param>
720 private void UpdateClientTreeViewNode(ClientData aClient)
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);
733 //We already have a node for that client
735 //Clear children as we are going to recreate them below
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];
748 if (aClient.Name != "")
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));
757 //No name, use session ID instead
758 node.Text = aClient.SessionId;
761 if (aClient.Texts.Count > 0)
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)
769 textsRoot.Nodes.Add(new TreeNode(field.Text));
777 private void buttonAddRow_Click(object sender, EventArgs e)
779 if (tableLayoutPanel.RowCount < 6)
781 tableLayoutPanel.RowCount++;
786 private void buttonRemoveRow_Click(object sender, EventArgs e)
788 if (tableLayoutPanel.RowCount > 1)
790 tableLayoutPanel.RowCount--;
795 private void buttonAddColumn_Click(object sender, EventArgs e)
797 if (tableLayoutPanel.ColumnCount < 8)
799 tableLayoutPanel.ColumnCount++;
804 private void buttonRemoveColumn_Click(object sender, EventArgs e)
806 if (tableLayoutPanel.ColumnCount > 1)
808 tableLayoutPanel.ColumnCount--;
813 private void buttonAlignLeft_Click(object sender, EventArgs e)
815 marqueeLabelTop.TextAlign = ContentAlignment.MiddleLeft;
816 marqueeLabelBottom.TextAlign = ContentAlignment.MiddleLeft;
819 private void buttonAlignCenter_Click(object sender, EventArgs e)
821 marqueeLabelTop.TextAlign = ContentAlignment.MiddleCenter;
822 marqueeLabelBottom.TextAlign = ContentAlignment.MiddleCenter;
825 private void buttonAlignRight_Click(object sender, EventArgs e)
827 marqueeLabelTop.TextAlign = ContentAlignment.MiddleRight;
828 marqueeLabelBottom.TextAlign = ContentAlignment.MiddleRight;
831 private void comboBoxDisplayType_SelectedIndexChanged(object sender, EventArgs e)
833 Properties.Settings.Default.CurrentDisplayIndex = comboBoxDisplayType.SelectedIndex;
834 cds.DisplayType = comboBoxDisplayType.SelectedIndex;
835 Properties.Settings.Default.Save();
836 if (iDisplay.IsOpen())
838 OpenDisplayConnection();
847 private void maskedTextBoxTimerInterval_TextChanged(object sender, EventArgs e)
849 if (maskedTextBoxTimerInterval.Text != "")
851 int interval = Convert.ToInt32(maskedTextBoxTimerInterval.Text);
855 timer.Interval = interval;
856 cds.TimerInterval = timer.Interval;
857 Properties.Settings.Default.Save();
865 /// A UI thread copy of a client relevant data.
866 /// Keeping this copy in the UI thread helps us deal with threading issues.
868 public class ClientData
870 public ClientData(string aSessionId, IDisplayServiceCallback aCallback)
872 SessionId = aSessionId;
874 Texts = new List<TextField>();
875 Callback = aCallback;
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; }