Server/FormMain.cs
author StephaneLenclud
Sun, 21 Aug 2016 16:30:58 +0200
changeset 248 0220cb84df58
parent 245 448e6a616c22
child 250 b2121d03f6f0
permissions -rw-r--r--
Fixing EAR event edition.
EAR HID event now displays 'Press a key' if not valid.
     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 Ear = SharpLib.Ear;
    50 
    51 namespace SharpDisplayManager
    52 {
    53     //Types declarations
    54     public delegate uint ColorProcessingDelegate(int aX, int aY, uint aPixel);
    55 
    56     public delegate int CoordinateTranslationDelegate(System.Drawing.Bitmap aBmp, int aInt);
    57 
    58     //Delegates are used for our thread safe method
    59     public delegate void AddClientDelegate(string aSessionId, ICallback aCallback);
    60 
    61     public delegate void RemoveClientDelegate(string aSessionId);
    62 
    63     public delegate void SetFieldDelegate(string SessionId, DataField aField);
    64 
    65     public delegate void SetFieldsDelegate(string SessionId, System.Collections.Generic.IList<DataField> aFields);
    66 
    67     public delegate void SetLayoutDelegate(string SessionId, TableLayout aLayout);
    68 
    69     public delegate void SetClientNameDelegate(string aSessionId, string aName);
    70 
    71     public delegate void SetClientPriorityDelegate(string aSessionId, uint aPriority);
    72 
    73     public delegate void PlainUpdateDelegate();
    74 
    75     public delegate void WndProcDelegate(ref Message aMessage);
    76 
    77     /// <summary>
    78     /// Our Display manager main form
    79     /// </summary>
    80     [System.ComponentModel.DesignerCategory("Form")]
    81     public partial class FormMain : FormMainHid, IMMNotificationClient
    82     {
    83         //public Manager iManager = new Manager();        
    84         DateTime LastTickTime;
    85         Display iDisplay;
    86         System.Drawing.Bitmap iBmp;
    87         bool iCreateBitmap; //Workaround render to bitmap issues when minimized
    88         ServiceHost iServiceHost;
    89         // Our collection of clients sorted by session id.
    90         public Dictionary<string, ClientData> iClients;
    91         // The name of the client which informations are currently displayed.
    92         public string iCurrentClientSessionId;
    93         ClientData iCurrentClientData;
    94         //
    95         public bool iClosing;
    96         //
    97         public bool iSkipFrameRendering;
    98         //Function pointer for pixel color filtering
    99         ColorProcessingDelegate iColorFx;
   100         //Function pointer for pixel X coordinate intercept
   101         CoordinateTranslationDelegate iScreenX;
   102         //Function pointer for pixel Y coordinate intercept
   103         CoordinateTranslationDelegate iScreenY;
   104         //NAudio
   105         private MMDeviceEnumerator iMultiMediaDeviceEnumerator;
   106         private MMDevice iMultiMediaDevice;
   107         //Network
   108         private NetworkManager iNetworkManager;
   109 
   110         /// <summary>
   111         /// CEC - Consumer Electronic Control.
   112         /// Notably used to turn TV on and off as Windows broadcast monitor on and off notifications.
   113         /// </summary>
   114         private ConsumerElectronicControl iCecManager;
   115 
   116         /// <summary>
   117         /// Manage run when Windows startup option
   118         /// </summary>
   119         private StartupManager iStartupManager;
   120 
   121         /// <summary>
   122         /// System notification icon used to hide our application from the task bar.
   123         /// </summary>
   124         private SharpLib.Notification.Control iNotifyIcon;
   125 
   126         /// <summary>
   127         /// System recording notification icon.
   128         /// </summary>
   129         private SharpLib.Notification.Control iRecordingNotification;
   130 
   131         /// <summary>
   132         /// 
   133         /// </summary>
   134         RichTextBoxTextWriter iWriter;
   135 
   136 
   137         /// <summary>
   138         /// Allow user to receive window messages;
   139         /// </summary>
   140         public event WndProcDelegate OnWndProc;
   141 
   142         public FormMain()
   143         {
   144             if (Properties.Settings.Default.EarManager == null)
   145             {
   146                 //No actions in our settings yet
   147                 Properties.Settings.Default.EarManager = new EarManager();
   148             }
   149             else
   150             {
   151                 // We loaded events and actions from our settings
   152                 // Internalizer apparently skips constructor so we need to initialize it here
   153                 // Though I reckon that should only be needed when loading an empty EAR manager I guess.
   154                 Properties.Settings.Default.EarManager.Construct();
   155             }
   156             iSkipFrameRendering = false;
   157             iClosing = false;
   158             iCurrentClientSessionId = "";
   159             iCurrentClientData = null;
   160             LastTickTime = DateTime.Now;
   161             //Instantiate our display and register for events notifications
   162             iDisplay = new Display();
   163             iDisplay.OnOpened += OnDisplayOpened;
   164             iDisplay.OnClosed += OnDisplayClosed;
   165             //
   166             iClients = new Dictionary<string, ClientData>();
   167             iStartupManager = new StartupManager();
   168             iNotifyIcon = new SharpLib.Notification.Control();
   169             iRecordingNotification = new SharpLib.Notification.Control();
   170 
   171             //Have our designer initialize its controls
   172             InitializeComponent();
   173 
   174             //Redirect console output
   175             iWriter = new RichTextBoxTextWriter(richTextBoxLogs);
   176             Console.SetOut(iWriter);
   177 
   178             //Populate device types
   179             PopulateDeviceTypes();
   180 
   181             //Initial status update 
   182             UpdateStatus();
   183 
   184             //We have a bug when drawing minimized and reusing our bitmap
   185             //Though I could not reproduce it on Windows 10
   186             iBmp = new System.Drawing.Bitmap(iTableLayoutPanel.Width, iTableLayoutPanel.Height,
   187                 PixelFormat.Format32bppArgb);
   188             iCreateBitmap = false;
   189 
   190             //Minimize our window if desired
   191             if (Properties.Settings.Default.StartMinimized)
   192             {
   193                 WindowState = FormWindowState.Minimized;
   194             }
   195 
   196         }
   197 
   198         /// <summary>
   199         ///
   200         /// </summary>
   201         /// <param name="sender"></param>
   202         /// <param name="e"></param>
   203         private void MainForm_Load(object sender, EventArgs e)
   204         {
   205             //Check if we are running a Click Once deployed application
   206             if (ApplicationDeployment.IsNetworkDeployed)
   207             {
   208                 //This is a proper Click Once installation, fetch and show our version number
   209                 this.Text += " - v" + ApplicationDeployment.CurrentDeployment.CurrentVersion;
   210             }
   211             else
   212             {
   213                 //Not a proper Click Once installation, assuming development build then
   214                 this.Text += " - development";
   215             }
   216 
   217             //NAudio
   218             iMultiMediaDeviceEnumerator = new MMDeviceEnumerator();
   219             iMultiMediaDeviceEnumerator.RegisterEndpointNotificationCallback(this);
   220             UpdateAudioDeviceAndMasterVolumeThreadSafe();
   221 
   222             //Network
   223             iNetworkManager = new NetworkManager();
   224             iNetworkManager.OnConnectivityChanged += OnConnectivityChanged;
   225             UpdateNetworkStatus();
   226 
   227             //CEC
   228             iCecManager = new ConsumerElectronicControl();
   229             OnWndProc += iCecManager.OnWndProc;
   230             ResetCec();
   231 
   232             //Harmony
   233             ResetHarmony();
   234 
   235             //Setup Events
   236             PopulateEventsTreeView();
   237 
   238             //Setup notification icon
   239             SetupTrayIcon();
   240 
   241             //Setup recording notification
   242             SetupRecordingNotification();
   243 
   244             // To make sure start up with minimize to tray works
   245             if (WindowState == FormWindowState.Minimized && Properties.Settings.Default.MinimizeToTray)
   246             {
   247                 Visible = false;
   248             }
   249 
   250 #if !DEBUG
   251     //When not debugging we want the screen to be empty until a client takes over
   252 			ClearLayout();
   253 #else
   254             //When developing we want at least one client for testing
   255             StartNewClient("abcdefghijklmnopqrst-0123456789", "ABCDEFGHIJKLMNOPQRST-0123456789");
   256 #endif
   257 
   258             //Open display connection on start-up if needed
   259             if (Properties.Settings.Default.DisplayConnectOnStartup)
   260             {
   261                 OpenDisplayConnection();
   262             }
   263 
   264             //Start our server so that we can get client requests
   265             StartServer();
   266 
   267             //Register for HID events
   268             RegisterHidDevices();
   269 
   270             //Start Idle client if needed
   271             if (Properties.Settings.Default.StartIdleClient)
   272             {
   273                 StartIdleClient();
   274             }
   275         }
   276 
   277         /// <summary>
   278         /// Called when our display is opened.
   279         /// </summary>
   280         /// <param name="aDisplay"></param>
   281         private void OnDisplayOpened(Display aDisplay)
   282         {
   283             //Make sure we resume frame rendering
   284             iSkipFrameRendering = false;
   285 
   286             //Set our screen size now that our display is connected
   287             //Our panelDisplay is the container of our tableLayoutPanel
   288             //tableLayoutPanel will resize itself to fit the client size of our panelDisplay
   289             //panelDisplay needs an extra 2 pixels for borders on each sides
   290             //tableLayoutPanel will eventually be the exact size of our display
   291             Size size = new Size(iDisplay.WidthInPixels() + 2, iDisplay.HeightInPixels() + 2);
   292             panelDisplay.Size = size;
   293 
   294             //Our display was just opened, update our UI
   295             UpdateStatus();
   296             //Initiate asynchronous request
   297             iDisplay.RequestFirmwareRevision();
   298 
   299             //Audio
   300             UpdateMasterVolumeThreadSafe();
   301             //Network
   302             UpdateNetworkStatus();
   303 
   304 #if DEBUG
   305             //Testing icon in debug, no arm done if icon not supported
   306             //iDisplay.SetIconStatus(Display.TMiniDisplayIconType.EMiniDisplayIconRecording, 0, 1);
   307             //iDisplay.SetAllIconsStatus(2);
   308 #endif
   309 
   310         }
   311 
   312         /// <summary>
   313         /// Populate tree view with events and actions
   314         /// </summary>
   315         private void PopulateEventsTreeView()
   316         {
   317             //Disable action buttons
   318             buttonActionAdd.Enabled = false;
   319             buttonActionDelete.Enabled = false;
   320 
   321             Ear.Event currentEvent = CurrentEvent();
   322             Ear.Action currentAction = CurrentAction();
   323             TreeNode treeNodeToSelect = null;
   324             
   325             //Reset our tree
   326             iTreeViewEvents.Nodes.Clear();
   327             //Populate registered events
   328             foreach (Ear.Event e in Properties.Settings.Default.EarManager.Events)
   329             {
   330                 //Create our event node
   331                 TreeNode eventNode = iTreeViewEvents.Nodes.Add(e.Brief());
   332                 eventNode.Tag = e; //For easy access to our event
   333                 if (!e.Enabled)
   334                 {
   335                     //Dim our nodes if disabled
   336                     eventNode.ForeColor = Color.DimGray;
   337                 }
   338 
   339                 //Add event description as child node
   340                 eventNode.Nodes.Add(e.Description).ForeColor = eventNode.ForeColor; 
   341                 //Create child node for actions root
   342                 TreeNode actionsNodes = eventNode.Nodes.Add("Actions");
   343                 actionsNodes.ForeColor = eventNode.ForeColor;
   344 
   345                 // Add our actions for that event
   346                 foreach (Ear.Action a in e.Actions)
   347                 {
   348                     TreeNode actionNode = actionsNodes.Nodes.Add(a.Brief());
   349                     actionNode.Tag = a;
   350                     actionNode.ForeColor = eventNode.ForeColor;
   351                     if (a == currentAction)
   352                     {
   353                         treeNodeToSelect = actionNode;
   354                     }
   355                 }
   356             }
   357 
   358             iTreeViewEvents.ExpandAll();
   359             SelectEvent(currentEvent);
   360             
   361             if (treeNodeToSelect != null)
   362             {
   363                 iTreeViewEvents.SelectedNode = treeNodeToSelect;
   364             }
   365             else if (iTreeViewEvents.SelectedNode != null && iTreeViewEvents.SelectedNode.Nodes[1].GetNodeCount(false) > 0)
   366             {
   367                 //Select the last action if any 
   368                 iTreeViewEvents.SelectedNode =
   369                     iTreeViewEvents.SelectedNode.Nodes[1].Nodes[
   370                         iTreeViewEvents.SelectedNode.Nodes[1].GetNodeCount(false) - 1];
   371             }
   372             else if (iTreeViewEvents.SelectedNode == null && iTreeViewEvents.Nodes.Count > 0)
   373             {
   374                 //Still no selected node select the first one then
   375                 iTreeViewEvents.SelectedNode = iTreeViewEvents.Nodes[0];
   376             }
   377 
   378 
   379             UpdateEventView();
   380         }
   381 
   382         /// <summary>
   383         /// Called when our display is closed.
   384         /// </summary>
   385         /// <param name="aDisplay"></param>
   386         private void OnDisplayClosed(Display aDisplay)
   387         {
   388             //Our display was just closed, update our UI consequently
   389             UpdateStatus();
   390         }
   391 
   392         public void OnConnectivityChanged(NetworkManager aNetwork, NLM_CONNECTIVITY newConnectivity)
   393         {
   394             //Update network status
   395             UpdateNetworkStatus();
   396         }
   397 
   398         /// <summary>
   399         /// Update our Network Status
   400         /// </summary>
   401         private void UpdateNetworkStatus()
   402         {
   403             if (iDisplay.IsOpen())
   404             {
   405                 iDisplay.SetIconOnOff(MiniDisplay.IconType.Internet,
   406                     iNetworkManager.NetworkListManager.IsConnectedToInternet);
   407                 iDisplay.SetIconOnOff(MiniDisplay.IconType.NetworkSignal, iNetworkManager.NetworkListManager.IsConnected);
   408             }
   409         }
   410 
   411 
   412         int iLastNetworkIconIndex = 0;
   413         int iUpdateCountSinceLastNetworkAnimation = 0;
   414 
   415         /// <summary>
   416         /// 
   417         /// </summary>
   418         private void UpdateNetworkSignal(DateTime aLastTickTime, DateTime aNewTickTime)
   419         {
   420             iUpdateCountSinceLastNetworkAnimation++;
   421             iUpdateCountSinceLastNetworkAnimation = iUpdateCountSinceLastNetworkAnimation%4;
   422 
   423             if (iDisplay.IsOpen() && iNetworkManager.NetworkListManager.IsConnected &&
   424                 iUpdateCountSinceLastNetworkAnimation == 0)
   425             {
   426                 int iconCount = iDisplay.IconCount(MiniDisplay.IconType.NetworkSignal);
   427                 if (iconCount <= 0)
   428                 {
   429                     //Prevents div by zero and other undefined behavior
   430                     return;
   431                 }
   432                 iLastNetworkIconIndex++;
   433                 iLastNetworkIconIndex = iLastNetworkIconIndex%(iconCount*2);
   434                 for (int i = 0; i < iconCount; i++)
   435                 {
   436                     if (i < iLastNetworkIconIndex && !(i == 0 && iLastNetworkIconIndex > 3) &&
   437                         !(i == 1 && iLastNetworkIconIndex > 4))
   438                     {
   439                         iDisplay.SetIconOn(MiniDisplay.IconType.NetworkSignal, i);
   440                     }
   441                     else
   442                     {
   443                         iDisplay.SetIconOff(MiniDisplay.IconType.NetworkSignal, i);
   444                     }
   445                 }
   446             }
   447         }
   448 
   449 
   450 
   451         /// <summary>
   452         /// Receive volume change notification and reflect changes on our slider.
   453         /// </summary>
   454         /// <param name="data"></param>
   455         public void OnVolumeNotificationThreadSafe(AudioVolumeNotificationData data)
   456         {
   457             UpdateMasterVolumeThreadSafe();
   458         }
   459 
   460         /// <summary>
   461         /// Update master volume when user moves our slider.
   462         /// </summary>
   463         /// <param name="sender"></param>
   464         /// <param name="e"></param>
   465         private void trackBarMasterVolume_Scroll(object sender, EventArgs e)
   466         {
   467             //Just like Windows Volume Mixer we unmute if the volume is adjusted
   468             iMultiMediaDevice.AudioEndpointVolume.Mute = false;
   469             //Set volume level according to our volume slider new position
   470             iMultiMediaDevice.AudioEndpointVolume.MasterVolumeLevelScalar = trackBarMasterVolume.Value/100.0f;
   471         }
   472 
   473 
   474         /// <summary>
   475         /// Mute check box changed.
   476         /// </summary>
   477         /// <param name="sender"></param>
   478         /// <param name="e"></param>
   479         private void checkBoxMute_CheckedChanged(object sender, EventArgs e)
   480         {
   481             iMultiMediaDevice.AudioEndpointVolume.Mute = checkBoxMute.Checked;
   482         }
   483 
   484         /// <summary>
   485         /// Device State Changed
   486         /// </summary>
   487         public void OnDeviceStateChanged([MarshalAs(UnmanagedType.LPWStr)] string deviceId,
   488             [MarshalAs(UnmanagedType.I4)] DeviceState newState)
   489         {
   490         }
   491 
   492         /// <summary>
   493         /// Device Added
   494         /// </summary>
   495         public void OnDeviceAdded([MarshalAs(UnmanagedType.LPWStr)] string pwstrDeviceId)
   496         {
   497         }
   498 
   499         /// <summary>
   500         /// Device Removed
   501         /// </summary>
   502         public void OnDeviceRemoved([MarshalAs(UnmanagedType.LPWStr)] string deviceId)
   503         {
   504         }
   505 
   506         /// <summary>
   507         /// Default Device Changed
   508         /// </summary>
   509         public void OnDefaultDeviceChanged(DataFlow flow, Role role,
   510             [MarshalAs(UnmanagedType.LPWStr)] string defaultDeviceId)
   511         {
   512             if (role == Role.Multimedia && flow == DataFlow.Render)
   513             {
   514                 UpdateAudioDeviceAndMasterVolumeThreadSafe();
   515             }
   516         }
   517 
   518         /// <summary>
   519         /// Property Value Changed
   520         /// </summary>
   521         /// <param name="pwstrDeviceId"></param>
   522         /// <param name="key"></param>
   523         public void OnPropertyValueChanged([MarshalAs(UnmanagedType.LPWStr)] string pwstrDeviceId, PropertyKey key)
   524         {
   525         }
   526 
   527 
   528 
   529 
   530         /// <summary>
   531         /// Update master volume indicators based our current system states.
   532         /// This typically includes volume levels and mute status.
   533         /// </summary>
   534         private void UpdateMasterVolumeThreadSafe()
   535         {
   536             if (this.InvokeRequired)
   537             {
   538                 //Not in the proper thread, invoke ourselves
   539                 PlainUpdateDelegate d = new PlainUpdateDelegate(UpdateMasterVolumeThreadSafe);
   540                 this.Invoke(d, new object[] {});
   541                 return;
   542             }
   543 
   544             //Update volume slider
   545             float volumeLevelScalar = iMultiMediaDevice.AudioEndpointVolume.MasterVolumeLevelScalar;
   546             trackBarMasterVolume.Value = Convert.ToInt32(volumeLevelScalar*100);
   547             //Update mute checkbox
   548             checkBoxMute.Checked = iMultiMediaDevice.AudioEndpointVolume.Mute;
   549 
   550             //If our display connection is open we need to update its icons
   551             if (iDisplay.IsOpen())
   552             {
   553                 //First take care our our volume level icons
   554                 int volumeIconCount = iDisplay.IconCount(MiniDisplay.IconType.Volume);
   555                 if (volumeIconCount > 0)
   556                 {
   557                     //Compute current volume level from system level and the number of segments in our display volume bar.
   558                     //That tells us how many segments in our volume bar needs to be turned on.
   559                     float currentVolume = volumeLevelScalar*volumeIconCount;
   560                     int segmentOnCount = Convert.ToInt32(currentVolume);
   561                     //Check if our segment count was rounded up, this will later be used for half brightness segment
   562                     bool roundedUp = segmentOnCount > currentVolume;
   563 
   564                     for (int i = 0; i < volumeIconCount; i++)
   565                     {
   566                         if (i < segmentOnCount)
   567                         {
   568                             //If we are dealing with our last segment and our segment count was rounded up then we will use half brightness.
   569                             if (i == segmentOnCount - 1 && roundedUp)
   570                             {
   571                                 //Half brightness
   572                                 iDisplay.SetIconStatus(MiniDisplay.IconType.Volume, i,
   573                                     (iDisplay.IconStatusCount(MiniDisplay.IconType.Volume) - 1)/2);
   574                             }
   575                             else
   576                             {
   577                                 //Full brightness
   578                                 iDisplay.SetIconStatus(MiniDisplay.IconType.Volume, i,
   579                                     iDisplay.IconStatusCount(MiniDisplay.IconType.Volume) - 1);
   580                             }
   581                         }
   582                         else
   583                         {
   584                             iDisplay.SetIconStatus(MiniDisplay.IconType.Volume, i, 0);
   585                         }
   586                     }
   587                 }
   588 
   589                 //Take care of our mute icon
   590                 iDisplay.SetIconOnOff(MiniDisplay.IconType.Mute, iMultiMediaDevice.AudioEndpointVolume.Mute);
   591             }
   592 
   593         }
   594 
   595         /// <summary>
   596         /// 
   597         /// </summary>
   598         private void UpdateAudioDeviceAndMasterVolumeThreadSafe()
   599         {
   600             if (this.InvokeRequired)
   601             {
   602                 //Not in the proper thread, invoke ourselves
   603                 PlainUpdateDelegate d = new PlainUpdateDelegate(UpdateAudioDeviceAndMasterVolumeThreadSafe);
   604                 this.Invoke(d, new object[] {});
   605                 return;
   606             }
   607 
   608             //We are in the correct thread just go ahead.
   609             try
   610             {
   611                 //Get our master volume            
   612                 iMultiMediaDevice = iMultiMediaDeviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
   613                 //Update our label
   614                 labelDefaultAudioDevice.Text = iMultiMediaDevice.FriendlyName;
   615 
   616                 //Show our volume in our track bar
   617                 UpdateMasterVolumeThreadSafe();
   618 
   619                 //Register to get volume modifications
   620                 iMultiMediaDevice.AudioEndpointVolume.OnVolumeNotification += OnVolumeNotificationThreadSafe;
   621                 //
   622                 trackBarMasterVolume.Enabled = true;
   623             }
   624             catch (Exception ex)
   625             {
   626                 Debug.WriteLine("Exception thrown in UpdateAudioDeviceAndMasterVolume");
   627                 Debug.WriteLine(ex.ToString());
   628                 //Something went wrong S/PDIF device ca throw exception I guess
   629                 trackBarMasterVolume.Enabled = false;
   630             }
   631         }
   632 
   633         /// <summary>
   634         /// 
   635         /// </summary>
   636         private void PopulateDeviceTypes()
   637         {
   638             int count = Display.TypeCount();
   639 
   640             for (int i = 0; i < count; i++)
   641             {
   642                 comboBoxDisplayType.Items.Add(Display.TypeName((MiniDisplay.Type) i));
   643             }
   644         }
   645 
   646         /// <summary>
   647         ///
   648         /// </summary>
   649         private void SetupTrayIcon()
   650         {
   651             iNotifyIcon.Icon = GetIcon("vfd.ico");
   652             iNotifyIcon.Text = "Sharp Display Manager";
   653             iNotifyIcon.Visible = true;
   654 
   655             //Double click toggles visibility - typically brings up the application
   656             iNotifyIcon.DoubleClick += delegate(object obj, EventArgs args)
   657             {
   658                 SysTrayHideShow();
   659             };
   660 
   661             //Adding a context menu, useful to be able to exit the application
   662             ContextMenu contextMenu = new ContextMenu();
   663             //Context menu item to toggle visibility
   664             MenuItem hideShowItem = new MenuItem("Hide/Show");
   665             hideShowItem.Click += delegate(object obj, EventArgs args)
   666             {
   667                 SysTrayHideShow();
   668             };
   669             contextMenu.MenuItems.Add(hideShowItem);
   670 
   671             //Context menu item separator
   672             contextMenu.MenuItems.Add(new MenuItem("-"));
   673 
   674             //Context menu exit item
   675             MenuItem exitItem = new MenuItem("Exit");
   676             exitItem.Click += delegate(object obj, EventArgs args)
   677             {
   678                 Application.Exit();
   679             };
   680             contextMenu.MenuItems.Add(exitItem);
   681 
   682             iNotifyIcon.ContextMenu = contextMenu;
   683         }
   684 
   685         /// <summary>
   686         ///
   687         /// </summary>
   688         private void SetupRecordingNotification()
   689         {
   690             iRecordingNotification.Icon = GetIcon("record.ico");
   691             iRecordingNotification.Text = "No recording";
   692             iRecordingNotification.Visible = false;
   693         }
   694 
   695         /// <summary>
   696         /// Access icons from embedded resources.
   697         /// </summary>
   698         /// <param name="aName"></param>
   699         /// <returns></returns>
   700         public static Icon GetIcon(string aName)
   701         {
   702             string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames();
   703             foreach (string name in names)
   704             {
   705                 //Find a resource name that ends with the given name
   706                 if (name.EndsWith(aName))
   707                 {
   708                     using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))
   709                     {
   710                         return new Icon(stream);
   711                     }
   712                 }
   713             }
   714 
   715             return null;
   716         }
   717 
   718 
   719         /// <summary>
   720         /// Set our current client.
   721         /// This will take care of applying our client layout and set data fields.
   722         /// </summary>
   723         /// <param name="aSessionId"></param>
   724         void SetCurrentClient(string aSessionId, bool aForce = false)
   725         {
   726             if (aSessionId == iCurrentClientSessionId)
   727             {
   728                 //Given client is already the current one.
   729                 //Don't bother changing anything then.
   730                 return;
   731             }
   732 
   733             ClientData requestedClientData = iClients[aSessionId];
   734 
   735             //Check when was the last time we switched to that client
   736             if (iCurrentClientData != null)
   737             {
   738                 //Do not switch client if priority of current client is higher 
   739                 if (!aForce && requestedClientData.Priority < iCurrentClientData.Priority)
   740                 {
   741                     return;
   742                 }
   743 
   744 
   745                 double lastSwitchToClientSecondsAgo = (DateTime.Now - iCurrentClientData.LastSwitchTime).TotalSeconds;
   746                 //TODO: put that hard coded value as a client property
   747                 //Clients should be able to define how often they can be interrupted
   748                 //Thus a background client can set this to zero allowing any other client to interrupt at any time
   749                 //We could also compute this delay by looking at the requests frequencies?
   750                 if (!aForce &&
   751                     requestedClientData.Priority == iCurrentClientData.Priority &&
   752                     //Time sharing is only if clients have the same priority
   753                     (lastSwitchToClientSecondsAgo < 30)) //Make sure a client is on for at least 30 seconds
   754                 {
   755                     //Don't switch clients too often
   756                     return;
   757                 }
   758             }
   759 
   760             //Set current client ID.
   761             iCurrentClientSessionId = aSessionId;
   762             //Set the time we last switched to that client
   763             iClients[aSessionId].LastSwitchTime = DateTime.Now;
   764             //Fetch and set current client data.
   765             iCurrentClientData = requestedClientData;
   766             //Apply layout and set data fields.
   767             UpdateTableLayoutPanel(iCurrentClientData);
   768         }
   769 
   770         private void buttonFont_Click(object sender, EventArgs e)
   771         {
   772             //fontDialog.ShowColor = true;
   773             //fontDialog.ShowApply = true;
   774             fontDialog.ShowEffects = true;
   775             fontDialog.Font = cds.Font;
   776 
   777             fontDialog.FixedPitchOnly = checkBoxFixedPitchFontOnly.Checked;
   778 
   779             //fontDialog.ShowHelp = true;
   780 
   781             //fontDlg.MaxSize = 40;
   782             //fontDlg.MinSize = 22;
   783 
   784             //fontDialog.Parent = this;
   785             //fontDialog.StartPosition = FormStartPosition.CenterParent;
   786 
   787             //DlgBox.ShowDialog(fontDialog);
   788 
   789             //if (fontDialog.ShowDialog(this) != DialogResult.Cancel)
   790             if (DlgBox.ShowDialog(fontDialog) != DialogResult.Cancel)
   791             {
   792                 //Set the fonts to all our labels in our layout
   793                 foreach (Control ctrl in iTableLayoutPanel.Controls)
   794                 {
   795                     if (ctrl is MarqueeLabel)
   796                     {
   797                         ((MarqueeLabel) ctrl).Font = fontDialog.Font;
   798                     }
   799                 }
   800 
   801                 //Save font settings
   802                 cds.Font = fontDialog.Font;
   803                 Properties.Settings.Default.Save();
   804                 //
   805                 CheckFontHeight();
   806             }
   807         }
   808 
   809         /// <summary>
   810         ///
   811         /// </summary>
   812         void CheckFontHeight()
   813         {
   814             //Show font height and width
   815             labelFontHeight.Text = "Font height: " + cds.Font.Height;
   816             float charWidth = IsFixedWidth(cds.Font);
   817             if (charWidth == 0.0f)
   818             {
   819                 labelFontWidth.Visible = false;
   820             }
   821             else
   822             {
   823                 labelFontWidth.Visible = true;
   824                 labelFontWidth.Text = "Font width: " + charWidth;
   825             }
   826 
   827             MarqueeLabel label = null;
   828             //Get the first label control we can find
   829             foreach (Control ctrl in iTableLayoutPanel.Controls)
   830             {
   831                 if (ctrl is MarqueeLabel)
   832                 {
   833                     label = (MarqueeLabel) ctrl;
   834                     break;
   835                 }
   836             }
   837 
   838             //Now check font height and show a warning if needed.
   839             if (label != null && label.Font.Height > label.Height)
   840             {
   841                 labelWarning.Text = "WARNING: Selected font is too height by " + (label.Font.Height - label.Height) +
   842                                     " pixels!";
   843                 labelWarning.Visible = true;
   844             }
   845             else
   846             {
   847                 labelWarning.Visible = false;
   848             }
   849 
   850         }
   851 
   852         private void buttonCapture_Click(object sender, EventArgs e)
   853         {
   854             System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(iTableLayoutPanel.Width, iTableLayoutPanel.Height);
   855             iTableLayoutPanel.DrawToBitmap(bmp, iTableLayoutPanel.ClientRectangle);
   856             //Bitmap bmpToSave = new Bitmap(bmp);
   857             bmp.Save("D:\\capture.png");
   858 
   859             ((MarqueeLabel) iTableLayoutPanel.Controls[0]).Text = "Captured";
   860 
   861             /*
   862             string outputFileName = "d:\\capture.png";
   863             using (MemoryStream memory = new MemoryStream())
   864             {
   865                 using (FileStream fs = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
   866                 {
   867                     bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
   868                     byte[] bytes = memory.ToArray();
   869                     fs.Write(bytes, 0, bytes.Length);
   870                 }
   871             }
   872              */
   873 
   874         }
   875 
   876         private void CheckForRequestResults()
   877         {
   878             if (iDisplay.IsRequestPending())
   879             {
   880                 switch (iDisplay.AttemptRequestCompletion())
   881                 {
   882                     case MiniDisplay.Request.FirmwareRevision:
   883                         toolStripStatusLabelConnect.Text += " v" + iDisplay.FirmwareRevision();
   884                         //Issue next request then
   885                         iDisplay.RequestPowerSupplyStatus();
   886                         break;
   887 
   888                     case MiniDisplay.Request.PowerSupplyStatus:
   889                         if (iDisplay.PowerSupplyStatus())
   890                         {
   891                             toolStripStatusLabelPower.Text = "ON";
   892                         }
   893                         else
   894                         {
   895                             toolStripStatusLabelPower.Text = "OFF";
   896                         }
   897                         //Issue next request then
   898                         iDisplay.RequestDeviceId();
   899                         break;
   900 
   901                     case MiniDisplay.Request.DeviceId:
   902                         toolStripStatusLabelConnect.Text += " - " + iDisplay.DeviceId();
   903                         //No more request to issue
   904                         break;
   905                 }
   906             }
   907         }
   908 
   909         public static uint ColorWhiteIsOn(int aX, int aY, uint aPixel)
   910         {
   911             if ((aPixel & 0x00FFFFFF) == 0x00FFFFFF)
   912             {
   913                 return 0xFFFFFFFF;
   914             }
   915             return 0x00000000;
   916         }
   917 
   918         public static uint ColorUntouched(int aX, int aY, uint aPixel)
   919         {
   920             return aPixel;
   921         }
   922 
   923         public static uint ColorInversed(int aX, int aY, uint aPixel)
   924         {
   925             return ~aPixel;
   926         }
   927 
   928         public static uint ColorChessboard(int aX, int aY, uint aPixel)
   929         {
   930             if ((aX%2 == 0) && (aY%2 == 0))
   931             {
   932                 return ~aPixel;
   933             }
   934             else if ((aX%2 != 0) && (aY%2 != 0))
   935             {
   936                 return ~aPixel;
   937             }
   938             return 0x00000000;
   939         }
   940 
   941 
   942         public static int ScreenReversedX(System.Drawing.Bitmap aBmp, int aX)
   943         {
   944             return aBmp.Width - aX - 1;
   945         }
   946 
   947         public int ScreenReversedY(System.Drawing.Bitmap aBmp, int aY)
   948         {
   949             return iBmp.Height - aY - 1;
   950         }
   951 
   952         public int ScreenX(System.Drawing.Bitmap aBmp, int aX)
   953         {
   954             return aX;
   955         }
   956 
   957         public int ScreenY(System.Drawing.Bitmap aBmp, int aY)
   958         {
   959             return aY;
   960         }
   961 
   962         /// <summary>
   963         /// Select proper pixel delegates according to our current settings.
   964         /// </summary>
   965         private void SetupPixelDelegates()
   966         {
   967             //Select our pixel processing routine
   968             if (cds.InverseColors)
   969             {
   970                 //iColorFx = ColorChessboard;
   971                 iColorFx = ColorInversed;
   972             }
   973             else
   974             {
   975                 iColorFx = ColorWhiteIsOn;
   976             }
   977 
   978             //Select proper coordinate translation functions
   979             //We used delegate/function pointer to support reverse screen without doing an extra test on each pixels
   980             if (cds.ReverseScreen)
   981             {
   982                 iScreenX = ScreenReversedX;
   983                 iScreenY = ScreenReversedY;
   984             }
   985             else
   986             {
   987                 iScreenX = ScreenX;
   988                 iScreenY = ScreenY;
   989             }
   990 
   991         }
   992 
   993         //This is our timer tick responsible to perform our render
   994         private void timer_Tick(object sender, EventArgs e)
   995         {
   996             //Not ideal cause this has nothing to do with display render
   997             LogsUpdate();
   998 
   999             //Update our animations
  1000             DateTime NewTickTime = DateTime.Now;
  1001 
  1002             UpdateNetworkSignal(LastTickTime, NewTickTime);
  1003 
  1004             //Update animation for all our marquees
  1005             foreach (Control ctrl in iTableLayoutPanel.Controls)
  1006             {
  1007                 if (ctrl is MarqueeLabel)
  1008                 {
  1009                     ((MarqueeLabel) ctrl).UpdateAnimation(LastTickTime, NewTickTime);
  1010                 }
  1011             }
  1012 
  1013             //Update our display
  1014             if (iDisplay.IsOpen())
  1015             {
  1016                 CheckForRequestResults();
  1017 
  1018                 //Check if frame rendering is needed
  1019                 //Typically used when showing clock
  1020                 if (!iSkipFrameRendering)
  1021                 {
  1022                     //Draw to bitmap
  1023                     if (iCreateBitmap)
  1024                     {
  1025                         iBmp = new System.Drawing.Bitmap(iTableLayoutPanel.Width, iTableLayoutPanel.Height,
  1026                             PixelFormat.Format32bppArgb);
  1027                         iCreateBitmap = false;
  1028                     }
  1029                     iTableLayoutPanel.DrawToBitmap(iBmp, iTableLayoutPanel.ClientRectangle);
  1030                     //iBmp.Save("D:\\capture.png");
  1031 
  1032                     //Send it to our display
  1033                     for (int i = 0; i < iBmp.Width; i++)
  1034                     {
  1035                         for (int j = 0; j < iBmp.Height; j++)
  1036                         {
  1037                             unchecked
  1038                             {
  1039                                 //Get our processed pixel coordinates
  1040                                 int x = iScreenX(iBmp, i);
  1041                                 int y = iScreenY(iBmp, j);
  1042                                 //Get pixel color
  1043                                 uint color = (uint) iBmp.GetPixel(i, j).ToArgb();
  1044                                 //Apply color effects
  1045                                 color = iColorFx(x, y, color);
  1046                                 //Now set our pixel
  1047                                 iDisplay.SetPixel(x, y, color);
  1048                             }
  1049                         }
  1050                     }
  1051 
  1052                     iDisplay.SwapBuffers();
  1053                 }
  1054             }
  1055 
  1056             //Compute instant FPS
  1057             toolStripStatusLabelFps.Text = (1.0/NewTickTime.Subtract(LastTickTime).TotalSeconds).ToString("F0") + " / " +
  1058                                            (1000/timer.Interval).ToString() + " FPS";
  1059 
  1060             LastTickTime = NewTickTime;
  1061 
  1062         }
  1063 
  1064         /// <summary>
  1065         /// Attempt to establish connection with our display hardware.
  1066         /// </summary>
  1067         private void OpenDisplayConnection()
  1068         {
  1069             CloseDisplayConnection();
  1070 
  1071             if (!iDisplay.Open((MiniDisplay.Type) cds.DisplayType))
  1072             {
  1073                 UpdateStatus();
  1074                 toolStripStatusLabelConnect.Text = "Connection error";
  1075             }
  1076         }
  1077 
  1078         private void CloseDisplayConnection()
  1079         {
  1080             //Status will be updated upon receiving the closed event
  1081 
  1082             if (iDisplay == null || !iDisplay.IsOpen())
  1083             {
  1084                 return;
  1085             }
  1086 
  1087             //Do not clear if we gave up on rendering already.
  1088             //This means we will keep on displaying clock on MDM166AA for instance.
  1089             if (!iSkipFrameRendering)
  1090             {
  1091                 iDisplay.Clear();
  1092                 iDisplay.SwapBuffers();
  1093             }
  1094 
  1095             iDisplay.SetAllIconsStatus(0); //Turn off all icons
  1096             iDisplay.Close();
  1097         }
  1098 
  1099         private void buttonOpen_Click(object sender, EventArgs e)
  1100         {
  1101             OpenDisplayConnection();
  1102         }
  1103 
  1104         private void buttonClose_Click(object sender, EventArgs e)
  1105         {
  1106             CloseDisplayConnection();
  1107         }
  1108 
  1109         private void buttonClear_Click(object sender, EventArgs e)
  1110         {
  1111             iDisplay.Clear();
  1112             iDisplay.SwapBuffers();
  1113         }
  1114 
  1115         private void buttonFill_Click(object sender, EventArgs e)
  1116         {
  1117             iDisplay.Fill();
  1118             iDisplay.SwapBuffers();
  1119         }
  1120 
  1121         private void trackBarBrightness_Scroll(object sender, EventArgs e)
  1122         {
  1123             cds.Brightness = trackBarBrightness.Value;
  1124             Properties.Settings.Default.Save();
  1125             iDisplay.SetBrightness(trackBarBrightness.Value);
  1126 
  1127         }
  1128 
  1129 
  1130         /// <summary>
  1131         /// CDS stands for Current Display Settings
  1132         /// </summary>
  1133         private DisplaySettings cds
  1134         {
  1135             get
  1136             {
  1137                 DisplaysSettings settings = Properties.Settings.Default.DisplaysSettings;
  1138                 if (settings == null)
  1139                 {
  1140                     settings = new DisplaysSettings();
  1141                     settings.Init();
  1142                     Properties.Settings.Default.DisplaysSettings = settings;
  1143                 }
  1144 
  1145                 //Make sure all our settings have been created
  1146                 while (settings.Displays.Count <= Properties.Settings.Default.CurrentDisplayIndex)
  1147                 {
  1148                     settings.Displays.Add(new DisplaySettings());
  1149                 }
  1150 
  1151                 DisplaySettings displaySettings = settings.Displays[Properties.Settings.Default.CurrentDisplayIndex];
  1152                 return displaySettings;
  1153             }
  1154         }
  1155 
  1156         /// <summary>
  1157         /// Check if the given font has a fixed character pitch.
  1158         /// </summary>
  1159         /// <param name="ft"></param>
  1160         /// <returns>0.0f if this is not a monospace font, otherwise returns the character width.</returns>
  1161         public float IsFixedWidth(Font ft)
  1162         {
  1163             Graphics g = CreateGraphics();
  1164             char[] charSizes = new char[] {'i', 'a', 'Z', '%', '#', 'a', 'B', 'l', 'm', ',', '.'};
  1165             float charWidth = g.MeasureString("I", ft, Int32.MaxValue, StringFormat.GenericTypographic).Width;
  1166 
  1167             bool fixedWidth = true;
  1168 
  1169             foreach (char c in charSizes)
  1170                 if (g.MeasureString(c.ToString(), ft, Int32.MaxValue, StringFormat.GenericTypographic).Width !=
  1171                     charWidth)
  1172                     fixedWidth = false;
  1173 
  1174             if (fixedWidth)
  1175             {
  1176                 return charWidth;
  1177             }
  1178 
  1179             return 0.0f;
  1180         }
  1181 
  1182         /// <summary>
  1183         /// Synchronize UI with settings
  1184         /// </summary>
  1185         private void UpdateStatus()
  1186         {
  1187             //Load settings
  1188             checkBoxShowBorders.Checked = cds.ShowBorders;
  1189             iTableLayoutPanel.CellBorderStyle = (cds.ShowBorders
  1190                 ? TableLayoutPanelCellBorderStyle.Single
  1191                 : TableLayoutPanelCellBorderStyle.None);
  1192 
  1193             //Set the proper font to each of our labels
  1194             foreach (MarqueeLabel ctrl in iTableLayoutPanel.Controls)
  1195             {
  1196                 ctrl.Font = cds.Font;
  1197             }
  1198 
  1199             CheckFontHeight();
  1200             //Check if "run on Windows startup" is enabled
  1201             checkBoxAutoStart.Checked = iStartupManager.Startup;
  1202 
  1203             //Harmony settings
  1204             iTextBoxHarmonyHubAddress.Text = Properties.Settings.Default.HarmonyHubAddress;
  1205 
  1206             //CEC settings
  1207             comboBoxHdmiPort.SelectedIndex = Properties.Settings.Default.CecHdmiPort - 1;
  1208 
  1209             //Mini Display settings
  1210             checkBoxReverseScreen.Checked = cds.ReverseScreen;
  1211             checkBoxInverseColors.Checked = cds.InverseColors;
  1212             checkBoxShowVolumeLabel.Checked = cds.ShowVolumeLabel;
  1213             checkBoxScaleToFit.Checked = cds.ScaleToFit;
  1214             maskedTextBoxMinFontSize.Enabled = cds.ScaleToFit;
  1215             labelMinFontSize.Enabled = cds.ScaleToFit;
  1216             maskedTextBoxMinFontSize.Text = cds.MinFontSize.ToString();
  1217             maskedTextBoxScrollingSpeed.Text = cds.ScrollingSpeedInPixelsPerSecond.ToString();
  1218             comboBoxDisplayType.SelectedIndex = cds.DisplayType;
  1219             timer.Interval = cds.TimerInterval;
  1220             maskedTextBoxTimerInterval.Text = cds.TimerInterval.ToString();
  1221             textBoxScrollLoopSeparator.Text = cds.Separator;
  1222             //
  1223             SetupPixelDelegates();
  1224 
  1225             if (iDisplay.IsOpen())
  1226             {
  1227                 //We have a display connection
  1228                 //Reflect that in our UI
  1229                 StartTimer();
  1230 
  1231                 iTableLayoutPanel.Enabled = true;
  1232                 panelDisplay.Enabled = true;
  1233 
  1234                 //Only setup brightness if display is open
  1235                 trackBarBrightness.Minimum = iDisplay.MinBrightness();
  1236                 trackBarBrightness.Maximum = iDisplay.MaxBrightness();
  1237                 if (cds.Brightness < iDisplay.MinBrightness() || cds.Brightness > iDisplay.MaxBrightness())
  1238                 {
  1239                     //Brightness out of range, this can occur when using auto-detect
  1240                     //Use max brightness instead
  1241                     trackBarBrightness.Value = iDisplay.MaxBrightness();
  1242                     iDisplay.SetBrightness(iDisplay.MaxBrightness());
  1243                 }
  1244                 else
  1245                 {
  1246                     trackBarBrightness.Value = cds.Brightness;
  1247                     iDisplay.SetBrightness(cds.Brightness);
  1248                 }
  1249 
  1250                 //Try compute the steps to something that makes sense
  1251                 trackBarBrightness.LargeChange = Math.Max(1, (iDisplay.MaxBrightness() - iDisplay.MinBrightness())/5);
  1252                 trackBarBrightness.SmallChange = 1;
  1253 
  1254                 //
  1255                 buttonFill.Enabled = true;
  1256                 buttonClear.Enabled = true;
  1257                 buttonOpen.Enabled = false;
  1258                 buttonClose.Enabled = true;
  1259                 trackBarBrightness.Enabled = true;
  1260                 toolStripStatusLabelConnect.Text = "Connected - " + iDisplay.Vendor() + " - " + iDisplay.Product();
  1261                 //+ " - " + iDisplay.SerialNumber();
  1262 
  1263                 if (iDisplay.SupportPowerOnOff())
  1264                 {
  1265                     buttonPowerOn.Enabled = true;
  1266                     buttonPowerOff.Enabled = true;
  1267                 }
  1268                 else
  1269                 {
  1270                     buttonPowerOn.Enabled = false;
  1271                     buttonPowerOff.Enabled = false;
  1272                 }
  1273 
  1274                 if (iDisplay.SupportClock())
  1275                 {
  1276                     buttonShowClock.Enabled = true;
  1277                     buttonHideClock.Enabled = true;
  1278                 }
  1279                 else
  1280                 {
  1281                     buttonShowClock.Enabled = false;
  1282                     buttonHideClock.Enabled = false;
  1283                 }
  1284 
  1285 
  1286                 //Check if Volume Label is supported. To date only MDM166AA supports that crap :)
  1287                 checkBoxShowVolumeLabel.Enabled = iDisplay.IconCount(MiniDisplay.IconType.VolumeLabel) > 0;
  1288 
  1289                 if (cds.ShowVolumeLabel)
  1290                 {
  1291                     iDisplay.SetIconOn(MiniDisplay.IconType.VolumeLabel);
  1292                 }
  1293                 else
  1294                 {
  1295                     iDisplay.SetIconOff(MiniDisplay.IconType.VolumeLabel);
  1296                 }
  1297             }
  1298             else
  1299             {
  1300                 //Display connection not available
  1301                 //Reflect that in our UI
  1302 #if DEBUG
  1303                 //In debug start our timer even if we don't have a display connection
  1304                 StartTimer();
  1305 #else
  1306     //In production environment we don't need our timer if no display connection
  1307                 StopTimer();
  1308 #endif
  1309                 checkBoxShowVolumeLabel.Enabled = false;
  1310                 iTableLayoutPanel.Enabled = false;
  1311                 panelDisplay.Enabled = false;
  1312                 buttonFill.Enabled = false;
  1313                 buttonClear.Enabled = false;
  1314                 buttonOpen.Enabled = true;
  1315                 buttonClose.Enabled = false;
  1316                 trackBarBrightness.Enabled = false;
  1317                 buttonPowerOn.Enabled = false;
  1318                 buttonPowerOff.Enabled = false;
  1319                 buttonShowClock.Enabled = false;
  1320                 buttonHideClock.Enabled = false;
  1321                 toolStripStatusLabelConnect.Text = "Disconnected";
  1322                 toolStripStatusLabelPower.Text = "N/A";
  1323             }
  1324 
  1325         }
  1326 
  1327 
  1328         /// <summary>
  1329         /// 
  1330         /// </summary>
  1331         /// <param name="sender"></param>
  1332         /// <param name="e"></param>
  1333         private void checkBoxShowVolumeLabel_CheckedChanged(object sender, EventArgs e)
  1334         {
  1335             cds.ShowVolumeLabel = checkBoxShowVolumeLabel.Checked;
  1336             Properties.Settings.Default.Save();
  1337             UpdateStatus();
  1338         }
  1339 
  1340         private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
  1341         {
  1342             //Save our show borders setting
  1343             iTableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked
  1344                 ? TableLayoutPanelCellBorderStyle.Single
  1345                 : TableLayoutPanelCellBorderStyle.None);
  1346             cds.ShowBorders = checkBoxShowBorders.Checked;
  1347             Properties.Settings.Default.Save();
  1348             CheckFontHeight();
  1349         }
  1350 
  1351         private void checkBoxAutoStart_CheckedChanged(object sender, EventArgs e)
  1352         {
  1353             iStartupManager.Startup = checkBoxAutoStart.Checked;
  1354         }
  1355 
  1356 
  1357         private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
  1358         {
  1359             //Save our reverse screen setting
  1360             cds.ReverseScreen = checkBoxReverseScreen.Checked;
  1361             Properties.Settings.Default.Save();
  1362             SetupPixelDelegates();
  1363         }
  1364 
  1365         private void checkBoxInverseColors_CheckedChanged(object sender, EventArgs e)
  1366         {
  1367             //Save our inverse colors setting
  1368             cds.InverseColors = checkBoxInverseColors.Checked;
  1369             Properties.Settings.Default.Save();
  1370             SetupPixelDelegates();
  1371         }
  1372 
  1373         private void checkBoxScaleToFit_CheckedChanged(object sender, EventArgs e)
  1374         {
  1375             //Save our scale to fit setting
  1376             cds.ScaleToFit = checkBoxScaleToFit.Checked;
  1377             Properties.Settings.Default.Save();
  1378             //
  1379             labelMinFontSize.Enabled = cds.ScaleToFit;
  1380             maskedTextBoxMinFontSize.Enabled = cds.ScaleToFit;
  1381         }
  1382 
  1383         private void MainForm_Resize(object sender, EventArgs e)
  1384         {
  1385             if (WindowState == FormWindowState.Minimized)
  1386             {
  1387                 // To workaround our empty bitmap bug on Windows 7 we need to recreate our bitmap when the application is minimized
  1388                 // That's apparently not needed on Windows 10 but we better leave it in place.
  1389                 iCreateBitmap = true;
  1390             }
  1391         }
  1392 
  1393         private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
  1394         {
  1395             iCecManager.Stop();
  1396             iNetworkManager.Dispose();
  1397             CloseDisplayConnection();
  1398             StopServer();
  1399             e.Cancel = iClosing;
  1400         }
  1401 
  1402         public void StartServer()
  1403         {
  1404             iServiceHost = new ServiceHost
  1405                 (
  1406                 typeof(Session),
  1407                 new Uri[] {new Uri("net.tcp://localhost:8001/")}
  1408                 );
  1409 
  1410             iServiceHost.AddServiceEndpoint(typeof(IService), new NetTcpBinding(SecurityMode.None, true),
  1411                 "DisplayService");
  1412             iServiceHost.Open();
  1413         }
  1414 
  1415         public void StopServer()
  1416         {
  1417             if (iClients.Count > 0 && !iClosing)
  1418             {
  1419                 //Tell our clients
  1420                 iClosing = true;
  1421                 BroadcastCloseEvent();
  1422             }
  1423             else if (iClosing)
  1424             {
  1425                 if (
  1426                     MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo,
  1427                         MessageBoxIcon.Warning) == DialogResult.Yes)
  1428                 {
  1429                     iClosing = false; //We make sure we force close if asked twice
  1430                 }
  1431             }
  1432             else
  1433             {
  1434                 //We removed that as it often lags for some reason
  1435                 //iServiceHost.Close();
  1436             }
  1437         }
  1438 
  1439         public void BroadcastCloseEvent()
  1440         {
  1441             Trace.TraceInformation("BroadcastCloseEvent - start");
  1442 
  1443             var inactiveClients = new List<string>();
  1444             foreach (var client in iClients)
  1445             {
  1446                 //if (client.Key != eventData.ClientName)
  1447                 {
  1448                     try
  1449                     {
  1450                         Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
  1451                         client.Value.Callback.OnCloseOrder( /*eventData*/);
  1452                     }
  1453                     catch (Exception ex)
  1454                     {
  1455                         inactiveClients.Add(client.Key);
  1456                     }
  1457                 }
  1458             }
  1459 
  1460             if (inactiveClients.Count > 0)
  1461             {
  1462                 foreach (var client in inactiveClients)
  1463                 {
  1464                     iClients.Remove(client);
  1465                     Program.iFormMain.iTreeViewClients.Nodes.Remove(
  1466                         Program.iFormMain.iTreeViewClients.Nodes.Find(client, false)[0]);
  1467                 }
  1468             }
  1469 
  1470             if (iClients.Count == 0)
  1471             {
  1472                 ClearLayout();
  1473             }
  1474         }
  1475 
  1476         /// <summary>
  1477         /// Just remove all our fields.
  1478         /// </summary>
  1479         private void ClearLayout()
  1480         {
  1481             iTableLayoutPanel.Controls.Clear();
  1482             iTableLayoutPanel.RowStyles.Clear();
  1483             iTableLayoutPanel.ColumnStyles.Clear();
  1484             iCurrentClientData = null;
  1485         }
  1486 
  1487         /// <summary>
  1488         /// Just launch a demo client.
  1489         /// </summary>
  1490         private void StartNewClient(string aTopText = "", string aBottomText = "")
  1491         {
  1492             Thread clientThread = new Thread(SharpDisplayClient.Program.MainWithParams);
  1493             SharpDisplayClient.StartParams myParams = new SharpDisplayClient.StartParams(
  1494                 new Point(this.Right, this.Top), aTopText, aBottomText);
  1495             clientThread.Start(myParams);
  1496             BringToFront();
  1497         }
  1498 
  1499         /// <summary>
  1500         /// Just launch our idle client.
  1501         /// </summary>
  1502         private void StartIdleClient(string aTopText = "", string aBottomText = "")
  1503         {
  1504             Thread clientThread = new Thread(SharpDisplayClientIdle.Program.MainWithParams);
  1505             SharpDisplayClientIdle.StartParams myParams =
  1506                 new SharpDisplayClientIdle.StartParams(new Point(this.Right, this.Top), aTopText, aBottomText);
  1507             clientThread.Start(myParams);
  1508             BringToFront();
  1509         }
  1510 
  1511 
  1512         private void buttonStartClient_Click(object sender, EventArgs e)
  1513         {
  1514             StartNewClient();
  1515         }
  1516 
  1517         private void buttonSuspend_Click(object sender, EventArgs e)
  1518         {
  1519             ToggleTimer();
  1520         }
  1521 
  1522         private void StartTimer()
  1523         {
  1524             LastTickTime = DateTime.Now; //Reset timer to prevent jump
  1525             timer.Enabled = true;
  1526             UpdateSuspendButton();
  1527         }
  1528 
  1529         private void StopTimer()
  1530         {
  1531             LastTickTime = DateTime.Now; //Reset timer to prevent jump
  1532             timer.Enabled = false;
  1533             UpdateSuspendButton();
  1534         }
  1535 
  1536         private void ToggleTimer()
  1537         {
  1538             LastTickTime = DateTime.Now; //Reset timer to prevent jump
  1539             timer.Enabled = !timer.Enabled;
  1540             UpdateSuspendButton();
  1541         }
  1542 
  1543         private void UpdateSuspendButton()
  1544         {
  1545             if (!timer.Enabled)
  1546             {
  1547                 buttonSuspend.Text = "Run";
  1548             }
  1549             else
  1550             {
  1551                 buttonSuspend.Text = "Pause";
  1552             }
  1553         }
  1554 
  1555 
  1556         private void buttonCloseClients_Click(object sender, EventArgs e)
  1557         {
  1558             BroadcastCloseEvent();
  1559         }
  1560 
  1561         private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
  1562         {
  1563             //Root node must have at least one child
  1564             if (e.Node.Nodes.Count == 0)
  1565             {
  1566                 return;
  1567             }
  1568 
  1569             //If the selected node is the root node of a client then switch to it
  1570             string sessionId = e.Node.Nodes[0].Text; //First child of a root node is the sessionId
  1571             if (iClients.ContainsKey(sessionId)) //Check that's actually what we are looking at
  1572             {
  1573                 //We have a valid session just switch to that client
  1574                 SetCurrentClient(sessionId, true);
  1575             }
  1576 
  1577         }
  1578 
  1579 
  1580         /// <summary>
  1581         ///
  1582         /// </summary>
  1583         /// <param name="aSessionId"></param>
  1584         /// <param name="aCallback"></param>
  1585         public void AddClientThreadSafe(string aSessionId, ICallback aCallback)
  1586         {
  1587             if (this.InvokeRequired)
  1588             {
  1589                 //Not in the proper thread, invoke ourselves
  1590                 AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
  1591                 this.Invoke(d, new object[] {aSessionId, aCallback});
  1592             }
  1593             else
  1594             {
  1595                 //We are in the proper thread
  1596                 //Add this session to our collection of clients
  1597                 ClientData newClient = new ClientData(aSessionId, aCallback);
  1598                 Program.iFormMain.iClients.Add(aSessionId, newClient);
  1599                 //Add this session to our UI
  1600                 UpdateClientTreeViewNode(newClient);
  1601             }
  1602         }
  1603 
  1604 
  1605         /// <summary>
  1606         /// Find the client with the highest priority if any.
  1607         /// </summary>
  1608         /// <returns>Our highest priority client or null if not a single client is connected.</returns>
  1609         public ClientData FindHighestPriorityClient()
  1610         {
  1611             ClientData highestPriorityClient = null;
  1612             foreach (var client in iClients)
  1613             {
  1614                 if (highestPriorityClient == null || client.Value.Priority > highestPriorityClient.Priority)
  1615                 {
  1616                     highestPriorityClient = client.Value;
  1617                 }
  1618             }
  1619 
  1620             return highestPriorityClient;
  1621         }
  1622 
  1623         /// <summary>
  1624         ///
  1625         /// </summary>
  1626         /// <param name="aSessionId"></param>
  1627         public void RemoveClientThreadSafe(string aSessionId)
  1628         {
  1629             if (this.InvokeRequired)
  1630             {
  1631                 //Not in the proper thread, invoke ourselves
  1632                 RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
  1633                 this.Invoke(d, new object[] {aSessionId});
  1634             }
  1635             else
  1636             {
  1637                 //We are in the proper thread
  1638                 //Remove this session from both client collection and UI tree view
  1639                 if (Program.iFormMain.iClients.Keys.Contains(aSessionId))
  1640                 {
  1641                     Program.iFormMain.iClients.Remove(aSessionId);
  1642                     Program.iFormMain.iTreeViewClients.Nodes.Remove(
  1643                         Program.iFormMain.iTreeViewClients.Nodes.Find(aSessionId, false)[0]);
  1644                     //Update recording status too whenever a client is removed
  1645                     UpdateRecordingNotification();
  1646                 }
  1647 
  1648                 if (iCurrentClientSessionId == aSessionId)
  1649                 {
  1650                     //The current client is closing
  1651                     iCurrentClientData = null;
  1652                     //Find the client with the highest priority and set it as current
  1653                     ClientData newCurrentClient = FindHighestPriorityClient();
  1654                     if (newCurrentClient != null)
  1655                     {
  1656                         SetCurrentClient(newCurrentClient.SessionId, true);
  1657                     }
  1658                 }
  1659 
  1660                 if (iClients.Count == 0)
  1661                 {
  1662                     //Clear our screen when last client disconnects
  1663                     ClearLayout();
  1664 
  1665                     if (iClosing)
  1666                     {
  1667                         //We were closing our form
  1668                         //All clients are now closed
  1669                         //Just resume our close operation
  1670                         iClosing = false;
  1671                         Close();
  1672                     }
  1673                 }
  1674             }
  1675         }
  1676 
  1677         /// <summary>
  1678         ///
  1679         /// </summary>
  1680         /// <param name="aSessionId"></param>
  1681         /// <param name="aLayout"></param>
  1682         public void SetClientLayoutThreadSafe(string aSessionId, TableLayout aLayout)
  1683         {
  1684             if (this.InvokeRequired)
  1685             {
  1686                 //Not in the proper thread, invoke ourselves
  1687                 SetLayoutDelegate d = new SetLayoutDelegate(SetClientLayoutThreadSafe);
  1688                 this.Invoke(d, new object[] {aSessionId, aLayout});
  1689             }
  1690             else
  1691             {
  1692                 ClientData client = iClients[aSessionId];
  1693                 if (client != null)
  1694                 {
  1695                     //Don't change a thing if the layout is the same
  1696                     if (!client.Layout.IsSameAs(aLayout))
  1697                     {
  1698                         Debug.Print("SetClientLayoutThreadSafe: Layout updated.");
  1699                         //Set our client layout then
  1700                         client.Layout = aLayout;
  1701                         //So that next time we update all our fields at ones
  1702                         client.HasNewLayout = true;
  1703                         //Layout has changed clear our fields then
  1704                         client.Fields.Clear();
  1705                         //
  1706                         UpdateClientTreeViewNode(client);
  1707                     }
  1708                     else
  1709                     {
  1710                         Debug.Print("SetClientLayoutThreadSafe: Layout has not changed.");
  1711                     }
  1712                 }
  1713             }
  1714         }
  1715 
  1716         /// <summary>
  1717         ///
  1718         /// </summary>
  1719         /// <param name="aSessionId"></param>
  1720         /// <param name="aField"></param>
  1721         public void SetClientFieldThreadSafe(string aSessionId, DataField aField)
  1722         {
  1723             if (this.InvokeRequired)
  1724             {
  1725                 //Not in the proper thread, invoke ourselves
  1726                 SetFieldDelegate d = new SetFieldDelegate(SetClientFieldThreadSafe);
  1727                 this.Invoke(d, new object[] {aSessionId, aField});
  1728             }
  1729             else
  1730             {
  1731                 //We are in the proper thread
  1732                 //Call the non-thread-safe variant
  1733                 SetClientField(aSessionId, aField);
  1734             }
  1735         }
  1736 
  1737 
  1738 
  1739 
  1740         /// <summary>
  1741         /// Set a data field in the given client.
  1742         /// </summary>
  1743         /// <param name="aSessionId"></param>
  1744         /// <param name="aField"></param>
  1745         private void SetClientField(string aSessionId, DataField aField)
  1746         {
  1747             //TODO: should check if the field actually changed?
  1748 
  1749             ClientData client = iClients[aSessionId];
  1750             bool layoutChanged = false;
  1751             bool contentChanged = true;
  1752 
  1753             //Fetch our field index
  1754             int fieldIndex = client.FindSameFieldIndex(aField);
  1755 
  1756             if (fieldIndex < 0)
  1757             {
  1758                 //No corresponding field, just bail out
  1759                 return;
  1760             }
  1761 
  1762             //Keep our previous field in there
  1763             DataField previousField = client.Fields[fieldIndex];
  1764             //Just update that field then 
  1765             client.Fields[fieldIndex] = aField;
  1766 
  1767             if (!aField.IsTableField)
  1768             {
  1769                 //We are done then if that field is not in our table layout
  1770                 return;
  1771             }
  1772 
  1773             TableField tableField = (TableField) aField;
  1774 
  1775             if (previousField.IsSameLayout(aField))
  1776             {
  1777                 //If we are updating a field in our current client we need to update it in our panel
  1778                 if (aSessionId == iCurrentClientSessionId)
  1779                 {
  1780                     Control ctrl = iTableLayoutPanel.GetControlFromPosition(tableField.Column, tableField.Row);
  1781                     if (aField.IsTextField && ctrl is MarqueeLabel)
  1782                     {
  1783                         TextField textField = (TextField) aField;
  1784                         //Text field control already in place, just change the text
  1785                         MarqueeLabel label = (MarqueeLabel) ctrl;
  1786                         contentChanged = (label.Text != textField.Text || label.TextAlign != textField.Alignment);
  1787                         label.Text = textField.Text;
  1788                         label.TextAlign = textField.Alignment;
  1789                     }
  1790                     else if (aField.IsBitmapField && ctrl is PictureBox)
  1791                     {
  1792                         BitmapField bitmapField = (BitmapField) aField;
  1793                         contentChanged = true; //TODO: Bitmap comp or should we leave that to clients?
  1794                         //Bitmap field control already in place just change the bitmap
  1795                         PictureBox pictureBox = (PictureBox) ctrl;
  1796                         pictureBox.Image = bitmapField.Bitmap;
  1797                     }
  1798                     else
  1799                     {
  1800                         layoutChanged = true;
  1801                     }
  1802                 }
  1803             }
  1804             else
  1805             {
  1806                 layoutChanged = true;
  1807             }
  1808 
  1809             //If either content or layout changed we need to update our tree view to reflect the changes
  1810             if (contentChanged || layoutChanged)
  1811             {
  1812                 UpdateClientTreeViewNode(client);
  1813                 //
  1814                 if (layoutChanged)
  1815                 {
  1816                     Debug.Print("Layout changed");
  1817                     //Our layout has changed, if we are already the current client we need to update our panel
  1818                     if (aSessionId == iCurrentClientSessionId)
  1819                     {
  1820                         //Apply layout and set data fields.
  1821                         UpdateTableLayoutPanel(iCurrentClientData);
  1822                     }
  1823                 }
  1824                 else
  1825                 {
  1826                     Debug.Print("Layout has not changed.");
  1827                 }
  1828             }
  1829             else
  1830             {
  1831                 Debug.Print("WARNING: content and layout have not changed!");
  1832             }
  1833 
  1834             //When a client field is set we try switching to this client to present the new information to our user
  1835             SetCurrentClient(aSessionId);
  1836         }
  1837 
  1838         /// <summary>
  1839         ///
  1840         /// </summary>
  1841         /// <param name="aTexts"></param>
  1842         public void SetClientFieldsThreadSafe(string aSessionId, System.Collections.Generic.IList<DataField> aFields)
  1843         {
  1844             if (this.InvokeRequired)
  1845             {
  1846                 //Not in the proper thread, invoke ourselves
  1847                 SetFieldsDelegate d = new SetFieldsDelegate(SetClientFieldsThreadSafe);
  1848                 this.Invoke(d, new object[] {aSessionId, aFields});
  1849             }
  1850             else
  1851             {
  1852                 ClientData client = iClients[aSessionId];
  1853 
  1854                 if (client.HasNewLayout)
  1855                 {
  1856                     //TODO: Assert client.Count == 0
  1857                     //Our layout was just changed
  1858                     //Do some special handling to avoid re-creating our panel N times, once for each fields
  1859                     client.HasNewLayout = false;
  1860                     //Just set all our fields then
  1861                     client.Fields.AddRange(aFields);
  1862                     //Try switch to that client
  1863                     SetCurrentClient(aSessionId);
  1864 
  1865                     //If we are updating the current client update our panel
  1866                     if (aSessionId == iCurrentClientSessionId)
  1867                     {
  1868                         //Apply layout and set data fields.
  1869                         UpdateTableLayoutPanel(iCurrentClientData);
  1870                     }
  1871 
  1872                     UpdateClientTreeViewNode(client);
  1873                 }
  1874                 else
  1875                 {
  1876                     //Put each our text fields in a label control
  1877                     foreach (DataField field in aFields)
  1878                     {
  1879                         SetClientField(aSessionId, field);
  1880                     }
  1881                 }
  1882             }
  1883         }
  1884 
  1885         /// <summary>
  1886         ///
  1887         /// </summary>
  1888         /// <param name="aSessionId"></param>
  1889         /// <param name="aName"></param>
  1890         public void SetClientNameThreadSafe(string aSessionId, string aName)
  1891         {
  1892             if (this.InvokeRequired)
  1893             {
  1894                 //Not in the proper thread, invoke ourselves
  1895                 SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
  1896                 this.Invoke(d, new object[] {aSessionId, aName});
  1897             }
  1898             else
  1899             {
  1900                 //We are in the proper thread
  1901                 //Get our client
  1902                 ClientData client = iClients[aSessionId];
  1903                 if (client != null)
  1904                 {
  1905                     //Set its name
  1906                     client.Name = aName;
  1907                     //Update our tree-view
  1908                     UpdateClientTreeViewNode(client);
  1909                 }
  1910             }
  1911         }
  1912 
  1913         ///
  1914         public void SetClientPriorityThreadSafe(string aSessionId, uint aPriority)
  1915         {
  1916             if (this.InvokeRequired)
  1917             {
  1918                 //Not in the proper thread, invoke ourselves
  1919                 SetClientPriorityDelegate d = new SetClientPriorityDelegate(SetClientPriorityThreadSafe);
  1920                 this.Invoke(d, new object[] {aSessionId, aPriority});
  1921             }
  1922             else
  1923             {
  1924                 //We are in the proper thread
  1925                 //Get our client
  1926                 ClientData client = iClients[aSessionId];
  1927                 if (client != null)
  1928                 {
  1929                     //Set its name
  1930                     client.Priority = aPriority;
  1931                     //Update our tree-view
  1932                     UpdateClientTreeViewNode(client);
  1933                     //Change our current client as per new priority
  1934                     ClientData newCurrentClient = FindHighestPriorityClient();
  1935                     if (newCurrentClient != null)
  1936                     {
  1937                         SetCurrentClient(newCurrentClient.SessionId);
  1938                     }
  1939                 }
  1940             }
  1941         }
  1942 
  1943         /// <summary>
  1944         /// 
  1945         /// </summary>
  1946         /// <param name="value"></param>
  1947         /// <param name="maxChars"></param>
  1948         /// <returns></returns>
  1949         public static string Truncate(string value, int maxChars)
  1950         {
  1951             return value.Length <= maxChars ? value : value.Substring(0, maxChars - 3) + "...";
  1952         }
  1953 
  1954         /// <summary>
  1955         /// Update our recording notification.
  1956         /// </summary>
  1957         private void UpdateRecordingNotification()
  1958         {
  1959             //Go through each 
  1960             bool activeRecording = false;
  1961             string text = "";
  1962             RecordingField recField = new RecordingField();
  1963             foreach (var client in iClients)
  1964             {
  1965                 RecordingField rec = (RecordingField) client.Value.FindSameFieldAs(recField);
  1966                 if (rec != null && rec.IsActive)
  1967                 {
  1968                     activeRecording = true;
  1969                     //Don't break cause we are collecting the names/texts.
  1970                     if (!String.IsNullOrEmpty(rec.Text))
  1971                     {
  1972                         text += (rec.Text + "\n");
  1973                     }
  1974                     else
  1975                     {
  1976                         //Not text for that recording, use client name instead
  1977                         text += client.Value.Name + " recording\n";
  1978                     }
  1979 
  1980                 }
  1981             }
  1982 
  1983             //Update our text no matter what, can't have more than 63 characters otherwise it throws an exception.
  1984             iRecordingNotification.Text = Truncate(text, 63);
  1985 
  1986             //Change visibility of notification if needed
  1987             if (iRecordingNotification.Visible != activeRecording)
  1988             {
  1989                 iRecordingNotification.Visible = activeRecording;
  1990                 //Assuming the notification icon is in sync with our display icon
  1991                 //Take care of our REC icon
  1992                 if (iDisplay.IsOpen())
  1993                 {
  1994                     iDisplay.SetIconOnOff(MiniDisplay.IconType.Recording, activeRecording);
  1995                 }
  1996             }
  1997         }
  1998 
  1999         /// <summary>
  2000         ///
  2001         /// </summary>
  2002         /// <param name="aClient"></param>
  2003         private void UpdateClientTreeViewNode(ClientData aClient)
  2004         {
  2005             Debug.Print("UpdateClientTreeViewNode");
  2006 
  2007             if (aClient == null)
  2008             {
  2009                 return;
  2010             }
  2011 
  2012             //Hook in record icon update too
  2013             UpdateRecordingNotification();
  2014 
  2015             TreeNode node = null;
  2016             //Check that our client node already exists
  2017             //Get our client root node using its key which is our session ID
  2018             TreeNode[] nodes = iTreeViewClients.Nodes.Find(aClient.SessionId, false);
  2019             if (nodes.Count() > 0)
  2020             {
  2021                 //We already have a node for that client
  2022                 node = nodes[0];
  2023                 //Clear children as we are going to recreate them below
  2024                 node.Nodes.Clear();
  2025             }
  2026             else
  2027             {
  2028                 //Client node does not exists create a new one
  2029                 iTreeViewClients.Nodes.Add(aClient.SessionId, aClient.SessionId);
  2030                 node = iTreeViewClients.Nodes.Find(aClient.SessionId, false)[0];
  2031             }
  2032 
  2033             if (node != null)
  2034             {
  2035                 //Change its name
  2036                 if (!String.IsNullOrEmpty(aClient.Name))
  2037                 {
  2038                     //We have a name, use it as text for our root node
  2039                     node.Text = aClient.Name;
  2040                     //Add a child with SessionId
  2041                     node.Nodes.Add(new TreeNode(aClient.SessionId));
  2042                 }
  2043                 else
  2044                 {
  2045                     //No name, use session ID instead
  2046                     node.Text = aClient.SessionId;
  2047                 }
  2048 
  2049                 //Display client priority
  2050                 node.Nodes.Add(new TreeNode("Priority: " + aClient.Priority));
  2051 
  2052                 if (aClient.Fields.Count > 0)
  2053                 {
  2054                     //Create root node for our texts
  2055                     TreeNode textsRoot = new TreeNode("Fields");
  2056                     node.Nodes.Add(textsRoot);
  2057                     //For each text add a new entry
  2058                     foreach (DataField field in aClient.Fields)
  2059                     {
  2060                         if (field.IsTextField)
  2061                         {
  2062                             TextField textField = (TextField) field;
  2063                             textsRoot.Nodes.Add(new TreeNode("[Text]" + textField.Text));
  2064                         }
  2065                         else if (field.IsBitmapField)
  2066                         {
  2067                             textsRoot.Nodes.Add(new TreeNode("[Bitmap]"));
  2068                         }
  2069                         else if (field.IsRecordingField)
  2070                         {
  2071                             RecordingField recordingField = (RecordingField) field;
  2072                             textsRoot.Nodes.Add(new TreeNode("[Recording]" + recordingField.IsActive));
  2073                         }
  2074                     }
  2075                 }
  2076 
  2077                 node.ExpandAll();
  2078             }
  2079         }
  2080 
  2081         /// <summary>
  2082         /// Update our table layout row styles to make sure each rows have similar height
  2083         /// </summary>
  2084         private void UpdateTableLayoutRowStyles()
  2085         {
  2086             foreach (RowStyle rowStyle in iTableLayoutPanel.RowStyles)
  2087             {
  2088                 rowStyle.SizeType = SizeType.Percent;
  2089                 rowStyle.Height = 100/iTableLayoutPanel.RowCount;
  2090             }
  2091         }
  2092 
  2093         /// <summary>
  2094         /// Update our display table layout.
  2095         /// Will instanciated every field control as defined by our client.
  2096         /// Fields must be specified by rows from the left.
  2097         /// </summary>
  2098         /// <param name="aLayout"></param>
  2099         private void UpdateTableLayoutPanel(ClientData aClient)
  2100         {
  2101             Debug.Print("UpdateTableLayoutPanel");
  2102 
  2103             if (aClient == null)
  2104             {
  2105                 //Just drop it
  2106                 return;
  2107             }
  2108 
  2109 
  2110             TableLayout layout = aClient.Layout;
  2111 
  2112             //First clean our current panel
  2113             iTableLayoutPanel.Controls.Clear();
  2114             iTableLayoutPanel.RowStyles.Clear();
  2115             iTableLayoutPanel.ColumnStyles.Clear();
  2116             iTableLayoutPanel.RowCount = 0;
  2117             iTableLayoutPanel.ColumnCount = 0;
  2118 
  2119             //Then recreate our rows...
  2120             while (iTableLayoutPanel.RowCount < layout.Rows.Count)
  2121             {
  2122                 iTableLayoutPanel.RowCount++;
  2123             }
  2124 
  2125             // ...and columns 
  2126             while (iTableLayoutPanel.ColumnCount < layout.Columns.Count)
  2127             {
  2128                 iTableLayoutPanel.ColumnCount++;
  2129             }
  2130 
  2131             //For each column
  2132             for (int i = 0; i < iTableLayoutPanel.ColumnCount; i++)
  2133             {
  2134                 //Create our column styles
  2135                 this.iTableLayoutPanel.ColumnStyles.Add(layout.Columns[i]);
  2136 
  2137                 //For each rows
  2138                 for (int j = 0; j < iTableLayoutPanel.RowCount; j++)
  2139                 {
  2140                     if (i == 0)
  2141                     {
  2142                         //Create our row styles
  2143                         this.iTableLayoutPanel.RowStyles.Add(layout.Rows[j]);
  2144                     }
  2145                     else
  2146                     {
  2147                         continue;
  2148                     }
  2149                 }
  2150             }
  2151 
  2152             //For each field
  2153             foreach (DataField field in aClient.Fields)
  2154             {
  2155                 if (!field.IsTableField)
  2156                 {
  2157                     //That field is not taking part in our table layout skip it
  2158                     continue;
  2159                 }
  2160 
  2161                 TableField tableField = (TableField) field;
  2162 
  2163                 //Create a control corresponding to the field specified for that cell
  2164                 Control control = CreateControlForDataField(tableField);
  2165 
  2166                 //Add newly created control to our table layout at the specified row and column
  2167                 iTableLayoutPanel.Controls.Add(control, tableField.Column, tableField.Row);
  2168                 //Make sure we specify column and row span for that new control
  2169                 iTableLayoutPanel.SetColumnSpan(control, tableField.ColumnSpan);
  2170                 iTableLayoutPanel.SetRowSpan(control, tableField.RowSpan);
  2171             }
  2172 
  2173 
  2174             CheckFontHeight();
  2175         }
  2176 
  2177         /// <summary>
  2178         /// Check our type of data field and create corresponding control
  2179         /// </summary>
  2180         /// <param name="aField"></param>
  2181         private Control CreateControlForDataField(DataField aField)
  2182         {
  2183             Control control = null;
  2184             if (aField.IsTextField)
  2185             {
  2186                 MarqueeLabel label = new SharpDisplayManager.MarqueeLabel();
  2187                 label.AutoEllipsis = true;
  2188                 label.AutoSize = true;
  2189                 label.BackColor = System.Drawing.Color.Transparent;
  2190                 label.Dock = System.Windows.Forms.DockStyle.Fill;
  2191                 label.Location = new System.Drawing.Point(1, 1);
  2192                 label.Margin = new System.Windows.Forms.Padding(0);
  2193                 label.Name = "marqueeLabel" + aField;
  2194                 label.OwnTimer = false;
  2195                 label.PixelsPerSecond = cds.ScrollingSpeedInPixelsPerSecond;
  2196                 label.Separator = cds.Separator;
  2197                 label.MinFontSize = cds.MinFontSize;
  2198                 label.ScaleToFit = cds.ScaleToFit;
  2199                 //control.Size = new System.Drawing.Size(254, 30);
  2200                 //control.TabIndex = 2;
  2201                 label.Font = cds.Font;
  2202 
  2203                 TextField field = (TextField) aField;
  2204                 label.TextAlign = field.Alignment;
  2205                 label.UseCompatibleTextRendering = true;
  2206                 label.Text = field.Text;
  2207                 //
  2208                 control = label;
  2209             }
  2210             else if (aField.IsBitmapField)
  2211             {
  2212                 //Create picture box
  2213                 PictureBox picture = new PictureBox();
  2214                 picture.AutoSize = true;
  2215                 picture.BackColor = System.Drawing.Color.Transparent;
  2216                 picture.Dock = System.Windows.Forms.DockStyle.Fill;
  2217                 picture.Location = new System.Drawing.Point(1, 1);
  2218                 picture.Margin = new System.Windows.Forms.Padding(0);
  2219                 picture.Name = "pictureBox" + aField;
  2220                 //Set our image
  2221                 BitmapField field = (BitmapField) aField;
  2222                 picture.Image = field.Bitmap;
  2223                 //
  2224                 control = picture;
  2225             }
  2226             //TODO: Handle recording field?
  2227 
  2228             return control;
  2229         }
  2230 
  2231         /// <summary>
  2232         /// Called when the user selected a new display type.
  2233         /// </summary>
  2234         /// <param name="sender"></param>
  2235         /// <param name="e"></param>
  2236         private void comboBoxDisplayType_SelectedIndexChanged(object sender, EventArgs e)
  2237         {
  2238             //Store the selected display type in our settings
  2239             Properties.Settings.Default.CurrentDisplayIndex = comboBoxDisplayType.SelectedIndex;
  2240             cds.DisplayType = comboBoxDisplayType.SelectedIndex;
  2241             Properties.Settings.Default.Save();
  2242 
  2243             //Try re-opening the display connection if we were already connected.
  2244             //Otherwise just update our status to reflect display type change.
  2245             if (iDisplay.IsOpen())
  2246             {
  2247                 OpenDisplayConnection();
  2248             }
  2249             else
  2250             {
  2251                 UpdateStatus();
  2252             }
  2253         }
  2254 
  2255         private void maskedTextBoxTimerInterval_TextChanged(object sender, EventArgs e)
  2256         {
  2257             if (maskedTextBoxTimerInterval.Text != "")
  2258             {
  2259                 int interval = Convert.ToInt32(maskedTextBoxTimerInterval.Text);
  2260 
  2261                 if (interval > 0)
  2262                 {
  2263                     timer.Interval = interval;
  2264                     cds.TimerInterval = timer.Interval;
  2265                     Properties.Settings.Default.Save();
  2266                 }
  2267             }
  2268         }
  2269 
  2270         private void maskedTextBoxMinFontSize_TextChanged(object sender, EventArgs e)
  2271         {
  2272             if (maskedTextBoxMinFontSize.Text != "")
  2273             {
  2274                 int minFontSize = Convert.ToInt32(maskedTextBoxMinFontSize.Text);
  2275 
  2276                 if (minFontSize > 0)
  2277                 {
  2278                     cds.MinFontSize = minFontSize;
  2279                     Properties.Settings.Default.Save();
  2280                     //We need to recreate our layout for that change to take effect
  2281                     UpdateTableLayoutPanel(iCurrentClientData);
  2282                 }
  2283             }
  2284         }
  2285 
  2286 
  2287         private void maskedTextBoxScrollingSpeed_TextChanged(object sender, EventArgs e)
  2288         {
  2289             if (maskedTextBoxScrollingSpeed.Text != "")
  2290             {
  2291                 int scrollingSpeed = Convert.ToInt32(maskedTextBoxScrollingSpeed.Text);
  2292 
  2293                 if (scrollingSpeed > 0)
  2294                 {
  2295                     cds.ScrollingSpeedInPixelsPerSecond = scrollingSpeed;
  2296                     Properties.Settings.Default.Save();
  2297                     //We need to recreate our layout for that change to take effect
  2298                     UpdateTableLayoutPanel(iCurrentClientData);
  2299                 }
  2300             }
  2301         }
  2302 
  2303         private void textBoxScrollLoopSeparator_TextChanged(object sender, EventArgs e)
  2304         {
  2305             cds.Separator = textBoxScrollLoopSeparator.Text;
  2306             Properties.Settings.Default.Save();
  2307 
  2308             //Update our text fields
  2309             foreach (MarqueeLabel ctrl in iTableLayoutPanel.Controls)
  2310             {
  2311                 ctrl.Separator = cds.Separator;
  2312             }
  2313 
  2314         }
  2315 
  2316         private void buttonPowerOn_Click(object sender, EventArgs e)
  2317         {
  2318             iDisplay.PowerOn();
  2319         }
  2320 
  2321         private void buttonPowerOff_Click(object sender, EventArgs e)
  2322         {
  2323             iDisplay.PowerOff();
  2324         }
  2325 
  2326         private void buttonShowClock_Click(object sender, EventArgs e)
  2327         {
  2328             ShowClock();
  2329         }
  2330 
  2331         private void buttonHideClock_Click(object sender, EventArgs e)
  2332         {
  2333             HideClock();
  2334         }
  2335 
  2336         private void buttonUpdate_Click(object sender, EventArgs e)
  2337         {
  2338             InstallUpdateSyncWithInfo();
  2339         }
  2340 
  2341         /// <summary>
  2342         /// 
  2343         /// </summary>
  2344         void ShowClock()
  2345         {
  2346             if (!iDisplay.IsOpen())
  2347             {
  2348                 return;
  2349             }
  2350 
  2351             //Devices like MDM166AA don't support windowing and frame rendering must be stopped while showing our clock
  2352             iSkipFrameRendering = true;
  2353             //Clear our screen 
  2354             iDisplay.Clear();
  2355             iDisplay.SwapBuffers();
  2356             //Then show our clock
  2357             iDisplay.ShowClock();
  2358         }
  2359 
  2360         /// <summary>
  2361         /// 
  2362         /// </summary>
  2363         void HideClock()
  2364         {
  2365             if (!iDisplay.IsOpen())
  2366             {
  2367                 return;
  2368             }
  2369 
  2370             //Devices like MDM166AA don't support windowing and frame rendering must be stopped while showing our clock
  2371             iSkipFrameRendering = false;
  2372             iDisplay.HideClock();
  2373         }
  2374 
  2375         private void InstallUpdateSyncWithInfo()
  2376         {
  2377             UpdateCheckInfo info = null;
  2378 
  2379             if (ApplicationDeployment.IsNetworkDeployed)
  2380             {
  2381                 ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
  2382 
  2383                 try
  2384                 {
  2385                     info = ad.CheckForDetailedUpdate();
  2386 
  2387                 }
  2388                 catch (DeploymentDownloadException dde)
  2389                 {
  2390                     MessageBox.Show(
  2391                         "The new version of the application cannot be downloaded at this time. \n\nPlease check your network connection, or try again later. Error: " +
  2392                         dde.Message);
  2393                     return;
  2394                 }
  2395                 catch (InvalidDeploymentException ide)
  2396                 {
  2397                     MessageBox.Show(
  2398                         "Cannot check for a new version of the application. The ClickOnce deployment is corrupt. Please redeploy the application and try again. Error: " +
  2399                         ide.Message);
  2400                     return;
  2401                 }
  2402                 catch (InvalidOperationException ioe)
  2403                 {
  2404                     MessageBox.Show(
  2405                         "This application cannot be updated. It is likely not a ClickOnce application. Error: " +
  2406                         ioe.Message);
  2407                     return;
  2408                 }
  2409 
  2410                 if (info.UpdateAvailable)
  2411                 {
  2412                     Boolean doUpdate = true;
  2413 
  2414                     if (!info.IsUpdateRequired)
  2415                     {
  2416                         DialogResult dr =
  2417                             MessageBox.Show("An update is available. Would you like to update the application now?",
  2418                                 "Update Available", MessageBoxButtons.OKCancel);
  2419                         if (!(DialogResult.OK == dr))
  2420                         {
  2421                             doUpdate = false;
  2422                         }
  2423                     }
  2424                     else
  2425                     {
  2426                         // Display a message that the application MUST reboot. Display the minimum required version.
  2427                         MessageBox.Show("This application has detected a mandatory update from your current " +
  2428                                         "version to version " + info.MinimumRequiredVersion.ToString() +
  2429                                         ". The application will now install the update and restart.",
  2430                             "Update Available", MessageBoxButtons.OK,
  2431                             MessageBoxIcon.Information);
  2432                     }
  2433 
  2434                     if (doUpdate)
  2435                     {
  2436                         try
  2437                         {
  2438                             ad.Update();
  2439                             MessageBox.Show("The application has been upgraded, and will now restart.");
  2440                             Application.Restart();
  2441                         }
  2442                         catch (DeploymentDownloadException dde)
  2443                         {
  2444                             MessageBox.Show(
  2445                                 "Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " +
  2446                                 dde);
  2447                             return;
  2448                         }
  2449                     }
  2450                 }
  2451                 else
  2452                 {
  2453                     MessageBox.Show("You are already running the latest version.", "Application up-to-date");
  2454                 }
  2455             }
  2456         }
  2457 
  2458 
  2459         /// <summary>
  2460         /// Used to
  2461         /// </summary>
  2462         private void SysTrayHideShow()
  2463         {
  2464             Visible = !Visible;
  2465             if (Visible)
  2466             {
  2467                 Activate();
  2468                 WindowState = FormWindowState.Normal;
  2469             }
  2470         }
  2471 
  2472         /// <summary>
  2473         /// Use to handle minimize events.
  2474         /// </summary>
  2475         /// <param name="sender"></param>
  2476         /// <param name="e"></param>
  2477         private void MainForm_SizeChanged(object sender, EventArgs e)
  2478         {
  2479             if (WindowState == FormWindowState.Minimized && Properties.Settings.Default.MinimizeToTray)
  2480             {
  2481                 if (Visible)
  2482                 {
  2483                     SysTrayHideShow();
  2484                 }
  2485             }
  2486         }
  2487 
  2488         /// <summary>
  2489         /// 
  2490         /// </summary>
  2491         /// <param name="sender"></param>
  2492         /// <param name="e"></param>
  2493         private void tableLayoutPanel_SizeChanged(object sender, EventArgs e)
  2494         {
  2495             //Our table layout size has changed which means our display size has changed.
  2496             //We need to re-create our bitmap.
  2497             iCreateBitmap = true;
  2498         }
  2499 
  2500         /// <summary>
  2501         /// 
  2502         /// </summary>
  2503         private void LogsUpdate()
  2504         {
  2505             if (iWriter != null)
  2506             {
  2507                 iWriter.Flush();
  2508             }
  2509 
  2510         }
  2511 
  2512         /// <summary>
  2513         /// Broadcast messages to subscribers.
  2514         /// </summary>
  2515         /// <param name="message"></param>
  2516         protected override void WndProc(ref Message aMessage)
  2517         {
  2518             LogsUpdate();
  2519 
  2520             if (OnWndProc != null)
  2521             {
  2522                 OnWndProc(ref aMessage);
  2523             }
  2524 
  2525             base.WndProc(ref aMessage);
  2526         }
  2527 
  2528         private void checkBoxCecEnabled_CheckedChanged(object sender, EventArgs e)
  2529         {
  2530             //
  2531             ResetCec();
  2532         }
  2533 
  2534         private void comboBoxHdmiPort_SelectedIndexChanged(object sender, EventArgs e)
  2535         {
  2536             //Save CEC HDMI port
  2537             Properties.Settings.Default.CecHdmiPort = Convert.ToByte(comboBoxHdmiPort.SelectedIndex);
  2538             Properties.Settings.Default.CecHdmiPort++;
  2539             Properties.Settings.Default.Save();
  2540             //
  2541             ResetCec();
  2542         }
  2543 
  2544         /// <summary>
  2545         /// 
  2546         /// </summary>
  2547         private void ResetCec()
  2548         {
  2549             if (iCecManager == null)
  2550             {
  2551                 //Thus skipping initial UI setup
  2552                 return;
  2553             }
  2554 
  2555             iCecManager.Stop();
  2556             //
  2557             if (Properties.Settings.Default.CecEnabled)
  2558             {
  2559                 iCecManager.Start(Handle, "CEC",
  2560                     Properties.Settings.Default.CecHdmiPort);
  2561 
  2562                 SetupCecLogLevel();
  2563             }
  2564         }
  2565 
  2566         /// <summary>
  2567         /// 
  2568         /// </summary>
  2569         private async void ResetHarmony()
  2570         {
  2571             // ConnectAsync already if we have an existing session cookie
  2572             if (Properties.Settings.Default.HarmonyEnabled && File.Exists("SessionToken"))
  2573             {
  2574 
  2575                 iButtonHarmonyConnect.Enabled = false;
  2576                 try
  2577                 {
  2578                     await ConnectHarmonyAsync();
  2579                 }
  2580                 finally
  2581                 {
  2582                     iButtonHarmonyConnect.Enabled = true;
  2583                 }
  2584             }
  2585         }
  2586 
  2587         /// <summary>
  2588         /// 
  2589         /// </summary>
  2590         private void SetupCecLogLevel()
  2591         {
  2592             //Setup log level
  2593             iCecManager.Client.LogLevel = 0;
  2594 
  2595             if (checkBoxCecLogError.Checked)
  2596                 iCecManager.Client.LogLevel |= (int) CecLogLevel.Error;
  2597 
  2598             if (checkBoxCecLogWarning.Checked)
  2599                 iCecManager.Client.LogLevel |= (int) CecLogLevel.Warning;
  2600 
  2601             if (checkBoxCecLogNotice.Checked)
  2602                 iCecManager.Client.LogLevel |= (int) CecLogLevel.Notice;
  2603 
  2604             if (checkBoxCecLogTraffic.Checked)
  2605                 iCecManager.Client.LogLevel |= (int) CecLogLevel.Traffic;
  2606 
  2607             if (checkBoxCecLogDebug.Checked)
  2608                 iCecManager.Client.LogLevel |= (int) CecLogLevel.Debug;
  2609 
  2610             iCecManager.Client.FilterOutPollLogs = checkBoxCecLogNoPoll.Checked;
  2611 
  2612         }
  2613 
  2614         private void ButtonStartIdleClient_Click(object sender, EventArgs e)
  2615         {
  2616             StartIdleClient();
  2617         }
  2618 
  2619         private void buttonClearLogs_Click(object sender, EventArgs e)
  2620         {
  2621             richTextBoxLogs.Clear();
  2622         }
  2623 
  2624         private void checkBoxCecLogs_CheckedChanged(object sender, EventArgs e)
  2625         {
  2626             SetupCecLogLevel();
  2627         }
  2628 
  2629 
  2630         /// <summary>
  2631         /// 
  2632         /// </summary>
  2633         /// <param name="aEvent"></param>
  2634         private void SelectEvent(Ear.Event aEvent)
  2635         {
  2636             if (aEvent == null)
  2637             {
  2638                 return;
  2639             }
  2640 
  2641             foreach (TreeNode node in iTreeViewEvents.Nodes)
  2642             {
  2643                 if (node.Tag == aEvent)
  2644                 {
  2645                     iTreeViewEvents.SelectedNode = node;
  2646                     iTreeViewEvents.Focus();
  2647                 }
  2648             }
  2649         }
  2650 
  2651 
  2652 
  2653         /// <summary>
  2654         /// Get the current event based on event tree view selection.
  2655         /// </summary>
  2656         /// <returns></returns>
  2657         private Ear.Event CurrentEvent()
  2658         {
  2659             //Walk up the tree from the selected node to find our event
  2660             TreeNode node = iTreeViewEvents.SelectedNode;
  2661             Ear.Event selectedEvent = null;
  2662             while (node != null)
  2663             {
  2664                 if (node.Tag is Ear.Event)
  2665                 {
  2666                     selectedEvent = (Ear.Event) node.Tag;
  2667                     break;
  2668                 }
  2669                 node = node.Parent;
  2670             }
  2671 
  2672             return selectedEvent;
  2673         }
  2674 
  2675         /// <summary>
  2676         /// Get the current action based on event tree view selection
  2677         /// </summary>
  2678         /// <returns></returns>
  2679         private Ear.Action CurrentAction()
  2680         {
  2681             TreeNode node = iTreeViewEvents.SelectedNode;
  2682             if (node != null && node.Tag is Ear.Action)
  2683             {
  2684                 return (Ear.Action) node.Tag;
  2685             }
  2686 
  2687             return null;
  2688         }
  2689 
  2690         /// <summary>
  2691         /// 
  2692         /// </summary>
  2693         /// <param name="sender"></param>
  2694         /// <param name="e"></param>
  2695         private void buttonActionAdd_Click(object sender, EventArgs e)
  2696         {
  2697             Ear.Event selectedEvent = CurrentEvent();
  2698             if (selectedEvent == null)
  2699             {
  2700                 //We did not find a corresponding event
  2701                 return;
  2702             }
  2703 
  2704             FormEditObject<Ear.Action> ea = new FormEditObject<Ear.Action>();
  2705             ea.Text = "Add action";
  2706             DialogResult res = CodeProject.Dialog.DlgBox.ShowDialog(ea);
  2707             if (res == DialogResult.OK)
  2708             {
  2709                 selectedEvent.Actions.Add(ea.Object);               
  2710                 Properties.Settings.Default.Save();
  2711                 PopulateEventsTreeView();
  2712             }
  2713         }
  2714 
  2715         /// <summary>
  2716         /// 
  2717         /// </summary>
  2718         /// <param name="sender"></param>
  2719         /// <param name="e"></param>
  2720         private void buttonActionEdit_Click(object sender, EventArgs e)
  2721         {
  2722             Ear.Event selectedEvent = CurrentEvent();
  2723             Ear.Action selectedAction = CurrentAction();
  2724             if (selectedEvent == null || selectedAction == null)
  2725             {
  2726                 //We did not find a corresponding event
  2727                 return;
  2728             }
  2729 
  2730             FormEditObject<Ear.Action> ea = new FormEditObject<Ear.Action>();
  2731             ea.Text = "Edit action";
  2732             ea.Object = selectedAction;
  2733             int actionIndex = iTreeViewEvents.SelectedNode.Index;
  2734             DialogResult res = CodeProject.Dialog.DlgBox.ShowDialog(ea);
  2735             if (res == DialogResult.OK)
  2736             {
  2737                 //Update our action
  2738                 selectedEvent.Actions[actionIndex]=ea.Object;
  2739                 //Save and rebuild our event tree view
  2740                 Properties.Settings.Default.Save();
  2741                 PopulateEventsTreeView();
  2742             }
  2743         }
  2744 
  2745         /// <summary>
  2746         /// 
  2747         /// </summary>
  2748         /// <param name="sender"></param>
  2749         /// <param name="e"></param>
  2750         private void buttonActionDelete_Click(object sender, EventArgs e)
  2751         {
  2752 
  2753             Ear.Action action = CurrentAction();
  2754             if (action == null)
  2755             {
  2756                 //Must select action node
  2757                 return;
  2758             }
  2759 
  2760             Properties.Settings.Default.EarManager.RemoveAction(action);
  2761             Properties.Settings.Default.Save();
  2762             PopulateEventsTreeView();
  2763         }
  2764 
  2765         /// <summary>
  2766         /// 
  2767         /// </summary>
  2768         /// <param name="sender"></param>
  2769         /// <param name="e"></param>
  2770         private void buttonActionTest_Click(object sender, EventArgs e)
  2771         {
  2772             Ear.Action a = CurrentAction();
  2773             if (a != null)
  2774             {
  2775                 a.Test();
  2776             }
  2777             iTreeViewEvents.Focus();
  2778         }
  2779 
  2780         /// <summary>
  2781         /// 
  2782         /// </summary>
  2783         /// <param name="sender"></param>
  2784         /// <param name="e"></param>
  2785         private void buttonActionMoveUp_Click(object sender, EventArgs e)
  2786         {
  2787             Ear.Action a = CurrentAction();
  2788             if (a == null || 
  2789                 //Action already at the top of the list
  2790                 iTreeViewEvents.SelectedNode.Index == 0)
  2791             {
  2792                 return;
  2793             }
  2794 
  2795             //Swap actions in event's action list
  2796             Ear.Event currentEvent = CurrentEvent();
  2797             int currentIndex = iTreeViewEvents.SelectedNode.Index;
  2798             Ear.Action movingUp = currentEvent.Actions[currentIndex];
  2799             Ear.Action movingDown = currentEvent.Actions[currentIndex-1];
  2800             currentEvent.Actions[currentIndex] = movingDown;
  2801             currentEvent.Actions[currentIndex-1] = movingUp;
  2802 
  2803             //Save and populate our tree again
  2804             Properties.Settings.Default.Save();
  2805             PopulateEventsTreeView();
  2806 
  2807         }
  2808 
  2809         /// <summary>
  2810         /// 
  2811         /// </summary>
  2812         /// <param name="sender"></param>
  2813         /// <param name="e"></param>
  2814         private void buttonActionMoveDown_Click(object sender, EventArgs e)
  2815         {
  2816             Ear.Action a = CurrentAction();
  2817             if (a == null ||
  2818                 //Action already at the bottom of the list
  2819                 iTreeViewEvents.SelectedNode.Index == iTreeViewEvents.SelectedNode.Parent.Nodes.Count - 1)
  2820             {
  2821                 return;
  2822             }
  2823 
  2824             //Swap actions in event's action list
  2825             Ear.Event currentEvent = CurrentEvent();
  2826             int currentIndex = iTreeViewEvents.SelectedNode.Index;
  2827             Ear.Action movingDown = currentEvent.Actions[currentIndex];
  2828             Ear.Action movingUp = currentEvent.Actions[currentIndex + 1];
  2829             currentEvent.Actions[currentIndex] = movingUp;
  2830             currentEvent.Actions[currentIndex + 1] = movingDown;
  2831 
  2832             //Save and populate our tree again
  2833             Properties.Settings.Default.Save();
  2834             PopulateEventsTreeView();
  2835         }
  2836 
  2837 
  2838         /// <summary>
  2839         /// 
  2840         /// </summary>
  2841         /// <param name="sender"></param>
  2842         /// <param name="e"></param>
  2843         private void buttonEventTest_Click(object sender, EventArgs e)
  2844         {
  2845             Ear.Event earEvent = CurrentEvent();
  2846             if (earEvent != null)
  2847             {
  2848                 earEvent.Test();
  2849             }
  2850         }
  2851 
  2852         /// <summary>
  2853         /// Manages events and actions buttons according to selected item in event tree.
  2854         /// </summary>
  2855         /// <param name="sender"></param>
  2856         /// <param name="e"></param>
  2857         private void iTreeViewEvents_AfterSelect(object sender, TreeViewEventArgs e)
  2858         {
  2859             UpdateEventView();
  2860         }
  2861 
  2862         /// <summary>
  2863         /// 
  2864         /// </summary>
  2865         private void UpdateEventView()
  2866         {
  2867             //One can always add an event
  2868             buttonEventAdd.Enabled = true;
  2869 
  2870             //Enable buttons according to selected item
  2871             buttonActionAdd.Enabled =
  2872             buttonEventTest.Enabled =
  2873             buttonEventDelete.Enabled =
  2874             buttonEventEdit.Enabled =
  2875                 CurrentEvent() != null;
  2876 
  2877             Ear.Action currentAction = CurrentAction();
  2878             //If an action is selected enable the following buttons
  2879             buttonActionTest.Enabled =
  2880             buttonActionDelete.Enabled =
  2881             buttonActionMoveUp.Enabled =
  2882             buttonActionMoveDown.Enabled =
  2883             buttonActionEdit.Enabled =
  2884                     currentAction != null;
  2885 
  2886             if (currentAction != null)
  2887             {
  2888                 //If an action is selected enable move buttons if needed
  2889                 buttonActionMoveUp.Enabled = iTreeViewEvents.SelectedNode.Index != 0;
  2890                 buttonActionMoveDown.Enabled = iTreeViewEvents.SelectedNode.Index <
  2891                                                iTreeViewEvents.SelectedNode.Parent.Nodes.Count - 1;
  2892             }
  2893         }
  2894 
  2895         private void buttonEventAdd_Click(object sender, EventArgs e)
  2896         {
  2897             FormEditObject<Ear.Event> ea = new FormEditObject<Ear.Event>();
  2898             ea.Text = "Add event";
  2899             DialogResult res = CodeProject.Dialog.DlgBox.ShowDialog(ea);
  2900             if (res == DialogResult.OK)
  2901             {
  2902                 Properties.Settings.Default.EarManager.Events.Add(ea.Object);
  2903                 Properties.Settings.Default.Save();
  2904                 PopulateEventsTreeView();
  2905                 SelectEvent(ea.Object);
  2906             }
  2907         }
  2908 
  2909         private void buttonEventDelete_Click(object sender, EventArgs e)
  2910         {
  2911             Ear.Event currentEvent = CurrentEvent();
  2912             if (currentEvent == null)
  2913             {
  2914                 //Must select action node
  2915                 return;
  2916             }
  2917 
  2918             Properties.Settings.Default.EarManager.Events.Remove(currentEvent);
  2919             Properties.Settings.Default.Save();
  2920             PopulateEventsTreeView();
  2921         }
  2922 
  2923         private void buttonEventEdit_Click(object sender, EventArgs e)
  2924         {
  2925             Ear.Event selectedEvent = CurrentEvent();
  2926             if (selectedEvent == null)
  2927             {
  2928                 //We did not find a corresponding event
  2929                 return;
  2930             }
  2931 
  2932             FormEditObject<Ear.Event> ea = new FormEditObject<Ear.Event>();
  2933             ea.Text = "Edit event";
  2934             ea.Object = selectedEvent;
  2935             int index = iTreeViewEvents.SelectedNode.Index;
  2936             DialogResult res = CodeProject.Dialog.DlgBox.ShowDialog(ea);
  2937             if (res == DialogResult.OK)
  2938             {                
  2939                 //Make sure we keep the same actions as before
  2940                 ea.Object.Actions = Properties.Settings.Default.EarManager.Events[index].Actions;
  2941                 //Update our event
  2942                 Properties.Settings.Default.EarManager.Events[index] = ea.Object;
  2943                 //Save and rebuild our event tree view
  2944                 Properties.Settings.Default.Save();
  2945                 PopulateEventsTreeView();
  2946             }
  2947         }
  2948 
  2949         private void iTreeViewEvents_Leave(object sender, EventArgs e)
  2950         {
  2951             //Make sure our event tree never looses focus
  2952             ((TreeView) sender).Focus();
  2953         }
  2954 
  2955         private async void iButtonHarmonyConnect_Click(object sender, EventArgs e)
  2956         {
  2957             //Save hub address
  2958             Properties.Settings.Default.HarmonyHubAddress = iTextBoxHarmonyHubAddress.Text;
  2959             Properties.Settings.Default.Save();
  2960 
  2961             iButtonHarmonyConnect.Enabled = false;
  2962             try
  2963             {
  2964                 await ConnectHarmonyAsync();
  2965             }
  2966             catch (Exception)
  2967             {
  2968                 iButtonHarmonyConnect.Enabled = true;
  2969             }
  2970 
  2971         }
  2972 
  2973 
  2974         private async Task ConnectHarmonyAsync()
  2975         {
  2976             if (Program.HarmonyClient != null)
  2977             {
  2978                 Program.HarmonyClient.Close();
  2979             }
  2980 
  2981             //Reset Harmony client & config
  2982             Program.HarmonyClient = null;
  2983             Program.HarmonyConfig = null;
  2984 
  2985             Console.WriteLine("Harmony: Connecting... ");
  2986             Program.HarmonyClient = new HarmonyHub.Client(iTextBoxHarmonyHubAddress.Text);
  2987             //First create our client and login
  2988             if (File.Exists("SessionToken"))
  2989             {
  2990                 var sessionToken = File.ReadAllText("SessionToken");
  2991                 Console.WriteLine("Harmony: Reusing token: {0}", sessionToken);
  2992                 Program.HarmonyClient.Open(sessionToken);
  2993             }
  2994             else
  2995             {
  2996                 if (string.IsNullOrEmpty(iTextBoxLogitechPassword.Text))
  2997                 {
  2998                     Console.WriteLine("Harmony: Credentials missing!");
  2999                     return;
  3000                 }
  3001 
  3002                 Console.WriteLine("Harmony: Authenticating with Logitech servers...");
  3003                 await Program.HarmonyClient.Open(iTextBoxLogitechUserName.Text, iTextBoxLogitechPassword.Text);
  3004                 File.WriteAllText("SessionToken", Program.HarmonyClient.Token);
  3005             }
  3006 
  3007             Console.WriteLine("Harmony: Fetching Harmony Hub configuration...");
  3008 
  3009             //Fetch our config
  3010             Program.HarmonyConfig = await Program.HarmonyClient.GetConfigAsync();
  3011             PopulateTreeViewHarmony(Program.HarmonyConfig);
  3012 
  3013             Console.WriteLine("Harmony: Ready");
  3014         }
  3015 
  3016         /// <summary>
  3017         /// 
  3018         /// </summary>
  3019         /// <param name="aConfig"></param>
  3020         private void PopulateTreeViewHarmony(HarmonyHub.Config aConfig)
  3021         {
  3022             iTreeViewHarmony.Nodes.Clear();
  3023             //Add our devices
  3024             foreach (HarmonyHub.Device device in aConfig.Devices)
  3025             {
  3026                 TreeNode deviceNode = iTreeViewHarmony.Nodes.Add(device.Id, $"{device.Label} ({device.DeviceTypeDisplayName}/{device.Model})");
  3027                 deviceNode.Tag = device;
  3028 
  3029                 foreach (HarmonyHub.ControlGroup cg in device.ControlGroups)
  3030                 {
  3031                     TreeNode cgNode = deviceNode.Nodes.Add(cg.Name);
  3032                     cgNode.Tag = cg;
  3033 
  3034                     foreach (HarmonyHub.Function f in cg.Functions)
  3035                     {
  3036                         TreeNode fNode = cgNode.Nodes.Add(f.Name);
  3037                         fNode.Tag = f;
  3038                     }
  3039                 }
  3040             }
  3041 
  3042             //treeViewConfig.ExpandAll();
  3043         }
  3044 
  3045         private async void iTreeViewHarmony_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
  3046         {
  3047             //Upon function node double click we execute it
  3048             var tag = e.Node.Tag as HarmonyHub.Function;
  3049             if (tag != null && e.Node.Parent.Parent.Tag is HarmonyHub.Device)
  3050             {
  3051                 HarmonyHub.Function f = tag;
  3052                 HarmonyHub.Device d = (HarmonyHub.Device)e.Node.Parent.Parent.Tag;
  3053 
  3054                 Console.WriteLine($"Harmony: Sending {f.Name} to {d.Label}...");
  3055 
  3056                 await Program.HarmonyClient.SendCommandAsync(d.Id, f.Name);
  3057             }
  3058         }
  3059     }
  3060 }