Renaming stuff.
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 SharpDisplayClient;
20 namespace SharpDisplayManager
22 public partial class MainForm : Form
24 DateTime LastTickTime;
26 System.Drawing.Bitmap iBmp;
27 bool iCreateBitmap; //Workaround render to bitmap issues when minimized
28 ServiceHost iServiceHost;
30 /// Our collection of clients
32 public Dictionary<string, ClientData> iClients;
37 LastTickTime = DateTime.Now;
38 iDisplay = new Display();
39 iClients = new Dictionary<string, ClientData>();
41 InitializeComponent();
43 //We have a bug when drawing minimized and reusing our bitmap
44 iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
45 iCreateBitmap = false;
48 private void MainForm_Load(object sender, EventArgs e)
52 if (Properties.Settings.Default.DisplayConnectOnStartup)
54 OpenDisplayConnection();
59 private void buttonFont_Click(object sender, EventArgs e)
61 //fontDialog.ShowColor = true;
62 //fontDialog.ShowApply = true;
63 fontDialog.ShowEffects = true;
64 fontDialog.Font = marqueeLabelTop.Font;
66 fontDialog.FixedPitchOnly = checkBoxFixedPitchFontOnly.Checked;
68 //fontDialog.ShowHelp = true;
70 //fontDlg.MaxSize = 40;
71 //fontDlg.MinSize = 22;
73 //fontDialog.Parent = this;
74 //fontDialog.StartPosition = FormStartPosition.CenterParent;
76 //DlgBox.ShowDialog(fontDialog);
78 //if (fontDialog.ShowDialog(this) != DialogResult.Cancel)
79 if (DlgBox.ShowDialog(fontDialog) != DialogResult.Cancel)
82 //MsgBox.Show("MessageBox MsgBox", "MsgBox caption");
84 //MessageBox.Show("Ok");
85 marqueeLabelTop.Font = fontDialog.Font;
86 marqueeLabelBottom.Font = fontDialog.Font;
87 cds.Font = fontDialog.Font;
88 Properties.Settings.Default.Save();
97 void CheckFontHeight()
99 //Show font height and width
100 labelFontHeight.Text = "Font height: " + cds.Font.Height;
101 float charWidth = IsFixedWidth(cds.Font);
102 if (charWidth == 0.0f)
104 labelFontWidth.Visible = false;
108 labelFontWidth.Visible = true;
109 labelFontWidth.Text = "Font width: " + charWidth;
112 //Now check font height and show a warning if needed.
113 if (marqueeLabelBottom.Font.Height > marqueeLabelBottom.Height)
115 labelWarning.Text = "WARNING: Selected font is too height by " + (marqueeLabelBottom.Font.Height - marqueeLabelBottom.Height) + " pixels!";
116 labelWarning.Visible = true;
120 labelWarning.Visible = false;
125 private void buttonCapture_Click(object sender, EventArgs e)
127 System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height);
128 tableLayoutPanel.DrawToBitmap(bmp, tableLayoutPanel.ClientRectangle);
129 //Bitmap bmpToSave = new Bitmap(bmp);
130 bmp.Save("D:\\capture.png");
132 marqueeLabelTop.Text = "Sweet";
135 string outputFileName = "d:\\capture.png";
136 using (MemoryStream memory = new MemoryStream())
138 using (FileStream fs = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
140 bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
141 byte[] bytes = memory.ToArray();
142 fs.Write(bytes, 0, bytes.Length);
149 private void CheckForRequestResults()
151 if (iDisplay.IsRequestPending())
153 switch (iDisplay.AttemptRequestCompletion())
155 case Display.TMiniDisplayRequest.EMiniDisplayRequestFirmwareRevision:
156 toolStripStatusLabelConnect.Text += " v" + iDisplay.FirmwareRevision();
157 //Issue next request then
158 iDisplay.RequestPowerSupplyStatus();
161 case Display.TMiniDisplayRequest.EMiniDisplayRequestPowerSupplyStatus:
162 if (iDisplay.PowerSupplyStatus())
164 toolStripStatusLabelPower.Text = "ON";
168 toolStripStatusLabelPower.Text = "OFF";
170 //Issue next request then
171 iDisplay.RequestDeviceId();
174 case Display.TMiniDisplayRequest.EMiniDisplayRequestDeviceId:
175 toolStripStatusLabelConnect.Text += " - " + iDisplay.DeviceId();
176 //No more request to issue
183 public delegate int CoordinateTranslationDelegate(System.Drawing.Bitmap aBmp, int aInt);
186 public static int ScreenReversedX(System.Drawing.Bitmap aBmp, int aX)
188 return aBmp.Width - aX - 1;
191 public int ScreenReversedY(System.Drawing.Bitmap aBmp, int aY)
193 return iBmp.Height - aY - 1;
196 public int ScreenX(System.Drawing.Bitmap aBmp, int aX)
201 public int ScreenY(System.Drawing.Bitmap aBmp, int aY)
207 //This is our timer tick responsible to perform our render
208 private void timer_Tick(object sender, EventArgs e)
210 //Update our animations
211 DateTime NewTickTime = DateTime.Now;
213 marqueeLabelTop.UpdateAnimation(LastTickTime, NewTickTime);
214 marqueeLabelBottom.UpdateAnimation(LastTickTime, NewTickTime);
217 if (iDisplay.IsOpen())
219 CheckForRequestResults();
224 iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
226 tableLayoutPanel.DrawToBitmap(iBmp, tableLayoutPanel.ClientRectangle);
227 //iBmp.Save("D:\\capture.png");
229 //Select proper coordinate translation functions
230 //We used delegate/function pointer to support reverse screen without doing an extra test on each pixels
231 CoordinateTranslationDelegate screenX;
232 CoordinateTranslationDelegate screenY;
234 if (cds.ReverseScreen)
236 screenX = ScreenReversedX;
237 screenY = ScreenReversedY;
245 //Send it to our display
246 for (int i = 0; i < iBmp.Width; i++)
248 for (int j = 0; j < iBmp.Height; j++)
252 uint color = (uint)iBmp.GetPixel(i, j).ToArgb();
253 //For some reason when the app is minimized in the task bar only the alpha of our color is set.
254 //Thus that strange test for rendering to work both when the app is in the task bar and when it isn't.
255 iDisplay.SetPixel(screenX(iBmp, i), screenY(iBmp, j), Convert.ToInt32(!(color != 0xFF000000)));
260 iDisplay.SwapBuffers();
264 //Compute instant FPS
265 toolStripStatusLabelFps.Text = (1.0/NewTickTime.Subtract(LastTickTime).TotalSeconds).ToString("F0") + " / " + (1000/timer.Interval).ToString() + " FPS";
267 LastTickTime = NewTickTime;
271 private void OpenDisplayConnection()
273 CloseDisplayConnection();
275 if (iDisplay.Open((Display.TMiniDisplayType)cds.DisplayType))
278 iDisplay.RequestFirmwareRevision();
283 toolStripStatusLabelConnect.Text = "Connection error";
287 private void CloseDisplayConnection()
293 private void buttonOpen_Click(object sender, EventArgs e)
295 OpenDisplayConnection();
298 private void buttonClose_Click(object sender, EventArgs e)
300 CloseDisplayConnection();
303 private void buttonClear_Click(object sender, EventArgs e)
306 iDisplay.SwapBuffers();
309 private void buttonFill_Click(object sender, EventArgs e)
312 iDisplay.SwapBuffers();
315 private void trackBarBrightness_Scroll(object sender, EventArgs e)
317 cds.Brightness = trackBarBrightness.Value;
318 Properties.Settings.Default.Save();
319 iDisplay.SetBrightness(trackBarBrightness.Value);
325 /// CDS stands for Current Display Settings
327 private DisplaySettings cds
331 DisplaysSettings settings = Properties.Settings.Default.DisplaySettings;
332 if (settings == null)
334 settings = new DisplaysSettings();
336 Properties.Settings.Default.DisplaySettings = settings;
339 //Make sure all our settings have been created
340 while (settings.Displays.Count <= Properties.Settings.Default.CurrentDisplayIndex)
342 settings.Displays.Add(new DisplaySettings());
345 DisplaySettings displaySettings = settings.Displays[Properties.Settings.Default.CurrentDisplayIndex];
346 return displaySettings;
351 /// Check if the given font has a fixed character pitch.
353 /// <param name="ft"></param>
354 /// <returns>0.0f if this is not a monospace font, otherwise returns the character width.</returns>
355 public float IsFixedWidth(Font ft)
357 Graphics g = CreateGraphics();
358 char[] charSizes = new char[] { 'i', 'a', 'Z', '%', '#', 'a', 'B', 'l', 'm', ',', '.' };
359 float charWidth = g.MeasureString("I", ft, Int32.MaxValue, StringFormat.GenericTypographic).Width;
361 bool fixedWidth = true;
363 foreach (char c in charSizes)
364 if (g.MeasureString(c.ToString(), ft, Int32.MaxValue, StringFormat.GenericTypographic).Width != charWidth)
375 private void UpdateStatus()
377 //Synchronize UI with settings
380 checkBoxShowBorders.Checked = cds.ShowBorders;
381 tableLayoutPanel.CellBorderStyle = (cds.ShowBorders ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
382 marqueeLabelTop.Font = cds.Font;
383 marqueeLabelBottom.Font = cds.Font;
385 checkBoxConnectOnStartup.Checked = Properties.Settings.Default.DisplayConnectOnStartup;
386 checkBoxReverseScreen.Checked = cds.ReverseScreen;
387 comboBoxDisplayType.SelectedIndex = cds.DisplayType;
388 timer.Interval = cds.TimerInterval;
389 maskedTextBoxTimerInterval.Text = cds.TimerInterval.ToString();
392 if (iDisplay.IsOpen())
394 //Only setup brightness if display is open
395 trackBarBrightness.Minimum = iDisplay.MinBrightness();
396 trackBarBrightness.Maximum = iDisplay.MaxBrightness();
397 trackBarBrightness.Value = cds.Brightness;
398 trackBarBrightness.LargeChange = Math.Max(1, (iDisplay.MaxBrightness() - iDisplay.MinBrightness()) / 5);
399 trackBarBrightness.SmallChange = 1;
400 iDisplay.SetBrightness(cds.Brightness);
402 buttonFill.Enabled = true;
403 buttonClear.Enabled = true;
404 buttonOpen.Enabled = false;
405 buttonClose.Enabled = true;
406 trackBarBrightness.Enabled = true;
407 toolStripStatusLabelConnect.Text = "Connected - " + iDisplay.Vendor() + " - " + iDisplay.Product();
408 //+ " - " + iDisplay.SerialNumber();
410 if (iDisplay.SupportPowerOnOff())
412 buttonPowerOn.Enabled = true;
413 buttonPowerOff.Enabled = true;
417 buttonPowerOn.Enabled = false;
418 buttonPowerOff.Enabled = false;
421 if (iDisplay.SupportClock())
423 buttonShowClock.Enabled = true;
424 buttonHideClock.Enabled = true;
428 buttonShowClock.Enabled = false;
429 buttonHideClock.Enabled = false;
434 buttonFill.Enabled = false;
435 buttonClear.Enabled = false;
436 buttonOpen.Enabled = true;
437 buttonClose.Enabled = false;
438 trackBarBrightness.Enabled = false;
439 buttonPowerOn.Enabled = false;
440 buttonPowerOff.Enabled = false;
441 buttonShowClock.Enabled = false;
442 buttonHideClock.Enabled = false;
443 toolStripStatusLabelConnect.Text = "Disconnected";
444 toolStripStatusLabelPower.Text = "N/A";
450 private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
452 //Save our show borders setting
453 tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
454 cds.ShowBorders = checkBoxShowBorders.Checked;
455 Properties.Settings.Default.Save();
458 private void checkBoxConnectOnStartup_CheckedChanged(object sender, EventArgs e)
460 //Save our connect on startup setting
461 Properties.Settings.Default.DisplayConnectOnStartup = checkBoxConnectOnStartup.Checked;
462 Properties.Settings.Default.Save();
465 private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
467 //Save our reverse screen setting
468 cds.ReverseScreen = checkBoxReverseScreen.Checked;
469 Properties.Settings.Default.Save();
472 private void MainForm_Resize(object sender, EventArgs e)
474 if (WindowState == FormWindowState.Minimized)
477 //iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
478 iCreateBitmap = true;
482 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
488 public void StartServer()
490 iServiceHost = new ServiceHost
493 new Uri[] { new Uri("net.tcp://localhost:8001/") }
496 iServiceHost.AddServiceEndpoint(typeof(IService), new NetTcpBinding(SecurityMode.None, true), "DisplayService");
500 public void StopServer()
502 if (iClients.Count > 0 && !iClosing)
506 BroadcastCloseEvent();
510 if (MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
512 iClosing = false; //We make sure we force close if asked twice
517 //We removed that as it often lags for some reason
518 //iServiceHost.Close();
522 public void BroadcastCloseEvent()
524 Trace.TraceInformation("BroadcastCloseEvent - start");
526 var inactiveClients = new List<string>();
527 foreach (var client in iClients)
529 //if (client.Key != eventData.ClientName)
533 Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
534 client.Value.Callback.OnCloseOrder(/*eventData*/);
538 inactiveClients.Add(client.Key);
543 if (inactiveClients.Count > 0)
545 foreach (var client in inactiveClients)
547 iClients.Remove(client);
548 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(client, false)[0]);
553 private void buttonStartClient_Click(object sender, EventArgs e)
555 Thread clientThread = new Thread(SharpDisplayClient.Program.Main);
556 clientThread.Start();
560 private void buttonSuspend_Click(object sender, EventArgs e)
562 LastTickTime = DateTime.Now; //Reset timer to prevent jump
563 timer.Enabled = !timer.Enabled;
566 buttonSuspend.Text = "Run";
570 buttonSuspend.Text = "Pause";
574 private void buttonCloseClients_Click(object sender, EventArgs e)
576 BroadcastCloseEvent();
579 private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
584 //Delegates are used for our thread safe method
585 public delegate void AddClientDelegate(string aSessionId, ICallback aCallback);
586 public delegate void RemoveClientDelegate(string aSessionId);
587 public delegate void SetTextDelegate(string SessionId, TextField aTextField);
588 public delegate void SetTextsDelegate(string SessionId, System.Collections.Generic.IList<TextField> aTextFields);
589 public delegate void SetClientNameDelegate(string aSessionId, string aName);
595 /// <param name="aSessionId"></param>
596 /// <param name="aCallback"></param>
597 public void AddClientThreadSafe(string aSessionId, ICallback aCallback)
599 if (this.InvokeRequired)
601 //Not in the proper thread, invoke ourselves
602 AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
603 this.Invoke(d, new object[] { aSessionId, aCallback });
607 //We are in the proper thread
608 //Add this session to our collection of clients
609 ClientData newClient = new ClientData(aSessionId, aCallback);
610 Program.iMainForm.iClients.Add(aSessionId, newClient);
611 //Add this session to our UI
612 UpdateClientTreeViewNode(newClient);
619 /// <param name="aSessionId"></param>
620 public void RemoveClientThreadSafe(string aSessionId)
622 if (this.InvokeRequired)
624 //Not in the proper thread, invoke ourselves
625 RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
626 this.Invoke(d, new object[] { aSessionId });
630 //We are in the proper thread
631 //Remove this session from both client collection and UI tree view
632 if (Program.iMainForm.iClients.Keys.Contains(aSessionId))
634 Program.iMainForm.iClients.Remove(aSessionId);
635 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(aSessionId, false)[0]);
638 if (iClosing && iClients.Count == 0)
640 //We were closing our form
641 //All clients are now closed
642 //Just resume our close operation
652 /// <param name="aLineIndex"></param>
653 /// <param name="aText"></param>
654 public void SetTextThreadSafe(string aSessionId, TextField aTextField)
656 if (this.InvokeRequired)
658 //Not in the proper thread, invoke ourselves
659 SetTextDelegate d = new SetTextDelegate(SetTextThreadSafe);
660 this.Invoke(d, new object[] { aSessionId, aTextField });
664 ClientData client = iClients[aSessionId];
667 //Make sure all our texts are in place
668 while (client.Texts.Count < (aTextField.Index + 1))
670 //Add a text field with proper index
671 client.Texts.Add(new TextField(client.Texts.Count));
673 client.Texts[aTextField.Index] = aTextField;
675 //We are in the proper thread
676 //Only support two lines for now
677 if (aTextField.Index == 0)
679 marqueeLabelTop.Text = aTextField.Text;
680 marqueeLabelTop.TextAlign = aTextField.Alignment;
682 else if (aTextField.Index == 1)
684 marqueeLabelBottom.Text = aTextField.Text;
685 marqueeLabelBottom.TextAlign = aTextField.Alignment;
689 UpdateClientTreeViewNode(client);
697 /// <param name="aTexts"></param>
698 public void SetTextsThreadSafe(string aSessionId, System.Collections.Generic.IList<TextField> aTextFields)
700 if (this.InvokeRequired)
702 //Not in the proper thread, invoke ourselves
703 SetTextsDelegate d = new SetTextsDelegate(SetTextsThreadSafe);
704 this.Invoke(d, new object[] { aSessionId, aTextFields });
708 //We are in the proper thread
709 ClientData client = iClients[aSessionId];
712 //Populate our client with the given text fields
714 foreach (TextField textField in aTextFields)
716 if (client.Texts.Count < (j + 1))
718 client.Texts.Add(textField);
722 client.Texts[j] = textField;
726 //Only support two lines for now
727 for (int i = 0; i < aTextFields.Count; i++)
729 if (aTextFields[i].Index == 0)
731 marqueeLabelTop.Text = aTextFields[i].Text;
732 marqueeLabelTop.TextAlign = aTextFields[i].Alignment;
734 else if (aTextFields[i].Index == 1)
736 marqueeLabelBottom.Text = aTextFields[i].Text;
737 marqueeLabelBottom.TextAlign = aTextFields[i].Alignment;
742 UpdateClientTreeViewNode(client);
751 /// <param name="aSessionId"></param>
752 /// <param name="aName"></param>
753 public void SetClientNameThreadSafe(string aSessionId, string aName)
755 if (this.InvokeRequired)
757 //Not in the proper thread, invoke ourselves
758 SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
759 this.Invoke(d, new object[] { aSessionId, aName });
763 //We are in the proper thread
765 ClientData client = iClients[aSessionId];
770 //Update our tree-view
771 UpdateClientTreeViewNode(client);
779 /// <param name="aClient"></param>
780 private void UpdateClientTreeViewNode(ClientData aClient)
787 TreeNode node = null;
788 //Check that our client node already exists
789 //Get our client root node using its key which is our session ID
790 TreeNode[] nodes = treeViewClients.Nodes.Find(aClient.SessionId, false);
793 //We already have a node for that client
795 //Clear children as we are going to recreate them below
800 //Client node does not exists create a new one
801 treeViewClients.Nodes.Add(aClient.SessionId, aClient.SessionId);
802 node = treeViewClients.Nodes.Find(aClient.SessionId, false)[0];
808 if (aClient.Name != "")
810 //We have a name, us it as text for our root node
811 node.Text = aClient.Name;
812 //Add a child with SessionId
813 node.Nodes.Add(new TreeNode(aClient.SessionId));
817 //No name, use session ID instead
818 node.Text = aClient.SessionId;
821 if (aClient.Texts.Count > 0)
823 //Create root node for our texts
824 TreeNode textsRoot = new TreeNode("Text");
825 node.Nodes.Add(textsRoot);
826 //For each text add a new entry
827 foreach (TextField field in aClient.Texts)
829 textsRoot.Nodes.Add(new TreeNode(field.Text));
837 private void buttonAddRow_Click(object sender, EventArgs e)
839 if (tableLayoutPanel.RowCount < 6)
841 tableLayoutPanel.RowCount++;
846 private void buttonRemoveRow_Click(object sender, EventArgs e)
848 if (tableLayoutPanel.RowCount > 1)
850 tableLayoutPanel.RowCount--;
855 private void buttonAddColumn_Click(object sender, EventArgs e)
857 if (tableLayoutPanel.ColumnCount < 8)
859 tableLayoutPanel.ColumnCount++;
864 private void buttonRemoveColumn_Click(object sender, EventArgs e)
866 if (tableLayoutPanel.ColumnCount > 1)
868 tableLayoutPanel.ColumnCount--;
873 private void buttonAlignLeft_Click(object sender, EventArgs e)
875 marqueeLabelTop.TextAlign = ContentAlignment.MiddleLeft;
876 marqueeLabelBottom.TextAlign = ContentAlignment.MiddleLeft;
879 private void buttonAlignCenter_Click(object sender, EventArgs e)
881 marqueeLabelTop.TextAlign = ContentAlignment.MiddleCenter;
882 marqueeLabelBottom.TextAlign = ContentAlignment.MiddleCenter;
885 private void buttonAlignRight_Click(object sender, EventArgs e)
887 marqueeLabelTop.TextAlign = ContentAlignment.MiddleRight;
888 marqueeLabelBottom.TextAlign = ContentAlignment.MiddleRight;
891 private void comboBoxDisplayType_SelectedIndexChanged(object sender, EventArgs e)
893 Properties.Settings.Default.CurrentDisplayIndex = comboBoxDisplayType.SelectedIndex;
894 cds.DisplayType = comboBoxDisplayType.SelectedIndex;
895 Properties.Settings.Default.Save();
896 if (iDisplay.IsOpen())
898 OpenDisplayConnection();
907 private void maskedTextBoxTimerInterval_TextChanged(object sender, EventArgs e)
909 if (maskedTextBoxTimerInterval.Text != "")
911 int interval = Convert.ToInt32(maskedTextBoxTimerInterval.Text);
915 timer.Interval = interval;
916 cds.TimerInterval = timer.Interval;
917 Properties.Settings.Default.Save();
922 private void buttonPowerOn_Click(object sender, EventArgs e)
927 private void buttonPowerOff_Click(object sender, EventArgs e)
932 private void buttonShowClock_Click(object sender, EventArgs e)
934 iDisplay.ShowClock();
937 private void buttonHideClock_Click(object sender, EventArgs e)
939 iDisplay.HideClock();
945 /// A UI thread copy of a client relevant data.
946 /// Keeping this copy in the UI thread helps us deal with threading issues.
948 public class ClientData
950 public ClientData(string aSessionId, ICallback aCallback)
952 SessionId = aSessionId;
954 Texts = new List<TextField>();
955 Callback = aCallback;
958 public string SessionId { get; set; }
959 public string Name { get; set; }
960 public List<TextField> Texts { get; set; }
961 public ICallback Callback { get; set; }