Adding missing file.
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.EMiniDisplayRequestPowerSupplyStatus:
151 if (iDisplay.PowerSupplyStatus())
153 toolStripStatusLabelPower.Text = "ON";
157 toolStripStatusLabelPower.Text = "OFF";
159 //Issue next request then
160 iDisplay.RequestDeviceId();
163 case Display.TMiniDisplayRequest.EMiniDisplayRequestDeviceId:
164 toolStripStatusLabelConnect.Text += " - " + iDisplay.DeviceId();
165 //Issue next request then
166 iDisplay.RequestFirmwareRevision();
169 case Display.TMiniDisplayRequest.EMiniDisplayRequestFirmwareRevision:
170 toolStripStatusLabelConnect.Text += " v" + iDisplay.FirmwareRevision();
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.RequestPowerSupplyStatus();
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 DisplaySettingsEntry cds
326 DisplaySettings settings = Properties.Settings.Default.DisplaySettings;
328 //Make sure all our settings have been created
329 while (settings.Displays.Count <= Properties.Settings.Default.CurrentDisplayIndex)
331 settings.Displays.Add(new DisplaySettingsEntry());
334 DisplaySettingsEntry displaySettings = settings.Displays[Properties.Settings.Default.CurrentDisplayIndex];
335 return displaySettings;
339 private void UpdateStatus()
341 //Synchronize UI with settings
343 marqueeLabelTop.Font = cds.Font;
344 marqueeLabelBottom.Font = cds.Font;
345 checkBoxShowBorders.Checked = cds.ShowBorders;
346 checkBoxConnectOnStartup.Checked = Properties.Settings.Default.DisplayConnectOnStartup;
347 checkBoxReverseScreen.Checked = cds.ReverseScreen;
348 comboBoxDisplayType.SelectedIndex = cds.DisplayType;
349 timer.Interval = cds.TimerInterval;
350 maskedTextBoxTimerInterval.Text = cds.TimerInterval.ToString();
353 if (iDisplay.IsOpen())
355 //Only setup brightness if display is open
356 trackBarBrightness.Minimum = iDisplay.MinBrightness();
357 trackBarBrightness.Maximum = iDisplay.MaxBrightness();
358 trackBarBrightness.Value = cds.Brightness;
359 trackBarBrightness.LargeChange = Math.Max(1, (iDisplay.MaxBrightness() - iDisplay.MinBrightness()) / 5);
360 trackBarBrightness.SmallChange = 1;
361 iDisplay.SetBrightness(cds.Brightness);
363 buttonFill.Enabled = true;
364 buttonClear.Enabled = true;
365 buttonOpen.Enabled = false;
366 buttonClose.Enabled = true;
367 trackBarBrightness.Enabled = true;
368 toolStripStatusLabelConnect.Text = "Connected - " + iDisplay.Vendor() + " - " + iDisplay.Product();
369 //+ " - " + iDisplay.SerialNumber();
373 buttonFill.Enabled = false;
374 buttonClear.Enabled = false;
375 buttonOpen.Enabled = true;
376 buttonClose.Enabled = false;
377 trackBarBrightness.Enabled = false;
378 toolStripStatusLabelConnect.Text = "Disconnected";
379 toolStripStatusLabelPower.Text = "N/A";
385 private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
387 //Save our show borders setting
388 tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
389 cds.ShowBorders = checkBoxShowBorders.Checked;
390 Properties.Settings.Default.Save();
393 private void checkBoxConnectOnStartup_CheckedChanged(object sender, EventArgs e)
395 //Save our connect on startup setting
396 Properties.Settings.Default.DisplayConnectOnStartup = checkBoxConnectOnStartup.Checked;
397 Properties.Settings.Default.Save();
400 private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
402 //Save our reverse screen setting
403 cds.ReverseScreen = checkBoxReverseScreen.Checked;
404 Properties.Settings.Default.Save();
407 private void MainForm_Resize(object sender, EventArgs e)
409 if (WindowState == FormWindowState.Minimized)
412 //iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
413 iCreateBitmap = true;
417 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
423 public void StartServer()
425 iServiceHost = new ServiceHost
427 typeof(DisplayServer),
428 new Uri[] { new Uri("net.tcp://localhost:8001/") }
431 iServiceHost.AddServiceEndpoint(typeof(IDisplayService), new NetTcpBinding(SecurityMode.None,true), "DisplayService");
435 public void StopServer()
437 if (iClients.Count > 0 && !iClosing)
441 BroadcastCloseEvent();
445 if (MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
447 iClosing = false; //We make sure we force close if asked twice
452 //We removed that as it often lags for some reason
453 //iServiceHost.Close();
457 public void BroadcastCloseEvent()
459 Trace.TraceInformation("BroadcastCloseEvent - start");
461 var inactiveClients = new List<string>();
462 foreach (var client in iClients)
464 //if (client.Key != eventData.ClientName)
468 Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
469 client.Value.Callback.OnCloseOrder(/*eventData*/);
473 inactiveClients.Add(client.Key);
478 if (inactiveClients.Count > 0)
480 foreach (var client in inactiveClients)
482 iClients.Remove(client);
483 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(client, false)[0]);
488 private void buttonStartClient_Click(object sender, EventArgs e)
490 Thread clientThread = new Thread(SharpDisplayClient.Program.Main);
491 clientThread.Start();
495 private void buttonSuspend_Click(object sender, EventArgs e)
497 timer.Enabled = !timer.Enabled;
500 buttonSuspend.Text = "Suspend";
504 buttonSuspend.Text = "Pause";
508 private void buttonCloseClients_Click(object sender, EventArgs e)
510 BroadcastCloseEvent();
513 private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
518 //Delegates are used for our thread safe method
519 public delegate void AddClientDelegate(string aSessionId, IDisplayServiceCallback aCallback);
520 public delegate void RemoveClientDelegate(string aSessionId);
521 public delegate void SetTextDelegate(string SessionId, TextField aTextField);
522 public delegate void SetTextsDelegate(string SessionId, System.Collections.Generic.IList<TextField> aTextFields);
523 public delegate void SetClientNameDelegate(string aSessionId, string aName);
529 /// <param name="aSessionId"></param>
530 /// <param name="aCallback"></param>
531 public void AddClientThreadSafe(string aSessionId, IDisplayServiceCallback aCallback)
533 if (this.InvokeRequired)
535 //Not in the proper thread, invoke ourselves
536 AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
537 this.Invoke(d, new object[] { aSessionId, aCallback });
541 //We are in the proper thread
542 //Add this session to our collection of clients
543 ClientData newClient = new ClientData(aSessionId, aCallback);
544 Program.iMainForm.iClients.Add(aSessionId, newClient);
545 //Add this session to our UI
546 UpdateClientTreeViewNode(newClient);
553 /// <param name="aSessionId"></param>
554 public void RemoveClientThreadSafe(string aSessionId)
556 if (this.InvokeRequired)
558 //Not in the proper thread, invoke ourselves
559 RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
560 this.Invoke(d, new object[] { aSessionId });
564 //We are in the proper thread
565 //Remove this session from both client collection and UI tree view
566 if (Program.iMainForm.iClients.Keys.Contains(aSessionId))
568 Program.iMainForm.iClients.Remove(aSessionId);
569 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(aSessionId, false)[0]);
572 if (iClosing && iClients.Count == 0)
574 //We were closing our form
575 //All clients are now closed
576 //Just resume our close operation
586 /// <param name="aLineIndex"></param>
587 /// <param name="aText"></param>
588 public void SetTextThreadSafe(string aSessionId, TextField aTextField)
590 if (this.InvokeRequired)
592 //Not in the proper thread, invoke ourselves
593 SetTextDelegate d = new SetTextDelegate(SetTextThreadSafe);
594 this.Invoke(d, new object[] { aSessionId, aTextField });
598 ClientData client = iClients[aSessionId];
601 //Make sure all our texts are in place
602 while (client.Texts.Count < (aTextField.Index + 1))
604 //Add a text field with proper index
605 client.Texts.Add(new TextField(client.Texts.Count));
607 client.Texts[aTextField.Index] = aTextField;
609 //We are in the proper thread
610 //Only support two lines for now
611 if (aTextField.Index == 0)
613 marqueeLabelTop.Text = aTextField.Text;
614 marqueeLabelTop.TextAlign = aTextField.Alignment;
616 else if (aTextField.Index == 1)
618 marqueeLabelBottom.Text = aTextField.Text;
619 marqueeLabelBottom.TextAlign = aTextField.Alignment;
623 UpdateClientTreeViewNode(client);
631 /// <param name="aTexts"></param>
632 public void SetTextsThreadSafe(string aSessionId, System.Collections.Generic.IList<TextField> aTextFields)
634 if (this.InvokeRequired)
636 //Not in the proper thread, invoke ourselves
637 SetTextsDelegate d = new SetTextsDelegate(SetTextsThreadSafe);
638 this.Invoke(d, new object[] { aSessionId, aTextFields });
642 //We are in the proper thread
643 ClientData client = iClients[aSessionId];
646 //Populate our client with the given text fields
648 foreach (TextField textField in aTextFields)
650 if (client.Texts.Count < (j + 1))
652 client.Texts.Add(textField);
656 client.Texts[j] = textField;
660 //Only support two lines for now
661 for (int i = 0; i < aTextFields.Count; i++)
663 if (aTextFields[i].Index == 0)
665 marqueeLabelTop.Text = aTextFields[i].Text;
666 marqueeLabelTop.TextAlign = aTextFields[i].Alignment;
668 else if (aTextFields[i].Index == 1)
670 marqueeLabelBottom.Text = aTextFields[i].Text;
671 marqueeLabelBottom.TextAlign = aTextFields[i].Alignment;
676 UpdateClientTreeViewNode(client);
685 /// <param name="aSessionId"></param>
686 /// <param name="aName"></param>
687 public void SetClientNameThreadSafe(string aSessionId, string aName)
689 if (this.InvokeRequired)
691 //Not in the proper thread, invoke ourselves
692 SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
693 this.Invoke(d, new object[] { aSessionId, aName });
697 //We are in the proper thread
699 ClientData client = iClients[aSessionId];
704 //Update our tree-view
705 UpdateClientTreeViewNode(client);
713 /// <param name="aClient"></param>
714 private void UpdateClientTreeViewNode(ClientData aClient)
721 TreeNode node = null;
722 //Check that our client node already exists
723 //Get our client root node using its key which is our session ID
724 TreeNode[] nodes = treeViewClients.Nodes.Find(aClient.SessionId, false);
727 //We already have a node for that client
729 //Clear children as we are going to recreate them below
734 //Client node does not exists create a new one
735 treeViewClients.Nodes.Add(aClient.SessionId, aClient.SessionId);
736 node = treeViewClients.Nodes.Find(aClient.SessionId, false)[0];
742 if (aClient.Name != "")
744 //We have a name, us it as text for our root node
745 node.Text = aClient.Name;
746 //Add a child with SessionId
747 node.Nodes.Add(new TreeNode(aClient.SessionId));
751 //No name, use session ID instead
752 node.Text = aClient.SessionId;
755 if (aClient.Texts.Count > 0)
757 //Create root node for our texts
758 TreeNode textsRoot = new TreeNode("Text");
759 node.Nodes.Add(textsRoot);
760 //For each text add a new entry
761 foreach (TextField field in aClient.Texts)
763 textsRoot.Nodes.Add(new TreeNode(field.Text));
771 private void buttonAddRow_Click(object sender, EventArgs e)
773 if (tableLayoutPanel.RowCount < 6)
775 tableLayoutPanel.RowCount++;
780 private void buttonRemoveRow_Click(object sender, EventArgs e)
782 if (tableLayoutPanel.RowCount > 1)
784 tableLayoutPanel.RowCount--;
789 private void buttonAddColumn_Click(object sender, EventArgs e)
791 if (tableLayoutPanel.ColumnCount < 8)
793 tableLayoutPanel.ColumnCount++;
798 private void buttonRemoveColumn_Click(object sender, EventArgs e)
800 if (tableLayoutPanel.ColumnCount > 1)
802 tableLayoutPanel.ColumnCount--;
807 private void buttonAlignLeft_Click(object sender, EventArgs e)
809 marqueeLabelTop.TextAlign = ContentAlignment.MiddleLeft;
810 marqueeLabelBottom.TextAlign = ContentAlignment.MiddleLeft;
813 private void buttonAlignCenter_Click(object sender, EventArgs e)
815 marqueeLabelTop.TextAlign = ContentAlignment.MiddleCenter;
816 marqueeLabelBottom.TextAlign = ContentAlignment.MiddleCenter;
819 private void buttonAlignRight_Click(object sender, EventArgs e)
821 marqueeLabelTop.TextAlign = ContentAlignment.MiddleRight;
822 marqueeLabelBottom.TextAlign = ContentAlignment.MiddleRight;
825 private void comboBoxDisplayType_SelectedIndexChanged(object sender, EventArgs e)
827 Properties.Settings.Default.CurrentDisplayIndex = comboBoxDisplayType.SelectedIndex;
828 cds.DisplayType = comboBoxDisplayType.SelectedIndex;
829 Properties.Settings.Default.Save();
830 OpenDisplayConnection();
834 private void maskedTextBoxTimerInterval_TextChanged(object sender, EventArgs e)
836 if (maskedTextBoxTimerInterval.Text != "")
838 timer.Interval = Convert.ToInt32(maskedTextBoxTimerInterval.Text);
839 cds.TimerInterval = timer.Interval;
840 Properties.Settings.Default.Save();
847 /// A UI thread copy of a client relevant data.
848 /// Keeping this copy in the UI thread helps us deal with threading issues.
850 public class ClientData
852 public ClientData(string aSessionId, IDisplayServiceCallback aCallback)
854 SessionId = aSessionId;
856 Texts = new List<TextField>();
857 Callback = aCallback;
860 public string SessionId { get; set; }
861 public string Name { get; set; }
862 public List<TextField> Texts { get; set; }
863 public IDisplayServiceCallback Callback { get; set; }