Adding warning when newly selected font is too height.
Reworking our UI.
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 marqueeLabelTop.Font = Properties.Settings.Default.DisplayFont;
47 marqueeLabelBottom.Font = Properties.Settings.Default.DisplayFont;
48 checkBoxShowBorders.Checked = Properties.Settings.Default.DisplayShowBorders;
49 checkBoxConnectOnStartup.Checked = Properties.Settings.Default.DisplayConnectOnStartup;
50 checkBoxReverseScreen.Checked = Properties.Settings.Default.DisplayReverseScreen;
52 tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
53 //We have a bug when drawing minimized and reusing our bitmap
54 iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
55 iCreateBitmap = false;
58 private void MainForm_Load(object sender, EventArgs e)
62 if (Properties.Settings.Default.DisplayConnectOnStartup)
70 private void buttonFont_Click(object sender, EventArgs e)
72 //fontDialog.ShowColor = true;
73 //fontDialog.ShowApply = true;
74 fontDialog.ShowEffects = true;
75 fontDialog.Font = marqueeLabelTop.Font;
77 fontDialog.FixedPitchOnly = checkBoxFixedPitchFontOnly.Checked;
79 //fontDialog.ShowHelp = true;
81 //fontDlg.MaxSize = 40;
82 //fontDlg.MinSize = 22;
84 //fontDialog.Parent = this;
85 //fontDialog.StartPosition = FormStartPosition.CenterParent;
87 //DlgBox.ShowDialog(fontDialog);
89 //if (fontDialog.ShowDialog(this) != DialogResult.Cancel)
90 if (DlgBox.ShowDialog(fontDialog) != DialogResult.Cancel)
93 //MsgBox.Show("MessageBox MsgBox", "MsgBox caption");
95 //MessageBox.Show("Ok");
96 marqueeLabelTop.Font = fontDialog.Font;
97 marqueeLabelBottom.Font = fontDialog.Font;
98 Properties.Settings.Default.DisplayFont = fontDialog.Font;
99 Properties.Settings.Default.Save();
101 if (fontDialog.Font.Height > marqueeLabelBottom.Height)
103 labelWarning.Text = "WARNING: Selected font is too height by " + (fontDialog.Font.Height - marqueeLabelBottom.Height) + " pixels!";
104 labelWarning.Visible = true;
108 labelWarning.Visible = false;
114 private void buttonCapture_Click(object sender, EventArgs e)
116 System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height);
117 tableLayoutPanel.DrawToBitmap(bmp, tableLayoutPanel.ClientRectangle);
118 //Bitmap bmpToSave = new Bitmap(bmp);
119 bmp.Save("D:\\capture.png");
121 marqueeLabelTop.Text = "Sweet";
124 string outputFileName = "d:\\capture.png";
125 using (MemoryStream memory = new MemoryStream())
127 using (FileStream fs = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
129 bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
130 byte[] bytes = memory.ToArray();
131 fs.Write(bytes, 0, bytes.Length);
138 private void CheckForRequestResults()
140 if (iDisplay.IsRequestPending())
142 switch (iDisplay.AttemptRequestCompletion())
144 case Display.TMiniDisplayRequest.EMiniDisplayRequestPowerSupplyStatus:
145 if (iDisplay.PowerSupplyStatus())
147 toolStripStatusLabelPower.Text = "ON";
151 toolStripStatusLabelPower.Text = "OFF";
153 //Issue next request then
154 iDisplay.RequestDeviceId();
157 case Display.TMiniDisplayRequest.EMiniDisplayRequestDeviceId:
158 toolStripStatusLabelConnect.Text += " - " + iDisplay.DeviceId();
159 //Issue next request then
160 iDisplay.RequestFirmwareRevision();
163 case Display.TMiniDisplayRequest.EMiniDisplayRequestFirmwareRevision:
164 toolStripStatusLabelConnect.Text += " v" + iDisplay.FirmwareRevision();
165 //No more request to issue
172 public delegate int CoordinateTranslationDelegate(System.Drawing.Bitmap aBmp, int aInt);
175 public static int ScreenReversedX(System.Drawing.Bitmap aBmp, int aX)
177 return aBmp.Width - aX - 1;
180 public int ScreenReversedY(System.Drawing.Bitmap aBmp, int aY)
182 return iBmp.Height - aY - 1;
185 public int ScreenX(System.Drawing.Bitmap aBmp, int aX)
190 public int ScreenY(System.Drawing.Bitmap aBmp, int aY)
196 //This is our timer tick responsible to perform our render
197 private void timer_Tick(object sender, EventArgs e)
199 //Update our animations
200 DateTime NewTickTime = DateTime.Now;
202 marqueeLabelTop.UpdateAnimation(LastTickTime, NewTickTime);
203 marqueeLabelBottom.UpdateAnimation(LastTickTime, NewTickTime);
206 if (iDisplay.IsOpen())
208 CheckForRequestResults();
213 iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
215 tableLayoutPanel.DrawToBitmap(iBmp, tableLayoutPanel.ClientRectangle);
216 //iBmp.Save("D:\\capture.png");
218 //Select proper coordinate translation functions
219 //We used delegate/function pointer to support reverse screen without doing an extra test on each pixels
220 CoordinateTranslationDelegate screenX;
221 CoordinateTranslationDelegate screenY;
223 if (Properties.Settings.Default.DisplayReverseScreen)
225 screenX = ScreenReversedX;
226 screenY = ScreenReversedY;
234 //Send it to our display
235 for (int i = 0; i < iBmp.Width; i++)
237 for (int j = 0; j < iBmp.Height; j++)
241 uint color = (uint)iBmp.GetPixel(i, j).ToArgb();
242 //For some reason when the app is minimized in the task bar only the alpha of our color is set.
243 //Thus that strange test for rendering to work both when the app is in the task bar and when it isn't.
244 iDisplay.SetPixel(screenX(iBmp, i), screenY(iBmp, j), Convert.ToInt32(!(color != 0xFF000000)));
249 iDisplay.SwapBuffers();
253 //Compute instant FPS
254 toolStripStatusLabelFps.Text = (1.0/NewTickTime.Subtract(LastTickTime).TotalSeconds).ToString("F0") + " FPS";
256 LastTickTime = NewTickTime;
260 private void buttonOpen_Click(object sender, EventArgs e)
265 iDisplay.RequestPowerSupplyStatus();
270 toolStripStatusLabelConnect.Text = "Connection error";
275 private void buttonClose_Click(object sender, EventArgs e)
281 private void buttonClear_Click(object sender, EventArgs e)
284 iDisplay.SwapBuffers();
287 private void buttonFill_Click(object sender, EventArgs e)
290 iDisplay.SwapBuffers();
293 private void trackBarBrightness_Scroll(object sender, EventArgs e)
295 Properties.Settings.Default.DisplayBrightness = trackBarBrightness.Value;
296 Properties.Settings.Default.Save();
297 iDisplay.SetBrightness(trackBarBrightness.Value);
301 private void UpdateStatus()
303 if (iDisplay.IsOpen())
305 buttonFill.Enabled = true;
306 buttonClear.Enabled = true;
307 buttonOpen.Enabled = false;
308 buttonClose.Enabled = true;
309 trackBarBrightness.Enabled = true;
310 trackBarBrightness.Minimum = iDisplay.MinBrightness();
311 trackBarBrightness.Maximum = iDisplay.MaxBrightness();
312 trackBarBrightness.Value = Properties.Settings.Default.DisplayBrightness;
313 trackBarBrightness.LargeChange = Math.Max(1,(iDisplay.MaxBrightness() - iDisplay.MinBrightness())/5);
314 trackBarBrightness.SmallChange = 1;
315 iDisplay.SetBrightness(Properties.Settings.Default.DisplayBrightness);
317 toolStripStatusLabelConnect.Text = "Connected - " + iDisplay.Vendor() + " - " + iDisplay.Product();
318 //+ " - " + iDisplay.SerialNumber();
322 buttonFill.Enabled = false;
323 buttonClear.Enabled = false;
324 buttonOpen.Enabled = true;
325 buttonClose.Enabled = false;
326 trackBarBrightness.Enabled = false;
327 toolStripStatusLabelConnect.Text = "Disconnected";
333 private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
335 //Save our show borders setting
336 tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
337 Properties.Settings.Default.DisplayShowBorders = checkBoxShowBorders.Checked;
338 Properties.Settings.Default.Save();
341 private void checkBoxConnectOnStartup_CheckedChanged(object sender, EventArgs e)
343 //Save our connect on startup setting
344 Properties.Settings.Default.DisplayConnectOnStartup = checkBoxConnectOnStartup.Checked;
345 Properties.Settings.Default.Save();
348 private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
350 //Save our reverse screen setting
351 Properties.Settings.Default.DisplayReverseScreen = checkBoxReverseScreen.Checked;
352 Properties.Settings.Default.Save();
355 private void MainForm_Resize(object sender, EventArgs e)
357 if (WindowState == FormWindowState.Minimized)
360 //iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
361 iCreateBitmap = true;
365 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
371 public void StartServer()
373 iServiceHost = new ServiceHost
375 typeof(DisplayServer),
376 new Uri[] { new Uri("net.tcp://localhost:8001/") }
379 iServiceHost.AddServiceEndpoint(typeof(IDisplayService), new NetTcpBinding(SecurityMode.None,true), "DisplayService");
383 public void StopServer()
385 if (iClients.Count > 0 && !iClosing)
389 BroadcastCloseEvent();
393 if (MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
395 iClosing = false; //We make sure we force close if asked twice
400 //We removed that as it often lags for some reason
401 //iServiceHost.Close();
405 public void BroadcastCloseEvent()
407 Trace.TraceInformation("BroadcastCloseEvent - start");
409 var inactiveClients = new List<string>();
410 foreach (var client in iClients)
412 //if (client.Key != eventData.ClientName)
416 Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
417 client.Value.Callback.OnCloseOrder(/*eventData*/);
421 inactiveClients.Add(client.Key);
426 if (inactiveClients.Count > 0)
428 foreach (var client in inactiveClients)
430 iClients.Remove(client);
431 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(client, false)[0]);
436 private void buttonStartClient_Click(object sender, EventArgs e)
438 Thread clientThread = new Thread(SharpDisplayClient.Program.Main);
439 clientThread.Start();
443 private void buttonSuspend_Click(object sender, EventArgs e)
445 timer.Enabled = !timer.Enabled;
448 buttonSuspend.Text = "Suspend";
452 buttonSuspend.Text = "Pause";
456 private void buttonCloseClients_Click(object sender, EventArgs e)
458 BroadcastCloseEvent();
461 private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
466 //Delegates are used for our thread safe method
467 public delegate void AddClientDelegate(string aSessionId, IDisplayServiceCallback aCallback);
468 public delegate void RemoveClientDelegate(string aSessionId);
469 public delegate void SetTextDelegate(string SessionId, int aLineIndex, string aText);
470 public delegate void SetTextsDelegate(string SessionId, System.Collections.Generic.IList<string> aTexts);
471 public delegate void SetClientNameDelegate(string aSessionId, string aName);
477 /// <param name="aSessionId"></param>
478 /// <param name="aCallback"></param>
479 public void AddClientThreadSafe(string aSessionId, IDisplayServiceCallback aCallback)
481 if (this.InvokeRequired)
483 //Not in the proper thread, invoke ourselves
484 AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
485 this.Invoke(d, new object[] { aSessionId, aCallback });
489 //We are in the proper thread
490 //Add this session to our collection of clients
491 ClientData newClient = new ClientData(aSessionId, aCallback);
492 Program.iMainForm.iClients.Add(aSessionId, newClient);
493 //Add this session to our UI
494 UpdateClientTreeViewNode(newClient);
501 /// <param name="aSessionId"></param>
502 public void RemoveClientThreadSafe(string aSessionId)
504 if (this.InvokeRequired)
506 //Not in the proper thread, invoke ourselves
507 RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
508 this.Invoke(d, new object[] { aSessionId });
512 //We are in the proper thread
513 //Remove this session from both client collection and UI tree view
514 if (Program.iMainForm.iClients.Keys.Contains(aSessionId))
516 Program.iMainForm.iClients.Remove(aSessionId);
517 Program.iMainForm.treeViewClients.Nodes.Remove(Program.iMainForm.treeViewClients.Nodes.Find(aSessionId, false)[0]);
520 if (iClosing && iClients.Count == 0)
522 //We were closing our form
523 //All clients are now closed
524 //Just resume our close operation
534 /// <param name="aLineIndex"></param>
535 /// <param name="aText"></param>
536 public void SetTextThreadSafe(string aSessionId, int aLineIndex, string aText)
538 if (this.InvokeRequired)
540 //Not in the proper thread, invoke ourselves
541 SetTextDelegate d = new SetTextDelegate(SetTextThreadSafe);
542 this.Invoke(d, new object[] { aSessionId, aLineIndex, aText });
546 ClientData client = iClients[aSessionId];
549 //Make sure all our texts are in place
550 while (client.Texts.Count < (aLineIndex + 1))
552 client.Texts.Add("");
554 client.Texts[aLineIndex] = aText;
556 //We are in the proper thread
557 //Only support two lines for now
560 marqueeLabelTop.Text = aText;
562 else if (aLineIndex == 1)
564 marqueeLabelBottom.Text = aText;
568 UpdateClientTreeViewNode(client);
576 /// <param name="aTexts"></param>
577 public void SetTextsThreadSafe(string aSessionId, System.Collections.Generic.IList<string> aTexts)
579 if (this.InvokeRequired)
581 //Not in the proper thread, invoke ourselves
582 SetTextsDelegate d = new SetTextsDelegate(SetTextsThreadSafe);
583 this.Invoke(d, new object[] { aSessionId, aTexts });
587 ClientData client = iClients[aSessionId];
590 //Populate our client with the given texts
592 foreach (string text in aTexts)
594 if (client.Texts.Count < (j + 1))
596 client.Texts.Add(text);
600 client.Texts[j]=text;
604 //We are in the proper thread
605 //Only support two lines for now
606 for (int i = 0; i < aTexts.Count; i++)
610 marqueeLabelTop.Text = aTexts[i];
614 marqueeLabelBottom.Text = aTexts[i];
619 UpdateClientTreeViewNode(client);
628 /// <param name="aSessionId"></param>
629 /// <param name="aName"></param>
630 public void SetClientNameThreadSafe(string aSessionId, string aName)
632 if (this.InvokeRequired)
634 //Not in the proper thread, invoke ourselves
635 SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
636 this.Invoke(d, new object[] { aSessionId, aName });
640 //We are in the proper thread
642 ClientData client = iClients[aSessionId];
647 //Update our tree-view
648 UpdateClientTreeViewNode(client);
656 /// <param name="aClient"></param>
657 private void UpdateClientTreeViewNode(ClientData aClient)
664 TreeNode node = null;
665 //Check that our client node already exists
666 //Get our client root node using its key which is our session ID
667 TreeNode[] nodes = treeViewClients.Nodes.Find(aClient.SessionId, false);
670 //We already have a node for that client
672 //Clear children as we are going to recreate them below
677 //Client node does not exists create a new one
678 treeViewClients.Nodes.Add(aClient.SessionId, aClient.SessionId);
679 node = treeViewClients.Nodes.Find(aClient.SessionId, false)[0];
685 if (aClient.Name != "")
687 //We have a name, us it as text for our root node
688 node.Text = aClient.Name;
689 //Add a child with SessionId
690 node.Nodes.Add(new TreeNode(aClient.SessionId));
694 //No name, use session ID instead
695 node.Text = aClient.SessionId;
698 if (aClient.Texts.Count > 0)
700 //Create root node for our texts
701 TreeNode textsRoot = new TreeNode("Text");
702 node.Nodes.Add(textsRoot);
703 //For each text add a new entry
704 foreach (string text in aClient.Texts)
706 textsRoot.Nodes.Add(new TreeNode(text));
718 /// A UI thread copy of a client relevant data.
719 /// Keeping this copy in the UI thread helps us deal with threading issues.
721 public class ClientData
723 public ClientData(string aSessionId, IDisplayServiceCallback aCallback)
725 SessionId = aSessionId;
727 Texts = new List<string>();
728 Callback = aCallback;
731 public string SessionId { get; set; }
732 public string Name { get; set; }
733 public List<string> Texts { get; set; }
734 public IDisplayServiceCallback Callback { get; set; }