Removing obsolete CEC options.
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;
45 using SharpDisplayClient;
47 using MiniDisplayInterop;
48 using SharpLib.Display;
51 namespace SharpDisplayManager
54 public delegate uint ColorProcessingDelegate(int aX, int aY, uint aPixel);
55 public delegate int CoordinateTranslationDelegate(System.Drawing.Bitmap aBmp, int aInt);
56 //Delegates are used for our thread safe method
57 public delegate void AddClientDelegate(string aSessionId, ICallback aCallback);
58 public delegate void RemoveClientDelegate(string aSessionId);
59 public delegate void SetFieldDelegate(string SessionId, DataField aField);
60 public delegate void SetFieldsDelegate(string SessionId, System.Collections.Generic.IList<DataField> aFields);
61 public delegate void SetLayoutDelegate(string SessionId, TableLayout aLayout);
62 public delegate void SetClientNameDelegate(string aSessionId, string aName);
63 public delegate void SetClientPriorityDelegate(string aSessionId, uint aPriority);
64 public delegate void PlainUpdateDelegate();
65 public delegate void WndProcDelegate(ref Message aMessage);
68 /// Our Display manager main form
70 [System.ComponentModel.DesignerCategory("Form")]
71 public partial class MainForm : MainFormHid, IMMNotificationClient
73 //public ManagerEventAction iManager = new ManagerEventAction();
74 DateTime LastTickTime;
76 System.Drawing.Bitmap iBmp;
77 bool iCreateBitmap; //Workaround render to bitmap issues when minimized
78 ServiceHost iServiceHost;
79 // Our collection of clients sorted by session id.
80 public Dictionary<string, ClientData> iClients;
81 // The name of the client which informations are currently displayed.
82 public string iCurrentClientSessionId;
83 ClientData iCurrentClientData;
87 public bool iSkipFrameRendering;
88 //Function pointer for pixel color filtering
89 ColorProcessingDelegate iColorFx;
90 //Function pointer for pixel X coordinate intercept
91 CoordinateTranslationDelegate iScreenX;
92 //Function pointer for pixel Y coordinate intercept
93 CoordinateTranslationDelegate iScreenY;
95 private MMDeviceEnumerator iMultiMediaDeviceEnumerator;
96 private MMDevice iMultiMediaDevice;
98 private NetworkManager iNetworkManager;
101 /// CEC - Consumer Electronic Control.
102 /// Notably used to turn TV on and off as Windows broadcast monitor on and off notifications.
104 private ConsumerElectronicControl iCecManager;
107 /// Manage run when Windows startup option
109 private StartupManager iStartupManager;
112 /// System notification icon used to hide our application from the task bar.
114 private SharpLib.Notification.Control iNotifyIcon;
117 /// System recording notification icon.
119 private SharpLib.Notification.Control iRecordingNotification;
124 RichTextBoxTextWriter iWriter;
128 /// Allow user to receive window messages;
130 public event WndProcDelegate OnWndProc;
134 ManagerEventAction.Current = Properties.Settings.Default.Actions;
135 if (ManagerEventAction.Current == null)
137 //No actions in our settings yet
138 ManagerEventAction.Current = new ManagerEventAction();
139 Properties.Settings.Default.Actions = ManagerEventAction.Current;
143 //We loaded actions from our settings
144 //We need to hook them with corresponding events
145 ManagerEventAction.Current.Init();
147 iSkipFrameRendering = false;
149 iCurrentClientSessionId = "";
150 iCurrentClientData = null;
151 LastTickTime = DateTime.Now;
152 //Instantiate our display and register for events notifications
153 iDisplay = new Display();
154 iDisplay.OnOpened += OnDisplayOpened;
155 iDisplay.OnClosed += OnDisplayClosed;
157 iClients = new Dictionary<string, ClientData>();
158 iStartupManager = new StartupManager();
159 iNotifyIcon = new SharpLib.Notification.Control();
160 iRecordingNotification = new SharpLib.Notification.Control();
162 //Have our designer initialize its controls
163 InitializeComponent();
165 //Redirect console output
166 iWriter = new RichTextBoxTextWriter(richTextBoxLogs);
167 Console.SetOut(iWriter);
169 //Populate device types
170 PopulateDeviceTypes();
172 //Populate optical drives
173 PopulateOpticalDrives();
175 //Initial status update
178 //We have a bug when drawing minimized and reusing our bitmap
179 //Though I could not reproduce it on Windows 10
180 iBmp = new System.Drawing.Bitmap(iTableLayoutPanel.Width, iTableLayoutPanel.Height, PixelFormat.Format32bppArgb);
181 iCreateBitmap = false;
183 //Minimize our window if desired
184 if (Properties.Settings.Default.StartMinimized)
186 WindowState = FormWindowState.Minimized;
194 /// <param name="sender"></param>
195 /// <param name="e"></param>
196 private void MainForm_Load(object sender, EventArgs e)
198 //Check if we are running a Click Once deployed application
199 if (ApplicationDeployment.IsNetworkDeployed)
201 //This is a proper Click Once installation, fetch and show our version number
202 this.Text += " - v" + ApplicationDeployment.CurrentDeployment.CurrentVersion;
206 //Not a proper Click Once installation, assuming development build then
207 this.Text += " - development";
211 iMultiMediaDeviceEnumerator = new MMDeviceEnumerator();
212 iMultiMediaDeviceEnumerator.RegisterEndpointNotificationCallback(this);
213 UpdateAudioDeviceAndMasterVolumeThreadSafe();
216 iNetworkManager = new NetworkManager();
217 iNetworkManager.OnConnectivityChanged += OnConnectivityChanged;
218 UpdateNetworkStatus();
221 iCecManager = new ConsumerElectronicControl();
222 OnWndProc += iCecManager.OnWndProc;
228 //Setup notification icon
231 //Setup recording notification
232 SetupRecordingNotification();
234 // To make sure start up with minimize to tray works
235 if (WindowState == FormWindowState.Minimized && Properties.Settings.Default.MinimizeToTray)
241 //When not debugging we want the screen to be empty until a client takes over
244 //When developing we want at least one client for testing
245 StartNewClient("abcdefghijklmnopqrst-0123456789","ABCDEFGHIJKLMNOPQRST-0123456789");
248 //Open display connection on start-up if needed
249 if (Properties.Settings.Default.DisplayConnectOnStartup)
251 OpenDisplayConnection();
254 //Start our server so that we can get client requests
257 //Register for HID events
258 RegisterHidDevices();
260 //Start Idle client if needed
261 if (Properties.Settings.Default.StartIdleClient)
268 /// Called when our display is opened.
270 /// <param name="aDisplay"></param>
271 private void OnDisplayOpened(Display aDisplay)
273 //Make sure we resume frame rendering
274 iSkipFrameRendering = false;
276 //Set our screen size now that our display is connected
277 //Our panelDisplay is the container of our tableLayoutPanel
278 //tableLayoutPanel will resize itself to fit the client size of our panelDisplay
279 //panelDisplay needs an extra 2 pixels for borders on each sides
280 //tableLayoutPanel will eventually be the exact size of our display
281 Size size = new Size(iDisplay.WidthInPixels() + 2, iDisplay.HeightInPixels() + 2);
282 panelDisplay.Size = size;
284 //Our display was just opened, update our UI
286 //Initiate asynchronous request
287 iDisplay.RequestFirmwareRevision();
290 UpdateMasterVolumeThreadSafe();
292 UpdateNetworkStatus();
295 //Testing icon in debug, no arm done if icon not supported
296 //iDisplay.SetIconStatus(Display.TMiniDisplayIconType.EMiniDisplayIconRecording, 0, 1);
297 //iDisplay.SetAllIconsStatus(2);
305 private void SetupEvents()
308 iTreeViewEvents.Nodes.Clear();
309 //Populate registered events
310 foreach (string key in ManagerEventAction.Current.Events.Keys)
312 Event e = ManagerEventAction.Current.Events[key];
313 TreeNode eventNode = iTreeViewEvents.Nodes.Add(key,e.Name);
315 eventNode.Nodes.Add(key + ".Description", e.Description);
316 TreeNode actionsNodes = eventNode.Nodes.Add(key + ".Actions", "Actions");
318 // Add our actions for that event
319 foreach (SharpLib.Ear.Action a in e.Actions)
321 TreeNode actionNode = actionsNodes.Nodes.Add(a.Name);
326 iTreeViewEvents.ExpandAll();
331 /// Called when our display is closed.
333 /// <param name="aDisplay"></param>
334 private void OnDisplayClosed(Display aDisplay)
336 //Our display was just closed, update our UI consequently
340 public void OnConnectivityChanged(NetworkManager aNetwork, NLM_CONNECTIVITY newConnectivity)
342 //Update network status
343 UpdateNetworkStatus();
347 /// Update our Network Status
349 private void UpdateNetworkStatus()
351 if (iDisplay.IsOpen())
353 iDisplay.SetIconOnOff(MiniDisplay.IconType.Internet, iNetworkManager.NetworkListManager.IsConnectedToInternet);
354 iDisplay.SetIconOnOff(MiniDisplay.IconType.NetworkSignal, iNetworkManager.NetworkListManager.IsConnected);
359 int iLastNetworkIconIndex = 0;
360 int iUpdateCountSinceLastNetworkAnimation = 0;
365 private void UpdateNetworkSignal(DateTime aLastTickTime, DateTime aNewTickTime)
367 iUpdateCountSinceLastNetworkAnimation++;
368 iUpdateCountSinceLastNetworkAnimation = iUpdateCountSinceLastNetworkAnimation % 4;
370 if (iDisplay.IsOpen() && iNetworkManager.NetworkListManager.IsConnected && iUpdateCountSinceLastNetworkAnimation==0)
372 int iconCount = iDisplay.IconCount(MiniDisplay.IconType.NetworkSignal);
375 //Prevents div by zero and other undefined behavior
378 iLastNetworkIconIndex++;
379 iLastNetworkIconIndex = iLastNetworkIconIndex % (iconCount*2);
380 for (int i=0;i<iconCount;i++)
382 if (i < iLastNetworkIconIndex && !(i == 0 && iLastNetworkIconIndex > 3) && !(i == 1 && iLastNetworkIconIndex > 4))
384 iDisplay.SetIconOn(MiniDisplay.IconType.NetworkSignal, i);
388 iDisplay.SetIconOff(MiniDisplay.IconType.NetworkSignal, i);
397 /// Receive volume change notification and reflect changes on our slider.
399 /// <param name="data"></param>
400 public void OnVolumeNotificationThreadSafe(AudioVolumeNotificationData data)
402 UpdateMasterVolumeThreadSafe();
406 /// Update master volume when user moves our slider.
408 /// <param name="sender"></param>
409 /// <param name="e"></param>
410 private void trackBarMasterVolume_Scroll(object sender, EventArgs e)
412 //Just like Windows Volume Mixer we unmute if the volume is adjusted
413 iMultiMediaDevice.AudioEndpointVolume.Mute = false;
414 //Set volume level according to our volume slider new position
415 iMultiMediaDevice.AudioEndpointVolume.MasterVolumeLevelScalar = trackBarMasterVolume.Value / 100.0f;
420 /// Mute check box changed.
422 /// <param name="sender"></param>
423 /// <param name="e"></param>
424 private void checkBoxMute_CheckedChanged(object sender, EventArgs e)
426 iMultiMediaDevice.AudioEndpointVolume.Mute = checkBoxMute.Checked;
430 /// Device State Changed
432 public void OnDeviceStateChanged([MarshalAs(UnmanagedType.LPWStr)] string deviceId, [MarshalAs(UnmanagedType.I4)] DeviceState newState){}
437 public void OnDeviceAdded([MarshalAs(UnmanagedType.LPWStr)] string pwstrDeviceId) { }
442 public void OnDeviceRemoved([MarshalAs(UnmanagedType.LPWStr)] string deviceId) { }
445 /// Default Device Changed
447 public void OnDefaultDeviceChanged(DataFlow flow, Role role, [MarshalAs(UnmanagedType.LPWStr)] string defaultDeviceId)
449 if (role == Role.Multimedia && flow == DataFlow.Render)
451 UpdateAudioDeviceAndMasterVolumeThreadSafe();
456 /// Property Value Changed
458 /// <param name="pwstrDeviceId"></param>
459 /// <param name="key"></param>
460 public void OnPropertyValueChanged([MarshalAs(UnmanagedType.LPWStr)] string pwstrDeviceId, PropertyKey key){}
466 /// Update master volume indicators based our current system states.
467 /// This typically includes volume levels and mute status.
469 private void UpdateMasterVolumeThreadSafe()
471 if (this.InvokeRequired)
473 //Not in the proper thread, invoke ourselves
474 PlainUpdateDelegate d = new PlainUpdateDelegate(UpdateMasterVolumeThreadSafe);
475 this.Invoke(d, new object[] { });
479 //Update volume slider
480 float volumeLevelScalar = iMultiMediaDevice.AudioEndpointVolume.MasterVolumeLevelScalar;
481 trackBarMasterVolume.Value = Convert.ToInt32(volumeLevelScalar * 100);
482 //Update mute checkbox
483 checkBoxMute.Checked = iMultiMediaDevice.AudioEndpointVolume.Mute;
485 //If our display connection is open we need to update its icons
486 if (iDisplay.IsOpen())
488 //First take care our our volume level icons
489 int volumeIconCount = iDisplay.IconCount(MiniDisplay.IconType.Volume);
490 if (volumeIconCount > 0)
492 //Compute current volume level from system level and the number of segments in our display volume bar.
493 //That tells us how many segments in our volume bar needs to be turned on.
494 float currentVolume = volumeLevelScalar * volumeIconCount;
495 int segmentOnCount = Convert.ToInt32(currentVolume);
496 //Check if our segment count was rounded up, this will later be used for half brightness segment
497 bool roundedUp = segmentOnCount > currentVolume;
499 for (int i = 0; i < volumeIconCount; i++)
501 if (i < segmentOnCount)
503 //If we are dealing with our last segment and our segment count was rounded up then we will use half brightness.
504 if (i == segmentOnCount - 1 && roundedUp)
507 iDisplay.SetIconStatus(MiniDisplay.IconType.Volume, i, (iDisplay.IconStatusCount(MiniDisplay.IconType.Volume) - 1) / 2);
512 iDisplay.SetIconStatus(MiniDisplay.IconType.Volume, i, iDisplay.IconStatusCount(MiniDisplay.IconType.Volume) - 1);
517 iDisplay.SetIconStatus(MiniDisplay.IconType.Volume, i, 0);
522 //Take care of our mute icon
523 iDisplay.SetIconOnOff(MiniDisplay.IconType.Mute, iMultiMediaDevice.AudioEndpointVolume.Mute);
531 private void UpdateAudioDeviceAndMasterVolumeThreadSafe()
533 if (this.InvokeRequired)
535 //Not in the proper thread, invoke ourselves
536 PlainUpdateDelegate d = new PlainUpdateDelegate(UpdateAudioDeviceAndMasterVolumeThreadSafe);
537 this.Invoke(d, new object[] { });
541 //We are in the correct thread just go ahead.
544 //Get our master volume
545 iMultiMediaDevice = iMultiMediaDeviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
547 labelDefaultAudioDevice.Text = iMultiMediaDevice.FriendlyName;
549 //Show our volume in our track bar
550 UpdateMasterVolumeThreadSafe();
552 //Register to get volume modifications
553 iMultiMediaDevice.AudioEndpointVolume.OnVolumeNotification += OnVolumeNotificationThreadSafe;
555 trackBarMasterVolume.Enabled = true;
559 Debug.WriteLine("Exception thrown in UpdateAudioDeviceAndMasterVolume");
560 Debug.WriteLine(ex.ToString());
561 //Something went wrong S/PDIF device ca throw exception I guess
562 trackBarMasterVolume.Enabled = false;
569 private void PopulateDeviceTypes()
571 int count = Display.TypeCount();
573 for (int i = 0; i < count; i++)
575 comboBoxDisplayType.Items.Add(Display.TypeName((MiniDisplay.Type)i));
582 private void PopulateOpticalDrives()
584 //Reset our list of drives
585 comboBoxOpticalDrives.Items.Clear();
586 comboBoxOpticalDrives.Items.Add("None");
588 //Go through each drives on our system and collected the optical ones in our list
589 DriveInfo[] allDrives = DriveInfo.GetDrives();
590 foreach (DriveInfo d in allDrives)
592 Debug.WriteLine("Drive " + d.Name);
593 Debug.WriteLine(" Drive type: {0}", d.DriveType);
595 if (d.DriveType==DriveType.CDRom)
597 //This is an optical drive, add it now
598 comboBoxOpticalDrives.Items.Add(d.Name.Substring(0,2));
606 /// <returns></returns>
607 public string OpticalDriveToEject()
609 return comboBoxOpticalDrives.SelectedItem.ToString();
617 private void SetupTrayIcon()
619 iNotifyIcon.Icon = GetIcon("vfd.ico");
620 iNotifyIcon.Text = "Sharp Display Manager";
621 iNotifyIcon.Visible = true;
623 //Double click toggles visibility - typically brings up the application
624 iNotifyIcon.DoubleClick += delegate(object obj, EventArgs args)
629 //Adding a context menu, useful to be able to exit the application
630 ContextMenu contextMenu = new ContextMenu();
631 //Context menu item to toggle visibility
632 MenuItem hideShowItem = new MenuItem("Hide/Show");
633 hideShowItem.Click += delegate(object obj, EventArgs args)
637 contextMenu.MenuItems.Add(hideShowItem);
639 //Context menu item separator
640 contextMenu.MenuItems.Add(new MenuItem("-"));
642 //Context menu exit item
643 MenuItem exitItem = new MenuItem("Exit");
644 exitItem.Click += delegate(object obj, EventArgs args)
648 contextMenu.MenuItems.Add(exitItem);
650 iNotifyIcon.ContextMenu = contextMenu;
656 private void SetupRecordingNotification()
658 iRecordingNotification.Icon = GetIcon("record.ico");
659 iRecordingNotification.Text = "No recording";
660 iRecordingNotification.Visible = false;
664 /// Access icons from embedded resources.
666 /// <param name="aName"></param>
667 /// <returns></returns>
668 public static Icon GetIcon(string aName)
670 string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames();
671 foreach (string name in names)
673 //Find a resource name that ends with the given name
674 if (name.EndsWith(aName))
676 using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))
678 return new Icon(stream);
688 /// Set our current client.
689 /// This will take care of applying our client layout and set data fields.
691 /// <param name="aSessionId"></param>
692 void SetCurrentClient(string aSessionId, bool aForce=false)
694 if (aSessionId == iCurrentClientSessionId)
696 //Given client is already the current one.
697 //Don't bother changing anything then.
701 ClientData requestedClientData = iClients[aSessionId];
703 //Check when was the last time we switched to that client
704 if (iCurrentClientData != null)
706 //Do not switch client if priority of current client is higher
707 if (!aForce && requestedClientData.Priority < iCurrentClientData.Priority)
713 double lastSwitchToClientSecondsAgo = (DateTime.Now - iCurrentClientData.LastSwitchTime).TotalSeconds;
714 //TODO: put that hard coded value as a client property
715 //Clients should be able to define how often they can be interrupted
716 //Thus a background client can set this to zero allowing any other client to interrupt at any time
717 //We could also compute this delay by looking at the requests frequencies?
719 requestedClientData.Priority == iCurrentClientData.Priority && //Time sharing is only if clients have the same priority
720 (lastSwitchToClientSecondsAgo < 30)) //Make sure a client is on for at least 30 seconds
722 //Don't switch clients too often
727 //Set current client ID.
728 iCurrentClientSessionId = aSessionId;
729 //Set the time we last switched to that client
730 iClients[aSessionId].LastSwitchTime = DateTime.Now;
731 //Fetch and set current client data.
732 iCurrentClientData = requestedClientData;
733 //Apply layout and set data fields.
734 UpdateTableLayoutPanel(iCurrentClientData);
737 private void buttonFont_Click(object sender, EventArgs e)
739 //fontDialog.ShowColor = true;
740 //fontDialog.ShowApply = true;
741 fontDialog.ShowEffects = true;
742 fontDialog.Font = cds.Font;
744 fontDialog.FixedPitchOnly = checkBoxFixedPitchFontOnly.Checked;
746 //fontDialog.ShowHelp = true;
748 //fontDlg.MaxSize = 40;
749 //fontDlg.MinSize = 22;
751 //fontDialog.Parent = this;
752 //fontDialog.StartPosition = FormStartPosition.CenterParent;
754 //DlgBox.ShowDialog(fontDialog);
756 //if (fontDialog.ShowDialog(this) != DialogResult.Cancel)
757 if (DlgBox.ShowDialog(fontDialog) != DialogResult.Cancel)
759 //Set the fonts to all our labels in our layout
760 foreach (Control ctrl in iTableLayoutPanel.Controls)
762 if (ctrl is MarqueeLabel)
764 ((MarqueeLabel)ctrl).Font = fontDialog.Font;
769 cds.Font = fontDialog.Font;
770 Properties.Settings.Default.Save();
779 void CheckFontHeight()
781 //Show font height and width
782 labelFontHeight.Text = "Font height: " + cds.Font.Height;
783 float charWidth = IsFixedWidth(cds.Font);
784 if (charWidth == 0.0f)
786 labelFontWidth.Visible = false;
790 labelFontWidth.Visible = true;
791 labelFontWidth.Text = "Font width: " + charWidth;
794 MarqueeLabel label = null;
795 //Get the first label control we can find
796 foreach (Control ctrl in iTableLayoutPanel.Controls)
798 if (ctrl is MarqueeLabel)
800 label = (MarqueeLabel)ctrl;
805 //Now check font height and show a warning if needed.
806 if (label != null && label.Font.Height > label.Height)
808 labelWarning.Text = "WARNING: Selected font is too height by " + (label.Font.Height - label.Height) + " pixels!";
809 labelWarning.Visible = true;
813 labelWarning.Visible = false;
818 private void buttonCapture_Click(object sender, EventArgs e)
820 System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(iTableLayoutPanel.Width, iTableLayoutPanel.Height);
821 iTableLayoutPanel.DrawToBitmap(bmp, iTableLayoutPanel.ClientRectangle);
822 //Bitmap bmpToSave = new Bitmap(bmp);
823 bmp.Save("D:\\capture.png");
825 ((MarqueeLabel)iTableLayoutPanel.Controls[0]).Text = "Captured";
828 string outputFileName = "d:\\capture.png";
829 using (MemoryStream memory = new MemoryStream())
831 using (FileStream fs = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
833 bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
834 byte[] bytes = memory.ToArray();
835 fs.Write(bytes, 0, bytes.Length);
842 private void CheckForRequestResults()
844 if (iDisplay.IsRequestPending())
846 switch (iDisplay.AttemptRequestCompletion())
848 case MiniDisplay.Request.FirmwareRevision:
849 toolStripStatusLabelConnect.Text += " v" + iDisplay.FirmwareRevision();
850 //Issue next request then
851 iDisplay.RequestPowerSupplyStatus();
854 case MiniDisplay.Request.PowerSupplyStatus:
855 if (iDisplay.PowerSupplyStatus())
857 toolStripStatusLabelPower.Text = "ON";
861 toolStripStatusLabelPower.Text = "OFF";
863 //Issue next request then
864 iDisplay.RequestDeviceId();
867 case MiniDisplay.Request.DeviceId:
868 toolStripStatusLabelConnect.Text += " - " + iDisplay.DeviceId();
869 //No more request to issue
875 public static uint ColorWhiteIsOn(int aX, int aY, uint aPixel)
877 if ((aPixel & 0x00FFFFFF) == 0x00FFFFFF)
884 public static uint ColorUntouched(int aX, int aY, uint aPixel)
889 public static uint ColorInversed(int aX, int aY, uint aPixel)
894 public static uint ColorChessboard(int aX, int aY, uint aPixel)
896 if ((aX % 2 == 0) && (aY % 2 == 0))
900 else if ((aX % 2 != 0) && (aY % 2 != 0))
908 public static int ScreenReversedX(System.Drawing.Bitmap aBmp, int aX)
910 return aBmp.Width - aX - 1;
913 public int ScreenReversedY(System.Drawing.Bitmap aBmp, int aY)
915 return iBmp.Height - aY - 1;
918 public int ScreenX(System.Drawing.Bitmap aBmp, int aX)
923 public int ScreenY(System.Drawing.Bitmap aBmp, int aY)
929 /// Select proper pixel delegates according to our current settings.
931 private void SetupPixelDelegates()
933 //Select our pixel processing routine
934 if (cds.InverseColors)
936 //iColorFx = ColorChessboard;
937 iColorFx = ColorInversed;
941 iColorFx = ColorWhiteIsOn;
944 //Select proper coordinate translation functions
945 //We used delegate/function pointer to support reverse screen without doing an extra test on each pixels
946 if (cds.ReverseScreen)
948 iScreenX = ScreenReversedX;
949 iScreenY = ScreenReversedY;
959 //This is our timer tick responsible to perform our render
960 private void timer_Tick(object sender, EventArgs e)
962 //Not ideal cause this has nothing to do with display render
965 //Update our animations
966 DateTime NewTickTime = DateTime.Now;
968 UpdateNetworkSignal(LastTickTime, NewTickTime);
970 //Update animation for all our marquees
971 foreach (Control ctrl in iTableLayoutPanel.Controls)
973 if (ctrl is MarqueeLabel)
975 ((MarqueeLabel)ctrl).UpdateAnimation(LastTickTime, NewTickTime);
980 if (iDisplay.IsOpen())
982 CheckForRequestResults();
984 //Check if frame rendering is needed
985 //Typically used when showing clock
986 if (!iSkipFrameRendering)
991 iBmp = new System.Drawing.Bitmap(iTableLayoutPanel.Width, iTableLayoutPanel.Height, PixelFormat.Format32bppArgb);
992 iCreateBitmap = false;
994 iTableLayoutPanel.DrawToBitmap(iBmp, iTableLayoutPanel.ClientRectangle);
995 //iBmp.Save("D:\\capture.png");
997 //Send it to our display
998 for (int i = 0; i < iBmp.Width; i++)
1000 for (int j = 0; j < iBmp.Height; j++)
1004 //Get our processed pixel coordinates
1005 int x = iScreenX(iBmp, i);
1006 int y = iScreenY(iBmp, j);
1008 uint color = (uint)iBmp.GetPixel(i, j).ToArgb();
1009 //Apply color effects
1010 color = iColorFx(x, y, color);
1012 iDisplay.SetPixel(x, y, color);
1017 iDisplay.SwapBuffers();
1021 //Compute instant FPS
1022 toolStripStatusLabelFps.Text = (1.0/NewTickTime.Subtract(LastTickTime).TotalSeconds).ToString("F0") + " / " + (1000/timer.Interval).ToString() + " FPS";
1024 LastTickTime = NewTickTime;
1029 /// Attempt to establish connection with our display hardware.
1031 private void OpenDisplayConnection()
1033 CloseDisplayConnection();
1035 if (!iDisplay.Open((MiniDisplay.Type)cds.DisplayType))
1038 toolStripStatusLabelConnect.Text = "Connection error";
1042 private void CloseDisplayConnection()
1044 //Status will be updated upon receiving the closed event
1046 if (iDisplay == null || !iDisplay.IsOpen())
1051 //Do not clear if we gave up on rendering already.
1052 //This means we will keep on displaying clock on MDM166AA for instance.
1053 if (!iSkipFrameRendering)
1056 iDisplay.SwapBuffers();
1059 iDisplay.SetAllIconsStatus(0); //Turn off all icons
1063 private void buttonOpen_Click(object sender, EventArgs e)
1065 OpenDisplayConnection();
1068 private void buttonClose_Click(object sender, EventArgs e)
1070 CloseDisplayConnection();
1073 private void buttonClear_Click(object sender, EventArgs e)
1076 iDisplay.SwapBuffers();
1079 private void buttonFill_Click(object sender, EventArgs e)
1082 iDisplay.SwapBuffers();
1085 private void trackBarBrightness_Scroll(object sender, EventArgs e)
1087 cds.Brightness = trackBarBrightness.Value;
1088 Properties.Settings.Default.Save();
1089 iDisplay.SetBrightness(trackBarBrightness.Value);
1095 /// CDS stands for Current Display Settings
1097 private DisplaySettings cds
1101 DisplaysSettings settings = Properties.Settings.Default.DisplaysSettings;
1102 if (settings == null)
1104 settings = new DisplaysSettings();
1106 Properties.Settings.Default.DisplaysSettings = settings;
1109 //Make sure all our settings have been created
1110 while (settings.Displays.Count <= Properties.Settings.Default.CurrentDisplayIndex)
1112 settings.Displays.Add(new DisplaySettings());
1115 DisplaySettings displaySettings = settings.Displays[Properties.Settings.Default.CurrentDisplayIndex];
1116 return displaySettings;
1121 /// Check if the given font has a fixed character pitch.
1123 /// <param name="ft"></param>
1124 /// <returns>0.0f if this is not a monospace font, otherwise returns the character width.</returns>
1125 public float IsFixedWidth(Font ft)
1127 Graphics g = CreateGraphics();
1128 char[] charSizes = new char[] { 'i', 'a', 'Z', '%', '#', 'a', 'B', 'l', 'm', ',', '.' };
1129 float charWidth = g.MeasureString("I", ft, Int32.MaxValue, StringFormat.GenericTypographic).Width;
1131 bool fixedWidth = true;
1133 foreach (char c in charSizes)
1134 if (g.MeasureString(c.ToString(), ft, Int32.MaxValue, StringFormat.GenericTypographic).Width != charWidth)
1146 /// Synchronize UI with settings
1148 private void UpdateStatus()
1151 checkBoxShowBorders.Checked = cds.ShowBorders;
1152 iTableLayoutPanel.CellBorderStyle = (cds.ShowBorders ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
1154 //Set the proper font to each of our labels
1155 foreach (MarqueeLabel ctrl in iTableLayoutPanel.Controls)
1157 ctrl.Font = cds.Font;
1161 //Check if "run on Windows startup" is enabled
1162 checkBoxAutoStart.Checked = iStartupManager.Startup;
1164 checkBoxConnectOnStartup.Checked = Properties.Settings.Default.DisplayConnectOnStartup;
1165 checkBoxMinimizeToTray.Checked = Properties.Settings.Default.MinimizeToTray;
1166 checkBoxStartMinimized.Checked = Properties.Settings.Default.StartMinimized;
1167 iCheckBoxStartIdleClient.Checked = Properties.Settings.Default.StartIdleClient;
1168 labelStartFileName.Text = Properties.Settings.Default.StartFileName;
1171 //Try find our drive in our drive list
1172 int opticalDriveItemIndex=0;
1173 bool driveNotFound = true;
1174 string opticalDriveToEject=Properties.Settings.Default.OpticalDriveToEject;
1175 foreach (object item in comboBoxOpticalDrives.Items)
1177 if (opticalDriveToEject == item.ToString())
1179 comboBoxOpticalDrives.SelectedIndex = opticalDriveItemIndex;
1180 driveNotFound = false;
1183 opticalDriveItemIndex++;
1188 //We could not find the drive we had saved.
1189 //Select "None" then.
1190 comboBoxOpticalDrives.SelectedIndex = 0;
1194 checkBoxCecEnabled.Checked = Properties.Settings.Default.CecEnabled;
1195 comboBoxHdmiPort.SelectedIndex = Properties.Settings.Default.CecHdmiPort - 1;
1197 //Mini Display settings
1198 checkBoxReverseScreen.Checked = cds.ReverseScreen;
1199 checkBoxInverseColors.Checked = cds.InverseColors;
1200 checkBoxShowVolumeLabel.Checked = cds.ShowVolumeLabel;
1201 checkBoxScaleToFit.Checked = cds.ScaleToFit;
1202 maskedTextBoxMinFontSize.Enabled = cds.ScaleToFit;
1203 labelMinFontSize.Enabled = cds.ScaleToFit;
1204 maskedTextBoxMinFontSize.Text = cds.MinFontSize.ToString();
1205 maskedTextBoxScrollingSpeed.Text = cds.ScrollingSpeedInPixelsPerSecond.ToString();
1206 comboBoxDisplayType.SelectedIndex = cds.DisplayType;
1207 timer.Interval = cds.TimerInterval;
1208 maskedTextBoxTimerInterval.Text = cds.TimerInterval.ToString();
1209 textBoxScrollLoopSeparator.Text = cds.Separator;
1211 SetupPixelDelegates();
1213 if (iDisplay.IsOpen())
1215 //We have a display connection
1216 //Reflect that in our UI
1219 iTableLayoutPanel.Enabled = true;
1220 panelDisplay.Enabled = true;
1222 //Only setup brightness if display is open
1223 trackBarBrightness.Minimum = iDisplay.MinBrightness();
1224 trackBarBrightness.Maximum = iDisplay.MaxBrightness();
1225 if (cds.Brightness < iDisplay.MinBrightness() || cds.Brightness > iDisplay.MaxBrightness())
1227 //Brightness out of range, this can occur when using auto-detect
1228 //Use max brightness instead
1229 trackBarBrightness.Value = iDisplay.MaxBrightness();
1230 iDisplay.SetBrightness(iDisplay.MaxBrightness());
1234 trackBarBrightness.Value = cds.Brightness;
1235 iDisplay.SetBrightness(cds.Brightness);
1238 //Try compute the steps to something that makes sense
1239 trackBarBrightness.LargeChange = Math.Max(1, (iDisplay.MaxBrightness() - iDisplay.MinBrightness()) / 5);
1240 trackBarBrightness.SmallChange = 1;
1243 buttonFill.Enabled = true;
1244 buttonClear.Enabled = true;
1245 buttonOpen.Enabled = false;
1246 buttonClose.Enabled = true;
1247 trackBarBrightness.Enabled = true;
1248 toolStripStatusLabelConnect.Text = "Connected - " + iDisplay.Vendor() + " - " + iDisplay.Product();
1249 //+ " - " + iDisplay.SerialNumber();
1251 if (iDisplay.SupportPowerOnOff())
1253 buttonPowerOn.Enabled = true;
1254 buttonPowerOff.Enabled = true;
1258 buttonPowerOn.Enabled = false;
1259 buttonPowerOff.Enabled = false;
1262 if (iDisplay.SupportClock())
1264 buttonShowClock.Enabled = true;
1265 buttonHideClock.Enabled = true;
1269 buttonShowClock.Enabled = false;
1270 buttonHideClock.Enabled = false;
1274 //Check if Volume Label is supported. To date only MDM166AA supports that crap :)
1275 checkBoxShowVolumeLabel.Enabled = iDisplay.IconCount(MiniDisplay.IconType.VolumeLabel)>0;
1277 if (cds.ShowVolumeLabel)
1279 iDisplay.SetIconOn(MiniDisplay.IconType.VolumeLabel);
1283 iDisplay.SetIconOff(MiniDisplay.IconType.VolumeLabel);
1288 //Display connection not available
1289 //Reflect that in our UI
1291 //In debug start our timer even if we don't have a display connection
1294 //In production environment we don't need our timer if no display connection
1297 checkBoxShowVolumeLabel.Enabled = false;
1298 iTableLayoutPanel.Enabled = false;
1299 panelDisplay.Enabled = false;
1300 buttonFill.Enabled = false;
1301 buttonClear.Enabled = false;
1302 buttonOpen.Enabled = true;
1303 buttonClose.Enabled = false;
1304 trackBarBrightness.Enabled = false;
1305 buttonPowerOn.Enabled = false;
1306 buttonPowerOff.Enabled = false;
1307 buttonShowClock.Enabled = false;
1308 buttonHideClock.Enabled = false;
1309 toolStripStatusLabelConnect.Text = "Disconnected";
1310 toolStripStatusLabelPower.Text = "N/A";
1319 /// <param name="sender"></param>
1320 /// <param name="e"></param>
1321 private void checkBoxShowVolumeLabel_CheckedChanged(object sender, EventArgs e)
1323 cds.ShowVolumeLabel = checkBoxShowVolumeLabel.Checked;
1324 Properties.Settings.Default.Save();
1328 private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
1330 //Save our show borders setting
1331 iTableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
1332 cds.ShowBorders = checkBoxShowBorders.Checked;
1333 Properties.Settings.Default.Save();
1337 private void checkBoxConnectOnStartup_CheckedChanged(object sender, EventArgs e)
1339 //Save our connect on startup setting
1340 Properties.Settings.Default.DisplayConnectOnStartup = checkBoxConnectOnStartup.Checked;
1341 Properties.Settings.Default.Save();
1344 private void checkBoxMinimizeToTray_CheckedChanged(object sender, EventArgs e)
1346 //Save our "Minimize to tray" setting
1347 Properties.Settings.Default.MinimizeToTray = checkBoxMinimizeToTray.Checked;
1348 Properties.Settings.Default.Save();
1352 private void checkBoxStartMinimized_CheckedChanged(object sender, EventArgs e)
1354 //Save our "Start minimized" setting
1355 Properties.Settings.Default.StartMinimized = checkBoxStartMinimized.Checked;
1356 Properties.Settings.Default.Save();
1359 private void checkBoxStartIdleClient_CheckedChanged(object sender, EventArgs e)
1361 Properties.Settings.Default.StartIdleClient = iCheckBoxStartIdleClient.Checked;
1362 Properties.Settings.Default.Save();
1365 private void checkBoxAutoStart_CheckedChanged(object sender, EventArgs e)
1367 iStartupManager.Startup = checkBoxAutoStart.Checked;
1371 private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
1373 //Save our reverse screen setting
1374 cds.ReverseScreen = checkBoxReverseScreen.Checked;
1375 Properties.Settings.Default.Save();
1376 SetupPixelDelegates();
1379 private void checkBoxInverseColors_CheckedChanged(object sender, EventArgs e)
1381 //Save our inverse colors setting
1382 cds.InverseColors = checkBoxInverseColors.Checked;
1383 Properties.Settings.Default.Save();
1384 SetupPixelDelegates();
1387 private void checkBoxScaleToFit_CheckedChanged(object sender, EventArgs e)
1389 //Save our scale to fit setting
1390 cds.ScaleToFit = checkBoxScaleToFit.Checked;
1391 Properties.Settings.Default.Save();
1393 labelMinFontSize.Enabled = cds.ScaleToFit;
1394 maskedTextBoxMinFontSize.Enabled = cds.ScaleToFit;
1397 private void MainForm_Resize(object sender, EventArgs e)
1399 if (WindowState == FormWindowState.Minimized)
1401 // To workaround our empty bitmap bug on Windows 7 we need to recreate our bitmap when the application is minimized
1402 // That's apparently not needed on Windows 10 but we better leave it in place.
1403 iCreateBitmap = true;
1407 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
1410 iNetworkManager.Dispose();
1411 CloseDisplayConnection();
1413 e.Cancel = iClosing;
1416 public void StartServer()
1418 iServiceHost = new ServiceHost
1421 new Uri[] { new Uri("net.tcp://localhost:8001/") }
1424 iServiceHost.AddServiceEndpoint(typeof(IService), new NetTcpBinding(SecurityMode.None, true), "DisplayService");
1425 iServiceHost.Open();
1428 public void StopServer()
1430 if (iClients.Count > 0 && !iClosing)
1434 BroadcastCloseEvent();
1438 if (MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
1440 iClosing = false; //We make sure we force close if asked twice
1445 //We removed that as it often lags for some reason
1446 //iServiceHost.Close();
1450 public void BroadcastCloseEvent()
1452 Trace.TraceInformation("BroadcastCloseEvent - start");
1454 var inactiveClients = new List<string>();
1455 foreach (var client in iClients)
1457 //if (client.Key != eventData.ClientName)
1461 Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
1462 client.Value.Callback.OnCloseOrder(/*eventData*/);
1464 catch (Exception ex)
1466 inactiveClients.Add(client.Key);
1471 if (inactiveClients.Count > 0)
1473 foreach (var client in inactiveClients)
1475 iClients.Remove(client);
1476 Program.iMainForm.iTreeViewClients.Nodes.Remove(Program.iMainForm.iTreeViewClients.Nodes.Find(client, false)[0]);
1480 if (iClients.Count==0)
1487 /// Just remove all our fields.
1489 private void ClearLayout()
1491 iTableLayoutPanel.Controls.Clear();
1492 iTableLayoutPanel.RowStyles.Clear();
1493 iTableLayoutPanel.ColumnStyles.Clear();
1494 iCurrentClientData = null;
1498 /// Just launch a demo client.
1500 private void StartNewClient(string aTopText = "", string aBottomText = "")
1502 Thread clientThread = new Thread(SharpDisplayClient.Program.MainWithParams);
1503 SharpDisplayClient.StartParams myParams = new SharpDisplayClient.StartParams(new Point(this.Right, this.Top),aTopText,aBottomText);
1504 clientThread.Start(myParams);
1509 /// Just launch our idle client.
1511 private void StartIdleClient(string aTopText = "", string aBottomText = "")
1513 Thread clientThread = new Thread(SharpDisplayIdleClient.Program.MainWithParams);
1514 SharpDisplayIdleClient.StartParams myParams = new SharpDisplayIdleClient.StartParams(new Point(this.Right, this.Top), aTopText, aBottomText);
1515 clientThread.Start(myParams);
1520 private void buttonStartClient_Click(object sender, EventArgs e)
1525 private void buttonSuspend_Click(object sender, EventArgs e)
1530 private void StartTimer()
1532 LastTickTime = DateTime.Now; //Reset timer to prevent jump
1533 timer.Enabled = true;
1534 UpdateSuspendButton();
1537 private void StopTimer()
1539 LastTickTime = DateTime.Now; //Reset timer to prevent jump
1540 timer.Enabled = false;
1541 UpdateSuspendButton();
1544 private void ToggleTimer()
1546 LastTickTime = DateTime.Now; //Reset timer to prevent jump
1547 timer.Enabled = !timer.Enabled;
1548 UpdateSuspendButton();
1551 private void UpdateSuspendButton()
1555 buttonSuspend.Text = "Run";
1559 buttonSuspend.Text = "Pause";
1564 private void buttonCloseClients_Click(object sender, EventArgs e)
1566 BroadcastCloseEvent();
1569 private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
1571 //Root node must have at least one child
1572 if (e.Node.Nodes.Count == 0)
1577 //If the selected node is the root node of a client then switch to it
1578 string sessionId=e.Node.Nodes[0].Text; //First child of a root node is the sessionId
1579 if (iClients.ContainsKey(sessionId)) //Check that's actually what we are looking at
1581 //We have a valid session just switch to that client
1582 SetCurrentClient(sessionId,true);
1591 /// <param name="aSessionId"></param>
1592 /// <param name="aCallback"></param>
1593 public void AddClientThreadSafe(string aSessionId, ICallback aCallback)
1595 if (this.InvokeRequired)
1597 //Not in the proper thread, invoke ourselves
1598 AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
1599 this.Invoke(d, new object[] { aSessionId, aCallback });
1603 //We are in the proper thread
1604 //Add this session to our collection of clients
1605 ClientData newClient = new ClientData(aSessionId, aCallback);
1606 Program.iMainForm.iClients.Add(aSessionId, newClient);
1607 //Add this session to our UI
1608 UpdateClientTreeViewNode(newClient);
1614 /// Find the client with the highest priority if any.
1616 /// <returns>Our highest priority client or null if not a single client is connected.</returns>
1617 public ClientData FindHighestPriorityClient()
1619 ClientData highestPriorityClient = null;
1620 foreach (var client in iClients)
1622 if (highestPriorityClient == null || client.Value.Priority > highestPriorityClient.Priority)
1624 highestPriorityClient = client.Value;
1628 return highestPriorityClient;
1634 /// <param name="aSessionId"></param>
1635 public void RemoveClientThreadSafe(string aSessionId)
1637 if (this.InvokeRequired)
1639 //Not in the proper thread, invoke ourselves
1640 RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
1641 this.Invoke(d, new object[] { aSessionId });
1645 //We are in the proper thread
1646 //Remove this session from both client collection and UI tree view
1647 if (Program.iMainForm.iClients.Keys.Contains(aSessionId))
1649 Program.iMainForm.iClients.Remove(aSessionId);
1650 Program.iMainForm.iTreeViewClients.Nodes.Remove(Program.iMainForm.iTreeViewClients.Nodes.Find(aSessionId, false)[0]);
1651 //Update recording status too whenever a client is removed
1652 UpdateRecordingNotification();
1655 if (iCurrentClientSessionId == aSessionId)
1657 //The current client is closing
1658 iCurrentClientData = null;
1659 //Find the client with the highest priority and set it as current
1660 ClientData newCurrentClient = FindHighestPriorityClient();
1661 if (newCurrentClient!=null)
1663 SetCurrentClient(newCurrentClient.SessionId, true);
1667 if (iClients.Count == 0)
1669 //Clear our screen when last client disconnects
1674 //We were closing our form
1675 //All clients are now closed
1676 //Just resume our close operation
1687 /// <param name="aSessionId"></param>
1688 /// <param name="aLayout"></param>
1689 public void SetClientLayoutThreadSafe(string aSessionId, TableLayout aLayout)
1691 if (this.InvokeRequired)
1693 //Not in the proper thread, invoke ourselves
1694 SetLayoutDelegate d = new SetLayoutDelegate(SetClientLayoutThreadSafe);
1695 this.Invoke(d, new object[] { aSessionId, aLayout });
1699 ClientData client = iClients[aSessionId];
1702 //Don't change a thing if the layout is the same
1703 if (!client.Layout.IsSameAs(aLayout))
1705 Debug.Print("SetClientLayoutThreadSafe: Layout updated.");
1706 //Set our client layout then
1707 client.Layout = aLayout;
1708 //So that next time we update all our fields at ones
1709 client.HasNewLayout = true;
1710 //Layout has changed clear our fields then
1711 client.Fields.Clear();
1713 UpdateClientTreeViewNode(client);
1717 Debug.Print("SetClientLayoutThreadSafe: Layout has not changed.");
1726 /// <param name="aSessionId"></param>
1727 /// <param name="aField"></param>
1728 public void SetClientFieldThreadSafe(string aSessionId, DataField aField)
1730 if (this.InvokeRequired)
1732 //Not in the proper thread, invoke ourselves
1733 SetFieldDelegate d = new SetFieldDelegate(SetClientFieldThreadSafe);
1734 this.Invoke(d, new object[] { aSessionId, aField });
1738 //We are in the proper thread
1739 //Call the non-thread-safe variant
1740 SetClientField(aSessionId, aField);
1748 /// Set a data field in the given client.
1750 /// <param name="aSessionId"></param>
1751 /// <param name="aField"></param>
1752 private void SetClientField(string aSessionId, DataField aField)
1754 //TODO: should check if the field actually changed?
1756 ClientData client = iClients[aSessionId];
1757 bool layoutChanged = false;
1758 bool contentChanged = true;
1760 //Fetch our field index
1761 int fieldIndex = client.FindSameFieldIndex(aField);
1765 //No corresponding field, just bail out
1769 //Keep our previous field in there
1770 DataField previousField = client.Fields[fieldIndex];
1771 //Just update that field then
1772 client.Fields[fieldIndex] = aField;
1774 if (!aField.IsTableField)
1776 //We are done then if that field is not in our table layout
1780 TableField tableField = (TableField) aField;
1782 if (previousField.IsSameLayout(aField))
1784 //If we are updating a field in our current client we need to update it in our panel
1785 if (aSessionId == iCurrentClientSessionId)
1787 Control ctrl=iTableLayoutPanel.GetControlFromPosition(tableField.Column, tableField.Row);
1788 if (aField.IsTextField && ctrl is MarqueeLabel)
1790 TextField textField=(TextField)aField;
1791 //Text field control already in place, just change the text
1792 MarqueeLabel label = (MarqueeLabel)ctrl;
1793 contentChanged = (label.Text != textField.Text || label.TextAlign != textField.Alignment);
1794 label.Text = textField.Text;
1795 label.TextAlign = textField.Alignment;
1797 else if (aField.IsBitmapField && ctrl is PictureBox)
1799 BitmapField bitmapField = (BitmapField)aField;
1800 contentChanged = true; //TODO: Bitmap comp or should we leave that to clients?
1801 //Bitmap field control already in place just change the bitmap
1802 PictureBox pictureBox = (PictureBox)ctrl;
1803 pictureBox.Image = bitmapField.Bitmap;
1807 layoutChanged = true;
1813 layoutChanged = true;
1816 //If either content or layout changed we need to update our tree view to reflect the changes
1817 if (contentChanged || layoutChanged)
1819 UpdateClientTreeViewNode(client);
1823 Debug.Print("Layout changed");
1824 //Our layout has changed, if we are already the current client we need to update our panel
1825 if (aSessionId == iCurrentClientSessionId)
1827 //Apply layout and set data fields.
1828 UpdateTableLayoutPanel(iCurrentClientData);
1833 Debug.Print("Layout has not changed.");
1838 Debug.Print("WARNING: content and layout have not changed!");
1841 //When a client field is set we try switching to this client to present the new information to our user
1842 SetCurrentClient(aSessionId);
1848 /// <param name="aTexts"></param>
1849 public void SetClientFieldsThreadSafe(string aSessionId, System.Collections.Generic.IList<DataField> aFields)
1851 if (this.InvokeRequired)
1853 //Not in the proper thread, invoke ourselves
1854 SetFieldsDelegate d = new SetFieldsDelegate(SetClientFieldsThreadSafe);
1855 this.Invoke(d, new object[] { aSessionId, aFields });
1859 ClientData client = iClients[aSessionId];
1861 if (client.HasNewLayout)
1863 //TODO: Assert client.Count == 0
1864 //Our layout was just changed
1865 //Do some special handling to avoid re-creating our panel N times, once for each fields
1866 client.HasNewLayout = false;
1867 //Just set all our fields then
1868 client.Fields.AddRange(aFields);
1869 //Try switch to that client
1870 SetCurrentClient(aSessionId);
1872 //If we are updating the current client update our panel
1873 if (aSessionId == iCurrentClientSessionId)
1875 //Apply layout and set data fields.
1876 UpdateTableLayoutPanel(iCurrentClientData);
1879 UpdateClientTreeViewNode(client);
1883 //Put each our text fields in a label control
1884 foreach (DataField field in aFields)
1886 SetClientField(aSessionId, field);
1895 /// <param name="aSessionId"></param>
1896 /// <param name="aName"></param>
1897 public void SetClientNameThreadSafe(string aSessionId, string aName)
1899 if (this.InvokeRequired)
1901 //Not in the proper thread, invoke ourselves
1902 SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
1903 this.Invoke(d, new object[] { aSessionId, aName });
1907 //We are in the proper thread
1909 ClientData client = iClients[aSessionId];
1913 client.Name = aName;
1914 //Update our tree-view
1915 UpdateClientTreeViewNode(client);
1921 public void SetClientPriorityThreadSafe(string aSessionId, uint aPriority)
1923 if (this.InvokeRequired)
1925 //Not in the proper thread, invoke ourselves
1926 SetClientPriorityDelegate d = new SetClientPriorityDelegate(SetClientPriorityThreadSafe);
1927 this.Invoke(d, new object[] { aSessionId, aPriority });
1931 //We are in the proper thread
1933 ClientData client = iClients[aSessionId];
1937 client.Priority = aPriority;
1938 //Update our tree-view
1939 UpdateClientTreeViewNode(client);
1940 //Change our current client as per new priority
1941 ClientData newCurrentClient = FindHighestPriorityClient();
1942 if (newCurrentClient!=null)
1944 SetCurrentClient(newCurrentClient.SessionId);
1953 /// <param name="value"></param>
1954 /// <param name="maxChars"></param>
1955 /// <returns></returns>
1956 public static string Truncate(string value, int maxChars)
1958 return value.Length <= maxChars ? value : value.Substring(0, maxChars-3) + "...";
1962 /// Update our recording notification.
1964 private void UpdateRecordingNotification()
1967 bool activeRecording = false;
1969 RecordingField recField=new RecordingField();
1970 foreach (var client in iClients)
1972 RecordingField rec=(RecordingField)client.Value.FindSameFieldAs(recField);
1973 if (rec!=null && rec.IsActive)
1975 activeRecording = true;
1976 //Don't break cause we are collecting the names/texts.
1977 if (!String.IsNullOrEmpty(rec.Text))
1979 text += (rec.Text + "\n");
1983 //Not text for that recording, use client name instead
1984 text += client.Value.Name + " recording\n";
1990 //Update our text no matter what, can't have more than 63 characters otherwise it throws an exception.
1991 iRecordingNotification.Text = Truncate(text,63);
1993 //Change visibility of notification if needed
1994 if (iRecordingNotification.Visible != activeRecording)
1996 iRecordingNotification.Visible = activeRecording;
1997 //Assuming the notification icon is in sync with our display icon
1998 //Take care of our REC icon
1999 if (iDisplay.IsOpen())
2001 iDisplay.SetIconOnOff(MiniDisplay.IconType.Recording, activeRecording);
2009 /// <param name="aClient"></param>
2010 private void UpdateClientTreeViewNode(ClientData aClient)
2012 Debug.Print("UpdateClientTreeViewNode");
2014 if (aClient == null)
2019 //Hook in record icon update too
2020 UpdateRecordingNotification();
2022 TreeNode node = null;
2023 //Check that our client node already exists
2024 //Get our client root node using its key which is our session ID
2025 TreeNode[] nodes = iTreeViewClients.Nodes.Find(aClient.SessionId, false);
2026 if (nodes.Count()>0)
2028 //We already have a node for that client
2030 //Clear children as we are going to recreate them below
2035 //Client node does not exists create a new one
2036 iTreeViewClients.Nodes.Add(aClient.SessionId, aClient.SessionId);
2037 node = iTreeViewClients.Nodes.Find(aClient.SessionId, false)[0];
2043 if (!String.IsNullOrEmpty(aClient.Name))
2045 //We have a name, use it as text for our root node
2046 node.Text = aClient.Name;
2047 //Add a child with SessionId
2048 node.Nodes.Add(new TreeNode(aClient.SessionId));
2052 //No name, use session ID instead
2053 node.Text = aClient.SessionId;
2056 //Display client priority
2057 node.Nodes.Add(new TreeNode("Priority: " + aClient.Priority));
2059 if (aClient.Fields.Count > 0)
2061 //Create root node for our texts
2062 TreeNode textsRoot = new TreeNode("Fields");
2063 node.Nodes.Add(textsRoot);
2064 //For each text add a new entry
2065 foreach (DataField field in aClient.Fields)
2067 if (field.IsTextField)
2069 TextField textField = (TextField)field;
2070 textsRoot.Nodes.Add(new TreeNode("[Text]" + textField.Text));
2072 else if (field.IsBitmapField)
2074 textsRoot.Nodes.Add(new TreeNode("[Bitmap]"));
2076 else if (field.IsRecordingField)
2078 RecordingField recordingField = (RecordingField)field;
2079 textsRoot.Nodes.Add(new TreeNode("[Recording]" + recordingField.IsActive));
2089 /// Update our table layout row styles to make sure each rows have similar height
2091 private void UpdateTableLayoutRowStyles()
2093 foreach (RowStyle rowStyle in iTableLayoutPanel.RowStyles)
2095 rowStyle.SizeType = SizeType.Percent;
2096 rowStyle.Height = 100 / iTableLayoutPanel.RowCount;
2101 /// Update our display table layout.
2102 /// Will instanciated every field control as defined by our client.
2103 /// Fields must be specified by rows from the left.
2105 /// <param name="aLayout"></param>
2106 private void UpdateTableLayoutPanel(ClientData aClient)
2108 Debug.Print("UpdateTableLayoutPanel");
2110 if (aClient == null)
2117 TableLayout layout = aClient.Layout;
2119 //First clean our current panel
2120 iTableLayoutPanel.Controls.Clear();
2121 iTableLayoutPanel.RowStyles.Clear();
2122 iTableLayoutPanel.ColumnStyles.Clear();
2123 iTableLayoutPanel.RowCount = 0;
2124 iTableLayoutPanel.ColumnCount = 0;
2126 //Then recreate our rows...
2127 while (iTableLayoutPanel.RowCount < layout.Rows.Count)
2129 iTableLayoutPanel.RowCount++;
2133 while (iTableLayoutPanel.ColumnCount < layout.Columns.Count)
2135 iTableLayoutPanel.ColumnCount++;
2139 for (int i = 0; i < iTableLayoutPanel.ColumnCount; i++)
2141 //Create our column styles
2142 this.iTableLayoutPanel.ColumnStyles.Add(layout.Columns[i]);
2145 for (int j = 0; j < iTableLayoutPanel.RowCount; j++)
2149 //Create our row styles
2150 this.iTableLayoutPanel.RowStyles.Add(layout.Rows[j]);
2160 foreach (DataField field in aClient.Fields)
2162 if (!field.IsTableField)
2164 //That field is not taking part in our table layout skip it
2168 TableField tableField = (TableField)field;
2170 //Create a control corresponding to the field specified for that cell
2171 Control control = CreateControlForDataField(tableField);
2173 //Add newly created control to our table layout at the specified row and column
2174 iTableLayoutPanel.Controls.Add(control, tableField.Column, tableField.Row);
2175 //Make sure we specify column and row span for that new control
2176 iTableLayoutPanel.SetColumnSpan(control, tableField.ColumnSpan);
2177 iTableLayoutPanel.SetRowSpan(control, tableField.RowSpan);
2185 /// Check our type of data field and create corresponding control
2187 /// <param name="aField"></param>
2188 private Control CreateControlForDataField(DataField aField)
2190 Control control=null;
2191 if (aField.IsTextField)
2193 MarqueeLabel label = new SharpDisplayManager.MarqueeLabel();
2194 label.AutoEllipsis = true;
2195 label.AutoSize = true;
2196 label.BackColor = System.Drawing.Color.Transparent;
2197 label.Dock = System.Windows.Forms.DockStyle.Fill;
2198 label.Location = new System.Drawing.Point(1, 1);
2199 label.Margin = new System.Windows.Forms.Padding(0);
2200 label.Name = "marqueeLabel" + aField;
2201 label.OwnTimer = false;
2202 label.PixelsPerSecond = cds.ScrollingSpeedInPixelsPerSecond;
2203 label.Separator = cds.Separator;
2204 label.MinFontSize = cds.MinFontSize;
2205 label.ScaleToFit = cds.ScaleToFit;
2206 //control.Size = new System.Drawing.Size(254, 30);
2207 //control.TabIndex = 2;
2208 label.Font = cds.Font;
2210 TextField field = (TextField)aField;
2211 label.TextAlign = field.Alignment;
2212 label.UseCompatibleTextRendering = true;
2213 label.Text = field.Text;
2217 else if (aField.IsBitmapField)
2219 //Create picture box
2220 PictureBox picture = new PictureBox();
2221 picture.AutoSize = true;
2222 picture.BackColor = System.Drawing.Color.Transparent;
2223 picture.Dock = System.Windows.Forms.DockStyle.Fill;
2224 picture.Location = new System.Drawing.Point(1, 1);
2225 picture.Margin = new System.Windows.Forms.Padding(0);
2226 picture.Name = "pictureBox" + aField;
2228 BitmapField field = (BitmapField)aField;
2229 picture.Image = field.Bitmap;
2233 //TODO: Handle recording field?
2239 /// Called when the user selected a new display type.
2241 /// <param name="sender"></param>
2242 /// <param name="e"></param>
2243 private void comboBoxDisplayType_SelectedIndexChanged(object sender, EventArgs e)
2245 //Store the selected display type in our settings
2246 Properties.Settings.Default.CurrentDisplayIndex = comboBoxDisplayType.SelectedIndex;
2247 cds.DisplayType = comboBoxDisplayType.SelectedIndex;
2248 Properties.Settings.Default.Save();
2250 //Try re-opening the display connection if we were already connected.
2251 //Otherwise just update our status to reflect display type change.
2252 if (iDisplay.IsOpen())
2254 OpenDisplayConnection();
2262 private void maskedTextBoxTimerInterval_TextChanged(object sender, EventArgs e)
2264 if (maskedTextBoxTimerInterval.Text != "")
2266 int interval = Convert.ToInt32(maskedTextBoxTimerInterval.Text);
2270 timer.Interval = interval;
2271 cds.TimerInterval = timer.Interval;
2272 Properties.Settings.Default.Save();
2277 private void maskedTextBoxMinFontSize_TextChanged(object sender, EventArgs e)
2279 if (maskedTextBoxMinFontSize.Text != "")
2281 int minFontSize = Convert.ToInt32(maskedTextBoxMinFontSize.Text);
2283 if (minFontSize > 0)
2285 cds.MinFontSize = minFontSize;
2286 Properties.Settings.Default.Save();
2287 //We need to recreate our layout for that change to take effect
2288 UpdateTableLayoutPanel(iCurrentClientData);
2294 private void maskedTextBoxScrollingSpeed_TextChanged(object sender, EventArgs e)
2296 if (maskedTextBoxScrollingSpeed.Text != "")
2298 int scrollingSpeed = Convert.ToInt32(maskedTextBoxScrollingSpeed.Text);
2300 if (scrollingSpeed > 0)
2302 cds.ScrollingSpeedInPixelsPerSecond = scrollingSpeed;
2303 Properties.Settings.Default.Save();
2304 //We need to recreate our layout for that change to take effect
2305 UpdateTableLayoutPanel(iCurrentClientData);
2310 private void textBoxScrollLoopSeparator_TextChanged(object sender, EventArgs e)
2312 cds.Separator = textBoxScrollLoopSeparator.Text;
2313 Properties.Settings.Default.Save();
2315 //Update our text fields
2316 foreach (MarqueeLabel ctrl in iTableLayoutPanel.Controls)
2318 ctrl.Separator = cds.Separator;
2323 private void buttonPowerOn_Click(object sender, EventArgs e)
2328 private void buttonPowerOff_Click(object sender, EventArgs e)
2330 iDisplay.PowerOff();
2333 private void buttonShowClock_Click(object sender, EventArgs e)
2338 private void buttonHideClock_Click(object sender, EventArgs e)
2343 private void buttonUpdate_Click(object sender, EventArgs e)
2345 InstallUpdateSyncWithInfo();
2353 if (!iDisplay.IsOpen())
2358 //Devices like MDM166AA don't support windowing and frame rendering must be stopped while showing our clock
2359 iSkipFrameRendering = true;
2362 iDisplay.SwapBuffers();
2363 //Then show our clock
2364 iDisplay.ShowClock();
2372 if (!iDisplay.IsOpen())
2377 //Devices like MDM166AA don't support windowing and frame rendering must be stopped while showing our clock
2378 iSkipFrameRendering = false;
2379 iDisplay.HideClock();
2382 private void InstallUpdateSyncWithInfo()
2384 UpdateCheckInfo info = null;
2386 if (ApplicationDeployment.IsNetworkDeployed)
2388 ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
2392 info = ad.CheckForDetailedUpdate();
2395 catch (DeploymentDownloadException dde)
2397 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);
2400 catch (InvalidDeploymentException ide)
2402 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);
2405 catch (InvalidOperationException ioe)
2407 MessageBox.Show("This application cannot be updated. It is likely not a ClickOnce application. Error: " + ioe.Message);
2411 if (info.UpdateAvailable)
2413 Boolean doUpdate = true;
2415 if (!info.IsUpdateRequired)
2417 DialogResult dr = MessageBox.Show("An update is available. Would you like to update the application now?", "Update Available", MessageBoxButtons.OKCancel);
2418 if (!(DialogResult.OK == dr))
2425 // Display a message that the application MUST reboot. Display the minimum required version.
2426 MessageBox.Show("This application has detected a mandatory update from your current " +
2427 "version to version " + info.MinimumRequiredVersion.ToString() +
2428 ". The application will now install the update and restart.",
2429 "Update Available", MessageBoxButtons.OK,
2430 MessageBoxIcon.Information);
2438 MessageBox.Show("The application has been upgraded, and will now restart.");
2439 Application.Restart();
2441 catch (DeploymentDownloadException dde)
2443 MessageBox.Show("Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " + dde);
2450 MessageBox.Show("You are already running the latest version.", "Application up-to-date");
2459 private void SysTrayHideShow()
2465 WindowState = FormWindowState.Normal;
2470 /// Use to handle minimize events.
2472 /// <param name="sender"></param>
2473 /// <param name="e"></param>
2474 private void MainForm_SizeChanged(object sender, EventArgs e)
2476 if (WindowState == FormWindowState.Minimized && Properties.Settings.Default.MinimizeToTray)
2488 /// <param name="sender"></param>
2489 /// <param name="e"></param>
2490 private void tableLayoutPanel_SizeChanged(object sender, EventArgs e)
2492 //Our table layout size has changed which means our display size has changed.
2493 //We need to re-create our bitmap.
2494 iCreateBitmap = true;
2500 /// <param name="sender"></param>
2501 /// <param name="e"></param>
2502 private void buttonSelectFile_Click(object sender, EventArgs e)
2504 //openFileDialog1.InitialDirectory = "c:\\";
2505 //openFileDialog.Filter = "EXE files (*.exe)|*.exe|All files (*.*)|*.*";
2506 //openFileDialog.FilterIndex = 1;
2507 openFileDialog.RestoreDirectory = true;
2509 if (DlgBox.ShowDialog(openFileDialog) == DialogResult.OK)
2511 labelStartFileName.Text = openFileDialog.FileName;
2512 Properties.Settings.Default.StartFileName = openFileDialog.FileName;
2513 Properties.Settings.Default.Save();
2520 /// <param name="sender"></param>
2521 /// <param name="e"></param>
2522 private void comboBoxOpticalDrives_SelectedIndexChanged(object sender, EventArgs e)
2524 //Save the optical drive the user selected for ejection
2525 Properties.Settings.Default.OpticalDriveToEject = comboBoxOpticalDrives.SelectedItem.ToString();
2526 Properties.Settings.Default.Save();
2533 private void LogsUpdate()
2535 if (iWriter != null)
2543 /// Broadcast messages to subscribers.
2545 /// <param name="message"></param>
2546 protected override void WndProc(ref Message aMessage)
2550 if (OnWndProc!=null)
2552 OnWndProc(ref aMessage);
2555 base.WndProc(ref aMessage);
2558 private void checkBoxCecEnabled_CheckedChanged(object sender, EventArgs e)
2560 //Save CEC enabled status
2561 Properties.Settings.Default.CecEnabled = checkBoxCecEnabled.Checked;
2562 Properties.Settings.Default.Save();
2567 private void comboBoxHdmiPort_SelectedIndexChanged(object sender, EventArgs e)
2569 //Save CEC HDMI port
2570 Properties.Settings.Default.CecHdmiPort = Convert.ToByte(comboBoxHdmiPort.SelectedIndex);
2571 Properties.Settings.Default.CecHdmiPort++;
2572 Properties.Settings.Default.Save();
2580 private void ResetCec()
2582 if (iCecManager==null)
2584 //Thus skipping initial UI setup
2590 if (Properties.Settings.Default.CecEnabled)
2592 iCecManager.Start(Handle, "CEC",
2593 Properties.Settings.Default.CecHdmiPort);
2602 private void SetupCecLogLevel()
2605 iCecManager.Client.LogLevel = 0;
2607 if (checkBoxCecLogError.Checked)
2608 iCecManager.Client.LogLevel |= (int)CecLogLevel.Error;
2610 if (checkBoxCecLogWarning.Checked)
2611 iCecManager.Client.LogLevel |= (int)CecLogLevel.Warning;
2613 if (checkBoxCecLogNotice.Checked)
2614 iCecManager.Client.LogLevel |= (int)CecLogLevel.Notice;
2616 if (checkBoxCecLogTraffic.Checked)
2617 iCecManager.Client.LogLevel |= (int)CecLogLevel.Traffic;
2619 if (checkBoxCecLogDebug.Checked)
2620 iCecManager.Client.LogLevel |= (int)CecLogLevel.Debug;
2622 iCecManager.Client.FilterOutPollLogs = checkBoxCecLogNoPoll.Checked;
2626 private void ButtonStartIdleClient_Click(object sender, EventArgs e)
2631 private void buttonClearLogs_Click(object sender, EventArgs e)
2633 richTextBoxLogs.Clear();
2636 private void checkBoxCecLogs_CheckedChanged(object sender, EventArgs e)
2641 private void buttonAddAction_Click(object sender, EventArgs e)
2643 if (iTreeViewEvents.SelectedNode==null
2644 || !(iTreeViewEvents.SelectedNode.Tag is Event))
2649 Event earEvent = (Event)iTreeViewEvents.SelectedNode.Tag;
2650 if (earEvent == null)
2652 //Must select event node
2656 FormEditAction ea = new FormEditAction();
2657 DialogResult res = CodeProject.Dialog.DlgBox.ShowDialog(ea);
2658 if (res == DialogResult.OK)
2660 earEvent.Actions.Add(ea.Action);
2661 Properties.Settings.Default.Actions = ManagerEventAction.Current;
2662 Properties.Settings.Default.Save();
2667 private void buttonDeleteAction_Click(object sender, EventArgs e)
2669 if (iTreeViewEvents.SelectedNode == null
2670 || !(iTreeViewEvents.SelectedNode.Tag is SharpLib.Ear.Action))
2675 SharpLib.Ear.Action action = (SharpLib.Ear.Action)iTreeViewEvents.SelectedNode.Tag;
2678 //Must select action node
2682 ManagerEventAction.Current.RemoveAction(action);
2683 Properties.Settings.Default.Actions = ManagerEventAction.Current;
2684 Properties.Settings.Default.Save();