2 // Copyright (C) 2014-2015 Stéphane Lenclud.
4 // This file is part of SharpDisplayManager.
6 // SharpDisplayManager is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // (at your option) any later version.
11 // SharpDisplayManager is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with SharpDisplayManager. If not, see <http://www.gnu.org/licenses/>.
21 using System.Collections.Generic;
22 using System.ComponentModel;
27 using System.Threading.Tasks;
28 using System.Windows.Forms;
30 using CodeProject.Dialog;
31 using System.Drawing.Imaging;
32 using System.ServiceModel;
33 using System.Threading;
34 using System.Diagnostics;
35 using System.Deployment.Application;
36 using System.Reflection;
38 using NAudio.CoreAudioApi;
39 using NAudio.CoreAudioApi.Interfaces;
40 using System.Runtime.InteropServices;
44 using SharpDisplayClient;
46 using MiniDisplayInterop;
47 using SharpLib.Display;
49 namespace SharpDisplayManager
52 public delegate uint ColorProcessingDelegate(int aX, int aY, uint aPixel);
53 public delegate int CoordinateTranslationDelegate(System.Drawing.Bitmap aBmp, int aInt);
54 //Delegates are used for our thread safe method
55 public delegate void AddClientDelegate(string aSessionId, ICallback aCallback);
56 public delegate void RemoveClientDelegate(string aSessionId);
57 public delegate void SetFieldDelegate(string SessionId, DataField aField);
58 public delegate void SetFieldsDelegate(string SessionId, System.Collections.Generic.IList<DataField> aFields);
59 public delegate void SetLayoutDelegate(string SessionId, TableLayout aLayout);
60 public delegate void SetClientNameDelegate(string aSessionId, string aName);
61 public delegate void SetClientPriorityDelegate(string aSessionId, uint aPriority);
62 public delegate void PlainUpdateDelegate();
63 public delegate void WndProcDelegate(ref Message aMessage);
66 /// Our Display manager main form
68 [System.ComponentModel.DesignerCategory("Form")]
69 public partial class MainForm : MainFormHid, IMMNotificationClient
71 DateTime LastTickTime;
73 System.Drawing.Bitmap iBmp;
74 bool iCreateBitmap; //Workaround render to bitmap issues when minimized
75 ServiceHost iServiceHost;
76 // Our collection of clients sorted by session id.
77 public Dictionary<string, ClientData> iClients;
78 // The name of the client which informations are currently displayed.
79 public string iCurrentClientSessionId;
80 ClientData iCurrentClientData;
84 public bool iSkipFrameRendering;
85 //Function pointer for pixel color filtering
86 ColorProcessingDelegate iColorFx;
87 //Function pointer for pixel X coordinate intercept
88 CoordinateTranslationDelegate iScreenX;
89 //Function pointer for pixel Y coordinate intercept
90 CoordinateTranslationDelegate iScreenY;
92 private MMDeviceEnumerator iMultiMediaDeviceEnumerator;
93 private MMDevice iMultiMediaDevice;
95 private NetworkManager iNetworkManager;
98 /// CEC - Consumer Electronic Control.
99 /// Notably used to turn TV on and off as Windows broadcast monitor on and off notifications.
101 private ConsumerElectronicControl iCecManager;
104 /// Manage run when Windows startup option
106 private StartupManager iStartupManager;
109 /// System notification icon used to hide our application from the task bar.
111 private SharpLib.Notification.Control iNotifyIcon;
114 /// System recording notification icon.
116 private SharpLib.Notification.Control iRecordingNotification;
121 RichTextBoxTextWriter iWriter;
125 /// Allow user to receive window messages;
127 public event WndProcDelegate OnWndProc;
131 iSkipFrameRendering = false;
133 iCurrentClientSessionId = "";
134 iCurrentClientData = null;
135 LastTickTime = DateTime.Now;
136 //Instantiate our display and register for events notifications
137 iDisplay = new Display();
138 iDisplay.OnOpened += OnDisplayOpened;
139 iDisplay.OnClosed += OnDisplayClosed;
141 iClients = new Dictionary<string, ClientData>();
142 iStartupManager = new StartupManager();
143 iNotifyIcon = new SharpLib.Notification.Control();
144 iRecordingNotification = new SharpLib.Notification.Control();
146 //Have our designer initialize its controls
147 InitializeComponent();
149 //Redirect console output
150 iWriter = new RichTextBoxTextWriter(richTextBoxLogs);
151 Console.SetOut(iWriter);
153 //Populate device types
154 PopulateDeviceTypes();
156 //Populate optical drives
157 PopulateOpticalDrives();
159 //Initial status update
162 //We have a bug when drawing minimized and reusing our bitmap
163 //Though I could not reproduce it on Windows 10
164 iBmp = new System.Drawing.Bitmap(iTableLayoutPanel.Width, iTableLayoutPanel.Height, PixelFormat.Format32bppArgb);
165 iCreateBitmap = false;
167 //Minimize our window if desired
168 if (Properties.Settings.Default.StartMinimized)
170 WindowState = FormWindowState.Minimized;
178 /// <param name="sender"></param>
179 /// <param name="e"></param>
180 private void MainForm_Load(object sender, EventArgs e)
182 //Check if we are running a Click Once deployed application
183 if (ApplicationDeployment.IsNetworkDeployed)
185 //This is a proper Click Once installation, fetch and show our version number
186 this.Text += " - v" + ApplicationDeployment.CurrentDeployment.CurrentVersion;
190 //Not a proper Click Once installation, assuming development build then
191 this.Text += " - development";
195 iMultiMediaDeviceEnumerator = new MMDeviceEnumerator();
196 iMultiMediaDeviceEnumerator.RegisterEndpointNotificationCallback(this);
197 UpdateAudioDeviceAndMasterVolumeThreadSafe();
200 iNetworkManager = new NetworkManager();
201 iNetworkManager.OnConnectivityChanged += OnConnectivityChanged;
202 UpdateNetworkStatus();
205 iCecManager = new ConsumerElectronicControl();
206 OnWndProc += iCecManager.OnWndProc;
210 //Setup notification icon
213 //Setup recording notification
214 SetupRecordingNotification();
216 // To make sure start up with minimize to tray works
217 if (WindowState == FormWindowState.Minimized && Properties.Settings.Default.MinimizeToTray)
223 //When not debugging we want the screen to be empty until a client takes over
226 //When developing we want at least one client for testing
227 StartNewClient("abcdefghijklmnopqrst-0123456789","ABCDEFGHIJKLMNOPQRST-0123456789");
230 //Open display connection on start-up if needed
231 if (Properties.Settings.Default.DisplayConnectOnStartup)
233 OpenDisplayConnection();
236 //Start our server so that we can get client requests
239 //Register for HID events
240 RegisterHidDevices();
242 //Start Idle client if needed
243 if (Properties.Settings.Default.StartIdleClient)
250 /// Called when our display is opened.
252 /// <param name="aDisplay"></param>
253 private void OnDisplayOpened(Display aDisplay)
255 //Make sure we resume frame rendering
256 iSkipFrameRendering = false;
258 //Set our screen size now that our display is connected
259 //Our panelDisplay is the container of our tableLayoutPanel
260 //tableLayoutPanel will resize itself to fit the client size of our panelDisplay
261 //panelDisplay needs an extra 2 pixels for borders on each sides
262 //tableLayoutPanel will eventually be the exact size of our display
263 Size size = new Size(iDisplay.WidthInPixels() + 2, iDisplay.HeightInPixels() + 2);
264 panelDisplay.Size = size;
266 //Our display was just opened, update our UI
268 //Initiate asynchronous request
269 iDisplay.RequestFirmwareRevision();
272 UpdateMasterVolumeThreadSafe();
274 UpdateNetworkStatus();
277 //Testing icon in debug, no arm done if icon not supported
278 //iDisplay.SetIconStatus(Display.TMiniDisplayIconType.EMiniDisplayIconRecording, 0, 1);
279 //iDisplay.SetAllIconsStatus(2);
285 /// Called when our display is closed.
287 /// <param name="aDisplay"></param>
288 private void OnDisplayClosed(Display aDisplay)
290 //Our display was just closed, update our UI consequently
294 public void OnConnectivityChanged(NetworkManager aNetwork, NLM_CONNECTIVITY newConnectivity)
296 //Update network status
297 UpdateNetworkStatus();
301 /// Update our Network Status
303 private void UpdateNetworkStatus()
305 if (iDisplay.IsOpen())
307 iDisplay.SetIconOnOff(MiniDisplay.IconType.Internet, iNetworkManager.NetworkListManager.IsConnectedToInternet);
308 iDisplay.SetIconOnOff(MiniDisplay.IconType.NetworkSignal, iNetworkManager.NetworkListManager.IsConnected);
313 int iLastNetworkIconIndex = 0;
314 int iUpdateCountSinceLastNetworkAnimation = 0;
319 private void UpdateNetworkSignal(DateTime aLastTickTime, DateTime aNewTickTime)
321 iUpdateCountSinceLastNetworkAnimation++;
322 iUpdateCountSinceLastNetworkAnimation = iUpdateCountSinceLastNetworkAnimation % 4;
324 if (iDisplay.IsOpen() && iNetworkManager.NetworkListManager.IsConnected && iUpdateCountSinceLastNetworkAnimation==0)
326 int iconCount = iDisplay.IconCount(MiniDisplay.IconType.NetworkSignal);
329 //Prevents div by zero and other undefined behavior
332 iLastNetworkIconIndex++;
333 iLastNetworkIconIndex = iLastNetworkIconIndex % (iconCount*2);
334 for (int i=0;i<iconCount;i++)
336 if (i < iLastNetworkIconIndex && !(i == 0 && iLastNetworkIconIndex > 3) && !(i == 1 && iLastNetworkIconIndex > 4))
338 iDisplay.SetIconOn(MiniDisplay.IconType.NetworkSignal, i);
342 iDisplay.SetIconOff(MiniDisplay.IconType.NetworkSignal, i);
351 /// Receive volume change notification and reflect changes on our slider.
353 /// <param name="data"></param>
354 public void OnVolumeNotificationThreadSafe(AudioVolumeNotificationData data)
356 UpdateMasterVolumeThreadSafe();
360 /// Update master volume when user moves our slider.
362 /// <param name="sender"></param>
363 /// <param name="e"></param>
364 private void trackBarMasterVolume_Scroll(object sender, EventArgs e)
366 //Just like Windows Volume Mixer we unmute if the volume is adjusted
367 iMultiMediaDevice.AudioEndpointVolume.Mute = false;
368 //Set volume level according to our volume slider new position
369 iMultiMediaDevice.AudioEndpointVolume.MasterVolumeLevelScalar = trackBarMasterVolume.Value / 100.0f;
374 /// Mute check box changed.
376 /// <param name="sender"></param>
377 /// <param name="e"></param>
378 private void checkBoxMute_CheckedChanged(object sender, EventArgs e)
380 iMultiMediaDevice.AudioEndpointVolume.Mute = checkBoxMute.Checked;
384 /// Device State Changed
386 public void OnDeviceStateChanged([MarshalAs(UnmanagedType.LPWStr)] string deviceId, [MarshalAs(UnmanagedType.I4)] DeviceState newState){}
391 public void OnDeviceAdded([MarshalAs(UnmanagedType.LPWStr)] string pwstrDeviceId) { }
396 public void OnDeviceRemoved([MarshalAs(UnmanagedType.LPWStr)] string deviceId) { }
399 /// Default Device Changed
401 public void OnDefaultDeviceChanged(DataFlow flow, Role role, [MarshalAs(UnmanagedType.LPWStr)] string defaultDeviceId)
403 if (role == Role.Multimedia && flow == DataFlow.Render)
405 UpdateAudioDeviceAndMasterVolumeThreadSafe();
410 /// Property Value Changed
412 /// <param name="pwstrDeviceId"></param>
413 /// <param name="key"></param>
414 public void OnPropertyValueChanged([MarshalAs(UnmanagedType.LPWStr)] string pwstrDeviceId, PropertyKey key){}
420 /// Update master volume indicators based our current system states.
421 /// This typically includes volume levels and mute status.
423 private void UpdateMasterVolumeThreadSafe()
425 if (this.InvokeRequired)
427 //Not in the proper thread, invoke ourselves
428 PlainUpdateDelegate d = new PlainUpdateDelegate(UpdateMasterVolumeThreadSafe);
429 this.Invoke(d, new object[] { });
433 //Update volume slider
434 float volumeLevelScalar = iMultiMediaDevice.AudioEndpointVolume.MasterVolumeLevelScalar;
435 trackBarMasterVolume.Value = Convert.ToInt32(volumeLevelScalar * 100);
436 //Update mute checkbox
437 checkBoxMute.Checked = iMultiMediaDevice.AudioEndpointVolume.Mute;
439 //If our display connection is open we need to update its icons
440 if (iDisplay.IsOpen())
442 //First take care our our volume level icons
443 int volumeIconCount = iDisplay.IconCount(MiniDisplay.IconType.Volume);
444 if (volumeIconCount > 0)
446 //Compute current volume level from system level and the number of segments in our display volume bar.
447 //That tells us how many segments in our volume bar needs to be turned on.
448 float currentVolume = volumeLevelScalar * volumeIconCount;
449 int segmentOnCount = Convert.ToInt32(currentVolume);
450 //Check if our segment count was rounded up, this will later be used for half brightness segment
451 bool roundedUp = segmentOnCount > currentVolume;
453 for (int i = 0; i < volumeIconCount; i++)
455 if (i < segmentOnCount)
457 //If we are dealing with our last segment and our segment count was rounded up then we will use half brightness.
458 if (i == segmentOnCount - 1 && roundedUp)
461 iDisplay.SetIconStatus(MiniDisplay.IconType.Volume, i, (iDisplay.IconStatusCount(MiniDisplay.IconType.Volume) - 1) / 2);
466 iDisplay.SetIconStatus(MiniDisplay.IconType.Volume, i, iDisplay.IconStatusCount(MiniDisplay.IconType.Volume) - 1);
471 iDisplay.SetIconStatus(MiniDisplay.IconType.Volume, i, 0);
476 //Take care of our mute icon
477 iDisplay.SetIconOnOff(MiniDisplay.IconType.Mute, iMultiMediaDevice.AudioEndpointVolume.Mute);
485 private void UpdateAudioDeviceAndMasterVolumeThreadSafe()
487 if (this.InvokeRequired)
489 //Not in the proper thread, invoke ourselves
490 PlainUpdateDelegate d = new PlainUpdateDelegate(UpdateAudioDeviceAndMasterVolumeThreadSafe);
491 this.Invoke(d, new object[] { });
495 //We are in the correct thread just go ahead.
498 //Get our master volume
499 iMultiMediaDevice = iMultiMediaDeviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
501 labelDefaultAudioDevice.Text = iMultiMediaDevice.FriendlyName;
503 //Show our volume in our track bar
504 UpdateMasterVolumeThreadSafe();
506 //Register to get volume modifications
507 iMultiMediaDevice.AudioEndpointVolume.OnVolumeNotification += OnVolumeNotificationThreadSafe;
509 trackBarMasterVolume.Enabled = true;
513 Debug.WriteLine("Exception thrown in UpdateAudioDeviceAndMasterVolume");
514 Debug.WriteLine(ex.ToString());
515 //Something went wrong S/PDIF device ca throw exception I guess
516 trackBarMasterVolume.Enabled = false;
523 private void PopulateDeviceTypes()
525 int count = Display.TypeCount();
527 for (int i = 0; i < count; i++)
529 comboBoxDisplayType.Items.Add(Display.TypeName((MiniDisplay.Type)i));
536 private void PopulateOpticalDrives()
538 //Reset our list of drives
539 comboBoxOpticalDrives.Items.Clear();
540 comboBoxOpticalDrives.Items.Add("None");
542 //Go through each drives on our system and collected the optical ones in our list
543 DriveInfo[] allDrives = DriveInfo.GetDrives();
544 foreach (DriveInfo d in allDrives)
546 Debug.WriteLine("Drive " + d.Name);
547 Debug.WriteLine(" Drive type: {0}", d.DriveType);
549 if (d.DriveType==DriveType.CDRom)
551 //This is an optical drive, add it now
552 comboBoxOpticalDrives.Items.Add(d.Name.Substring(0,2));
560 /// <returns></returns>
561 public string OpticalDriveToEject()
563 return comboBoxOpticalDrives.SelectedItem.ToString();
571 private void SetupTrayIcon()
573 iNotifyIcon.Icon = GetIcon("vfd.ico");
574 iNotifyIcon.Text = "Sharp Display Manager";
575 iNotifyIcon.Visible = true;
577 //Double click toggles visibility - typically brings up the application
578 iNotifyIcon.DoubleClick += delegate(object obj, EventArgs args)
583 //Adding a context menu, useful to be able to exit the application
584 ContextMenu contextMenu = new ContextMenu();
585 //Context menu item to toggle visibility
586 MenuItem hideShowItem = new MenuItem("Hide/Show");
587 hideShowItem.Click += delegate(object obj, EventArgs args)
591 contextMenu.MenuItems.Add(hideShowItem);
593 //Context menu item separator
594 contextMenu.MenuItems.Add(new MenuItem("-"));
596 //Context menu exit item
597 MenuItem exitItem = new MenuItem("Exit");
598 exitItem.Click += delegate(object obj, EventArgs args)
602 contextMenu.MenuItems.Add(exitItem);
604 iNotifyIcon.ContextMenu = contextMenu;
610 private void SetupRecordingNotification()
612 iRecordingNotification.Icon = GetIcon("record.ico");
613 iRecordingNotification.Text = "No recording";
614 iRecordingNotification.Visible = false;
618 /// Access icons from embedded resources.
620 /// <param name="aName"></param>
621 /// <returns></returns>
622 public static Icon GetIcon(string aName)
624 string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames();
625 foreach (string name in names)
627 //Find a resource name that ends with the given name
628 if (name.EndsWith(aName))
630 using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))
632 return new Icon(stream);
642 /// Set our current client.
643 /// This will take care of applying our client layout and set data fields.
645 /// <param name="aSessionId"></param>
646 void SetCurrentClient(string aSessionId, bool aForce=false)
648 if (aSessionId == iCurrentClientSessionId)
650 //Given client is already the current one.
651 //Don't bother changing anything then.
655 ClientData requestedClientData = iClients[aSessionId];
657 //Check when was the last time we switched to that client
658 if (iCurrentClientData != null)
660 //Do not switch client if priority of current client is higher
661 if (!aForce && requestedClientData.Priority < iCurrentClientData.Priority)
667 double lastSwitchToClientSecondsAgo = (DateTime.Now - iCurrentClientData.LastSwitchTime).TotalSeconds;
668 //TODO: put that hard coded value as a client property
669 //Clients should be able to define how often they can be interrupted
670 //Thus a background client can set this to zero allowing any other client to interrupt at any time
671 //We could also compute this delay by looking at the requests frequencies?
673 requestedClientData.Priority == iCurrentClientData.Priority && //Time sharing is only if clients have the same priority
674 (lastSwitchToClientSecondsAgo < 30)) //Make sure a client is on for at least 30 seconds
676 //Don't switch clients too often
681 //Set current client ID.
682 iCurrentClientSessionId = aSessionId;
683 //Set the time we last switched to that client
684 iClients[aSessionId].LastSwitchTime = DateTime.Now;
685 //Fetch and set current client data.
686 iCurrentClientData = requestedClientData;
687 //Apply layout and set data fields.
688 UpdateTableLayoutPanel(iCurrentClientData);
691 private void buttonFont_Click(object sender, EventArgs e)
693 //fontDialog.ShowColor = true;
694 //fontDialog.ShowApply = true;
695 fontDialog.ShowEffects = true;
696 fontDialog.Font = cds.Font;
698 fontDialog.FixedPitchOnly = checkBoxFixedPitchFontOnly.Checked;
700 //fontDialog.ShowHelp = true;
702 //fontDlg.MaxSize = 40;
703 //fontDlg.MinSize = 22;
705 //fontDialog.Parent = this;
706 //fontDialog.StartPosition = FormStartPosition.CenterParent;
708 //DlgBox.ShowDialog(fontDialog);
710 //if (fontDialog.ShowDialog(this) != DialogResult.Cancel)
711 if (DlgBox.ShowDialog(fontDialog) != DialogResult.Cancel)
713 //Set the fonts to all our labels in our layout
714 foreach (Control ctrl in iTableLayoutPanel.Controls)
716 if (ctrl is MarqueeLabel)
718 ((MarqueeLabel)ctrl).Font = fontDialog.Font;
723 cds.Font = fontDialog.Font;
724 Properties.Settings.Default.Save();
733 void CheckFontHeight()
735 //Show font height and width
736 labelFontHeight.Text = "Font height: " + cds.Font.Height;
737 float charWidth = IsFixedWidth(cds.Font);
738 if (charWidth == 0.0f)
740 labelFontWidth.Visible = false;
744 labelFontWidth.Visible = true;
745 labelFontWidth.Text = "Font width: " + charWidth;
748 MarqueeLabel label = null;
749 //Get the first label control we can find
750 foreach (Control ctrl in iTableLayoutPanel.Controls)
752 if (ctrl is MarqueeLabel)
754 label = (MarqueeLabel)ctrl;
759 //Now check font height and show a warning if needed.
760 if (label != null && label.Font.Height > label.Height)
762 labelWarning.Text = "WARNING: Selected font is too height by " + (label.Font.Height - label.Height) + " pixels!";
763 labelWarning.Visible = true;
767 labelWarning.Visible = false;
772 private void buttonCapture_Click(object sender, EventArgs e)
774 System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(iTableLayoutPanel.Width, iTableLayoutPanel.Height);
775 iTableLayoutPanel.DrawToBitmap(bmp, iTableLayoutPanel.ClientRectangle);
776 //Bitmap bmpToSave = new Bitmap(bmp);
777 bmp.Save("D:\\capture.png");
779 ((MarqueeLabel)iTableLayoutPanel.Controls[0]).Text = "Captured";
782 string outputFileName = "d:\\capture.png";
783 using (MemoryStream memory = new MemoryStream())
785 using (FileStream fs = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
787 bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
788 byte[] bytes = memory.ToArray();
789 fs.Write(bytes, 0, bytes.Length);
796 private void CheckForRequestResults()
798 if (iDisplay.IsRequestPending())
800 switch (iDisplay.AttemptRequestCompletion())
802 case MiniDisplay.Request.FirmwareRevision:
803 toolStripStatusLabelConnect.Text += " v" + iDisplay.FirmwareRevision();
804 //Issue next request then
805 iDisplay.RequestPowerSupplyStatus();
808 case MiniDisplay.Request.PowerSupplyStatus:
809 if (iDisplay.PowerSupplyStatus())
811 toolStripStatusLabelPower.Text = "ON";
815 toolStripStatusLabelPower.Text = "OFF";
817 //Issue next request then
818 iDisplay.RequestDeviceId();
821 case MiniDisplay.Request.DeviceId:
822 toolStripStatusLabelConnect.Text += " - " + iDisplay.DeviceId();
823 //No more request to issue
829 public static uint ColorWhiteIsOn(int aX, int aY, uint aPixel)
831 if ((aPixel & 0x00FFFFFF) == 0x00FFFFFF)
838 public static uint ColorUntouched(int aX, int aY, uint aPixel)
843 public static uint ColorInversed(int aX, int aY, uint aPixel)
848 public static uint ColorChessboard(int aX, int aY, uint aPixel)
850 if ((aX % 2 == 0) && (aY % 2 == 0))
854 else if ((aX % 2 != 0) && (aY % 2 != 0))
862 public static int ScreenReversedX(System.Drawing.Bitmap aBmp, int aX)
864 return aBmp.Width - aX - 1;
867 public int ScreenReversedY(System.Drawing.Bitmap aBmp, int aY)
869 return iBmp.Height - aY - 1;
872 public int ScreenX(System.Drawing.Bitmap aBmp, int aX)
877 public int ScreenY(System.Drawing.Bitmap aBmp, int aY)
883 /// Select proper pixel delegates according to our current settings.
885 private void SetupPixelDelegates()
887 //Select our pixel processing routine
888 if (cds.InverseColors)
890 //iColorFx = ColorChessboard;
891 iColorFx = ColorInversed;
895 iColorFx = ColorWhiteIsOn;
898 //Select proper coordinate translation functions
899 //We used delegate/function pointer to support reverse screen without doing an extra test on each pixels
900 if (cds.ReverseScreen)
902 iScreenX = ScreenReversedX;
903 iScreenY = ScreenReversedY;
913 //This is our timer tick responsible to perform our render
914 private void timer_Tick(object sender, EventArgs e)
916 //Update our animations
917 DateTime NewTickTime = DateTime.Now;
919 UpdateNetworkSignal(LastTickTime, NewTickTime);
921 //Update animation for all our marquees
922 foreach (Control ctrl in iTableLayoutPanel.Controls)
924 if (ctrl is MarqueeLabel)
926 ((MarqueeLabel)ctrl).UpdateAnimation(LastTickTime, NewTickTime);
931 if (iDisplay.IsOpen())
933 CheckForRequestResults();
935 //Check if frame rendering is needed
936 //Typically used when showing clock
937 if (!iSkipFrameRendering)
942 iBmp = new System.Drawing.Bitmap(iTableLayoutPanel.Width, iTableLayoutPanel.Height, PixelFormat.Format32bppArgb);
943 iCreateBitmap = false;
945 iTableLayoutPanel.DrawToBitmap(iBmp, iTableLayoutPanel.ClientRectangle);
946 //iBmp.Save("D:\\capture.png");
948 //Send it to our display
949 for (int i = 0; i < iBmp.Width; i++)
951 for (int j = 0; j < iBmp.Height; j++)
955 //Get our processed pixel coordinates
956 int x = iScreenX(iBmp, i);
957 int y = iScreenY(iBmp, j);
959 uint color = (uint)iBmp.GetPixel(i, j).ToArgb();
960 //Apply color effects
961 color = iColorFx(x, y, color);
963 iDisplay.SetPixel(x, y, color);
968 iDisplay.SwapBuffers();
972 //Compute instant FPS
973 toolStripStatusLabelFps.Text = (1.0/NewTickTime.Subtract(LastTickTime).TotalSeconds).ToString("F0") + " / " + (1000/timer.Interval).ToString() + " FPS";
975 LastTickTime = NewTickTime;
980 /// Attempt to establish connection with our display hardware.
982 private void OpenDisplayConnection()
984 CloseDisplayConnection();
986 if (!iDisplay.Open((MiniDisplay.Type)cds.DisplayType))
989 toolStripStatusLabelConnect.Text = "Connection error";
993 private void CloseDisplayConnection()
995 //Status will be updated upon receiving the closed event
997 if (iDisplay == null || !iDisplay.IsOpen())
1002 //Do not clear if we gave up on rendering already.
1003 //This means we will keep on displaying clock on MDM166AA for instance.
1004 if (!iSkipFrameRendering)
1007 iDisplay.SwapBuffers();
1010 iDisplay.SetAllIconsStatus(0); //Turn off all icons
1014 private void buttonOpen_Click(object sender, EventArgs e)
1016 OpenDisplayConnection();
1019 private void buttonClose_Click(object sender, EventArgs e)
1021 CloseDisplayConnection();
1024 private void buttonClear_Click(object sender, EventArgs e)
1027 iDisplay.SwapBuffers();
1030 private void buttonFill_Click(object sender, EventArgs e)
1033 iDisplay.SwapBuffers();
1036 private void trackBarBrightness_Scroll(object sender, EventArgs e)
1038 cds.Brightness = trackBarBrightness.Value;
1039 Properties.Settings.Default.Save();
1040 iDisplay.SetBrightness(trackBarBrightness.Value);
1046 /// CDS stands for Current Display Settings
1048 private DisplaySettings cds
1052 DisplaysSettings settings = Properties.Settings.Default.DisplaysSettings;
1053 if (settings == null)
1055 settings = new DisplaysSettings();
1057 Properties.Settings.Default.DisplaysSettings = settings;
1060 //Make sure all our settings have been created
1061 while (settings.Displays.Count <= Properties.Settings.Default.CurrentDisplayIndex)
1063 settings.Displays.Add(new DisplaySettings());
1066 DisplaySettings displaySettings = settings.Displays[Properties.Settings.Default.CurrentDisplayIndex];
1067 return displaySettings;
1072 /// Check if the given font has a fixed character pitch.
1074 /// <param name="ft"></param>
1075 /// <returns>0.0f if this is not a monospace font, otherwise returns the character width.</returns>
1076 public float IsFixedWidth(Font ft)
1078 Graphics g = CreateGraphics();
1079 char[] charSizes = new char[] { 'i', 'a', 'Z', '%', '#', 'a', 'B', 'l', 'm', ',', '.' };
1080 float charWidth = g.MeasureString("I", ft, Int32.MaxValue, StringFormat.GenericTypographic).Width;
1082 bool fixedWidth = true;
1084 foreach (char c in charSizes)
1085 if (g.MeasureString(c.ToString(), ft, Int32.MaxValue, StringFormat.GenericTypographic).Width != charWidth)
1097 /// Synchronize UI with settings
1099 private void UpdateStatus()
1102 checkBoxShowBorders.Checked = cds.ShowBorders;
1103 iTableLayoutPanel.CellBorderStyle = (cds.ShowBorders ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
1105 //Set the proper font to each of our labels
1106 foreach (MarqueeLabel ctrl in iTableLayoutPanel.Controls)
1108 ctrl.Font = cds.Font;
1112 //Check if "run on Windows startup" is enabled
1113 checkBoxAutoStart.Checked = iStartupManager.Startup;
1115 checkBoxConnectOnStartup.Checked = Properties.Settings.Default.DisplayConnectOnStartup;
1116 checkBoxMinimizeToTray.Checked = Properties.Settings.Default.MinimizeToTray;
1117 checkBoxStartMinimized.Checked = Properties.Settings.Default.StartMinimized;
1118 iCheckBoxStartIdleClient.Checked = Properties.Settings.Default.StartIdleClient;
1119 labelStartFileName.Text = Properties.Settings.Default.StartFileName;
1122 //Try find our drive in our drive list
1123 int opticalDriveItemIndex=0;
1124 bool driveNotFound = true;
1125 string opticalDriveToEject=Properties.Settings.Default.OpticalDriveToEject;
1126 foreach (object item in comboBoxOpticalDrives.Items)
1128 if (opticalDriveToEject == item.ToString())
1130 comboBoxOpticalDrives.SelectedIndex = opticalDriveItemIndex;
1131 driveNotFound = false;
1134 opticalDriveItemIndex++;
1139 //We could not find the drive we had saved.
1140 //Select "None" then.
1141 comboBoxOpticalDrives.SelectedIndex = 0;
1145 checkBoxCecEnabled.Checked = Properties.Settings.Default.CecEnabled;
1146 checkBoxCecMonitorOn.Checked = Properties.Settings.Default.CecMonitorOn;
1147 checkBoxCecMonitorOff.Checked = Properties.Settings.Default.CecMonitorOff;
1148 comboBoxHdmiPort.SelectedIndex = Properties.Settings.Default.CecHdmiPort - 1;
1150 //Mini Display settings
1151 checkBoxReverseScreen.Checked = cds.ReverseScreen;
1152 checkBoxInverseColors.Checked = cds.InverseColors;
1153 checkBoxShowVolumeLabel.Checked = cds.ShowVolumeLabel;
1154 checkBoxScaleToFit.Checked = cds.ScaleToFit;
1155 maskedTextBoxMinFontSize.Enabled = cds.ScaleToFit;
1156 labelMinFontSize.Enabled = cds.ScaleToFit;
1157 maskedTextBoxMinFontSize.Text = cds.MinFontSize.ToString();
1158 maskedTextBoxScrollingSpeed.Text = cds.ScrollingSpeedInPixelsPerSecond.ToString();
1159 comboBoxDisplayType.SelectedIndex = cds.DisplayType;
1160 timer.Interval = cds.TimerInterval;
1161 maskedTextBoxTimerInterval.Text = cds.TimerInterval.ToString();
1162 textBoxScrollLoopSeparator.Text = cds.Separator;
1164 SetupPixelDelegates();
1166 if (iDisplay.IsOpen())
1168 //We have a display connection
1169 //Reflect that in our UI
1172 iTableLayoutPanel.Enabled = true;
1173 panelDisplay.Enabled = true;
1175 //Only setup brightness if display is open
1176 trackBarBrightness.Minimum = iDisplay.MinBrightness();
1177 trackBarBrightness.Maximum = iDisplay.MaxBrightness();
1178 if (cds.Brightness < iDisplay.MinBrightness() || cds.Brightness > iDisplay.MaxBrightness())
1180 //Brightness out of range, this can occur when using auto-detect
1181 //Use max brightness instead
1182 trackBarBrightness.Value = iDisplay.MaxBrightness();
1183 iDisplay.SetBrightness(iDisplay.MaxBrightness());
1187 trackBarBrightness.Value = cds.Brightness;
1188 iDisplay.SetBrightness(cds.Brightness);
1191 //Try compute the steps to something that makes sense
1192 trackBarBrightness.LargeChange = Math.Max(1, (iDisplay.MaxBrightness() - iDisplay.MinBrightness()) / 5);
1193 trackBarBrightness.SmallChange = 1;
1196 buttonFill.Enabled = true;
1197 buttonClear.Enabled = true;
1198 buttonOpen.Enabled = false;
1199 buttonClose.Enabled = true;
1200 trackBarBrightness.Enabled = true;
1201 toolStripStatusLabelConnect.Text = "Connected - " + iDisplay.Vendor() + " - " + iDisplay.Product();
1202 //+ " - " + iDisplay.SerialNumber();
1204 if (iDisplay.SupportPowerOnOff())
1206 buttonPowerOn.Enabled = true;
1207 buttonPowerOff.Enabled = true;
1211 buttonPowerOn.Enabled = false;
1212 buttonPowerOff.Enabled = false;
1215 if (iDisplay.SupportClock())
1217 buttonShowClock.Enabled = true;
1218 buttonHideClock.Enabled = true;
1222 buttonShowClock.Enabled = false;
1223 buttonHideClock.Enabled = false;
1227 //Check if Volume Label is supported. To date only MDM166AA supports that crap :)
1228 checkBoxShowVolumeLabel.Enabled = iDisplay.IconCount(MiniDisplay.IconType.VolumeLabel)>0;
1230 if (cds.ShowVolumeLabel)
1232 iDisplay.SetIconOn(MiniDisplay.IconType.VolumeLabel);
1236 iDisplay.SetIconOff(MiniDisplay.IconType.VolumeLabel);
1241 //Display connection not available
1242 //Reflect that in our UI
1244 //In debug start our timer even if we don't have a display connection
1247 //In production environment we don't need our timer if no display connection
1250 checkBoxShowVolumeLabel.Enabled = false;
1251 iTableLayoutPanel.Enabled = false;
1252 panelDisplay.Enabled = false;
1253 buttonFill.Enabled = false;
1254 buttonClear.Enabled = false;
1255 buttonOpen.Enabled = true;
1256 buttonClose.Enabled = false;
1257 trackBarBrightness.Enabled = false;
1258 buttonPowerOn.Enabled = false;
1259 buttonPowerOff.Enabled = false;
1260 buttonShowClock.Enabled = false;
1261 buttonHideClock.Enabled = false;
1262 toolStripStatusLabelConnect.Text = "Disconnected";
1263 toolStripStatusLabelPower.Text = "N/A";
1272 /// <param name="sender"></param>
1273 /// <param name="e"></param>
1274 private void checkBoxShowVolumeLabel_CheckedChanged(object sender, EventArgs e)
1276 cds.ShowVolumeLabel = checkBoxShowVolumeLabel.Checked;
1277 Properties.Settings.Default.Save();
1281 private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
1283 //Save our show borders setting
1284 iTableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
1285 cds.ShowBorders = checkBoxShowBorders.Checked;
1286 Properties.Settings.Default.Save();
1290 private void checkBoxConnectOnStartup_CheckedChanged(object sender, EventArgs e)
1292 //Save our connect on startup setting
1293 Properties.Settings.Default.DisplayConnectOnStartup = checkBoxConnectOnStartup.Checked;
1294 Properties.Settings.Default.Save();
1297 private void checkBoxMinimizeToTray_CheckedChanged(object sender, EventArgs e)
1299 //Save our "Minimize to tray" setting
1300 Properties.Settings.Default.MinimizeToTray = checkBoxMinimizeToTray.Checked;
1301 Properties.Settings.Default.Save();
1305 private void checkBoxStartMinimized_CheckedChanged(object sender, EventArgs e)
1307 //Save our "Start minimized" setting
1308 Properties.Settings.Default.StartMinimized = checkBoxStartMinimized.Checked;
1309 Properties.Settings.Default.Save();
1312 private void checkBoxStartIdleClient_CheckedChanged(object sender, EventArgs e)
1314 Properties.Settings.Default.StartIdleClient = iCheckBoxStartIdleClient.Checked;
1315 Properties.Settings.Default.Save();
1318 private void checkBoxAutoStart_CheckedChanged(object sender, EventArgs e)
1320 iStartupManager.Startup = checkBoxAutoStart.Checked;
1324 private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
1326 //Save our reverse screen setting
1327 cds.ReverseScreen = checkBoxReverseScreen.Checked;
1328 Properties.Settings.Default.Save();
1329 SetupPixelDelegates();
1332 private void checkBoxInverseColors_CheckedChanged(object sender, EventArgs e)
1334 //Save our inverse colors setting
1335 cds.InverseColors = checkBoxInverseColors.Checked;
1336 Properties.Settings.Default.Save();
1337 SetupPixelDelegates();
1340 private void checkBoxScaleToFit_CheckedChanged(object sender, EventArgs e)
1342 //Save our scale to fit setting
1343 cds.ScaleToFit = checkBoxScaleToFit.Checked;
1344 Properties.Settings.Default.Save();
1346 labelMinFontSize.Enabled = cds.ScaleToFit;
1347 maskedTextBoxMinFontSize.Enabled = cds.ScaleToFit;
1350 private void MainForm_Resize(object sender, EventArgs e)
1352 if (WindowState == FormWindowState.Minimized)
1354 // To workaround our empty bitmap bug on Windows 7 we need to recreate our bitmap when the application is minimized
1355 // That's apparently not needed on Windows 10 but we better leave it in place.
1356 iCreateBitmap = true;
1360 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
1363 iNetworkManager.Dispose();
1364 CloseDisplayConnection();
1366 e.Cancel = iClosing;
1369 public void StartServer()
1371 iServiceHost = new ServiceHost
1374 new Uri[] { new Uri("net.tcp://localhost:8001/") }
1377 iServiceHost.AddServiceEndpoint(typeof(IService), new NetTcpBinding(SecurityMode.None, true), "DisplayService");
1378 iServiceHost.Open();
1381 public void StopServer()
1383 if (iClients.Count > 0 && !iClosing)
1387 BroadcastCloseEvent();
1391 if (MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
1393 iClosing = false; //We make sure we force close if asked twice
1398 //We removed that as it often lags for some reason
1399 //iServiceHost.Close();
1403 public void BroadcastCloseEvent()
1405 Trace.TraceInformation("BroadcastCloseEvent - start");
1407 var inactiveClients = new List<string>();
1408 foreach (var client in iClients)
1410 //if (client.Key != eventData.ClientName)
1414 Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
1415 client.Value.Callback.OnCloseOrder(/*eventData*/);
1417 catch (Exception ex)
1419 inactiveClients.Add(client.Key);
1424 if (inactiveClients.Count > 0)
1426 foreach (var client in inactiveClients)
1428 iClients.Remove(client);
1429 Program.iMainForm.iTreeViewClients.Nodes.Remove(Program.iMainForm.iTreeViewClients.Nodes.Find(client, false)[0]);
1433 if (iClients.Count==0)
1440 /// Just remove all our fields.
1442 private void ClearLayout()
1444 iTableLayoutPanel.Controls.Clear();
1445 iTableLayoutPanel.RowStyles.Clear();
1446 iTableLayoutPanel.ColumnStyles.Clear();
1447 iCurrentClientData = null;
1451 /// Just launch a demo client.
1453 private void StartNewClient(string aTopText = "", string aBottomText = "")
1455 Thread clientThread = new Thread(SharpDisplayClient.Program.MainWithParams);
1456 SharpDisplayClient.StartParams myParams = new SharpDisplayClient.StartParams(new Point(this.Right, this.Top),aTopText,aBottomText);
1457 clientThread.Start(myParams);
1462 /// Just launch our idle client.
1464 private void StartIdleClient(string aTopText = "", string aBottomText = "")
1466 Thread clientThread = new Thread(SharpDisplayIdleClient.Program.MainWithParams);
1467 SharpDisplayIdleClient.StartParams myParams = new SharpDisplayIdleClient.StartParams(new Point(this.Right, this.Top), aTopText, aBottomText);
1468 clientThread.Start(myParams);
1473 private void buttonStartClient_Click(object sender, EventArgs e)
1478 private void buttonSuspend_Click(object sender, EventArgs e)
1483 private void StartTimer()
1485 LastTickTime = DateTime.Now; //Reset timer to prevent jump
1486 timer.Enabled = true;
1487 UpdateSuspendButton();
1490 private void StopTimer()
1492 LastTickTime = DateTime.Now; //Reset timer to prevent jump
1493 timer.Enabled = false;
1494 UpdateSuspendButton();
1497 private void ToggleTimer()
1499 LastTickTime = DateTime.Now; //Reset timer to prevent jump
1500 timer.Enabled = !timer.Enabled;
1501 UpdateSuspendButton();
1504 private void UpdateSuspendButton()
1508 buttonSuspend.Text = "Run";
1512 buttonSuspend.Text = "Pause";
1517 private void buttonCloseClients_Click(object sender, EventArgs e)
1519 BroadcastCloseEvent();
1522 private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
1524 //Root node must have at least one child
1525 if (e.Node.Nodes.Count == 0)
1530 //If the selected node is the root node of a client then switch to it
1531 string sessionId=e.Node.Nodes[0].Text; //First child of a root node is the sessionId
1532 if (iClients.ContainsKey(sessionId)) //Check that's actually what we are looking at
1534 //We have a valid session just switch to that client
1535 SetCurrentClient(sessionId,true);
1544 /// <param name="aSessionId"></param>
1545 /// <param name="aCallback"></param>
1546 public void AddClientThreadSafe(string aSessionId, ICallback aCallback)
1548 if (this.InvokeRequired)
1550 //Not in the proper thread, invoke ourselves
1551 AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
1552 this.Invoke(d, new object[] { aSessionId, aCallback });
1556 //We are in the proper thread
1557 //Add this session to our collection of clients
1558 ClientData newClient = new ClientData(aSessionId, aCallback);
1559 Program.iMainForm.iClients.Add(aSessionId, newClient);
1560 //Add this session to our UI
1561 UpdateClientTreeViewNode(newClient);
1567 /// Find the client with the highest priority if any.
1569 /// <returns>Our highest priority client or null if not a single client is connected.</returns>
1570 public ClientData FindHighestPriorityClient()
1572 ClientData highestPriorityClient = null;
1573 foreach (var client in iClients)
1575 if (highestPriorityClient == null || client.Value.Priority > highestPriorityClient.Priority)
1577 highestPriorityClient = client.Value;
1581 return highestPriorityClient;
1587 /// <param name="aSessionId"></param>
1588 public void RemoveClientThreadSafe(string aSessionId)
1590 if (this.InvokeRequired)
1592 //Not in the proper thread, invoke ourselves
1593 RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
1594 this.Invoke(d, new object[] { aSessionId });
1598 //We are in the proper thread
1599 //Remove this session from both client collection and UI tree view
1600 if (Program.iMainForm.iClients.Keys.Contains(aSessionId))
1602 Program.iMainForm.iClients.Remove(aSessionId);
1603 Program.iMainForm.iTreeViewClients.Nodes.Remove(Program.iMainForm.iTreeViewClients.Nodes.Find(aSessionId, false)[0]);
1604 //Update recording status too whenever a client is removed
1605 UpdateRecordingNotification();
1608 if (iCurrentClientSessionId == aSessionId)
1610 //The current client is closing
1611 iCurrentClientData = null;
1612 //Find the client with the highest priority and set it as current
1613 ClientData newCurrentClient = FindHighestPriorityClient();
1614 if (newCurrentClient!=null)
1616 SetCurrentClient(newCurrentClient.SessionId, true);
1620 if (iClients.Count == 0)
1622 //Clear our screen when last client disconnects
1627 //We were closing our form
1628 //All clients are now closed
1629 //Just resume our close operation
1640 /// <param name="aSessionId"></param>
1641 /// <param name="aLayout"></param>
1642 public void SetClientLayoutThreadSafe(string aSessionId, TableLayout aLayout)
1644 if (this.InvokeRequired)
1646 //Not in the proper thread, invoke ourselves
1647 SetLayoutDelegate d = new SetLayoutDelegate(SetClientLayoutThreadSafe);
1648 this.Invoke(d, new object[] { aSessionId, aLayout });
1652 ClientData client = iClients[aSessionId];
1655 //Don't change a thing if the layout is the same
1656 if (!client.Layout.IsSameAs(aLayout))
1658 Debug.Print("SetClientLayoutThreadSafe: Layout updated.");
1659 //Set our client layout then
1660 client.Layout = aLayout;
1661 //So that next time we update all our fields at ones
1662 client.HasNewLayout = true;
1663 //Layout has changed clear our fields then
1664 client.Fields.Clear();
1666 UpdateClientTreeViewNode(client);
1670 Debug.Print("SetClientLayoutThreadSafe: Layout has not changed.");
1679 /// <param name="aSessionId"></param>
1680 /// <param name="aField"></param>
1681 public void SetClientFieldThreadSafe(string aSessionId, DataField aField)
1683 if (this.InvokeRequired)
1685 //Not in the proper thread, invoke ourselves
1686 SetFieldDelegate d = new SetFieldDelegate(SetClientFieldThreadSafe);
1687 this.Invoke(d, new object[] { aSessionId, aField });
1691 //We are in the proper thread
1692 //Call the non-thread-safe variant
1693 SetClientField(aSessionId, aField);
1701 /// Set a data field in the given client.
1703 /// <param name="aSessionId"></param>
1704 /// <param name="aField"></param>
1705 private void SetClientField(string aSessionId, DataField aField)
1707 //TODO: should check if the field actually changed?
1709 ClientData client = iClients[aSessionId];
1710 bool layoutChanged = false;
1711 bool contentChanged = true;
1713 //Fetch our field index
1714 int fieldIndex = client.FindSameFieldIndex(aField);
1718 //No corresponding field, just bail out
1722 //Keep our previous field in there
1723 DataField previousField = client.Fields[fieldIndex];
1724 //Just update that field then
1725 client.Fields[fieldIndex] = aField;
1727 if (!aField.IsTableField)
1729 //We are done then if that field is not in our table layout
1733 TableField tableField = (TableField) aField;
1735 if (previousField.IsSameLayout(aField))
1737 //If we are updating a field in our current client we need to update it in our panel
1738 if (aSessionId == iCurrentClientSessionId)
1740 Control ctrl=iTableLayoutPanel.GetControlFromPosition(tableField.Column, tableField.Row);
1741 if (aField.IsTextField && ctrl is MarqueeLabel)
1743 TextField textField=(TextField)aField;
1744 //Text field control already in place, just change the text
1745 MarqueeLabel label = (MarqueeLabel)ctrl;
1746 contentChanged = (label.Text != textField.Text || label.TextAlign != textField.Alignment);
1747 label.Text = textField.Text;
1748 label.TextAlign = textField.Alignment;
1750 else if (aField.IsBitmapField && ctrl is PictureBox)
1752 BitmapField bitmapField = (BitmapField)aField;
1753 contentChanged = true; //TODO: Bitmap comp or should we leave that to clients?
1754 //Bitmap field control already in place just change the bitmap
1755 PictureBox pictureBox = (PictureBox)ctrl;
1756 pictureBox.Image = bitmapField.Bitmap;
1760 layoutChanged = true;
1766 layoutChanged = true;
1769 //If either content or layout changed we need to update our tree view to reflect the changes
1770 if (contentChanged || layoutChanged)
1772 UpdateClientTreeViewNode(client);
1776 Debug.Print("Layout changed");
1777 //Our layout has changed, if we are already the current client we need to update our panel
1778 if (aSessionId == iCurrentClientSessionId)
1780 //Apply layout and set data fields.
1781 UpdateTableLayoutPanel(iCurrentClientData);
1786 Debug.Print("Layout has not changed.");
1791 Debug.Print("WARNING: content and layout have not changed!");
1794 //When a client field is set we try switching to this client to present the new information to our user
1795 SetCurrentClient(aSessionId);
1801 /// <param name="aTexts"></param>
1802 public void SetClientFieldsThreadSafe(string aSessionId, System.Collections.Generic.IList<DataField> aFields)
1804 if (this.InvokeRequired)
1806 //Not in the proper thread, invoke ourselves
1807 SetFieldsDelegate d = new SetFieldsDelegate(SetClientFieldsThreadSafe);
1808 this.Invoke(d, new object[] { aSessionId, aFields });
1812 ClientData client = iClients[aSessionId];
1814 if (client.HasNewLayout)
1816 //TODO: Assert client.Count == 0
1817 //Our layout was just changed
1818 //Do some special handling to avoid re-creating our panel N times, once for each fields
1819 client.HasNewLayout = false;
1820 //Just set all our fields then
1821 client.Fields.AddRange(aFields);
1822 //Try switch to that client
1823 SetCurrentClient(aSessionId);
1825 //If we are updating the current client update our panel
1826 if (aSessionId == iCurrentClientSessionId)
1828 //Apply layout and set data fields.
1829 UpdateTableLayoutPanel(iCurrentClientData);
1832 UpdateClientTreeViewNode(client);
1836 //Put each our text fields in a label control
1837 foreach (DataField field in aFields)
1839 SetClientField(aSessionId, field);
1848 /// <param name="aSessionId"></param>
1849 /// <param name="aName"></param>
1850 public void SetClientNameThreadSafe(string aSessionId, string aName)
1852 if (this.InvokeRequired)
1854 //Not in the proper thread, invoke ourselves
1855 SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
1856 this.Invoke(d, new object[] { aSessionId, aName });
1860 //We are in the proper thread
1862 ClientData client = iClients[aSessionId];
1866 client.Name = aName;
1867 //Update our tree-view
1868 UpdateClientTreeViewNode(client);
1874 public void SetClientPriorityThreadSafe(string aSessionId, uint aPriority)
1876 if (this.InvokeRequired)
1878 //Not in the proper thread, invoke ourselves
1879 SetClientPriorityDelegate d = new SetClientPriorityDelegate(SetClientPriorityThreadSafe);
1880 this.Invoke(d, new object[] { aSessionId, aPriority });
1884 //We are in the proper thread
1886 ClientData client = iClients[aSessionId];
1890 client.Priority = aPriority;
1891 //Update our tree-view
1892 UpdateClientTreeViewNode(client);
1893 //Change our current client as per new priority
1894 ClientData newCurrentClient = FindHighestPriorityClient();
1895 if (newCurrentClient!=null)
1897 SetCurrentClient(newCurrentClient.SessionId);
1906 /// <param name="value"></param>
1907 /// <param name="maxChars"></param>
1908 /// <returns></returns>
1909 public static string Truncate(string value, int maxChars)
1911 return value.Length <= maxChars ? value : value.Substring(0, maxChars-3) + "...";
1915 /// Update our recording notification.
1917 private void UpdateRecordingNotification()
1920 bool activeRecording = false;
1922 RecordingField recField=new RecordingField();
1923 foreach (var client in iClients)
1925 RecordingField rec=(RecordingField)client.Value.FindSameFieldAs(recField);
1926 if (rec!=null && rec.IsActive)
1928 activeRecording = true;
1929 //Don't break cause we are collecting the names/texts.
1930 if (!String.IsNullOrEmpty(rec.Text))
1932 text += (rec.Text + "\n");
1936 //Not text for that recording, use client name instead
1937 text += client.Value.Name + " recording\n";
1943 //Update our text no matter what, can't have more than 63 characters otherwise it throws an exception.
1944 iRecordingNotification.Text = Truncate(text,63);
1946 //Change visibility of notification if needed
1947 if (iRecordingNotification.Visible != activeRecording)
1949 iRecordingNotification.Visible = activeRecording;
1950 //Assuming the notification icon is in sync with our display icon
1951 //Take care of our REC icon
1952 if (iDisplay.IsOpen())
1954 iDisplay.SetIconOnOff(MiniDisplay.IconType.Recording, activeRecording);
1962 /// <param name="aClient"></param>
1963 private void UpdateClientTreeViewNode(ClientData aClient)
1965 Debug.Print("UpdateClientTreeViewNode");
1967 if (aClient == null)
1972 //Hook in record icon update too
1973 UpdateRecordingNotification();
1975 TreeNode node = null;
1976 //Check that our client node already exists
1977 //Get our client root node using its key which is our session ID
1978 TreeNode[] nodes = iTreeViewClients.Nodes.Find(aClient.SessionId, false);
1979 if (nodes.Count()>0)
1981 //We already have a node for that client
1983 //Clear children as we are going to recreate them below
1988 //Client node does not exists create a new one
1989 iTreeViewClients.Nodes.Add(aClient.SessionId, aClient.SessionId);
1990 node = iTreeViewClients.Nodes.Find(aClient.SessionId, false)[0];
1996 if (!String.IsNullOrEmpty(aClient.Name))
1998 //We have a name, use it as text for our root node
1999 node.Text = aClient.Name;
2000 //Add a child with SessionId
2001 node.Nodes.Add(new TreeNode(aClient.SessionId));
2005 //No name, use session ID instead
2006 node.Text = aClient.SessionId;
2009 //Display client priority
2010 node.Nodes.Add(new TreeNode("Priority: " + aClient.Priority));
2012 if (aClient.Fields.Count > 0)
2014 //Create root node for our texts
2015 TreeNode textsRoot = new TreeNode("Fields");
2016 node.Nodes.Add(textsRoot);
2017 //For each text add a new entry
2018 foreach (DataField field in aClient.Fields)
2020 if (field.IsTextField)
2022 TextField textField = (TextField)field;
2023 textsRoot.Nodes.Add(new TreeNode("[Text]" + textField.Text));
2025 else if (field.IsBitmapField)
2027 textsRoot.Nodes.Add(new TreeNode("[Bitmap]"));
2029 else if (field.IsRecordingField)
2031 RecordingField recordingField = (RecordingField)field;
2032 textsRoot.Nodes.Add(new TreeNode("[Recording]" + recordingField.IsActive));
2042 /// Update our table layout row styles to make sure each rows have similar height
2044 private void UpdateTableLayoutRowStyles()
2046 foreach (RowStyle rowStyle in iTableLayoutPanel.RowStyles)
2048 rowStyle.SizeType = SizeType.Percent;
2049 rowStyle.Height = 100 / iTableLayoutPanel.RowCount;
2054 /// Update our display table layout.
2055 /// Will instanciated every field control as defined by our client.
2056 /// Fields must be specified by rows from the left.
2058 /// <param name="aLayout"></param>
2059 private void UpdateTableLayoutPanel(ClientData aClient)
2061 Debug.Print("UpdateTableLayoutPanel");
2063 if (aClient == null)
2070 TableLayout layout = aClient.Layout;
2072 //First clean our current panel
2073 iTableLayoutPanel.Controls.Clear();
2074 iTableLayoutPanel.RowStyles.Clear();
2075 iTableLayoutPanel.ColumnStyles.Clear();
2076 iTableLayoutPanel.RowCount = 0;
2077 iTableLayoutPanel.ColumnCount = 0;
2079 //Then recreate our rows...
2080 while (iTableLayoutPanel.RowCount < layout.Rows.Count)
2082 iTableLayoutPanel.RowCount++;
2086 while (iTableLayoutPanel.ColumnCount < layout.Columns.Count)
2088 iTableLayoutPanel.ColumnCount++;
2092 for (int i = 0; i < iTableLayoutPanel.ColumnCount; i++)
2094 //Create our column styles
2095 this.iTableLayoutPanel.ColumnStyles.Add(layout.Columns[i]);
2098 for (int j = 0; j < iTableLayoutPanel.RowCount; j++)
2102 //Create our row styles
2103 this.iTableLayoutPanel.RowStyles.Add(layout.Rows[j]);
2113 foreach (DataField field in aClient.Fields)
2115 if (!field.IsTableField)
2117 //That field is not taking part in our table layout skip it
2121 TableField tableField = (TableField)field;
2123 //Create a control corresponding to the field specified for that cell
2124 Control control = CreateControlForDataField(tableField);
2126 //Add newly created control to our table layout at the specified row and column
2127 iTableLayoutPanel.Controls.Add(control, tableField.Column, tableField.Row);
2128 //Make sure we specify column and row span for that new control
2129 iTableLayoutPanel.SetColumnSpan(control, tableField.ColumnSpan);
2130 iTableLayoutPanel.SetRowSpan(control, tableField.RowSpan);
2138 /// Check our type of data field and create corresponding control
2140 /// <param name="aField"></param>
2141 private Control CreateControlForDataField(DataField aField)
2143 Control control=null;
2144 if (aField.IsTextField)
2146 MarqueeLabel label = new SharpDisplayManager.MarqueeLabel();
2147 label.AutoEllipsis = true;
2148 label.AutoSize = true;
2149 label.BackColor = System.Drawing.Color.Transparent;
2150 label.Dock = System.Windows.Forms.DockStyle.Fill;
2151 label.Location = new System.Drawing.Point(1, 1);
2152 label.Margin = new System.Windows.Forms.Padding(0);
2153 label.Name = "marqueeLabel" + aField;
2154 label.OwnTimer = false;
2155 label.PixelsPerSecond = cds.ScrollingSpeedInPixelsPerSecond;
2156 label.Separator = cds.Separator;
2157 label.MinFontSize = cds.MinFontSize;
2158 label.ScaleToFit = cds.ScaleToFit;
2159 //control.Size = new System.Drawing.Size(254, 30);
2160 //control.TabIndex = 2;
2161 label.Font = cds.Font;
2163 TextField field = (TextField)aField;
2164 label.TextAlign = field.Alignment;
2165 label.UseCompatibleTextRendering = true;
2166 label.Text = field.Text;
2170 else if (aField.IsBitmapField)
2172 //Create picture box
2173 PictureBox picture = new PictureBox();
2174 picture.AutoSize = true;
2175 picture.BackColor = System.Drawing.Color.Transparent;
2176 picture.Dock = System.Windows.Forms.DockStyle.Fill;
2177 picture.Location = new System.Drawing.Point(1, 1);
2178 picture.Margin = new System.Windows.Forms.Padding(0);
2179 picture.Name = "pictureBox" + aField;
2181 BitmapField field = (BitmapField)aField;
2182 picture.Image = field.Bitmap;
2186 //TODO: Handle recording field?
2192 /// Called when the user selected a new display type.
2194 /// <param name="sender"></param>
2195 /// <param name="e"></param>
2196 private void comboBoxDisplayType_SelectedIndexChanged(object sender, EventArgs e)
2198 //Store the selected display type in our settings
2199 Properties.Settings.Default.CurrentDisplayIndex = comboBoxDisplayType.SelectedIndex;
2200 cds.DisplayType = comboBoxDisplayType.SelectedIndex;
2201 Properties.Settings.Default.Save();
2203 //Try re-opening the display connection if we were already connected.
2204 //Otherwise just update our status to reflect display type change.
2205 if (iDisplay.IsOpen())
2207 OpenDisplayConnection();
2215 private void maskedTextBoxTimerInterval_TextChanged(object sender, EventArgs e)
2217 if (maskedTextBoxTimerInterval.Text != "")
2219 int interval = Convert.ToInt32(maskedTextBoxTimerInterval.Text);
2223 timer.Interval = interval;
2224 cds.TimerInterval = timer.Interval;
2225 Properties.Settings.Default.Save();
2230 private void maskedTextBoxMinFontSize_TextChanged(object sender, EventArgs e)
2232 if (maskedTextBoxMinFontSize.Text != "")
2234 int minFontSize = Convert.ToInt32(maskedTextBoxMinFontSize.Text);
2236 if (minFontSize > 0)
2238 cds.MinFontSize = minFontSize;
2239 Properties.Settings.Default.Save();
2240 //We need to recreate our layout for that change to take effect
2241 UpdateTableLayoutPanel(iCurrentClientData);
2247 private void maskedTextBoxScrollingSpeed_TextChanged(object sender, EventArgs e)
2249 if (maskedTextBoxScrollingSpeed.Text != "")
2251 int scrollingSpeed = Convert.ToInt32(maskedTextBoxScrollingSpeed.Text);
2253 if (scrollingSpeed > 0)
2255 cds.ScrollingSpeedInPixelsPerSecond = scrollingSpeed;
2256 Properties.Settings.Default.Save();
2257 //We need to recreate our layout for that change to take effect
2258 UpdateTableLayoutPanel(iCurrentClientData);
2263 private void textBoxScrollLoopSeparator_TextChanged(object sender, EventArgs e)
2265 cds.Separator = textBoxScrollLoopSeparator.Text;
2266 Properties.Settings.Default.Save();
2268 //Update our text fields
2269 foreach (MarqueeLabel ctrl in iTableLayoutPanel.Controls)
2271 ctrl.Separator = cds.Separator;
2276 private void buttonPowerOn_Click(object sender, EventArgs e)
2281 private void buttonPowerOff_Click(object sender, EventArgs e)
2283 iDisplay.PowerOff();
2286 private void buttonShowClock_Click(object sender, EventArgs e)
2291 private void buttonHideClock_Click(object sender, EventArgs e)
2296 private void buttonUpdate_Click(object sender, EventArgs e)
2298 InstallUpdateSyncWithInfo();
2306 if (!iDisplay.IsOpen())
2311 //Devices like MDM166AA don't support windowing and frame rendering must be stopped while showing our clock
2312 iSkipFrameRendering = true;
2315 iDisplay.SwapBuffers();
2316 //Then show our clock
2317 iDisplay.ShowClock();
2325 if (!iDisplay.IsOpen())
2330 //Devices like MDM166AA don't support windowing and frame rendering must be stopped while showing our clock
2331 iSkipFrameRendering = false;
2332 iDisplay.HideClock();
2335 private void InstallUpdateSyncWithInfo()
2337 UpdateCheckInfo info = null;
2339 if (ApplicationDeployment.IsNetworkDeployed)
2341 ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
2345 info = ad.CheckForDetailedUpdate();
2348 catch (DeploymentDownloadException dde)
2350 MessageBox.Show("The new version of the application cannot be downloaded at this time. \n\nPlease check your network connection, or try again later. Error: " + dde.Message);
2353 catch (InvalidDeploymentException ide)
2355 MessageBox.Show("Cannot check for a new version of the application. The ClickOnce deployment is corrupt. Please redeploy the application and try again. Error: " + ide.Message);
2358 catch (InvalidOperationException ioe)
2360 MessageBox.Show("This application cannot be updated. It is likely not a ClickOnce application. Error: " + ioe.Message);
2364 if (info.UpdateAvailable)
2366 Boolean doUpdate = true;
2368 if (!info.IsUpdateRequired)
2370 DialogResult dr = MessageBox.Show("An update is available. Would you like to update the application now?", "Update Available", MessageBoxButtons.OKCancel);
2371 if (!(DialogResult.OK == dr))
2378 // Display a message that the application MUST reboot. Display the minimum required version.
2379 MessageBox.Show("This application has detected a mandatory update from your current " +
2380 "version to version " + info.MinimumRequiredVersion.ToString() +
2381 ". The application will now install the update and restart.",
2382 "Update Available", MessageBoxButtons.OK,
2383 MessageBoxIcon.Information);
2391 MessageBox.Show("The application has been upgraded, and will now restart.");
2392 Application.Restart();
2394 catch (DeploymentDownloadException dde)
2396 MessageBox.Show("Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " + dde);
2403 MessageBox.Show("You are already running the latest version.", "Application up-to-date");
2412 private void SysTrayHideShow()
2418 WindowState = FormWindowState.Normal;
2423 /// Use to handle minimize events.
2425 /// <param name="sender"></param>
2426 /// <param name="e"></param>
2427 private void MainForm_SizeChanged(object sender, EventArgs e)
2429 if (WindowState == FormWindowState.Minimized && Properties.Settings.Default.MinimizeToTray)
2441 /// <param name="sender"></param>
2442 /// <param name="e"></param>
2443 private void tableLayoutPanel_SizeChanged(object sender, EventArgs e)
2445 //Our table layout size has changed which means our display size has changed.
2446 //We need to re-create our bitmap.
2447 iCreateBitmap = true;
2453 /// <param name="sender"></param>
2454 /// <param name="e"></param>
2455 private void buttonSelectFile_Click(object sender, EventArgs e)
2457 //openFileDialog1.InitialDirectory = "c:\\";
2458 //openFileDialog.Filter = "EXE files (*.exe)|*.exe|All files (*.*)|*.*";
2459 //openFileDialog.FilterIndex = 1;
2460 openFileDialog.RestoreDirectory = true;
2462 if (DlgBox.ShowDialog(openFileDialog) == DialogResult.OK)
2464 labelStartFileName.Text = openFileDialog.FileName;
2465 Properties.Settings.Default.StartFileName = openFileDialog.FileName;
2466 Properties.Settings.Default.Save();
2473 /// <param name="sender"></param>
2474 /// <param name="e"></param>
2475 private void comboBoxOpticalDrives_SelectedIndexChanged(object sender, EventArgs e)
2477 //Save the optical drive the user selected for ejection
2478 Properties.Settings.Default.OpticalDriveToEject = comboBoxOpticalDrives.SelectedItem.ToString();
2479 Properties.Settings.Default.Save();
2483 /// Broadcast messages to subscribers.
2485 /// <param name="message"></param>
2486 protected override void WndProc(ref Message aMessage)
2488 if (iWriter != null)
2490 iWriter.FlushAccumulator();
2493 if (OnWndProc!=null)
2495 OnWndProc(ref aMessage);
2498 base.WndProc(ref aMessage);
2501 private void checkBoxCecEnabled_CheckedChanged(object sender, EventArgs e)
2503 //Save CEC enabled status
2504 Properties.Settings.Default.CecEnabled = checkBoxCecEnabled.Checked;
2505 Properties.Settings.Default.Save();
2510 private void comboBoxHdmiPort_SelectedIndexChanged(object sender, EventArgs e)
2512 //Save CEC HDMI port
2513 Properties.Settings.Default.CecHdmiPort = Convert.ToByte(comboBoxHdmiPort.SelectedIndex);
2514 Properties.Settings.Default.CecHdmiPort++;
2515 Properties.Settings.Default.Save();
2520 private void checkBoxCecMonitorOff_CheckedChanged(object sender, EventArgs e)
2522 Properties.Settings.Default.CecMonitorOff = checkBoxCecMonitorOff.Checked;
2523 Properties.Settings.Default.Save();
2528 private void checkBoxCecMonitorOn_CheckedChanged(object sender, EventArgs e)
2530 Properties.Settings.Default.CecMonitorOn = checkBoxCecMonitorOn.Checked;
2531 Properties.Settings.Default.Save();
2539 private void ResetCec()
2541 if (iCecManager==null)
2543 //Thus skipping initial UI setup
2549 if (Properties.Settings.Default.CecEnabled)
2551 iCecManager.Start(Handle, "CEC",
2552 Properties.Settings.Default.CecHdmiPort,
2553 Properties.Settings.Default.CecMonitorOn,
2554 Properties.Settings.Default.CecMonitorOff);
2558 private void ButtonStartIdleClient_Click(object sender, EventArgs e)