Server/MainForm.cs
author StephaneLenclud
Sun, 24 Jul 2016 20:46:34 +0200
changeset 215 5de8f8eaaa54
parent 214 4961ede27e0a
child 217 94f91d446339
permissions -rw-r--r--
Removing obsolete CEC options.
     1 //
     2 // Copyright (C) 2014-2015 Stéphane Lenclud.
     3 //
     4 // This file is part of SharpDisplayManager.
     5 //
     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.
    10 //
    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.
    15 //
    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/>.
    18 //
    19 
    20 using System;
    21 using System.Collections.Generic;
    22 using System.ComponentModel;
    23 using System.Data;
    24 using System.Drawing;
    25 using System.Linq;
    26 using System.Text;
    27 using System.Threading.Tasks;
    28 using System.Windows.Forms;
    29 using System.IO;
    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;
    37 //NAudio
    38 using NAudio.CoreAudioApi;
    39 using NAudio.CoreAudioApi.Interfaces;
    40 using System.Runtime.InteropServices;
    41 using CecSharp;
    42 //Network
    43 using NETWORKLIST;
    44 //
    45 using SharpDisplayClient;
    46 using SharpDisplay;
    47 using MiniDisplayInterop;
    48 using SharpLib.Display;
    49 using SharpLib.Ear;
    50 
    51 namespace SharpDisplayManager
    52 {
    53     //Types declarations
    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);
    66 
    67     /// <summary>
    68     /// Our Display manager main form
    69     /// </summary>
    70 	[System.ComponentModel.DesignerCategory("Form")]
    71 	public partial class MainForm : MainFormHid, IMMNotificationClient
    72     {
    73         //public ManagerEventAction iManager = new ManagerEventAction();        
    74         DateTime LastTickTime;
    75         Display iDisplay;
    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;
    84         //
    85         public bool iClosing;
    86 		//
    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;
    94 		//NAudio
    95 		private MMDeviceEnumerator iMultiMediaDeviceEnumerator;
    96 		private MMDevice iMultiMediaDevice;
    97 		//Network
    98 		private NetworkManager iNetworkManager;
    99 
   100         /// <summary>
   101         /// CEC - Consumer Electronic Control.
   102         /// Notably used to turn TV on and off as Windows broadcast monitor on and off notifications.
   103         /// </summary>
   104         private ConsumerElectronicControl iCecManager;
   105 		
   106 		/// <summary>
   107 		/// Manage run when Windows startup option
   108 		/// </summary>
   109 		private StartupManager iStartupManager;
   110 
   111 		/// <summary>
   112 		/// System notification icon used to hide our application from the task bar.
   113 		/// </summary>
   114 		private SharpLib.Notification.Control iNotifyIcon;
   115 
   116         /// <summary>
   117         /// System recording notification icon.
   118         /// </summary>
   119         private SharpLib.Notification.Control iRecordingNotification;
   120 
   121         /// <summary>
   122         /// 
   123         /// </summary>
   124         RichTextBoxTextWriter iWriter;
   125 
   126 
   127         /// <summary>
   128         /// Allow user to receive window messages;
   129         /// </summary>
   130         public event WndProcDelegate OnWndProc;
   131 
   132         public MainForm()
   133         {
   134             ManagerEventAction.Current = Properties.Settings.Default.Actions;
   135             if (ManagerEventAction.Current == null)
   136             {
   137                 //No actions in our settings yet
   138                 ManagerEventAction.Current = new ManagerEventAction();
   139                 Properties.Settings.Default.Actions = ManagerEventAction.Current;
   140             }
   141             else
   142             {
   143                 //We loaded actions from our settings
   144                 //We need to hook them with corresponding events
   145                 ManagerEventAction.Current.Init();
   146             }
   147             iSkipFrameRendering = false;
   148 			iClosing = 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;
   156 			//
   157 			iClients = new Dictionary<string, ClientData>();
   158 			iStartupManager = new StartupManager();
   159 			iNotifyIcon = new SharpLib.Notification.Control();
   160             iRecordingNotification = new SharpLib.Notification.Control();
   161 
   162             //Have our designer initialize its controls
   163             InitializeComponent();
   164 
   165             //Redirect console output
   166             iWriter = new RichTextBoxTextWriter(richTextBoxLogs);
   167             Console.SetOut(iWriter);
   168 
   169             //Populate device types
   170             PopulateDeviceTypes();
   171 
   172             //Populate optical drives
   173             PopulateOpticalDrives();
   174 
   175 			//Initial status update 
   176             UpdateStatus();
   177 
   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;
   182 
   183 			//Minimize our window if desired
   184 			if (Properties.Settings.Default.StartMinimized)
   185 			{
   186 				WindowState = FormWindowState.Minimized;
   187 			}
   188 
   189         }
   190 
   191 		/// <summary>
   192 		///
   193 		/// </summary>
   194 		/// <param name="sender"></param>
   195 		/// <param name="e"></param>
   196         private void MainForm_Load(object sender, EventArgs e)
   197         {
   198 			//Check if we are running a Click Once deployed application
   199 			if (ApplicationDeployment.IsNetworkDeployed)
   200 			{
   201 				//This is a proper Click Once installation, fetch and show our version number
   202 				this.Text += " - v" + ApplicationDeployment.CurrentDeployment.CurrentVersion;
   203 			}
   204 			else
   205 			{
   206 				//Not a proper Click Once installation, assuming development build then
   207 				this.Text += " - development";
   208 			}
   209 
   210 			//NAudio
   211 			iMultiMediaDeviceEnumerator = new MMDeviceEnumerator();
   212 			iMultiMediaDeviceEnumerator.RegisterEndpointNotificationCallback(this);			
   213 			UpdateAudioDeviceAndMasterVolumeThreadSafe();
   214 
   215 			//Network
   216 			iNetworkManager = new NetworkManager();
   217 			iNetworkManager.OnConnectivityChanged += OnConnectivityChanged;
   218 			UpdateNetworkStatus();
   219 
   220             //CEC
   221             iCecManager = new ConsumerElectronicControl();
   222             OnWndProc += iCecManager.OnWndProc;
   223             ResetCec();
   224 
   225             //Setup Events
   226             SetupEvents();
   227 
   228             //Setup notification icon
   229             SetupTrayIcon();
   230 
   231             //Setup recording notification
   232             SetupRecordingNotification();
   233 
   234             // To make sure start up with minimize to tray works
   235             if (WindowState == FormWindowState.Minimized && Properties.Settings.Default.MinimizeToTray)
   236 			{
   237 				Visible = false;
   238 			}
   239 
   240 #if !DEBUG
   241 			//When not debugging we want the screen to be empty until a client takes over
   242 			ClearLayout();
   243 #else
   244 			//When developing we want at least one client for testing
   245 			StartNewClient("abcdefghijklmnopqrst-0123456789","ABCDEFGHIJKLMNOPQRST-0123456789");
   246 #endif
   247 
   248 			//Open display connection on start-up if needed
   249 			if (Properties.Settings.Default.DisplayConnectOnStartup)
   250 			{
   251 				OpenDisplayConnection();
   252 			}
   253 
   254 			//Start our server so that we can get client requests
   255 			StartServer();
   256 
   257 			//Register for HID events
   258 			RegisterHidDevices();
   259 
   260             //Start Idle client if needed
   261             if (Properties.Settings.Default.StartIdleClient)
   262             {
   263                 StartIdleClient();
   264             }
   265         }
   266 
   267 		/// <summary>
   268 		/// Called when our display is opened.
   269 		/// </summary>
   270 		/// <param name="aDisplay"></param>
   271 		private void OnDisplayOpened(Display aDisplay)
   272 		{
   273             //Make sure we resume frame rendering
   274             iSkipFrameRendering = false;
   275 
   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;
   283 
   284 			//Our display was just opened, update our UI
   285 			UpdateStatus();
   286 			//Initiate asynchronous request
   287 			iDisplay.RequestFirmwareRevision();
   288 
   289 			//Audio
   290 			UpdateMasterVolumeThreadSafe();
   291 			//Network
   292 			UpdateNetworkStatus();
   293 
   294 #if DEBUG
   295 			//Testing icon in debug, no arm done if icon not supported
   296 			//iDisplay.SetIconStatus(Display.TMiniDisplayIconType.EMiniDisplayIconRecording, 0, 1);
   297 			//iDisplay.SetAllIconsStatus(2);
   298 #endif
   299 
   300 		}
   301 
   302         /// <summary>
   303         /// 
   304         /// </summary>
   305         private void SetupEvents()
   306         {
   307             //Reset our tree
   308             iTreeViewEvents.Nodes.Clear();
   309             //Populate registered events
   310             foreach (string key in ManagerEventAction.Current.Events.Keys)
   311             {
   312                 Event e = ManagerEventAction.Current.Events[key];
   313                 TreeNode eventNode = iTreeViewEvents.Nodes.Add(key,e.Name);
   314                 eventNode.Tag = e;
   315                 eventNode.Nodes.Add(key + ".Description", e.Description);
   316                 TreeNode actionsNodes = eventNode.Nodes.Add(key + ".Actions", "Actions");
   317 
   318                 // Add our actions for that event
   319                 foreach (SharpLib.Ear.Action a in e.Actions)
   320                 {
   321                     TreeNode actionNode = actionsNodes.Nodes.Add(a.Name);
   322                     actionNode.Tag = a;
   323                 }
   324             }
   325 
   326             iTreeViewEvents.ExpandAll();
   327 
   328         }
   329 
   330 		/// <summary>
   331 		/// Called when our display is closed.
   332 		/// </summary>
   333 		/// <param name="aDisplay"></param>
   334 		private void OnDisplayClosed(Display aDisplay)
   335 		{
   336             //Our display was just closed, update our UI consequently
   337             UpdateStatus();
   338 		}
   339 
   340 		public void OnConnectivityChanged(NetworkManager aNetwork, NLM_CONNECTIVITY newConnectivity)
   341 		{
   342 			//Update network status
   343 			UpdateNetworkStatus();			
   344 		}
   345 
   346 		/// <summary>
   347 		/// Update our Network Status
   348 		/// </summary>
   349 		private void UpdateNetworkStatus()
   350 		{
   351 			if (iDisplay.IsOpen())
   352 			{
   353                 iDisplay.SetIconOnOff(MiniDisplay.IconType.Internet, iNetworkManager.NetworkListManager.IsConnectedToInternet);
   354                 iDisplay.SetIconOnOff(MiniDisplay.IconType.NetworkSignal, iNetworkManager.NetworkListManager.IsConnected);
   355 			}
   356 		}
   357 
   358 
   359 		int iLastNetworkIconIndex = 0;
   360 		int iUpdateCountSinceLastNetworkAnimation = 0;
   361 
   362 		/// <summary>
   363 		/// 
   364 		/// </summary>
   365 		private void UpdateNetworkSignal(DateTime aLastTickTime, DateTime aNewTickTime)
   366 		{
   367 			iUpdateCountSinceLastNetworkAnimation++;
   368 			iUpdateCountSinceLastNetworkAnimation = iUpdateCountSinceLastNetworkAnimation % 4;
   369 
   370 			if (iDisplay.IsOpen() && iNetworkManager.NetworkListManager.IsConnected && iUpdateCountSinceLastNetworkAnimation==0)
   371 			{
   372                 int iconCount = iDisplay.IconCount(MiniDisplay.IconType.NetworkSignal);
   373 				if (iconCount <= 0)
   374 				{
   375 					//Prevents div by zero and other undefined behavior
   376 					return;
   377 				}
   378 				iLastNetworkIconIndex++;
   379 				iLastNetworkIconIndex = iLastNetworkIconIndex % (iconCount*2);
   380 				for (int i=0;i<iconCount;i++)
   381 				{
   382 					if (i < iLastNetworkIconIndex && !(i == 0 && iLastNetworkIconIndex > 3) && !(i == 1 && iLastNetworkIconIndex > 4))
   383 					{
   384                         iDisplay.SetIconOn(MiniDisplay.IconType.NetworkSignal, i);
   385 					}
   386 					else
   387 					{
   388                         iDisplay.SetIconOff(MiniDisplay.IconType.NetworkSignal, i);
   389 					}
   390 				}				
   391 			}
   392 		}
   393 
   394 
   395 
   396         /// <summary>
   397         /// Receive volume change notification and reflect changes on our slider.
   398         /// </summary>
   399         /// <param name="data"></param>
   400         public void OnVolumeNotificationThreadSafe(AudioVolumeNotificationData data)
   401         {
   402 			UpdateMasterVolumeThreadSafe();
   403         }
   404 
   405         /// <summary>
   406         /// Update master volume when user moves our slider.
   407         /// </summary>
   408         /// <param name="sender"></param>
   409         /// <param name="e"></param>
   410         private void trackBarMasterVolume_Scroll(object sender, EventArgs e)
   411         {
   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;
   416         }
   417 
   418 
   419 		/// <summary>
   420 		/// Mute check box changed.
   421 		/// </summary>
   422 		/// <param name="sender"></param>
   423 		/// <param name="e"></param>
   424 		private void checkBoxMute_CheckedChanged(object sender, EventArgs e)
   425 		{
   426 			iMultiMediaDevice.AudioEndpointVolume.Mute = checkBoxMute.Checked;
   427 		}
   428 
   429         /// <summary>
   430         /// Device State Changed
   431         /// </summary>
   432         public void OnDeviceStateChanged([MarshalAs(UnmanagedType.LPWStr)] string deviceId, [MarshalAs(UnmanagedType.I4)] DeviceState newState){}
   433 
   434         /// <summary>
   435         /// Device Added
   436         /// </summary>
   437         public void OnDeviceAdded([MarshalAs(UnmanagedType.LPWStr)] string pwstrDeviceId) { }
   438 
   439         /// <summary>
   440         /// Device Removed
   441         /// </summary>
   442         public void OnDeviceRemoved([MarshalAs(UnmanagedType.LPWStr)] string deviceId) { }
   443 
   444         /// <summary>
   445         /// Default Device Changed
   446         /// </summary>
   447         public void OnDefaultDeviceChanged(DataFlow flow, Role role, [MarshalAs(UnmanagedType.LPWStr)] string defaultDeviceId)
   448         {
   449             if (role == Role.Multimedia && flow == DataFlow.Render)
   450             {
   451                 UpdateAudioDeviceAndMasterVolumeThreadSafe();
   452             }
   453         }
   454 
   455         /// <summary>
   456         /// Property Value Changed
   457         /// </summary>
   458         /// <param name="pwstrDeviceId"></param>
   459         /// <param name="key"></param>
   460         public void OnPropertyValueChanged([MarshalAs(UnmanagedType.LPWStr)] string pwstrDeviceId, PropertyKey key){}
   461 
   462 
   463         
   464 
   465 		/// <summary>
   466 		/// Update master volume indicators based our current system states.
   467 		/// This typically includes volume levels and mute status.
   468 		/// </summary>
   469 		private void UpdateMasterVolumeThreadSafe()
   470 		{
   471 			if (this.InvokeRequired)
   472 			{
   473 				//Not in the proper thread, invoke ourselves
   474 				PlainUpdateDelegate d = new PlainUpdateDelegate(UpdateMasterVolumeThreadSafe);
   475 				this.Invoke(d, new object[] { });
   476 				return;
   477 			}
   478 
   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;
   484 
   485 			//If our display connection is open we need to update its icons
   486 			if (iDisplay.IsOpen())
   487 			{
   488 				//First take care our our volume level icons
   489                 int volumeIconCount = iDisplay.IconCount(MiniDisplay.IconType.Volume);
   490 				if (volumeIconCount > 0)
   491 				{					
   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;
   498 
   499 					for (int i = 0; i < volumeIconCount; i++)
   500 					{
   501 						if (i < segmentOnCount)
   502 						{
   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)
   505 							{
   506 								//Half brightness
   507                                 iDisplay.SetIconStatus(MiniDisplay.IconType.Volume, i, (iDisplay.IconStatusCount(MiniDisplay.IconType.Volume) - 1) / 2);
   508 							}
   509 							else
   510 							{
   511 								//Full brightness
   512                                 iDisplay.SetIconStatus(MiniDisplay.IconType.Volume, i, iDisplay.IconStatusCount(MiniDisplay.IconType.Volume) - 1);
   513 							}
   514 						}
   515 						else
   516 						{
   517                             iDisplay.SetIconStatus(MiniDisplay.IconType.Volume, i, 0);
   518 						}
   519 					}
   520 				}
   521 
   522 				//Take care of our mute icon
   523                 iDisplay.SetIconOnOff(MiniDisplay.IconType.Mute, iMultiMediaDevice.AudioEndpointVolume.Mute);
   524 			}
   525 
   526 		}
   527 
   528         /// <summary>
   529         /// 
   530         /// </summary>
   531         private void UpdateAudioDeviceAndMasterVolumeThreadSafe()
   532         {
   533             if (this.InvokeRequired)
   534             {
   535                 //Not in the proper thread, invoke ourselves
   536 				PlainUpdateDelegate d = new PlainUpdateDelegate(UpdateAudioDeviceAndMasterVolumeThreadSafe);
   537                 this.Invoke(d, new object[] { });
   538                 return;
   539             }
   540             
   541             //We are in the correct thread just go ahead.
   542             try
   543             {                
   544                 //Get our master volume            
   545 				iMultiMediaDevice = iMultiMediaDeviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
   546 				//Update our label
   547 				labelDefaultAudioDevice.Text = iMultiMediaDevice.FriendlyName;
   548 
   549                 //Show our volume in our track bar
   550 				UpdateMasterVolumeThreadSafe();
   551 
   552                 //Register to get volume modifications
   553 				iMultiMediaDevice.AudioEndpointVolume.OnVolumeNotification += OnVolumeNotificationThreadSafe;
   554                 //
   555 				trackBarMasterVolume.Enabled = true;
   556             }
   557             catch (Exception ex)
   558             {
   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;
   563             }
   564         }
   565 
   566 		/// <summary>
   567 		/// 
   568 		/// </summary>
   569 		private void PopulateDeviceTypes()
   570 		{
   571 			int count = Display.TypeCount();
   572 
   573 			for (int i = 0; i < count; i++)
   574 			{
   575 				comboBoxDisplayType.Items.Add(Display.TypeName((MiniDisplay.Type)i));
   576 			}
   577 		}
   578 
   579         /// <summary>
   580         /// 
   581         /// </summary>
   582         private void PopulateOpticalDrives()
   583         {
   584             //Reset our list of drives
   585             comboBoxOpticalDrives.Items.Clear();
   586             comboBoxOpticalDrives.Items.Add("None");
   587 
   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)
   591             {
   592                 Debug.WriteLine("Drive " + d.Name);
   593                 Debug.WriteLine("  Drive type: {0}", d.DriveType);
   594 
   595                 if (d.DriveType==DriveType.CDRom)
   596                 {
   597                     //This is an optical drive, add it now
   598                     comboBoxOpticalDrives.Items.Add(d.Name.Substring(0,2));
   599                 }                
   600             }           
   601         }
   602 
   603         /// <summary>
   604         /// 
   605         /// </summary>
   606         /// <returns></returns>
   607         public string OpticalDriveToEject()
   608         {
   609             return comboBoxOpticalDrives.SelectedItem.ToString();
   610         }
   611 
   612 
   613 
   614 		/// <summary>
   615 		///
   616 		/// </summary>
   617 		private void SetupTrayIcon()
   618 		{
   619 			iNotifyIcon.Icon = GetIcon("vfd.ico");
   620 			iNotifyIcon.Text = "Sharp Display Manager";
   621 			iNotifyIcon.Visible = true;
   622 
   623 			//Double click toggles visibility - typically brings up the application
   624 			iNotifyIcon.DoubleClick += delegate(object obj, EventArgs args)
   625 			{
   626 				SysTrayHideShow();
   627 			};
   628 
   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)
   634 			{
   635 				SysTrayHideShow();
   636 			};
   637 			contextMenu.MenuItems.Add(hideShowItem);
   638 
   639 			//Context menu item separator
   640 			contextMenu.MenuItems.Add(new MenuItem("-"));
   641 
   642 			//Context menu exit item
   643 			MenuItem exitItem = new MenuItem("Exit");
   644 			exitItem.Click += delegate(object obj, EventArgs args)
   645 			{
   646 				Application.Exit();
   647 			};
   648 			contextMenu.MenuItems.Add(exitItem);
   649 
   650 			iNotifyIcon.ContextMenu = contextMenu;
   651 		}
   652 
   653         /// <summary>
   654         ///
   655         /// </summary>
   656         private void SetupRecordingNotification()
   657         {
   658             iRecordingNotification.Icon = GetIcon("record.ico");
   659             iRecordingNotification.Text = "No recording";
   660             iRecordingNotification.Visible = false;
   661         }
   662 
   663         /// <summary>
   664         /// Access icons from embedded resources.
   665         /// </summary>
   666         /// <param name="aName"></param>
   667         /// <returns></returns>
   668         public static Icon GetIcon(string aName)
   669 		{
   670 			string[] names =  Assembly.GetExecutingAssembly().GetManifestResourceNames();
   671 			foreach (string name in names)
   672 			{
   673                 //Find a resource name that ends with the given name
   674 				if (name.EndsWith(aName))
   675 				{
   676 					using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))
   677 					{
   678 						return new Icon(stream);
   679 					}
   680 				}
   681 			}
   682 
   683 			return null;
   684 		}
   685 
   686 
   687         /// <summary>
   688         /// Set our current client.
   689         /// This will take care of applying our client layout and set data fields.
   690         /// </summary>
   691         /// <param name="aSessionId"></param>
   692         void SetCurrentClient(string aSessionId, bool aForce=false)
   693         {
   694             if (aSessionId == iCurrentClientSessionId)
   695             {
   696                 //Given client is already the current one.
   697                 //Don't bother changing anything then.
   698                 return;
   699             }
   700 
   701             ClientData requestedClientData = iClients[aSessionId];
   702 
   703             //Check when was the last time we switched to that client
   704             if (iCurrentClientData != null)
   705             {
   706                 //Do not switch client if priority of current client is higher 
   707                 if (!aForce && requestedClientData.Priority < iCurrentClientData.Priority)
   708                 {
   709                     return;
   710                 }
   711 
   712 
   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?
   718                 if (!aForce &&
   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
   721                 {
   722                     //Don't switch clients too often
   723                     return;
   724                 }
   725             }
   726 
   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);
   735         }
   736 
   737         private void buttonFont_Click(object sender, EventArgs e)
   738         {
   739             //fontDialog.ShowColor = true;
   740             //fontDialog.ShowApply = true;
   741             fontDialog.ShowEffects = true;
   742             fontDialog.Font = cds.Font;
   743 
   744             fontDialog.FixedPitchOnly = checkBoxFixedPitchFontOnly.Checked;
   745 
   746             //fontDialog.ShowHelp = true;
   747 
   748             //fontDlg.MaxSize = 40;
   749             //fontDlg.MinSize = 22;
   750 
   751             //fontDialog.Parent = this;
   752             //fontDialog.StartPosition = FormStartPosition.CenterParent;
   753 
   754             //DlgBox.ShowDialog(fontDialog);
   755 
   756             //if (fontDialog.ShowDialog(this) != DialogResult.Cancel)
   757             if (DlgBox.ShowDialog(fontDialog) != DialogResult.Cancel)
   758             {
   759                 //Set the fonts to all our labels in our layout
   760                 foreach (Control ctrl in iTableLayoutPanel.Controls)
   761                 {
   762                     if (ctrl is MarqueeLabel)
   763                     {
   764                         ((MarqueeLabel)ctrl).Font = fontDialog.Font;
   765                     }
   766                 }
   767 
   768                 //Save font settings
   769                 cds.Font = fontDialog.Font;
   770                 Properties.Settings.Default.Save();
   771                 //
   772                 CheckFontHeight();
   773             }
   774         }
   775 
   776         /// <summary>
   777         ///
   778         /// </summary>
   779         void CheckFontHeight()
   780         {
   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)
   785             {
   786                 labelFontWidth.Visible = false;
   787             }
   788             else
   789             {
   790                 labelFontWidth.Visible = true;
   791                 labelFontWidth.Text = "Font width: " + charWidth;
   792             }
   793 
   794             MarqueeLabel label = null;
   795             //Get the first label control we can find
   796             foreach (Control ctrl in iTableLayoutPanel.Controls)
   797             {
   798                 if (ctrl is MarqueeLabel)
   799                 {
   800                     label = (MarqueeLabel)ctrl;
   801                     break;
   802                 }
   803             }
   804 
   805             //Now check font height and show a warning if needed.
   806             if (label != null && label.Font.Height > label.Height)
   807             {
   808                 labelWarning.Text = "WARNING: Selected font is too height by " + (label.Font.Height - label.Height) + " pixels!";
   809                 labelWarning.Visible = true;
   810             }
   811             else
   812             {
   813                 labelWarning.Visible = false;
   814             }
   815 
   816         }
   817 
   818         private void buttonCapture_Click(object sender, EventArgs e)
   819         {
   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");
   824 
   825             ((MarqueeLabel)iTableLayoutPanel.Controls[0]).Text = "Captured";
   826 
   827             /*
   828             string outputFileName = "d:\\capture.png";
   829             using (MemoryStream memory = new MemoryStream())
   830             {
   831                 using (FileStream fs = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
   832                 {
   833                     bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
   834                     byte[] bytes = memory.ToArray();
   835                     fs.Write(bytes, 0, bytes.Length);
   836                 }
   837             }
   838              */
   839 
   840         }
   841 
   842         private void CheckForRequestResults()
   843         {
   844             if (iDisplay.IsRequestPending())
   845             {
   846                 switch (iDisplay.AttemptRequestCompletion())
   847                 {
   848                     case MiniDisplay.Request.FirmwareRevision:
   849                         toolStripStatusLabelConnect.Text += " v" + iDisplay.FirmwareRevision();
   850                         //Issue next request then
   851                         iDisplay.RequestPowerSupplyStatus();
   852                         break;
   853 
   854                     case MiniDisplay.Request.PowerSupplyStatus:
   855                         if (iDisplay.PowerSupplyStatus())
   856                         {
   857                             toolStripStatusLabelPower.Text = "ON";
   858                         }
   859                         else
   860                         {
   861                             toolStripStatusLabelPower.Text = "OFF";
   862                         }
   863                         //Issue next request then
   864                         iDisplay.RequestDeviceId();
   865                         break;
   866 
   867                     case MiniDisplay.Request.DeviceId:
   868                         toolStripStatusLabelConnect.Text += " - " + iDisplay.DeviceId();
   869                         //No more request to issue
   870                         break;
   871                 }
   872             }
   873         }
   874 
   875         public static uint ColorWhiteIsOn(int aX, int aY, uint aPixel)
   876         {
   877             if ((aPixel & 0x00FFFFFF) == 0x00FFFFFF)
   878             {
   879                 return 0xFFFFFFFF;
   880             }
   881             return 0x00000000;
   882         }
   883 
   884         public static uint ColorUntouched(int aX, int aY, uint aPixel)
   885         {
   886             return aPixel;
   887         }
   888 
   889         public static uint ColorInversed(int aX, int aY, uint aPixel)
   890         {
   891             return ~aPixel;
   892         }
   893 
   894         public static uint ColorChessboard(int aX, int aY, uint aPixel)
   895         {
   896             if ((aX % 2 == 0) && (aY % 2 == 0))
   897             {
   898                 return ~aPixel;
   899             }
   900             else if ((aX % 2 != 0) && (aY % 2 != 0))
   901             {
   902                 return ~aPixel;
   903             }
   904             return 0x00000000;
   905         }
   906 
   907 
   908         public static int ScreenReversedX(System.Drawing.Bitmap aBmp, int aX)
   909         {
   910             return aBmp.Width - aX - 1;
   911         }
   912 
   913         public int ScreenReversedY(System.Drawing.Bitmap aBmp, int aY)
   914         {
   915             return iBmp.Height - aY - 1;
   916         }
   917 
   918         public int ScreenX(System.Drawing.Bitmap aBmp, int aX)
   919         {
   920             return aX;
   921         }
   922 
   923         public int ScreenY(System.Drawing.Bitmap aBmp, int aY)
   924         {
   925             return aY;
   926         }
   927 
   928         /// <summary>
   929         /// Select proper pixel delegates according to our current settings.
   930         /// </summary>
   931         private void SetupPixelDelegates()
   932         {
   933             //Select our pixel processing routine
   934             if (cds.InverseColors)
   935             {
   936                 //iColorFx = ColorChessboard;
   937                 iColorFx = ColorInversed;
   938             }
   939             else
   940             {
   941                 iColorFx = ColorWhiteIsOn;
   942             }
   943 
   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)
   947             {
   948                 iScreenX = ScreenReversedX;
   949                 iScreenY = ScreenReversedY;
   950             }
   951             else
   952             {
   953                 iScreenX = ScreenX;
   954                 iScreenY = ScreenY;
   955             }
   956 
   957         }
   958 
   959         //This is our timer tick responsible to perform our render
   960         private void timer_Tick(object sender, EventArgs e)
   961         {
   962             //Not ideal cause this has nothing to do with display render
   963             LogsUpdate();
   964 
   965             //Update our animations
   966             DateTime NewTickTime = DateTime.Now;
   967 
   968 			UpdateNetworkSignal(LastTickTime, NewTickTime);
   969 
   970             //Update animation for all our marquees
   971             foreach (Control ctrl in iTableLayoutPanel.Controls)
   972             {
   973                 if (ctrl is MarqueeLabel)
   974                 {
   975                     ((MarqueeLabel)ctrl).UpdateAnimation(LastTickTime, NewTickTime);
   976                 }
   977             }
   978 
   979             //Update our display
   980             if (iDisplay.IsOpen())
   981             {
   982                 CheckForRequestResults();
   983 
   984 				//Check if frame rendering is needed
   985 				//Typically used when showing clock
   986 				if (!iSkipFrameRendering)
   987 				{
   988 					//Draw to bitmap
   989 					if (iCreateBitmap)
   990 					{
   991                         iBmp = new System.Drawing.Bitmap(iTableLayoutPanel.Width, iTableLayoutPanel.Height, PixelFormat.Format32bppArgb);
   992                         iCreateBitmap = false;
   993                     }
   994 					iTableLayoutPanel.DrawToBitmap(iBmp, iTableLayoutPanel.ClientRectangle);
   995 					//iBmp.Save("D:\\capture.png");
   996 
   997 					//Send it to our display
   998 					for (int i = 0; i < iBmp.Width; i++)
   999 					{
  1000 						for (int j = 0; j < iBmp.Height; j++)
  1001 						{
  1002 							unchecked
  1003 							{
  1004 								//Get our processed pixel coordinates
  1005 								int x = iScreenX(iBmp, i);
  1006 								int y = iScreenY(iBmp, j);
  1007 								//Get pixel color
  1008 								uint color = (uint)iBmp.GetPixel(i, j).ToArgb();
  1009 								//Apply color effects
  1010 								color = iColorFx(x, y, color);
  1011 								//Now set our pixel
  1012 								iDisplay.SetPixel(x, y, color);
  1013 							}
  1014 						}
  1015 					}
  1016 
  1017 					iDisplay.SwapBuffers();
  1018 				}
  1019             }
  1020 
  1021             //Compute instant FPS
  1022             toolStripStatusLabelFps.Text = (1.0/NewTickTime.Subtract(LastTickTime).TotalSeconds).ToString("F0") + " / " + (1000/timer.Interval).ToString() + " FPS";
  1023 
  1024             LastTickTime = NewTickTime;
  1025 
  1026         }
  1027 
  1028 		/// <summary>
  1029 		/// Attempt to establish connection with our display hardware.
  1030 		/// </summary>
  1031         private void OpenDisplayConnection()
  1032         {
  1033             CloseDisplayConnection();
  1034 
  1035             if (!iDisplay.Open((MiniDisplay.Type)cds.DisplayType))
  1036             {   
  1037 				UpdateStatus();               
  1038 				toolStripStatusLabelConnect.Text = "Connection error";
  1039             }
  1040         }
  1041 
  1042         private void CloseDisplayConnection()
  1043         {
  1044 			//Status will be updated upon receiving the closed event
  1045 
  1046 			if (iDisplay == null || !iDisplay.IsOpen())
  1047 			{
  1048 				return;
  1049 			}
  1050 
  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)
  1054 			{
  1055 				iDisplay.Clear();
  1056 				iDisplay.SwapBuffers();
  1057 			}
  1058 
  1059 			iDisplay.SetAllIconsStatus(0); //Turn off all icons
  1060             iDisplay.Close();
  1061         }
  1062 
  1063         private void buttonOpen_Click(object sender, EventArgs e)
  1064         {
  1065             OpenDisplayConnection();
  1066         }
  1067 
  1068         private void buttonClose_Click(object sender, EventArgs e)
  1069         {
  1070             CloseDisplayConnection();
  1071         }
  1072 
  1073         private void buttonClear_Click(object sender, EventArgs e)
  1074         {
  1075             iDisplay.Clear();
  1076             iDisplay.SwapBuffers();
  1077         }
  1078 
  1079         private void buttonFill_Click(object sender, EventArgs e)
  1080         {
  1081             iDisplay.Fill();
  1082             iDisplay.SwapBuffers();
  1083         }
  1084 
  1085         private void trackBarBrightness_Scroll(object sender, EventArgs e)
  1086         {
  1087             cds.Brightness = trackBarBrightness.Value;
  1088             Properties.Settings.Default.Save();
  1089             iDisplay.SetBrightness(trackBarBrightness.Value);
  1090 
  1091         }
  1092 
  1093 
  1094         /// <summary>
  1095         /// CDS stands for Current Display Settings
  1096         /// </summary>
  1097         private DisplaySettings cds
  1098         {
  1099             get
  1100             {
  1101                 DisplaysSettings settings = Properties.Settings.Default.DisplaysSettings;
  1102                 if (settings == null)
  1103                 {
  1104                     settings = new DisplaysSettings();
  1105                     settings.Init();
  1106                     Properties.Settings.Default.DisplaysSettings = settings;
  1107                 }
  1108 
  1109                 //Make sure all our settings have been created
  1110                 while (settings.Displays.Count <= Properties.Settings.Default.CurrentDisplayIndex)
  1111                 {
  1112                     settings.Displays.Add(new DisplaySettings());
  1113                 }
  1114 
  1115                 DisplaySettings displaySettings = settings.Displays[Properties.Settings.Default.CurrentDisplayIndex];
  1116                 return displaySettings;
  1117             }
  1118         }
  1119 
  1120         /// <summary>
  1121         /// Check if the given font has a fixed character pitch.
  1122         /// </summary>
  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)
  1126         {
  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;
  1130 
  1131             bool fixedWidth = true;
  1132 
  1133             foreach (char c in charSizes)
  1134                 if (g.MeasureString(c.ToString(), ft, Int32.MaxValue, StringFormat.GenericTypographic).Width != charWidth)
  1135                     fixedWidth = false;
  1136 
  1137             if (fixedWidth)
  1138             {
  1139                 return charWidth;
  1140             }
  1141 
  1142             return 0.0f;
  1143         }
  1144 
  1145 		/// <summary>
  1146 		/// Synchronize UI with settings
  1147 		/// </summary>
  1148         private void UpdateStatus()
  1149         {            
  1150             //Load settings
  1151             checkBoxShowBorders.Checked = cds.ShowBorders;
  1152             iTableLayoutPanel.CellBorderStyle = (cds.ShowBorders ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
  1153 
  1154             //Set the proper font to each of our labels
  1155             foreach (MarqueeLabel ctrl in iTableLayoutPanel.Controls)
  1156             {
  1157                 ctrl.Font = cds.Font;
  1158             }
  1159 
  1160             CheckFontHeight();
  1161 			//Check if "run on Windows startup" is enabled
  1162 			checkBoxAutoStart.Checked = iStartupManager.Startup;
  1163 			//
  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;
  1169 
  1170 
  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)
  1176             {
  1177                 if (opticalDriveToEject == item.ToString())
  1178                 {
  1179                     comboBoxOpticalDrives.SelectedIndex = opticalDriveItemIndex;
  1180                     driveNotFound = false;
  1181                     break;
  1182                 }
  1183                 opticalDriveItemIndex++;
  1184             }
  1185 
  1186             if (driveNotFound)
  1187             {
  1188                 //We could not find the drive we had saved.
  1189                 //Select "None" then.
  1190                 comboBoxOpticalDrives.SelectedIndex = 0;
  1191             }
  1192 
  1193             //CEC settings
  1194             checkBoxCecEnabled.Checked = Properties.Settings.Default.CecEnabled;
  1195             comboBoxHdmiPort.SelectedIndex = Properties.Settings.Default.CecHdmiPort - 1;
  1196 
  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;
  1210             //
  1211             SetupPixelDelegates();
  1212 
  1213             if (iDisplay.IsOpen())
  1214             {
  1215                 //We have a display connection
  1216                 //Reflect that in our UI
  1217                 StartTimer();
  1218 
  1219 				iTableLayoutPanel.Enabled = true;
  1220 				panelDisplay.Enabled = true;
  1221 
  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())
  1226 				{
  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());
  1231 				}
  1232 				else
  1233 				{
  1234 					trackBarBrightness.Value = cds.Brightness;
  1235 					iDisplay.SetBrightness(cds.Brightness);
  1236 				}
  1237 
  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;
  1241                 
  1242                 //
  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();
  1250 
  1251                 if (iDisplay.SupportPowerOnOff())
  1252                 {
  1253                     buttonPowerOn.Enabled = true;
  1254                     buttonPowerOff.Enabled = true;
  1255                 }
  1256                 else
  1257                 {
  1258                     buttonPowerOn.Enabled = false;
  1259                     buttonPowerOff.Enabled = false;
  1260                 }
  1261 
  1262                 if (iDisplay.SupportClock())
  1263                 {
  1264                     buttonShowClock.Enabled = true;
  1265                     buttonHideClock.Enabled = true;
  1266                 }
  1267                 else
  1268                 {
  1269                     buttonShowClock.Enabled = false;
  1270                     buttonHideClock.Enabled = false;
  1271                 }
  1272 
  1273 				
  1274 				//Check if Volume Label is supported. To date only MDM166AA supports that crap :)
  1275 				checkBoxShowVolumeLabel.Enabled = iDisplay.IconCount(MiniDisplay.IconType.VolumeLabel)>0;
  1276 
  1277 				if (cds.ShowVolumeLabel)
  1278 				{
  1279                     iDisplay.SetIconOn(MiniDisplay.IconType.VolumeLabel);
  1280 				}
  1281 				else
  1282 				{
  1283                     iDisplay.SetIconOff(MiniDisplay.IconType.VolumeLabel);
  1284 				}
  1285             }
  1286             else
  1287             {
  1288                 //Display connection not available
  1289                 //Reflect that in our UI
  1290 #if DEBUG
  1291                 //In debug start our timer even if we don't have a display connection
  1292                 StartTimer();
  1293 #else
  1294                 //In production environment we don't need our timer if no display connection
  1295                 StopTimer();
  1296 #endif
  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";
  1311             }
  1312 
  1313         }
  1314 
  1315 
  1316 		/// <summary>
  1317 		/// 
  1318 		/// </summary>
  1319 		/// <param name="sender"></param>
  1320 		/// <param name="e"></param>
  1321 		private void checkBoxShowVolumeLabel_CheckedChanged(object sender, EventArgs e)
  1322 		{
  1323 			cds.ShowVolumeLabel = checkBoxShowVolumeLabel.Checked;
  1324 			Properties.Settings.Default.Save();
  1325 			UpdateStatus();
  1326 		}
  1327 
  1328         private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
  1329         {
  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();
  1334             CheckFontHeight();
  1335         }
  1336 
  1337         private void checkBoxConnectOnStartup_CheckedChanged(object sender, EventArgs e)
  1338         {
  1339             //Save our connect on startup setting
  1340             Properties.Settings.Default.DisplayConnectOnStartup = checkBoxConnectOnStartup.Checked;
  1341             Properties.Settings.Default.Save();
  1342         }
  1343 
  1344 		private void checkBoxMinimizeToTray_CheckedChanged(object sender, EventArgs e)
  1345 		{
  1346 			//Save our "Minimize to tray" setting
  1347 			Properties.Settings.Default.MinimizeToTray = checkBoxMinimizeToTray.Checked;
  1348 			Properties.Settings.Default.Save();
  1349 
  1350 		}
  1351 
  1352 		private void checkBoxStartMinimized_CheckedChanged(object sender, EventArgs e)
  1353 		{
  1354 			//Save our "Start minimized" setting
  1355 			Properties.Settings.Default.StartMinimized = checkBoxStartMinimized.Checked;
  1356 			Properties.Settings.Default.Save();
  1357 		}
  1358 
  1359         private void checkBoxStartIdleClient_CheckedChanged(object sender, EventArgs e)
  1360         {
  1361             Properties.Settings.Default.StartIdleClient = iCheckBoxStartIdleClient.Checked;
  1362             Properties.Settings.Default.Save();
  1363         }
  1364 
  1365         private void checkBoxAutoStart_CheckedChanged(object sender, EventArgs e)
  1366 		{
  1367 			iStartupManager.Startup = checkBoxAutoStart.Checked;
  1368 		}
  1369 
  1370 
  1371         private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
  1372         {
  1373             //Save our reverse screen setting
  1374             cds.ReverseScreen = checkBoxReverseScreen.Checked;
  1375             Properties.Settings.Default.Save();
  1376             SetupPixelDelegates();
  1377         }
  1378 
  1379         private void checkBoxInverseColors_CheckedChanged(object sender, EventArgs e)
  1380         {
  1381             //Save our inverse colors setting
  1382             cds.InverseColors = checkBoxInverseColors.Checked;
  1383             Properties.Settings.Default.Save();
  1384             SetupPixelDelegates();
  1385         }
  1386 
  1387         private void checkBoxScaleToFit_CheckedChanged(object sender, EventArgs e)
  1388         {
  1389             //Save our scale to fit setting
  1390             cds.ScaleToFit = checkBoxScaleToFit.Checked;
  1391             Properties.Settings.Default.Save();
  1392             //
  1393             labelMinFontSize.Enabled = cds.ScaleToFit;
  1394             maskedTextBoxMinFontSize.Enabled = cds.ScaleToFit;
  1395         }
  1396 
  1397         private void MainForm_Resize(object sender, EventArgs e)
  1398         {
  1399             if (WindowState == FormWindowState.Minimized)
  1400             {
  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;
  1404             }
  1405         }
  1406 
  1407         private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
  1408         {
  1409             iCecManager.Stop();
  1410 			iNetworkManager.Dispose();
  1411 			CloseDisplayConnection();
  1412             StopServer();
  1413             e.Cancel = iClosing;
  1414         }
  1415 
  1416         public void StartServer()
  1417         {
  1418             iServiceHost = new ServiceHost
  1419                 (
  1420                     typeof(Session),
  1421                     new Uri[] { new Uri("net.tcp://localhost:8001/") }
  1422                 );
  1423 
  1424             iServiceHost.AddServiceEndpoint(typeof(IService), new NetTcpBinding(SecurityMode.None, true), "DisplayService");
  1425             iServiceHost.Open();
  1426         }
  1427 
  1428         public void StopServer()
  1429         {
  1430             if (iClients.Count > 0 && !iClosing)
  1431             {
  1432                 //Tell our clients
  1433                 iClosing = true;
  1434                 BroadcastCloseEvent();
  1435             }
  1436             else if (iClosing)
  1437             {
  1438                 if (MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
  1439                 {
  1440                     iClosing = false; //We make sure we force close if asked twice
  1441                 }
  1442             }
  1443             else
  1444             {
  1445                 //We removed that as it often lags for some reason
  1446                 //iServiceHost.Close();
  1447             }
  1448         }
  1449 
  1450         public void BroadcastCloseEvent()
  1451         {
  1452             Trace.TraceInformation("BroadcastCloseEvent - start");
  1453 
  1454             var inactiveClients = new List<string>();
  1455             foreach (var client in iClients)
  1456             {
  1457                 //if (client.Key != eventData.ClientName)
  1458                 {
  1459                     try
  1460                     {
  1461                         Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
  1462                         client.Value.Callback.OnCloseOrder(/*eventData*/);
  1463                     }
  1464                     catch (Exception ex)
  1465                     {
  1466                         inactiveClients.Add(client.Key);
  1467                     }
  1468                 }
  1469             }
  1470 
  1471             if (inactiveClients.Count > 0)
  1472             {
  1473                 foreach (var client in inactiveClients)
  1474                 {
  1475                     iClients.Remove(client);
  1476                     Program.iMainForm.iTreeViewClients.Nodes.Remove(Program.iMainForm.iTreeViewClients.Nodes.Find(client, false)[0]);
  1477                 }
  1478             }
  1479 
  1480 			if (iClients.Count==0)
  1481 			{
  1482 				ClearLayout();
  1483 			}
  1484         }
  1485 
  1486 		/// <summary>
  1487 		/// Just remove all our fields.
  1488 		/// </summary>
  1489 		private void ClearLayout()
  1490 		{
  1491 			iTableLayoutPanel.Controls.Clear();
  1492 			iTableLayoutPanel.RowStyles.Clear();
  1493 			iTableLayoutPanel.ColumnStyles.Clear();
  1494 			iCurrentClientData = null;
  1495 		}
  1496 
  1497 		/// <summary>
  1498 		/// Just launch a demo client.
  1499 		/// </summary>
  1500 		private void StartNewClient(string aTopText = "", string aBottomText = "")
  1501 		{
  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);
  1505 			BringToFront();
  1506 		}
  1507 
  1508         /// <summary>
  1509         /// Just launch our idle client.
  1510         /// </summary>
  1511         private void StartIdleClient(string aTopText = "", string aBottomText = "")
  1512         {
  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);
  1516             BringToFront();
  1517         }
  1518 
  1519 
  1520         private void buttonStartClient_Click(object sender, EventArgs e)
  1521         {
  1522 			StartNewClient();
  1523         }
  1524 
  1525         private void buttonSuspend_Click(object sender, EventArgs e)
  1526         {
  1527             ToggleTimer();
  1528         }
  1529 
  1530         private void StartTimer()
  1531         {
  1532             LastTickTime = DateTime.Now; //Reset timer to prevent jump
  1533             timer.Enabled = true;
  1534             UpdateSuspendButton();
  1535         }
  1536 
  1537         private void StopTimer()
  1538         {
  1539             LastTickTime = DateTime.Now; //Reset timer to prevent jump
  1540             timer.Enabled = false;
  1541             UpdateSuspendButton();
  1542         }
  1543 
  1544         private void ToggleTimer()
  1545         {
  1546             LastTickTime = DateTime.Now; //Reset timer to prevent jump
  1547             timer.Enabled = !timer.Enabled;
  1548             UpdateSuspendButton();
  1549         }
  1550 
  1551         private void UpdateSuspendButton()
  1552         {
  1553             if (!timer.Enabled)
  1554             {
  1555                 buttonSuspend.Text = "Run";
  1556             }
  1557             else
  1558             {
  1559                 buttonSuspend.Text = "Pause";
  1560             }
  1561         }
  1562 
  1563 
  1564         private void buttonCloseClients_Click(object sender, EventArgs e)
  1565         {
  1566             BroadcastCloseEvent();
  1567         }
  1568 
  1569         private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
  1570         {
  1571             //Root node must have at least one child
  1572             if (e.Node.Nodes.Count == 0)
  1573             {
  1574                 return;
  1575             }
  1576 
  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
  1580             {
  1581                 //We have a valid session just switch to that client
  1582                 SetCurrentClient(sessionId,true);
  1583             }
  1584             
  1585         }
  1586 
  1587 
  1588         /// <summary>
  1589         ///
  1590         /// </summary>
  1591         /// <param name="aSessionId"></param>
  1592         /// <param name="aCallback"></param>
  1593         public void AddClientThreadSafe(string aSessionId, ICallback aCallback)
  1594         {
  1595             if (this.InvokeRequired)
  1596             {
  1597                 //Not in the proper thread, invoke ourselves
  1598                 AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
  1599                 this.Invoke(d, new object[] { aSessionId, aCallback });
  1600             }
  1601             else
  1602             {
  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);
  1609             }
  1610         }
  1611 
  1612 
  1613         /// <summary>
  1614         /// Find the client with the highest priority if any.
  1615         /// </summary>
  1616         /// <returns>Our highest priority client or null if not a single client is connected.</returns>
  1617         public ClientData FindHighestPriorityClient()
  1618         {
  1619             ClientData highestPriorityClient = null;
  1620             foreach (var client in iClients)
  1621             {
  1622                 if (highestPriorityClient == null || client.Value.Priority > highestPriorityClient.Priority)
  1623                 {
  1624                     highestPriorityClient = client.Value;
  1625                 }
  1626             }
  1627 
  1628             return highestPriorityClient;
  1629         }
  1630 
  1631         /// <summary>
  1632         ///
  1633         /// </summary>
  1634         /// <param name="aSessionId"></param>
  1635         public void RemoveClientThreadSafe(string aSessionId)
  1636         {
  1637             if (this.InvokeRequired)
  1638             {
  1639                 //Not in the proper thread, invoke ourselves
  1640                 RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
  1641                 this.Invoke(d, new object[] { aSessionId });
  1642             }
  1643             else
  1644             {
  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))
  1648                 {
  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();
  1653                 }
  1654 
  1655                 if (iCurrentClientSessionId == aSessionId)
  1656                 {
  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)
  1662                     {
  1663                         SetCurrentClient(newCurrentClient.SessionId, true);
  1664                     }                    
  1665                 }
  1666 
  1667                 if (iClients.Count == 0)
  1668 				{
  1669 					//Clear our screen when last client disconnects
  1670 					ClearLayout();
  1671 
  1672 					if (iClosing)
  1673 					{
  1674 						//We were closing our form
  1675 						//All clients are now closed
  1676 						//Just resume our close operation
  1677 						iClosing = false;
  1678 						Close();
  1679 					}
  1680 				}
  1681             }
  1682         }
  1683 
  1684         /// <summary>
  1685         ///
  1686         /// </summary>
  1687         /// <param name="aSessionId"></param>
  1688         /// <param name="aLayout"></param>
  1689         public void SetClientLayoutThreadSafe(string aSessionId, TableLayout aLayout)
  1690         {
  1691             if (this.InvokeRequired)
  1692             {
  1693                 //Not in the proper thread, invoke ourselves
  1694                 SetLayoutDelegate d = new SetLayoutDelegate(SetClientLayoutThreadSafe);
  1695                 this.Invoke(d, new object[] { aSessionId, aLayout });
  1696             }
  1697             else
  1698             {
  1699                 ClientData client = iClients[aSessionId];
  1700                 if (client != null)
  1701                 {
  1702                     //Don't change a thing if the layout is the same
  1703                     if (!client.Layout.IsSameAs(aLayout))
  1704                     {
  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();
  1712                         //
  1713                         UpdateClientTreeViewNode(client);
  1714                     }
  1715                     else
  1716                     {
  1717                         Debug.Print("SetClientLayoutThreadSafe: Layout has not changed.");
  1718                     }
  1719                 }
  1720             }
  1721         }
  1722 
  1723         /// <summary>
  1724         ///
  1725         /// </summary>
  1726         /// <param name="aSessionId"></param>
  1727         /// <param name="aField"></param>
  1728         public void SetClientFieldThreadSafe(string aSessionId, DataField aField)
  1729         {
  1730             if (this.InvokeRequired)
  1731             {
  1732                 //Not in the proper thread, invoke ourselves
  1733                 SetFieldDelegate d = new SetFieldDelegate(SetClientFieldThreadSafe);
  1734                 this.Invoke(d, new object[] { aSessionId, aField });
  1735             }
  1736             else
  1737             {
  1738                 //We are in the proper thread
  1739                 //Call the non-thread-safe variant
  1740                 SetClientField(aSessionId, aField);
  1741             }
  1742         }
  1743 
  1744 
  1745 
  1746 
  1747         /// <summary>
  1748         /// Set a data field in the given client.
  1749         /// </summary>
  1750         /// <param name="aSessionId"></param>
  1751         /// <param name="aField"></param>
  1752         private void SetClientField(string aSessionId, DataField aField)
  1753         {   
  1754             //TODO: should check if the field actually changed?
  1755 
  1756             ClientData client = iClients[aSessionId];
  1757             bool layoutChanged = false;
  1758             bool contentChanged = true;
  1759 
  1760             //Fetch our field index
  1761             int fieldIndex = client.FindSameFieldIndex(aField);
  1762 
  1763             if (fieldIndex < 0)
  1764             {
  1765                 //No corresponding field, just bail out
  1766                 return;
  1767             }
  1768 
  1769             //Keep our previous field in there
  1770             DataField previousField = client.Fields[fieldIndex];
  1771             //Just update that field then 
  1772             client.Fields[fieldIndex] = aField;
  1773 
  1774             if (!aField.IsTableField)
  1775             {
  1776                 //We are done then if that field is not in our table layout
  1777                 return;
  1778             }
  1779 
  1780             TableField tableField = (TableField) aField;
  1781 
  1782             if (previousField.IsSameLayout(aField))
  1783             {
  1784                 //If we are updating a field in our current client we need to update it in our panel
  1785                 if (aSessionId == iCurrentClientSessionId)
  1786                 {
  1787                     Control ctrl=iTableLayoutPanel.GetControlFromPosition(tableField.Column, tableField.Row);
  1788                     if (aField.IsTextField && ctrl is MarqueeLabel)
  1789                     {
  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;
  1796                     }
  1797                     else if (aField.IsBitmapField && ctrl is PictureBox)
  1798                     {
  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;
  1804                     }
  1805                     else
  1806                     {
  1807                         layoutChanged = true;
  1808                     }
  1809                 }
  1810             }
  1811             else
  1812             {                
  1813                 layoutChanged = true;
  1814             }
  1815 
  1816             //If either content or layout changed we need to update our tree view to reflect the changes
  1817             if (contentChanged || layoutChanged)
  1818             {
  1819                 UpdateClientTreeViewNode(client);
  1820                 //
  1821                 if (layoutChanged)
  1822                 {
  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)
  1826                     {
  1827                         //Apply layout and set data fields.
  1828                         UpdateTableLayoutPanel(iCurrentClientData);
  1829                     }
  1830                 }
  1831                 else
  1832                 {
  1833                     Debug.Print("Layout has not changed.");
  1834                 }
  1835             }
  1836             else
  1837             {
  1838                 Debug.Print("WARNING: content and layout have not changed!");
  1839             }
  1840 
  1841             //When a client field is set we try switching to this client to present the new information to our user
  1842             SetCurrentClient(aSessionId);
  1843         }
  1844 
  1845         /// <summary>
  1846         ///
  1847         /// </summary>
  1848         /// <param name="aTexts"></param>
  1849         public void SetClientFieldsThreadSafe(string aSessionId, System.Collections.Generic.IList<DataField> aFields)
  1850         {
  1851             if (this.InvokeRequired)
  1852             {
  1853                 //Not in the proper thread, invoke ourselves
  1854                 SetFieldsDelegate d = new SetFieldsDelegate(SetClientFieldsThreadSafe);
  1855                 this.Invoke(d, new object[] { aSessionId, aFields });
  1856             }
  1857             else
  1858             {
  1859                 ClientData client = iClients[aSessionId];
  1860 
  1861                 if (client.HasNewLayout)
  1862                 {
  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);
  1871 
  1872                     //If we are updating the current client update our panel
  1873                     if (aSessionId == iCurrentClientSessionId)
  1874                     {
  1875                         //Apply layout and set data fields.
  1876                         UpdateTableLayoutPanel(iCurrentClientData);
  1877                     }
  1878 
  1879                     UpdateClientTreeViewNode(client);
  1880                 }
  1881                 else
  1882                 {
  1883                     //Put each our text fields in a label control
  1884                     foreach (DataField field in aFields)
  1885                     {
  1886                         SetClientField(aSessionId, field);
  1887                     }
  1888                 }
  1889             }
  1890         }
  1891 
  1892         /// <summary>
  1893         ///
  1894         /// </summary>
  1895         /// <param name="aSessionId"></param>
  1896         /// <param name="aName"></param>
  1897         public void SetClientNameThreadSafe(string aSessionId, string aName)
  1898         {
  1899             if (this.InvokeRequired)
  1900             {
  1901                 //Not in the proper thread, invoke ourselves
  1902                 SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
  1903                 this.Invoke(d, new object[] { aSessionId, aName });
  1904             }
  1905             else
  1906             {
  1907                 //We are in the proper thread
  1908                 //Get our client
  1909                 ClientData client = iClients[aSessionId];
  1910                 if (client != null)
  1911                 {
  1912                     //Set its name
  1913                     client.Name = aName;
  1914                     //Update our tree-view
  1915                     UpdateClientTreeViewNode(client);
  1916                 }
  1917             }
  1918         }
  1919 
  1920         ///
  1921         public void SetClientPriorityThreadSafe(string aSessionId, uint aPriority)
  1922         {
  1923             if (this.InvokeRequired)
  1924             {
  1925                 //Not in the proper thread, invoke ourselves
  1926                 SetClientPriorityDelegate d = new SetClientPriorityDelegate(SetClientPriorityThreadSafe);
  1927                 this.Invoke(d, new object[] { aSessionId, aPriority });
  1928             }
  1929             else
  1930             {
  1931                 //We are in the proper thread
  1932                 //Get our client
  1933                 ClientData client = iClients[aSessionId];
  1934                 if (client != null)
  1935                 {
  1936                     //Set its name
  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)
  1943                     {
  1944                         SetCurrentClient(newCurrentClient.SessionId);
  1945                     }
  1946                 }
  1947             }
  1948         }
  1949 
  1950         /// <summary>
  1951         /// 
  1952         /// </summary>
  1953         /// <param name="value"></param>
  1954         /// <param name="maxChars"></param>
  1955         /// <returns></returns>
  1956         public static string Truncate(string value, int maxChars)
  1957         {
  1958             return value.Length <= maxChars ? value : value.Substring(0, maxChars-3) + "...";
  1959         }
  1960 
  1961         /// <summary>
  1962         /// Update our recording notification.
  1963         /// </summary>
  1964         private void UpdateRecordingNotification()
  1965         {
  1966             //Go through each 
  1967             bool activeRecording = false;
  1968             string text="";
  1969             RecordingField recField=new RecordingField();
  1970             foreach (var client in iClients)
  1971             {
  1972                 RecordingField rec=(RecordingField)client.Value.FindSameFieldAs(recField);
  1973                 if (rec!=null && rec.IsActive)
  1974                 {
  1975                     activeRecording = true;
  1976                     //Don't break cause we are collecting the names/texts.
  1977                     if (!String.IsNullOrEmpty(rec.Text))
  1978                     {
  1979                         text += (rec.Text + "\n");
  1980                     }
  1981                     else
  1982                     {
  1983                         //Not text for that recording, use client name instead
  1984                         text += client.Value.Name + " recording\n";
  1985                     }
  1986                     
  1987                 }
  1988             }
  1989 
  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);
  1992 
  1993             //Change visibility of notification if needed
  1994             if (iRecordingNotification.Visible != activeRecording)
  1995             {                
  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())
  2000                 {
  2001                     iDisplay.SetIconOnOff(MiniDisplay.IconType.Recording, activeRecording);
  2002                 }                
  2003             }
  2004         }
  2005 
  2006         /// <summary>
  2007         ///
  2008         /// </summary>
  2009         /// <param name="aClient"></param>
  2010         private void UpdateClientTreeViewNode(ClientData aClient)
  2011         {
  2012             Debug.Print("UpdateClientTreeViewNode");
  2013 
  2014             if (aClient == null)
  2015             {
  2016                 return;
  2017             }
  2018 
  2019             //Hook in record icon update too
  2020             UpdateRecordingNotification();
  2021 
  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)
  2027             {
  2028                 //We already have a node for that client
  2029                 node = nodes[0];
  2030                 //Clear children as we are going to recreate them below
  2031                 node.Nodes.Clear();
  2032             }
  2033             else
  2034             {
  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];
  2038             }
  2039 
  2040             if (node != null)
  2041             {
  2042                 //Change its name
  2043                 if (!String.IsNullOrEmpty(aClient.Name))
  2044                 {
  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));
  2049                 }
  2050                 else
  2051                 {
  2052                     //No name, use session ID instead
  2053                     node.Text = aClient.SessionId;
  2054                 }
  2055 
  2056                 //Display client priority
  2057                 node.Nodes.Add(new TreeNode("Priority: " + aClient.Priority));
  2058 
  2059                 if (aClient.Fields.Count > 0)
  2060                 {
  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)
  2066                     {
  2067                         if (field.IsTextField)
  2068                         {
  2069                             TextField textField = (TextField)field;
  2070                             textsRoot.Nodes.Add(new TreeNode("[Text]" + textField.Text));
  2071                         }
  2072                         else if (field.IsBitmapField)
  2073                         {
  2074                             textsRoot.Nodes.Add(new TreeNode("[Bitmap]"));
  2075                         }
  2076                         else if (field.IsRecordingField)
  2077                         {
  2078                             RecordingField recordingField = (RecordingField)field;
  2079                             textsRoot.Nodes.Add(new TreeNode("[Recording]" + recordingField.IsActive));
  2080                         }
  2081                     }
  2082                 }
  2083 
  2084                 node.ExpandAll();
  2085             }
  2086         }
  2087 
  2088         /// <summary>
  2089         /// Update our table layout row styles to make sure each rows have similar height
  2090         /// </summary>
  2091         private void UpdateTableLayoutRowStyles()
  2092         {
  2093             foreach (RowStyle rowStyle in iTableLayoutPanel.RowStyles)
  2094             {
  2095                 rowStyle.SizeType = SizeType.Percent;
  2096                 rowStyle.Height = 100 / iTableLayoutPanel.RowCount;
  2097             }
  2098         }
  2099 
  2100         /// <summary>
  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.
  2104         /// </summary>
  2105         /// <param name="aLayout"></param>
  2106         private void UpdateTableLayoutPanel(ClientData aClient)
  2107         {
  2108             Debug.Print("UpdateTableLayoutPanel");
  2109 
  2110 			if (aClient == null)
  2111 			{
  2112 				//Just drop it
  2113 				return;
  2114 			}
  2115 
  2116 
  2117             TableLayout layout = aClient.Layout;
  2118 
  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;
  2125 
  2126             //Then recreate our rows...
  2127             while (iTableLayoutPanel.RowCount < layout.Rows.Count)
  2128             {
  2129                 iTableLayoutPanel.RowCount++;
  2130             }
  2131 
  2132             // ...and columns 
  2133             while (iTableLayoutPanel.ColumnCount < layout.Columns.Count)
  2134             {
  2135                 iTableLayoutPanel.ColumnCount++;
  2136             }
  2137 
  2138             //For each column
  2139             for (int i = 0; i < iTableLayoutPanel.ColumnCount; i++)
  2140             {
  2141                 //Create our column styles
  2142                 this.iTableLayoutPanel.ColumnStyles.Add(layout.Columns[i]);
  2143 
  2144                 //For each rows
  2145                 for (int j = 0; j < iTableLayoutPanel.RowCount; j++)
  2146                 {
  2147                     if (i == 0)
  2148                     {
  2149                         //Create our row styles
  2150                         this.iTableLayoutPanel.RowStyles.Add(layout.Rows[j]);
  2151                     }
  2152                     else
  2153                     {
  2154                         continue;
  2155                     }
  2156                 }
  2157             }
  2158 
  2159             //For each field
  2160             foreach (DataField field in aClient.Fields)
  2161             {
  2162                 if (!field.IsTableField)
  2163                 {
  2164                     //That field is not taking part in our table layout skip it
  2165                     continue;
  2166                 }
  2167 
  2168                 TableField tableField = (TableField)field;
  2169 
  2170                 //Create a control corresponding to the field specified for that cell
  2171                 Control control = CreateControlForDataField(tableField);
  2172 
  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);
  2178             }
  2179 
  2180 
  2181             CheckFontHeight();
  2182         }
  2183 
  2184         /// <summary>
  2185         /// Check our type of data field and create corresponding control
  2186         /// </summary>
  2187         /// <param name="aField"></param>
  2188         private Control CreateControlForDataField(DataField aField)
  2189         {
  2190             Control control=null;
  2191             if (aField.IsTextField)
  2192             {
  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;
  2209 
  2210                 TextField field = (TextField)aField;
  2211                 label.TextAlign = field.Alignment;
  2212                 label.UseCompatibleTextRendering = true;
  2213                 label.Text = field.Text;
  2214                 //
  2215                 control = label;
  2216             }
  2217             else if (aField.IsBitmapField)
  2218             {
  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;
  2227                 //Set our image
  2228                 BitmapField field = (BitmapField)aField;
  2229                 picture.Image = field.Bitmap;
  2230                 //
  2231                 control = picture;
  2232             }
  2233             //TODO: Handle recording field?
  2234 
  2235             return control;
  2236         }
  2237 
  2238 		/// <summary>
  2239 		/// Called when the user selected a new display type.
  2240 		/// </summary>
  2241 		/// <param name="sender"></param>
  2242 		/// <param name="e"></param>
  2243         private void comboBoxDisplayType_SelectedIndexChanged(object sender, EventArgs e)
  2244         {
  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();
  2249 
  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())
  2253             {
  2254                 OpenDisplayConnection();
  2255             }
  2256             else
  2257             {
  2258                 UpdateStatus();
  2259             }
  2260         }
  2261 
  2262         private void maskedTextBoxTimerInterval_TextChanged(object sender, EventArgs e)
  2263         {
  2264             if (maskedTextBoxTimerInterval.Text != "")
  2265             {
  2266                 int interval = Convert.ToInt32(maskedTextBoxTimerInterval.Text);
  2267 
  2268                 if (interval > 0)
  2269                 {
  2270                     timer.Interval = interval;
  2271                     cds.TimerInterval = timer.Interval;
  2272                     Properties.Settings.Default.Save();
  2273                 }
  2274             }
  2275         }
  2276 
  2277         private void maskedTextBoxMinFontSize_TextChanged(object sender, EventArgs e)
  2278         {
  2279             if (maskedTextBoxMinFontSize.Text != "")
  2280             {
  2281                 int minFontSize = Convert.ToInt32(maskedTextBoxMinFontSize.Text);
  2282 
  2283                 if (minFontSize > 0)
  2284                 {
  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);
  2289                 }
  2290             }
  2291         }
  2292 
  2293 
  2294 		private void maskedTextBoxScrollingSpeed_TextChanged(object sender, EventArgs e)
  2295 		{
  2296 			if (maskedTextBoxScrollingSpeed.Text != "")
  2297 			{
  2298 				int scrollingSpeed = Convert.ToInt32(maskedTextBoxScrollingSpeed.Text);
  2299 
  2300 				if (scrollingSpeed > 0)
  2301 				{
  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);
  2306 				}
  2307 			}
  2308 		}
  2309 
  2310         private void textBoxScrollLoopSeparator_TextChanged(object sender, EventArgs e)
  2311         {
  2312             cds.Separator = textBoxScrollLoopSeparator.Text;
  2313             Properties.Settings.Default.Save();
  2314 
  2315 			//Update our text fields
  2316 			foreach (MarqueeLabel ctrl in iTableLayoutPanel.Controls)
  2317 			{
  2318 				ctrl.Separator = cds.Separator;
  2319 			}
  2320 
  2321         }
  2322 
  2323         private void buttonPowerOn_Click(object sender, EventArgs e)
  2324         {
  2325             iDisplay.PowerOn();
  2326         }
  2327 
  2328         private void buttonPowerOff_Click(object sender, EventArgs e)
  2329         {
  2330             iDisplay.PowerOff();
  2331         }
  2332 
  2333         private void buttonShowClock_Click(object sender, EventArgs e)
  2334         {
  2335 			ShowClock();
  2336         }
  2337 
  2338         private void buttonHideClock_Click(object sender, EventArgs e)
  2339         {
  2340 			HideClock();
  2341         }
  2342 
  2343         private void buttonUpdate_Click(object sender, EventArgs e)
  2344         {
  2345             InstallUpdateSyncWithInfo();
  2346         }
  2347 
  2348 		/// <summary>
  2349 		/// 
  2350 		/// </summary>
  2351 		void ShowClock()
  2352 		{
  2353 			if (!iDisplay.IsOpen())
  2354 			{
  2355 				return;
  2356 			}
  2357 
  2358 			//Devices like MDM166AA don't support windowing and frame rendering must be stopped while showing our clock
  2359 			iSkipFrameRendering = true;
  2360 			//Clear our screen 
  2361 			iDisplay.Clear();
  2362 			iDisplay.SwapBuffers();
  2363 			//Then show our clock
  2364 			iDisplay.ShowClock();
  2365 		}
  2366 
  2367 		/// <summary>
  2368 		/// 
  2369 		/// </summary>
  2370 		void HideClock()
  2371 		{
  2372 			if (!iDisplay.IsOpen())
  2373 			{
  2374 				return;
  2375 			}
  2376 
  2377 			//Devices like MDM166AA don't support windowing and frame rendering must be stopped while showing our clock
  2378 			iSkipFrameRendering = false;
  2379 			iDisplay.HideClock();
  2380 		}
  2381 
  2382         private void InstallUpdateSyncWithInfo()
  2383         {
  2384             UpdateCheckInfo info = null;
  2385 
  2386             if (ApplicationDeployment.IsNetworkDeployed)
  2387             {
  2388                 ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
  2389 
  2390                 try
  2391                 {
  2392                     info = ad.CheckForDetailedUpdate();
  2393 
  2394                 }
  2395                 catch (DeploymentDownloadException dde)
  2396                 {
  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);
  2398                     return;
  2399                 }
  2400                 catch (InvalidDeploymentException ide)
  2401                 {
  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);
  2403                     return;
  2404                 }
  2405                 catch (InvalidOperationException ioe)
  2406                 {
  2407                     MessageBox.Show("This application cannot be updated. It is likely not a ClickOnce application. Error: " + ioe.Message);
  2408                     return;
  2409                 }
  2410 
  2411 				if (info.UpdateAvailable)
  2412 				{
  2413 					Boolean doUpdate = true;
  2414 
  2415 					if (!info.IsUpdateRequired)
  2416 					{
  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))
  2419 						{
  2420 							doUpdate = false;
  2421 						}
  2422 					}
  2423 					else
  2424 					{
  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);
  2431 					}
  2432 
  2433 					if (doUpdate)
  2434 					{
  2435 						try
  2436 						{
  2437 							ad.Update();
  2438 							MessageBox.Show("The application has been upgraded, and will now restart.");
  2439 							Application.Restart();
  2440 						}
  2441 						catch (DeploymentDownloadException dde)
  2442 						{
  2443 							MessageBox.Show("Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " + dde);
  2444 							return;
  2445 						}
  2446 					}
  2447 				}
  2448 				else
  2449 				{
  2450 					MessageBox.Show("You are already running the latest version.", "Application up-to-date");
  2451 				}
  2452             }
  2453         }
  2454 
  2455 
  2456 		/// <summary>
  2457 		/// Used to
  2458 		/// </summary>
  2459 		private void SysTrayHideShow()
  2460 		{
  2461 			Visible = !Visible;
  2462 			if (Visible)
  2463 			{
  2464 				Activate();
  2465 				WindowState = FormWindowState.Normal;
  2466 			}
  2467 		}
  2468 
  2469 		/// <summary>
  2470 		/// Use to handle minimize events.
  2471 		/// </summary>
  2472 		/// <param name="sender"></param>
  2473 		/// <param name="e"></param>
  2474 		private void MainForm_SizeChanged(object sender, EventArgs e)
  2475 		{
  2476 			if (WindowState == FormWindowState.Minimized && Properties.Settings.Default.MinimizeToTray)
  2477 			{
  2478 				if (Visible)
  2479 				{
  2480 					SysTrayHideShow();
  2481 				}
  2482 			}
  2483 		}
  2484 
  2485 		/// <summary>
  2486 		/// 
  2487 		/// </summary>
  2488 		/// <param name="sender"></param>
  2489 		/// <param name="e"></param>
  2490 		private void tableLayoutPanel_SizeChanged(object sender, EventArgs e)
  2491 		{
  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;
  2495 		}
  2496 
  2497 		/// <summary>
  2498 		/// 
  2499 		/// </summary>
  2500 		/// <param name="sender"></param>
  2501 		/// <param name="e"></param>
  2502 		private void buttonSelectFile_Click(object sender, EventArgs e)
  2503 		{
  2504 			//openFileDialog1.InitialDirectory = "c:\\";
  2505 			//openFileDialog.Filter = "EXE files (*.exe)|*.exe|All files (*.*)|*.*";
  2506 			//openFileDialog.FilterIndex = 1;
  2507 			openFileDialog.RestoreDirectory = true;
  2508 
  2509 			if (DlgBox.ShowDialog(openFileDialog) == DialogResult.OK)
  2510 			{
  2511 				labelStartFileName.Text = openFileDialog.FileName;
  2512 				Properties.Settings.Default.StartFileName = openFileDialog.FileName;
  2513 				Properties.Settings.Default.Save();
  2514 			}
  2515 		}
  2516 
  2517         /// <summary>
  2518         /// 
  2519         /// </summary>
  2520         /// <param name="sender"></param>
  2521         /// <param name="e"></param>
  2522         private void comboBoxOpticalDrives_SelectedIndexChanged(object sender, EventArgs e)
  2523         {
  2524             //Save the optical drive the user selected for ejection
  2525             Properties.Settings.Default.OpticalDriveToEject = comboBoxOpticalDrives.SelectedItem.ToString();
  2526             Properties.Settings.Default.Save();
  2527         }
  2528 
  2529 
  2530         /// <summary>
  2531         /// 
  2532         /// </summary>
  2533         private void LogsUpdate()
  2534         {
  2535             if (iWriter != null)
  2536             {
  2537                 iWriter.Flush();
  2538             }
  2539 
  2540         }
  2541 
  2542         /// <summary>
  2543         /// Broadcast messages to subscribers.
  2544         /// </summary>
  2545         /// <param name="message"></param>
  2546         protected override void WndProc(ref Message aMessage)
  2547         {
  2548             LogsUpdate();
  2549 
  2550             if (OnWndProc!=null)
  2551             {
  2552                 OnWndProc(ref aMessage);
  2553             }
  2554             
  2555             base.WndProc(ref aMessage);
  2556         }
  2557 
  2558         private void checkBoxCecEnabled_CheckedChanged(object sender, EventArgs e)
  2559         {
  2560             //Save CEC enabled status
  2561             Properties.Settings.Default.CecEnabled = checkBoxCecEnabled.Checked;
  2562             Properties.Settings.Default.Save();
  2563             //
  2564             ResetCec();
  2565         }
  2566 
  2567         private void comboBoxHdmiPort_SelectedIndexChanged(object sender, EventArgs e)
  2568         {
  2569             //Save CEC HDMI port
  2570             Properties.Settings.Default.CecHdmiPort = Convert.ToByte(comboBoxHdmiPort.SelectedIndex);
  2571             Properties.Settings.Default.CecHdmiPort++;
  2572             Properties.Settings.Default.Save();
  2573             //
  2574             ResetCec();
  2575         }
  2576 
  2577         /// <summary>
  2578         /// 
  2579         /// </summary>
  2580         private void ResetCec()
  2581         {
  2582             if (iCecManager==null)
  2583             {
  2584                 //Thus skipping initial UI setup
  2585                 return;
  2586             }
  2587 
  2588             iCecManager.Stop();
  2589             //
  2590             if (Properties.Settings.Default.CecEnabled)
  2591             {
  2592                 iCecManager.Start(Handle, "CEC",
  2593                 Properties.Settings.Default.CecHdmiPort);
  2594 
  2595                 SetupCecLogLevel();
  2596             }
  2597         }
  2598 
  2599         /// <summary>
  2600         /// 
  2601         /// </summary>
  2602         private void SetupCecLogLevel()
  2603         {
  2604             //Setup log level
  2605             iCecManager.Client.LogLevel = 0;
  2606 
  2607             if (checkBoxCecLogError.Checked)
  2608                 iCecManager.Client.LogLevel |= (int)CecLogLevel.Error;
  2609 
  2610             if (checkBoxCecLogWarning.Checked)
  2611                 iCecManager.Client.LogLevel |= (int)CecLogLevel.Warning;
  2612 
  2613             if (checkBoxCecLogNotice.Checked)
  2614                 iCecManager.Client.LogLevel |= (int)CecLogLevel.Notice;
  2615 
  2616             if (checkBoxCecLogTraffic.Checked)
  2617                 iCecManager.Client.LogLevel |= (int)CecLogLevel.Traffic;
  2618 
  2619             if (checkBoxCecLogDebug.Checked)
  2620                 iCecManager.Client.LogLevel |= (int)CecLogLevel.Debug;
  2621 
  2622             iCecManager.Client.FilterOutPollLogs = checkBoxCecLogNoPoll.Checked;
  2623 
  2624         }
  2625 
  2626         private void ButtonStartIdleClient_Click(object sender, EventArgs e)
  2627         {
  2628             StartIdleClient();
  2629         }
  2630 
  2631         private void buttonClearLogs_Click(object sender, EventArgs e)
  2632         {
  2633             richTextBoxLogs.Clear();
  2634         }
  2635 
  2636         private void checkBoxCecLogs_CheckedChanged(object sender, EventArgs e)
  2637         {
  2638             SetupCecLogLevel();
  2639         }
  2640 
  2641         private void buttonAddAction_Click(object sender, EventArgs e)
  2642         {
  2643             if (iTreeViewEvents.SelectedNode==null
  2644                 || !(iTreeViewEvents.SelectedNode.Tag is Event))
  2645             {
  2646                 return;
  2647             }
  2648 
  2649             Event earEvent = (Event)iTreeViewEvents.SelectedNode.Tag;
  2650             if (earEvent == null)
  2651             {
  2652                 //Must select event node
  2653                 return;
  2654             }
  2655 
  2656             FormEditAction ea = new FormEditAction();
  2657             DialogResult res = CodeProject.Dialog.DlgBox.ShowDialog(ea);
  2658             if (res == DialogResult.OK)
  2659             {
  2660                 earEvent.Actions.Add(ea.Action);                
  2661                 Properties.Settings.Default.Actions = ManagerEventAction.Current;
  2662                 Properties.Settings.Default.Save();
  2663                 SetupEvents();
  2664             }
  2665         }
  2666 
  2667         private void buttonDeleteAction_Click(object sender, EventArgs e)
  2668         {
  2669             if (iTreeViewEvents.SelectedNode == null
  2670                 || !(iTreeViewEvents.SelectedNode.Tag is SharpLib.Ear.Action))
  2671             {
  2672                 return;
  2673             }
  2674 
  2675             SharpLib.Ear.Action action = (SharpLib.Ear.Action)iTreeViewEvents.SelectedNode.Tag;
  2676             if (action == null)
  2677             {
  2678                 //Must select action node
  2679                 return;
  2680             }
  2681 
  2682             ManagerEventAction.Current.RemoveAction(action);
  2683             Properties.Settings.Default.Actions = ManagerEventAction.Current;
  2684             Properties.Settings.Default.Save();
  2685             SetupEvents();
  2686         }
  2687     }
  2688 }