Adding texts fields to our test client.
Trying to fix bugs and optimize our marquee control.
Creating a proper ClientData class to use in our UI thread client dictionary.
Centralising tree-view update.
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
24 /// A UI thread copy of a client relevant data.
25 /// Keeping this copy in the UI thread helps us deal with threading issues.
27 public class ClientData
29 public ClientData(string aSessionId, IDisplayServiceCallback aCallback)
31 SessionId = aSessionId;
33 Texts = new List<string>();
37 public string SessionId { get; set;}
38 public string Name { get; set;}
39 public List<string> Texts { get; set;}
40 public IDisplayServiceCallback Callback { get; set;}
44 public partial class MainForm : Form
46 DateTime LastTickTime;
48 System.Drawing.Bitmap iBmp;
49 bool iCreateBitmap; //Workaround render to bitmap issues when minimized
50 ServiceHost iServiceHost;
52 /// Our collection of clients
54 public Dictionary<string, ClientData> iClients;
59 LastTickTime = DateTime.Now;
60 iDisplay = new Display();
61 iClients = new Dictionary<string, ClientData>();
63 InitializeComponent();
67 marqueeLabelTop.Font = Properties.Settings.Default.DisplayFont;
68 marqueeLabelBottom.Font = Properties.Settings.Default.DisplayFont;
69 checkBoxShowBorders.Checked = Properties.Settings.Default.DisplayShowBorders;
70 checkBoxConnectOnStartup.Checked = Properties.Settings.Default.DisplayConnectOnStartup;
71 checkBoxReverseScreen.Checked = Properties.Settings.Default.DisplayReverseScreen;
73 tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
74 //We have a bug when drawing minimized and reusing our bitmap
75 iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
76 iCreateBitmap = false;
79 private void MainForm_Load(object sender, EventArgs e)
83 if (Properties.Settings.Default.DisplayConnectOnStartup)
91 private void buttonFont_Click(object sender, EventArgs e)
93 //fontDialog.ShowColor = true;
94 //fontDialog.ShowApply = true;
95 fontDialog.ShowEffects = true;
96 fontDialog.Font = marqueeLabelTop.Font;
98 fontDialog.FixedPitchOnly = checkBoxFixedPitchFontOnly.Checked;
100 //fontDialog.ShowHelp = true;
102 //fontDlg.MaxSize = 40;
103 //fontDlg.MinSize = 22;
105 //fontDialog.Parent = this;
106 //fontDialog.StartPosition = FormStartPosition.CenterParent;
108 //DlgBox.ShowDialog(fontDialog);
110 //if (fontDialog.ShowDialog(this) != DialogResult.Cancel)
111 if (DlgBox.ShowDialog(fontDialog) != DialogResult.Cancel)
114 //MsgBox.Show("MessageBox MsgBox", "MsgBox caption");
116 //MessageBox.Show("Ok");
117 marqueeLabelTop.Font = fontDialog.Font;
118 marqueeLabelBottom.Font = fontDialog.Font;
119 Properties.Settings.Default.DisplayFont = fontDialog.Font;
120 Properties.Settings.Default.Save();
121 //label1.Font = fontDlg.Font;
122 //textBox1.BackColor = fontDlg.Color;
123 //label1.ForeColor = fontDlg.Color;
127 private void buttonCapture_Click(object sender, EventArgs e)
129 System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height);
130 tableLayoutPanel.DrawToBitmap(bmp, tableLayoutPanel.ClientRectangle);
131 //Bitmap bmpToSave = new Bitmap(bmp);
132 bmp.Save("D:\\capture.png");
134 marqueeLabelTop.Text = "Sweet";
137 string outputFileName = "d:\\capture.png";
138 using (MemoryStream memory = new MemoryStream())
140 using (FileStream fs = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
142 bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
143 byte[] bytes = memory.ToArray();
144 fs.Write(bytes, 0, bytes.Length);
151 private void CheckForRequestResults()
153 if (iDisplay.IsRequestPending())
155 switch (iDisplay.AttemptRequestCompletion())
157 case Display.TMiniDisplayRequest.EMiniDisplayRequestPowerSupplyStatus:
158 if (iDisplay.PowerSupplyStatus())
160 toolStripStatusLabelPower.Text = "ON";
164 toolStripStatusLabelPower.Text = "OFF";
166 //Issue next request then
167 iDisplay.RequestDeviceId();
170 case Display.TMiniDisplayRequest.EMiniDisplayRequestDeviceId:
171 toolStripStatusLabelConnect.Text += " - " + iDisplay.DeviceId();
172 //Issue next request then
173 iDisplay.RequestFirmwareRevision();
176 case Display.TMiniDisplayRequest.EMiniDisplayRequestFirmwareRevision:
177 toolStripStatusLabelConnect.Text += " v" + iDisplay.FirmwareRevision();
178 //No more request to issue
185 public delegate int CoordinateTranslationDelegate(System.Drawing.Bitmap aBmp, int aInt);
188 public static int ScreenReversedX(System.Drawing.Bitmap aBmp, int aX)
190 return aBmp.Width - aX - 1;
193 public int ScreenReversedY(System.Drawing.Bitmap aBmp, int aY)
195 return iBmp.Height - aY - 1;
198 public int ScreenX(System.Drawing.Bitmap aBmp, int aX)
203 public int ScreenY(System.Drawing.Bitmap aBmp, int aY)
209 //This is our timer tick responsible to perform our render
210 private void timer_Tick(object sender, EventArgs e)
212 //Update our animations
213 DateTime NewTickTime = DateTime.Now;
215 marqueeLabelTop.UpdateAnimation(LastTickTime, NewTickTime);
216 marqueeLabelBottom.UpdateAnimation(LastTickTime, NewTickTime);
219 if (iDisplay.IsOpen())
221 CheckForRequestResults();
226 iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
228 tableLayoutPanel.DrawToBitmap(iBmp, tableLayoutPanel.ClientRectangle);
229 //iBmp.Save("D:\\capture.png");
231 //Select proper coordinate translation functions
232 //We used delegate/function pointer to support reverse screen without doing an extra test on each pixels
233 CoordinateTranslationDelegate screenX;
234 CoordinateTranslationDelegate screenY;
236 if (Properties.Settings.Default.DisplayReverseScreen)
238 screenX = ScreenReversedX;
239 screenY = ScreenReversedY;
247 //Send it to our display
248 for (int i = 0; i < iBmp.Width; i++)
250 for (int j = 0; j < iBmp.Height; j++)
254 uint color = (uint)iBmp.GetPixel(i, j).ToArgb();
255 //For some reason when the app is minimized in the task bar only the alpha of our color is set.
256 //Thus that strange test for rendering to work both when the app is in the task bar and when it isn't.
257 iDisplay.SetPixel(screenX(iBmp, i), screenY(iBmp, j), Convert.ToInt32(!(color != 0xFF000000)));
262 iDisplay.SwapBuffers();
266 //Compute instant FPS
267 toolStripStatusLabelFps.Text = (1.0/NewTickTime.Subtract(LastTickTime).TotalSeconds).ToString("F0") + " FPS";
269 LastTickTime = NewTickTime;
273 private void buttonOpen_Click(object sender, EventArgs e)
278 iDisplay.RequestPowerSupplyStatus();
283 toolStripStatusLabelConnect.Text = "Connection error";
288 private void buttonClose_Click(object sender, EventArgs e)
294 private void buttonClear_Click(object sender, EventArgs e)
297 iDisplay.SwapBuffers();
300 private void buttonFill_Click(object sender, EventArgs e)
303 iDisplay.SwapBuffers();
306 private void trackBarBrightness_Scroll(object sender, EventArgs e)
308 Properties.Settings.Default.DisplayBrightness = trackBarBrightness.Value;
309 Properties.Settings.Default.Save();
310 iDisplay.SetBrightness(trackBarBrightness.Value);
314 private void UpdateStatus()
316 if (iDisplay.IsOpen())
318 buttonFill.Enabled = true;
319 buttonClear.Enabled = true;
320 buttonOpen.Enabled = false;
321 buttonClose.Enabled = true;
322 trackBarBrightness.Enabled = true;
323 trackBarBrightness.Minimum = iDisplay.MinBrightness();
324 trackBarBrightness.Maximum = iDisplay.MaxBrightness();
325 trackBarBrightness.Value = Properties.Settings.Default.DisplayBrightness;
326 trackBarBrightness.LargeChange = Math.Max(1,(iDisplay.MaxBrightness() - iDisplay.MinBrightness())/5);
327 trackBarBrightness.SmallChange = 1;
328 iDisplay.SetBrightness(Properties.Settings.Default.DisplayBrightness);
330 toolStripStatusLabelConnect.Text = "Connected - " + iDisplay.Vendor() + " - " + iDisplay.Product();
331 //+ " - " + iDisplay.SerialNumber();
335 buttonFill.Enabled = false;
336 buttonClear.Enabled = false;
337 buttonOpen.Enabled = true;
338 buttonClose.Enabled = false;
339 trackBarBrightness.Enabled = false;
340 toolStripStatusLabelConnect.Text = "Disconnected";
346 private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
348 //Save our show borders setting
349 tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
350 Properties.Settings.Default.DisplayShowBorders = checkBoxShowBorders.Checked;
351 Properties.Settings.Default.Save();
354 private void checkBoxConnectOnStartup_CheckedChanged(object sender, EventArgs e)
356 //Save our connect on startup setting
357 Properties.Settings.Default.DisplayConnectOnStartup = checkBoxConnectOnStartup.Checked;
358 Properties.Settings.Default.Save();
361 private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
363 //Save our reverse screen setting
364 Properties.Settings.Default.DisplayReverseScreen = checkBoxReverseScreen.Checked;
365 Properties.Settings.Default.Save();
368 private void MainForm_Resize(object sender, EventArgs e)
370 if (WindowState == FormWindowState.Minimized)
373 //iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
374 iCreateBitmap = true;
378 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
384 public void StartServer()
386 iServiceHost = new ServiceHost
388 typeof(DisplayServer),
389 new Uri[] { new Uri("net.tcp://localhost:8001/") }
392 iServiceHost.AddServiceEndpoint(typeof(IDisplayService), new NetTcpBinding(SecurityMode.None,true), "DisplayService");
396 public void StopServer()
398 if (iClients.Count > 0 && !iClosing)
402 BroadcastCloseEvent();
406 if (MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
408 iClosing = false; //We make sure we force close if asked twice
413 //We removed that as it often lags for some reason
414 //iServiceHost.Close();
418 public void BroadcastCloseEvent()
420 Trace.TraceInformation("BroadcastCloseEvent - start");
422 var inactiveClients = new List<string>();
423 foreach (var client in iClients)
425 //if (client.Key != eventData.ClientName)
429 Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
430 client.Value.Callback.OnCloseOrder(/*eventData*/);
434 inactiveClients.Add(client.Key);
439 if (inactiveClients.Count > 0)
441 foreach (var client in inactiveClients)
443 iClients.Remove(client);
444 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(client, false)[0]);
449 private void buttonStartClient_Click(object sender, EventArgs e)
451 Thread clientThread = new Thread(SharpDisplayClient.Program.Main);
452 clientThread.Start();
455 private void buttonSuspend_Click(object sender, EventArgs e)
457 timer.Enabled = !timer.Enabled;
460 buttonSuspend.Text = "Suspend";
464 buttonSuspend.Text = "Pause";
468 private void buttonCloseClients_Click(object sender, EventArgs e)
470 BroadcastCloseEvent();
473 private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
478 //Delegates are used for our thread safe method
479 public delegate void AddClientDelegate(string aSessionId, IDisplayServiceCallback aCallback);
480 public delegate void RemoveClientDelegate(string aSessionId);
481 public delegate void SetTextDelegate(int aLineIndex, string aText);
482 public delegate void SetTextsDelegate(System.Collections.Generic.IList<string> aTexts);
483 public delegate void SetClientNameDelegate(string aSessionId, string aName);
489 /// <param name="aSessionId"></param>
490 /// <param name="aCallback"></param>
491 public void AddClientThreadSafe(string aSessionId, IDisplayServiceCallback aCallback)
493 if (this.InvokeRequired)
495 //Not in the proper thread, invoke ourselves
496 AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
497 this.Invoke(d, new object[] { aSessionId, aCallback });
501 //We are in the proper thread
502 //Add this session to our collection of clients
503 ClientData newClient = new ClientData(aSessionId, aCallback);
504 Program.iMainForm.iClients.Add(aSessionId, newClient);
505 //Add this session to our UI
506 UpdateClientTreeViewNode(newClient);
513 /// <param name="aSessionId"></param>
514 public void RemoveClientThreadSafe(string aSessionId)
516 if (this.InvokeRequired)
518 //Not in the proper thread, invoke ourselves
519 RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
520 this.Invoke(d, new object[] { aSessionId });
524 //We are in the proper thread
525 //Remove this session from both client collection and UI tree view
526 if (Program.iMainForm.iClients.Keys.Contains(aSessionId))
528 Program.iMainForm.iClients.Remove(aSessionId);
529 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(aSessionId, false)[0]);
532 if (iClosing && iClients.Count == 0)
534 //We were closing our form
535 //All clients are now closed
536 //Just resume our close operation
546 /// <param name="aLineIndex"></param>
547 /// <param name="aText"></param>
548 public void SetTextThreadSafe(int aLineIndex, string aText)
550 if (this.InvokeRequired)
552 //Not in the proper thread, invoke ourselves
553 SetTextDelegate d = new SetTextDelegate(SetTextThreadSafe);
554 this.Invoke(d, new object[] { aLineIndex, aText });
558 //We are in the proper thread
559 //Only support two lines for now
562 marqueeLabelTop.Text = aText;
564 else if (aLineIndex == 1)
566 marqueeLabelBottom.Text = aText;
574 /// <param name="aTexts"></param>
575 public void SetTextsThreadSafe(System.Collections.Generic.IList<string> aTexts)
577 if (this.InvokeRequired)
579 //Not in the proper thread, invoke ourselves
580 SetTextsDelegate d = new SetTextsDelegate(SetTextsThreadSafe);
581 this.Invoke(d, new object[] { aTexts });
585 //We are in the proper thread
586 //Only support two lines for now
587 for (int i = 0; i < aTexts.Count; i++)
591 marqueeLabelTop.Text = aTexts[i];
595 marqueeLabelBottom.Text = aTexts[i];
605 /// <param name="aSessionId"></param>
606 /// <param name="aName"></param>
607 public void SetClientNameThreadSafe(string aSessionId, string aName)
609 if (this.InvokeRequired)
611 //Not in the proper thread, invoke ourselves
612 SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
613 this.Invoke(d, new object[] { aSessionId, aName });
617 //We are in the proper thread
619 ClientData client = iClients[aSessionId];
624 //Update our tree-view
625 UpdateClientTreeViewNode(client);
633 /// <param name="aClient"></param>
634 private void UpdateClientTreeViewNode(ClientData aClient)
641 TreeNode node = null;
642 //Check that our client node already exists
643 //Get our client root node using its key which is our session ID
644 TreeNode[] nodes = treeViewClients.Nodes.Find(aClient.SessionId, false);
647 //We already have a node for that client
649 //Clear children as we are going to recreate them below
654 //Client node does not exists create a new one
655 treeViewClients.Nodes.Add(aClient.SessionId, aClient.SessionId);
656 node = treeViewClients.Nodes.Find(aClient.SessionId, false)[0];
662 if (aClient.Name != "")
664 //We have a name, us it as text for our root node
665 node.Text = aClient.Name;
666 //Add a child with SessionId
667 node.Nodes.Add(new TreeNode(aClient.SessionId));
671 //No name, use session ID instead
672 node.Text = aClient.SessionId;
675 if (aClient.Texts.Count > 0)
677 //Create root node for our texts
678 TreeNode textsRoot = new TreeNode("Text");
679 node.Nodes.Add(textsRoot);
680 //For each text add a new entry
681 foreach (string text in aClient.Texts)
683 textsRoot.Nodes.Add(new TreeNode(text));