Adding support for power on/off.
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;
390 buttonFill.Enabled = false;
391 buttonClear.Enabled = false;
392 buttonOpen.Enabled = true;
393 buttonClose.Enabled = false;
394 trackBarBrightness.Enabled = false;
395 buttonPowerOn.Enabled = false;
396 buttonPowerOff.Enabled = false;
397 toolStripStatusLabelConnect.Text = "Disconnected";
398 toolStripStatusLabelPower.Text = "N/A";
404 private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
406 //Save our show borders setting
407 tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
408 cds.ShowBorders = checkBoxShowBorders.Checked;
409 Properties.Settings.Default.Save();
412 private void checkBoxConnectOnStartup_CheckedChanged(object sender, EventArgs e)
414 //Save our connect on startup setting
415 Properties.Settings.Default.DisplayConnectOnStartup = checkBoxConnectOnStartup.Checked;
416 Properties.Settings.Default.Save();
419 private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
421 //Save our reverse screen setting
422 cds.ReverseScreen = checkBoxReverseScreen.Checked;
423 Properties.Settings.Default.Save();
426 private void MainForm_Resize(object sender, EventArgs e)
428 if (WindowState == FormWindowState.Minimized)
431 //iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
432 iCreateBitmap = true;
436 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
442 public void StartServer()
444 iServiceHost = new ServiceHost
446 typeof(DisplayServer),
447 new Uri[] { new Uri("net.tcp://localhost:8001/") }
450 iServiceHost.AddServiceEndpoint(typeof(IDisplayService), new NetTcpBinding(SecurityMode.None,true), "DisplayService");
454 public void StopServer()
456 if (iClients.Count > 0 && !iClosing)
460 BroadcastCloseEvent();
464 if (MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
466 iClosing = false; //We make sure we force close if asked twice
471 //We removed that as it often lags for some reason
472 //iServiceHost.Close();
476 public void BroadcastCloseEvent()
478 Trace.TraceInformation("BroadcastCloseEvent - start");
480 var inactiveClients = new List<string>();
481 foreach (var client in iClients)
483 //if (client.Key != eventData.ClientName)
487 Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
488 client.Value.Callback.OnCloseOrder(/*eventData*/);
492 inactiveClients.Add(client.Key);
497 if (inactiveClients.Count > 0)
499 foreach (var client in inactiveClients)
501 iClients.Remove(client);
502 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(client, false)[0]);
507 private void buttonStartClient_Click(object sender, EventArgs e)
509 Thread clientThread = new Thread(SharpDisplayClient.Program.Main);
510 clientThread.Start();
514 private void buttonSuspend_Click(object sender, EventArgs e)
516 LastTickTime = DateTime.Now; //Reset timer to prevent jump
517 timer.Enabled = !timer.Enabled;
520 buttonSuspend.Text = "Run";
524 buttonSuspend.Text = "Pause";
528 private void buttonCloseClients_Click(object sender, EventArgs e)
530 BroadcastCloseEvent();
533 private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
538 //Delegates are used for our thread safe method
539 public delegate void AddClientDelegate(string aSessionId, IDisplayServiceCallback aCallback);
540 public delegate void RemoveClientDelegate(string aSessionId);
541 public delegate void SetTextDelegate(string SessionId, TextField aTextField);
542 public delegate void SetTextsDelegate(string SessionId, System.Collections.Generic.IList<TextField> aTextFields);
543 public delegate void SetClientNameDelegate(string aSessionId, string aName);
549 /// <param name="aSessionId"></param>
550 /// <param name="aCallback"></param>
551 public void AddClientThreadSafe(string aSessionId, IDisplayServiceCallback aCallback)
553 if (this.InvokeRequired)
555 //Not in the proper thread, invoke ourselves
556 AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
557 this.Invoke(d, new object[] { aSessionId, aCallback });
561 //We are in the proper thread
562 //Add this session to our collection of clients
563 ClientData newClient = new ClientData(aSessionId, aCallback);
564 Program.iMainForm.iClients.Add(aSessionId, newClient);
565 //Add this session to our UI
566 UpdateClientTreeViewNode(newClient);
573 /// <param name="aSessionId"></param>
574 public void RemoveClientThreadSafe(string aSessionId)
576 if (this.InvokeRequired)
578 //Not in the proper thread, invoke ourselves
579 RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
580 this.Invoke(d, new object[] { aSessionId });
584 //We are in the proper thread
585 //Remove this session from both client collection and UI tree view
586 if (Program.iMainForm.iClients.Keys.Contains(aSessionId))
588 Program.iMainForm.iClients.Remove(aSessionId);
589 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(aSessionId, false)[0]);
592 if (iClosing && iClients.Count == 0)
594 //We were closing our form
595 //All clients are now closed
596 //Just resume our close operation
606 /// <param name="aLineIndex"></param>
607 /// <param name="aText"></param>
608 public void SetTextThreadSafe(string aSessionId, TextField aTextField)
610 if (this.InvokeRequired)
612 //Not in the proper thread, invoke ourselves
613 SetTextDelegate d = new SetTextDelegate(SetTextThreadSafe);
614 this.Invoke(d, new object[] { aSessionId, aTextField });
618 ClientData client = iClients[aSessionId];
621 //Make sure all our texts are in place
622 while (client.Texts.Count < (aTextField.Index + 1))
624 //Add a text field with proper index
625 client.Texts.Add(new TextField(client.Texts.Count));
627 client.Texts[aTextField.Index] = aTextField;
629 //We are in the proper thread
630 //Only support two lines for now
631 if (aTextField.Index == 0)
633 marqueeLabelTop.Text = aTextField.Text;
634 marqueeLabelTop.TextAlign = aTextField.Alignment;
636 else if (aTextField.Index == 1)
638 marqueeLabelBottom.Text = aTextField.Text;
639 marqueeLabelBottom.TextAlign = aTextField.Alignment;
643 UpdateClientTreeViewNode(client);
651 /// <param name="aTexts"></param>
652 public void SetTextsThreadSafe(string aSessionId, System.Collections.Generic.IList<TextField> aTextFields)
654 if (this.InvokeRequired)
656 //Not in the proper thread, invoke ourselves
657 SetTextsDelegate d = new SetTextsDelegate(SetTextsThreadSafe);
658 this.Invoke(d, new object[] { aSessionId, aTextFields });
662 //We are in the proper thread
663 ClientData client = iClients[aSessionId];
666 //Populate our client with the given text fields
668 foreach (TextField textField in aTextFields)
670 if (client.Texts.Count < (j + 1))
672 client.Texts.Add(textField);
676 client.Texts[j] = textField;
680 //Only support two lines for now
681 for (int i = 0; i < aTextFields.Count; i++)
683 if (aTextFields[i].Index == 0)
685 marqueeLabelTop.Text = aTextFields[i].Text;
686 marqueeLabelTop.TextAlign = aTextFields[i].Alignment;
688 else if (aTextFields[i].Index == 1)
690 marqueeLabelBottom.Text = aTextFields[i].Text;
691 marqueeLabelBottom.TextAlign = aTextFields[i].Alignment;
696 UpdateClientTreeViewNode(client);
705 /// <param name="aSessionId"></param>
706 /// <param name="aName"></param>
707 public void SetClientNameThreadSafe(string aSessionId, string aName)
709 if (this.InvokeRequired)
711 //Not in the proper thread, invoke ourselves
712 SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
713 this.Invoke(d, new object[] { aSessionId, aName });
717 //We are in the proper thread
719 ClientData client = iClients[aSessionId];
724 //Update our tree-view
725 UpdateClientTreeViewNode(client);
733 /// <param name="aClient"></param>
734 private void UpdateClientTreeViewNode(ClientData aClient)
741 TreeNode node = null;
742 //Check that our client node already exists
743 //Get our client root node using its key which is our session ID
744 TreeNode[] nodes = treeViewClients.Nodes.Find(aClient.SessionId, false);
747 //We already have a node for that client
749 //Clear children as we are going to recreate them below
754 //Client node does not exists create a new one
755 treeViewClients.Nodes.Add(aClient.SessionId, aClient.SessionId);
756 node = treeViewClients.Nodes.Find(aClient.SessionId, false)[0];
762 if (aClient.Name != "")
764 //We have a name, us it as text for our root node
765 node.Text = aClient.Name;
766 //Add a child with SessionId
767 node.Nodes.Add(new TreeNode(aClient.SessionId));
771 //No name, use session ID instead
772 node.Text = aClient.SessionId;
775 if (aClient.Texts.Count > 0)
777 //Create root node for our texts
778 TreeNode textsRoot = new TreeNode("Text");
779 node.Nodes.Add(textsRoot);
780 //For each text add a new entry
781 foreach (TextField field in aClient.Texts)
783 textsRoot.Nodes.Add(new TreeNode(field.Text));
791 private void buttonAddRow_Click(object sender, EventArgs e)
793 if (tableLayoutPanel.RowCount < 6)
795 tableLayoutPanel.RowCount++;
800 private void buttonRemoveRow_Click(object sender, EventArgs e)
802 if (tableLayoutPanel.RowCount > 1)
804 tableLayoutPanel.RowCount--;
809 private void buttonAddColumn_Click(object sender, EventArgs e)
811 if (tableLayoutPanel.ColumnCount < 8)
813 tableLayoutPanel.ColumnCount++;
818 private void buttonRemoveColumn_Click(object sender, EventArgs e)
820 if (tableLayoutPanel.ColumnCount > 1)
822 tableLayoutPanel.ColumnCount--;
827 private void buttonAlignLeft_Click(object sender, EventArgs e)
829 marqueeLabelTop.TextAlign = ContentAlignment.MiddleLeft;
830 marqueeLabelBottom.TextAlign = ContentAlignment.MiddleLeft;
833 private void buttonAlignCenter_Click(object sender, EventArgs e)
835 marqueeLabelTop.TextAlign = ContentAlignment.MiddleCenter;
836 marqueeLabelBottom.TextAlign = ContentAlignment.MiddleCenter;
839 private void buttonAlignRight_Click(object sender, EventArgs e)
841 marqueeLabelTop.TextAlign = ContentAlignment.MiddleRight;
842 marqueeLabelBottom.TextAlign = ContentAlignment.MiddleRight;
845 private void comboBoxDisplayType_SelectedIndexChanged(object sender, EventArgs e)
847 Properties.Settings.Default.CurrentDisplayIndex = comboBoxDisplayType.SelectedIndex;
848 cds.DisplayType = comboBoxDisplayType.SelectedIndex;
849 Properties.Settings.Default.Save();
850 if (iDisplay.IsOpen())
852 OpenDisplayConnection();
861 private void maskedTextBoxTimerInterval_TextChanged(object sender, EventArgs e)
863 if (maskedTextBoxTimerInterval.Text != "")
865 int interval = Convert.ToInt32(maskedTextBoxTimerInterval.Text);
869 timer.Interval = interval;
870 cds.TimerInterval = timer.Interval;
871 Properties.Settings.Default.Save();
876 private void buttonPowerOn_Click(object sender, EventArgs e)
881 private void buttonPowerOff_Click(object sender, EventArgs e)
889 /// A UI thread copy of a client relevant data.
890 /// Keeping this copy in the UI thread helps us deal with threading issues.
892 public class ClientData
894 public ClientData(string aSessionId, IDisplayServiceCallback aCallback)
896 SessionId = aSessionId;
898 Texts = new List<TextField>();
899 Callback = aCallback;
902 public string SessionId { get; set; }
903 public string Name { get; set; }
904 public List<TextField> Texts { get; set; }
905 public IDisplayServiceCallback Callback { get; set; }