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