Server/FormMain.cs
author St?phane Lenclud
Sun, 27 Nov 2016 19:56:09 +0100
changeset 271 24aec939b286
parent 270 5dcd226539d4
child 272 10de0c7c2fed
permissions -rw-r--r--
Published v1.3.5.
Updated Harmony library.
Removed Harmony Logitech password and username.
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@268
  1247
            
StephaneLenclud@168
  1248
            //CEC settings
StephaneLenclud@168
  1249
            comboBoxHdmiPort.SelectedIndex = Properties.Settings.Default.CecHdmiPort - 1;
StephaneLenclud@153
  1250
StephaneLenclud@168
  1251
            //Mini Display settings
sl@48
  1252
            checkBoxReverseScreen.Checked = cds.ReverseScreen;
sl@57
  1253
            checkBoxInverseColors.Checked = cds.InverseColors;
StephaneLenclud@223
  1254
            checkBoxShowVolumeLabel.Checked = cds.ShowVolumeLabel;
sl@100
  1255
            checkBoxScaleToFit.Checked = cds.ScaleToFit;
sl@100
  1256
            maskedTextBoxMinFontSize.Enabled = cds.ScaleToFit;
sl@100
  1257
            labelMinFontSize.Enabled = cds.ScaleToFit;
sl@100
  1258
            maskedTextBoxMinFontSize.Text = cds.MinFontSize.ToString();
StephaneLenclud@223
  1259
            maskedTextBoxScrollingSpeed.Text = cds.ScrollingSpeedInPixelsPerSecond.ToString();
sl@48
  1260
            comboBoxDisplayType.SelectedIndex = cds.DisplayType;
StephaneLenclud@270
  1261
            iTimerDisplay.Interval = cds.TimerInterval;
sl@48
  1262
            maskedTextBoxTimerInterval.Text = cds.TimerInterval.ToString();
sl@100
  1263
            textBoxScrollLoopSeparator.Text = cds.Separator;
sl@58
  1264
            //
sl@58
  1265
            SetupPixelDelegates();
sl@48
  1266
sl@7
  1267
            if (iDisplay.IsOpen())
sl@7
  1268
            {
StephaneLenclud@187
  1269
                //We have a display connection
StephaneLenclud@187
  1270
                //Reflect that in our UI
StephaneLenclud@187
  1271
                StartTimer();
StephaneLenclud@103
  1272
StephaneLenclud@223
  1273
                iTableLayoutPanel.Enabled = true;
StephaneLenclud@223
  1274
                panelDisplay.Enabled = true;
StephaneLenclud@103
  1275
sl@48
  1276
                //Only setup brightness if display is open
sl@48
  1277
                trackBarBrightness.Minimum = iDisplay.MinBrightness();
sl@48
  1278
                trackBarBrightness.Maximum = iDisplay.MaxBrightness();
StephaneLenclud@223
  1279
                if (cds.Brightness < iDisplay.MinBrightness() || cds.Brightness > iDisplay.MaxBrightness())
StephaneLenclud@223
  1280
                {
StephaneLenclud@223
  1281
                    //Brightness out of range, this can occur when using auto-detect
StephaneLenclud@223
  1282
                    //Use max brightness instead
StephaneLenclud@223
  1283
                    trackBarBrightness.Value = iDisplay.MaxBrightness();
StephaneLenclud@223
  1284
                    iDisplay.SetBrightness(iDisplay.MaxBrightness());
StephaneLenclud@223
  1285
                }
StephaneLenclud@223
  1286
                else
StephaneLenclud@223
  1287
                {
StephaneLenclud@223
  1288
                    trackBarBrightness.Value = cds.Brightness;
StephaneLenclud@223
  1289
                    iDisplay.SetBrightness(cds.Brightness);
StephaneLenclud@223
  1290
                }
StephaneLenclud@223
  1291
StephaneLenclud@223
  1292
                //Try compute the steps to something that makes sense
StephaneLenclud@223
  1293
                trackBarBrightness.LargeChange = Math.Max(1, (iDisplay.MaxBrightness() - iDisplay.MinBrightness())/5);
sl@48
  1294
                trackBarBrightness.SmallChange = 1;
StephaneLenclud@223
  1295
sl@48
  1296
                //
sl@7
  1297
                buttonFill.Enabled = true;
sl@7
  1298
                buttonClear.Enabled = true;
sl@7
  1299
                buttonOpen.Enabled = false;
sl@7
  1300
                buttonClose.Enabled = true;
sl@7
  1301
                trackBarBrightness.Enabled = true;
sl@10
  1302
                toolStripStatusLabelConnect.Text = "Connected - " + iDisplay.Vendor() + " - " + iDisplay.Product();
sl@10
  1303
                //+ " - " + iDisplay.SerialNumber();
sl@52
  1304
sl@52
  1305
                if (iDisplay.SupportPowerOnOff())
sl@52
  1306
                {
sl@52
  1307
                    buttonPowerOn.Enabled = true;
sl@52
  1308
                    buttonPowerOff.Enabled = true;
sl@52
  1309
                }
sl@52
  1310
                else
sl@52
  1311
                {
sl@52
  1312
                    buttonPowerOn.Enabled = false;
sl@52
  1313
                    buttonPowerOff.Enabled = false;
sl@52
  1314
                }
sl@53
  1315
sl@53
  1316
                if (iDisplay.SupportClock())
sl@53
  1317
                {
sl@53
  1318
                    buttonShowClock.Enabled = true;
sl@53
  1319
                    buttonHideClock.Enabled = true;
sl@53
  1320
                }
sl@53
  1321
                else
sl@53
  1322
                {
sl@53
  1323
                    buttonShowClock.Enabled = false;
sl@53
  1324
                    buttonHideClock.Enabled = false;
sl@53
  1325
                }
StephaneLenclud@115
  1326
StephaneLenclud@223
  1327
StephaneLenclud@223
  1328
                //Check if Volume Label is supported. To date only MDM166AA supports that crap :)
StephaneLenclud@223
  1329
                checkBoxShowVolumeLabel.Enabled = iDisplay.IconCount(MiniDisplay.IconType.VolumeLabel) > 0;
StephaneLenclud@223
  1330
StephaneLenclud@223
  1331
                if (cds.ShowVolumeLabel)
StephaneLenclud@223
  1332
                {
StephaneLenclud@135
  1333
                    iDisplay.SetIconOn(MiniDisplay.IconType.VolumeLabel);
StephaneLenclud@223
  1334
                }
StephaneLenclud@223
  1335
                else
StephaneLenclud@223
  1336
                {
StephaneLenclud@135
  1337
                    iDisplay.SetIconOff(MiniDisplay.IconType.VolumeLabel);
StephaneLenclud@223
  1338
                }
sl@7
  1339
            }
sl@7
  1340
            else
sl@7
  1341
            {
StephaneLenclud@187
  1342
                //Display connection not available
StephaneLenclud@187
  1343
                //Reflect that in our UI
StephaneLenclud@187
  1344
#if DEBUG
StephaneLenclud@187
  1345
                //In debug start our timer even if we don't have a display connection
StephaneLenclud@187
  1346
                StartTimer();
StephaneLenclud@187
  1347
#else
StephaneLenclud@223
  1348
    //In production environment we don't need our timer if no display connection
StephaneLenclud@187
  1349
                StopTimer();
StephaneLenclud@187
  1350
#endif
StephaneLenclud@187
  1351
                checkBoxShowVolumeLabel.Enabled = false;
StephaneLenclud@223
  1352
                iTableLayoutPanel.Enabled = false;
StephaneLenclud@223
  1353
                panelDisplay.Enabled = false;
sl@7
  1354
                buttonFill.Enabled = false;
sl@7
  1355
                buttonClear.Enabled = false;
sl@7
  1356
                buttonOpen.Enabled = true;
sl@7
  1357
                buttonClose.Enabled = false;
sl@7
  1358
                trackBarBrightness.Enabled = false;
sl@52
  1359
                buttonPowerOn.Enabled = false;
sl@52
  1360
                buttonPowerOff.Enabled = false;
sl@53
  1361
                buttonShowClock.Enabled = false;
sl@53
  1362
                buttonHideClock.Enabled = false;
sl@9
  1363
                toolStripStatusLabelConnect.Text = "Disconnected";
sl@48
  1364
                toolStripStatusLabelPower.Text = "N/A";
sl@7
  1365
            }
StephaneLenclud@106
  1366
sl@7
  1367
        }
sl@9
  1368
sl@13
  1369
StephaneLenclud@223
  1370
        /// <summary>
StephaneLenclud@223
  1371
        /// 
StephaneLenclud@223
  1372
        /// </summary>
StephaneLenclud@223
  1373
        /// <param name="sender"></param>
StephaneLenclud@223
  1374
        /// <param name="e"></param>
StephaneLenclud@223
  1375
        private void checkBoxShowVolumeLabel_CheckedChanged(object sender, EventArgs e)
StephaneLenclud@223
  1376
        {
StephaneLenclud@223
  1377
            cds.ShowVolumeLabel = checkBoxShowVolumeLabel.Checked;
StephaneLenclud@223
  1378
            Properties.Settings.Default.Save();
StephaneLenclud@223
  1379
            UpdateStatus();
StephaneLenclud@223
  1380
        }
sl@13
  1381
sl@9
  1382
        private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
sl@9
  1383
        {
sl@16
  1384
            //Save our show borders setting
StephaneLenclud@223
  1385
            iTableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked
StephaneLenclud@223
  1386
                ? TableLayoutPanelCellBorderStyle.Single
StephaneLenclud@223
  1387
                : TableLayoutPanelCellBorderStyle.None);
sl@48
  1388
            cds.ShowBorders = checkBoxShowBorders.Checked;
sl@9
  1389
            Properties.Settings.Default.Save();
sl@57
  1390
            CheckFontHeight();
sl@9
  1391
        }
sl@13
  1392
StephaneLenclud@194
  1393
        private void checkBoxAutoStart_CheckedChanged(object sender, EventArgs e)
StephaneLenclud@223
  1394
        {
StephaneLenclud@223
  1395
            iStartupManager.Startup = checkBoxAutoStart.Checked;
StephaneLenclud@223
  1396
        }
sl@94
  1397
sl@94
  1398
sl@16
  1399
        private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
sl@16
  1400
        {
sl@16
  1401
            //Save our reverse screen setting
sl@48
  1402
            cds.ReverseScreen = checkBoxReverseScreen.Checked;
sl@16
  1403
            Properties.Settings.Default.Save();
sl@58
  1404
            SetupPixelDelegates();
sl@16
  1405
        }
sl@16
  1406
sl@57
  1407
        private void checkBoxInverseColors_CheckedChanged(object sender, EventArgs e)
sl@57
  1408
        {
sl@57
  1409
            //Save our inverse colors setting
sl@57
  1410
            cds.InverseColors = checkBoxInverseColors.Checked;
sl@57
  1411
            Properties.Settings.Default.Save();
sl@58
  1412
            SetupPixelDelegates();
sl@57
  1413
        }
sl@57
  1414
sl@100
  1415
        private void checkBoxScaleToFit_CheckedChanged(object sender, EventArgs e)
sl@100
  1416
        {
sl@100
  1417
            //Save our scale to fit setting
sl@100
  1418
            cds.ScaleToFit = checkBoxScaleToFit.Checked;
sl@100
  1419
            Properties.Settings.Default.Save();
sl@100
  1420
            //
sl@100
  1421
            labelMinFontSize.Enabled = cds.ScaleToFit;
sl@100
  1422
            maskedTextBoxMinFontSize.Enabled = cds.ScaleToFit;
sl@100
  1423
        }
sl@100
  1424
sl@14
  1425
        private void MainForm_Resize(object sender, EventArgs e)
sl@14
  1426
        {
sl@14
  1427
            if (WindowState == FormWindowState.Minimized)
sl@14
  1428
            {
StephaneLenclud@158
  1429
                // To workaround our empty bitmap bug on Windows 7 we need to recreate our bitmap when the application is minimized
StephaneLenclud@158
  1430
                // That's apparently not needed on Windows 10 but we better leave it in place.
sl@14
  1431
                iCreateBitmap = true;
sl@14
  1432
            }
sl@14
  1433
        }
sl@14
  1434
sl@17
  1435
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
sl@17
  1436
        {
StephaneLenclud@167
  1437
            iCecManager.Stop();
StephaneLenclud@223
  1438
            iNetworkManager.Dispose();
StephaneLenclud@223
  1439
            CloseDisplayConnection();
sl@17
  1440
            StopServer();
sl@32
  1441
            e.Cancel = iClosing;
sl@17
  1442
        }
sl@17
  1443
sl@17
  1444
        public void StartServer()
sl@17
  1445
        {
sl@17
  1446
            iServiceHost = new ServiceHost
sl@17
  1447
                (
StephaneLenclud@223
  1448
                typeof(Session),
StephaneLenclud@223
  1449
                new Uri[] {new Uri("net.tcp://localhost:8001/")}
sl@17
  1450
                );
sl@17
  1451
StephaneLenclud@223
  1452
            iServiceHost.AddServiceEndpoint(typeof(IService), new NetTcpBinding(SecurityMode.None, true),
StephaneLenclud@223
  1453
                "DisplayService");
sl@17
  1454
            iServiceHost.Open();
sl@17
  1455
        }
sl@17
  1456
sl@17
  1457
        public void StopServer()
sl@17
  1458
        {
sl@32
  1459
            if (iClients.Count > 0 && !iClosing)
sl@29
  1460
            {
sl@29
  1461
                //Tell our clients
sl@32
  1462
                iClosing = true;
sl@29
  1463
                BroadcastCloseEvent();
sl@29
  1464
            }
sl@32
  1465
            else if (iClosing)
sl@32
  1466
            {
StephaneLenclud@223
  1467
                if (
StephaneLenclud@223
  1468
                    MessageBox.Show("Force exit?", "Waiting for clients...", MessageBoxButtons.YesNo,
StephaneLenclud@223
  1469
                        MessageBoxIcon.Warning) == DialogResult.Yes)
sl@32
  1470
                {
sl@32
  1471
                    iClosing = false; //We make sure we force close if asked twice
sl@32
  1472
                }
sl@32
  1473
            }
sl@32
  1474
            else
sl@36
  1475
            {
sl@32
  1476
                //We removed that as it often lags for some reason
sl@32
  1477
                //iServiceHost.Close();
sl@32
  1478
            }
sl@17
  1479
        }
sl@17
  1480
sl@21
  1481
        public void BroadcastCloseEvent()
sl@21
  1482
        {
sl@31
  1483
            Trace.TraceInformation("BroadcastCloseEvent - start");
sl@31
  1484
sl@21
  1485
            var inactiveClients = new List<string>();
sl@21
  1486
            foreach (var client in iClients)
sl@21
  1487
            {
sl@21
  1488
                //if (client.Key != eventData.ClientName)
sl@21
  1489
                {
sl@21
  1490
                    try
sl@21
  1491
                    {
sl@31
  1492
                        Trace.TraceInformation("BroadcastCloseEvent - " + client.Key);
StephaneLenclud@223
  1493
                        client.Value.Callback.OnCloseOrder( /*eventData*/);
sl@21
  1494
                    }
sl@21
  1495
                    catch (Exception ex)
sl@21
  1496
                    {
sl@21
  1497
                        inactiveClients.Add(client.Key);
sl@21
  1498
                    }
sl@21
  1499
                }
sl@21
  1500
            }
sl@21
  1501
sl@21
  1502
            if (inactiveClients.Count > 0)
sl@21
  1503
            {
sl@21
  1504
                foreach (var client in inactiveClients)
sl@21
  1505
                {
sl@21
  1506
                    iClients.Remove(client);
StephaneLenclud@226
  1507
                    Program.iFormMain.iTreeViewClients.Nodes.Remove(
StephaneLenclud@226
  1508
                        Program.iFormMain.iTreeViewClients.Nodes.Find(client, false)[0]);
sl@21
  1509
                }
sl@21
  1510
            }
sl@97
  1511
StephaneLenclud@223
  1512
            if (iClients.Count == 0)
StephaneLenclud@223
  1513
            {
StephaneLenclud@223
  1514
                ClearLayout();
StephaneLenclud@223
  1515
            }
sl@21
  1516
        }
sl@21
  1517
StephaneLenclud@223
  1518
        /// <summary>
StephaneLenclud@223
  1519
        /// Just remove all our fields.
StephaneLenclud@223
  1520
        /// </summary>
StephaneLenclud@223
  1521
        private void ClearLayout()
StephaneLenclud@223
  1522
        {
StephaneLenclud@223
  1523
            iTableLayoutPanel.Controls.Clear();
StephaneLenclud@223
  1524
            iTableLayoutPanel.RowStyles.Clear();
StephaneLenclud@223
  1525
            iTableLayoutPanel.ColumnStyles.Clear();
StephaneLenclud@223
  1526
            iCurrentClientData = null;
StephaneLenclud@223
  1527
        }
StephaneLenclud@223
  1528
StephaneLenclud@223
  1529
        /// <summary>
StephaneLenclud@223
  1530
        /// Just launch a demo client.
StephaneLenclud@223
  1531
        /// </summary>
StephaneLenclud@223
  1532
        private void StartNewClient(string aTopText = "", string aBottomText = "")
StephaneLenclud@223
  1533
        {
StephaneLenclud@223
  1534
            Thread clientThread = new Thread(SharpDisplayClient.Program.MainWithParams);
StephaneLenclud@223
  1535
            SharpDisplayClient.StartParams myParams = new SharpDisplayClient.StartParams(
StephaneLenclud@223
  1536
                new Point(this.Right, this.Top), aTopText, aBottomText);
StephaneLenclud@223
  1537
            clientThread.Start(myParams);
StephaneLenclud@223
  1538
            BringToFront();
StephaneLenclud@223
  1539
        }
StephaneLenclud@106
  1540
StephaneLenclud@189
  1541
        /// <summary>
StephaneLenclud@189
  1542
        /// Just launch our idle client.
StephaneLenclud@189
  1543
        /// </summary>
StephaneLenclud@189
  1544
        private void StartIdleClient(string aTopText = "", string aBottomText = "")
StephaneLenclud@189
  1545
        {
StephaneLenclud@225
  1546
            Thread clientThread = new Thread(SharpDisplayClientIdle.Program.MainWithParams);
StephaneLenclud@225
  1547
            SharpDisplayClientIdle.StartParams myParams =
StephaneLenclud@225
  1548
                new SharpDisplayClientIdle.StartParams(new Point(this.Right, this.Top), aTopText, aBottomText);
StephaneLenclud@189
  1549
            clientThread.Start(myParams);
StephaneLenclud@189
  1550
            BringToFront();
StephaneLenclud@189
  1551
        }
StephaneLenclud@189
  1552
StephaneLenclud@189
  1553
sl@25
  1554
        private void buttonStartClient_Click(object sender, EventArgs e)
sl@25
  1555
        {
StephaneLenclud@223
  1556
            StartNewClient();
sl@25
  1557
        }
sl@25
  1558
sl@27
  1559
        private void buttonSuspend_Click(object sender, EventArgs e)
sl@27
  1560
        {
StephaneLenclud@187
  1561
            ToggleTimer();
StephaneLenclud@187
  1562
        }
StephaneLenclud@187
  1563
StephaneLenclud@187
  1564
        private void StartTimer()
StephaneLenclud@187
  1565
        {
StephaneLenclud@187
  1566
            LastTickTime = DateTime.Now; //Reset timer to prevent jump
StephaneLenclud@270
  1567
            iTimerDisplay.Enabled = true;
StephaneLenclud@187
  1568
            UpdateSuspendButton();
StephaneLenclud@187
  1569
        }
StephaneLenclud@187
  1570
StephaneLenclud@187
  1571
        private void StopTimer()
StephaneLenclud@187
  1572
        {
StephaneLenclud@187
  1573
            LastTickTime = DateTime.Now; //Reset timer to prevent jump
StephaneLenclud@270
  1574
            iTimerDisplay.Enabled = false;
StephaneLenclud@187
  1575
            UpdateSuspendButton();
StephaneLenclud@187
  1576
        }
StephaneLenclud@187
  1577
StephaneLenclud@187
  1578
        private void ToggleTimer()
StephaneLenclud@187
  1579
        {
sl@52
  1580
            LastTickTime = DateTime.Now; //Reset timer to prevent jump
StephaneLenclud@270
  1581
            iTimerDisplay.Enabled = !iTimerDisplay.Enabled;
StephaneLenclud@187
  1582
            UpdateSuspendButton();
StephaneLenclud@187
  1583
        }
StephaneLenclud@187
  1584
StephaneLenclud@187
  1585
        private void UpdateSuspendButton()
StephaneLenclud@187
  1586
        {
StephaneLenclud@270
  1587
            if (!iTimerDisplay.Enabled)
sl@27
  1588
            {
sl@52
  1589
                buttonSuspend.Text = "Run";
sl@27
  1590
            }
sl@27
  1591
            else
sl@27
  1592
            {
sl@27
  1593
                buttonSuspend.Text = "Pause";
sl@27
  1594
            }
sl@27
  1595
        }
sl@27
  1596
StephaneLenclud@187
  1597
sl@29
  1598
        private void buttonCloseClients_Click(object sender, EventArgs e)
sl@29
  1599
        {
sl@29
  1600
            BroadcastCloseEvent();
sl@29
  1601
        }
sl@29
  1602
sl@30
  1603
        private void treeViewClients_AfterSelect(object sender, TreeViewEventArgs e)
sl@30
  1604
        {
StephaneLenclud@141
  1605
            //Root node must have at least one child
StephaneLenclud@141
  1606
            if (e.Node.Nodes.Count == 0)
StephaneLenclud@141
  1607
            {
StephaneLenclud@141
  1608
                return;
StephaneLenclud@141
  1609
            }
sl@21
  1610
StephaneLenclud@141
  1611
            //If the selected node is the root node of a client then switch to it
StephaneLenclud@223
  1612
            string sessionId = e.Node.Nodes[0].Text; //First child of a root node is the sessionId
StephaneLenclud@141
  1613
            if (iClients.ContainsKey(sessionId)) //Check that's actually what we are looking at
StephaneLenclud@141
  1614
            {
StephaneLenclud@141
  1615
                //We have a valid session just switch to that client
StephaneLenclud@223
  1616
                SetCurrentClient(sessionId, true);
StephaneLenclud@141
  1617
            }
StephaneLenclud@223
  1618
sl@30
  1619
        }
sl@30
  1620
sl@36
  1621
sl@30
  1622
        /// <summary>
sl@36
  1623
        ///
sl@30
  1624
        /// </summary>
sl@30
  1625
        /// <param name="aSessionId"></param>
sl@30
  1626
        /// <param name="aCallback"></param>
sl@55
  1627
        public void AddClientThreadSafe(string aSessionId, ICallback aCallback)
sl@30
  1628
        {
sl@33
  1629
            if (this.InvokeRequired)
sl@30
  1630
            {
sl@30
  1631
                //Not in the proper thread, invoke ourselves
sl@30
  1632
                AddClientDelegate d = new AddClientDelegate(AddClientThreadSafe);
StephaneLenclud@223
  1633
                this.Invoke(d, new object[] {aSessionId, aCallback});
sl@30
  1634
            }
sl@30
  1635
            else
sl@30
  1636
            {
sl@30
  1637
                //We are in the proper thread
sl@30
  1638
                //Add this session to our collection of clients
sl@33
  1639
                ClientData newClient = new ClientData(aSessionId, aCallback);
StephaneLenclud@226
  1640
                Program.iFormMain.iClients.Add(aSessionId, newClient);
sl@30
  1641
                //Add this session to our UI
sl@33
  1642
                UpdateClientTreeViewNode(newClient);
sl@30
  1643
            }
sl@30
  1644
        }
sl@30
  1645
Stephane@186
  1646
Stephane@186
  1647
        /// <summary>
Stephane@186
  1648
        /// Find the client with the highest priority if any.
Stephane@186
  1649
        /// </summary>
Stephane@186
  1650
        /// <returns>Our highest priority client or null if not a single client is connected.</returns>
Stephane@186
  1651
        public ClientData FindHighestPriorityClient()
Stephane@186
  1652
        {
Stephane@186
  1653
            ClientData highestPriorityClient = null;
Stephane@186
  1654
            foreach (var client in iClients)
Stephane@186
  1655
            {
Stephane@186
  1656
                if (highestPriorityClient == null || client.Value.Priority > highestPriorityClient.Priority)
Stephane@186
  1657
                {
Stephane@186
  1658
                    highestPriorityClient = client.Value;
Stephane@186
  1659
                }
Stephane@186
  1660
            }
Stephane@186
  1661
Stephane@186
  1662
            return highestPriorityClient;
Stephane@186
  1663
        }
Stephane@186
  1664
sl@30
  1665
        /// <summary>
sl@36
  1666
        ///
sl@30
  1667
        /// </summary>
sl@30
  1668
        /// <param name="aSessionId"></param>
sl@30
  1669
        public void RemoveClientThreadSafe(string aSessionId)
sl@30
  1670
        {
sl@33
  1671
            if (this.InvokeRequired)
sl@30
  1672
            {
sl@30
  1673
                //Not in the proper thread, invoke ourselves
sl@30
  1674
                RemoveClientDelegate d = new RemoveClientDelegate(RemoveClientThreadSafe);
StephaneLenclud@223
  1675
                this.Invoke(d, new object[] {aSessionId});
sl@30
  1676
            }
sl@30
  1677
            else
sl@30
  1678
            {
sl@30
  1679
                //We are in the proper thread
sl@33
  1680
                //Remove this session from both client collection and UI tree view
StephaneLenclud@226
  1681
                if (Program.iFormMain.iClients.Keys.Contains(aSessionId))
sl@30
  1682
                {
StephaneLenclud@226
  1683
                    Program.iFormMain.iClients.Remove(aSessionId);
StephaneLenclud@226
  1684
                    Program.iFormMain.iTreeViewClients.Nodes.Remove(
StephaneLenclud@226
  1685
                        Program.iFormMain.iTreeViewClients.Nodes.Find(aSessionId, false)[0]);
StephaneLenclud@188
  1686
                    //Update recording status too whenever a client is removed
StephaneLenclud@188
  1687
                    UpdateRecordingNotification();
sl@32
  1688
                }
sl@32
  1689
Stephane@186
  1690
                if (iCurrentClientSessionId == aSessionId)
Stephane@186
  1691
                {
Stephane@186
  1692
                    //The current client is closing
Stephane@186
  1693
                    iCurrentClientData = null;
Stephane@186
  1694
                    //Find the client with the highest priority and set it as current
Stephane@186
  1695
                    ClientData newCurrentClient = FindHighestPriorityClient();
StephaneLenclud@223
  1696
                    if (newCurrentClient != null)
Stephane@186
  1697
                    {
Stephane@186
  1698
                        SetCurrentClient(newCurrentClient.SessionId, true);
StephaneLenclud@223
  1699
                    }
Stephane@186
  1700
                }
Stephane@186
  1701
Stephane@186
  1702
                if (iClients.Count == 0)
StephaneLenclud@223
  1703
                {
StephaneLenclud@223
  1704
                    //Clear our screen when last client disconnects
StephaneLenclud@223
  1705
                    ClearLayout();
StephaneLenclud@223
  1706
StephaneLenclud@223
  1707
                    if (iClosing)
StephaneLenclud@223
  1708
                    {
StephaneLenclud@223
  1709
                        //We were closing our form
StephaneLenclud@223
  1710
                        //All clients are now closed
StephaneLenclud@223
  1711
                        //Just resume our close operation
StephaneLenclud@223
  1712
                        iClosing = false;
StephaneLenclud@223
  1713
                        Close();
StephaneLenclud@223
  1714
                    }
StephaneLenclud@223
  1715
                }
sl@30
  1716
            }
sl@30
  1717
        }
sl@30
  1718
sl@30
  1719
        /// <summary>
sl@36
  1720
        ///
sl@30
  1721
        /// </summary>
sl@62
  1722
        /// <param name="aSessionId"></param>
sl@72
  1723
        /// <param name="aLayout"></param>
sl@62
  1724
        public void SetClientLayoutThreadSafe(string aSessionId, TableLayout aLayout)
sl@62
  1725
        {
sl@62
  1726
            if (this.InvokeRequired)
sl@62
  1727
            {
sl@62
  1728
                //Not in the proper thread, invoke ourselves
sl@62
  1729
                SetLayoutDelegate d = new SetLayoutDelegate(SetClientLayoutThreadSafe);
StephaneLenclud@223
  1730
                this.Invoke(d, new object[] {aSessionId, aLayout});
sl@62
  1731
            }
sl@62
  1732
            else
sl@62
  1733
            {
sl@62
  1734
                ClientData client = iClients[aSessionId];
sl@62
  1735
                if (client != null)
sl@62
  1736
                {
StephaneLenclud@148
  1737
                    //Don't change a thing if the layout is the same
StephaneLenclud@148
  1738
                    if (!client.Layout.IsSameAs(aLayout))
StephaneLenclud@148
  1739
                    {
StephaneLenclud@158
  1740
                        Debug.Print("SetClientLayoutThreadSafe: Layout updated.");
StephaneLenclud@148
  1741
                        //Set our client layout then
StephaneLenclud@148
  1742
                        client.Layout = aLayout;
StephaneLenclud@175
  1743
                        //So that next time we update all our fields at ones
StephaneLenclud@175
  1744
                        client.HasNewLayout = true;
StephaneLenclud@158
  1745
                        //Layout has changed clear our fields then
StephaneLenclud@158
  1746
                        client.Fields.Clear();
StephaneLenclud@148
  1747
                        //
StephaneLenclud@148
  1748
                        UpdateClientTreeViewNode(client);
StephaneLenclud@148
  1749
                    }
StephaneLenclud@158
  1750
                    else
StephaneLenclud@158
  1751
                    {
StephaneLenclud@158
  1752
                        Debug.Print("SetClientLayoutThreadSafe: Layout has not changed.");
StephaneLenclud@158
  1753
                    }
sl@62
  1754
                }
sl@62
  1755
            }
sl@62
  1756
        }
sl@62
  1757
sl@62
  1758
        /// <summary>
sl@62
  1759
        ///
sl@62
  1760
        /// </summary>
sl@67
  1761
        /// <param name="aSessionId"></param>
sl@72
  1762
        /// <param name="aField"></param>
sl@75
  1763
        public void SetClientFieldThreadSafe(string aSessionId, DataField aField)
sl@30
  1764
        {
sl@33
  1765
            if (this.InvokeRequired)
sl@30
  1766
            {
sl@30
  1767
                //Not in the proper thread, invoke ourselves
sl@79
  1768
                SetFieldDelegate d = new SetFieldDelegate(SetClientFieldThreadSafe);
StephaneLenclud@223
  1769
                this.Invoke(d, new object[] {aSessionId, aField});
sl@30
  1770
            }
sl@30
  1771
            else
sl@30
  1772
            {
sl@75
  1773
                //We are in the proper thread
sl@75
  1774
                //Call the non-thread-safe variant
sl@75
  1775
                SetClientField(aSessionId, aField);
sl@75
  1776
            }
sl@75
  1777
        }
sl@75
  1778
StephaneLenclud@176
  1779
StephaneLenclud@176
  1780
StephaneLenclud@176
  1781
sl@75
  1782
        /// <summary>
StephaneLenclud@175
  1783
        /// Set a data field in the given client.
sl@75
  1784
        /// </summary>
sl@75
  1785
        /// <param name="aSessionId"></param>
sl@75
  1786
        /// <param name="aField"></param>
sl@75
  1787
        private void SetClientField(string aSessionId, DataField aField)
StephaneLenclud@223
  1788
        {
StephaneLenclud@141
  1789
            //TODO: should check if the field actually changed?
StephaneLenclud@141
  1790
sl@75
  1791
            ClientData client = iClients[aSessionId];
StephaneLenclud@141
  1792
            bool layoutChanged = false;
StephaneLenclud@148
  1793
            bool contentChanged = true;
StephaneLenclud@141
  1794
StephaneLenclud@176
  1795
            //Fetch our field index
StephaneLenclud@176
  1796
            int fieldIndex = client.FindSameFieldIndex(aField);
StephaneLenclud@176
  1797
StephaneLenclud@176
  1798
            if (fieldIndex < 0)
sl@75
  1799
            {
StephaneLenclud@176
  1800
                //No corresponding field, just bail out
StephaneLenclud@176
  1801
                return;
StephaneLenclud@141
  1802
            }
sl@76
  1803
StephaneLenclud@175
  1804
            //Keep our previous field in there
StephaneLenclud@176
  1805
            DataField previousField = client.Fields[fieldIndex];
StephaneLenclud@176
  1806
            //Just update that field then 
StephaneLenclud@176
  1807
            client.Fields[fieldIndex] = aField;
StephaneLenclud@148
  1808
StephaneLenclud@176
  1809
            if (!aField.IsTableField)
StephaneLenclud@176
  1810
            {
StephaneLenclud@176
  1811
                //We are done then if that field is not in our table layout
StephaneLenclud@176
  1812
                return;
StephaneLenclud@176
  1813
            }
StephaneLenclud@176
  1814
StephaneLenclud@176
  1815
            TableField tableField = (TableField) aField;
StephaneLenclud@172
  1816
StephaneLenclud@175
  1817
            if (previousField.IsSameLayout(aField))
StephaneLenclud@141
  1818
            {
StephaneLenclud@141
  1819
                //If we are updating a field in our current client we need to update it in our panel
StephaneLenclud@141
  1820
                if (aSessionId == iCurrentClientSessionId)
sl@30
  1821
                {
StephaneLenclud@223
  1822
                    Control ctrl = iTableLayoutPanel.GetControlFromPosition(tableField.Column, tableField.Row);
StephaneLenclud@176
  1823
                    if (aField.IsTextField && ctrl is MarqueeLabel)
sl@79
  1824
                    {
StephaneLenclud@223
  1825
                        TextField textField = (TextField) aField;
sl@75
  1826
                        //Text field control already in place, just change the text
StephaneLenclud@223
  1827
                        MarqueeLabel label = (MarqueeLabel) ctrl;
StephaneLenclud@172
  1828
                        contentChanged = (label.Text != textField.Text || label.TextAlign != textField.Alignment);
StephaneLenclud@172
  1829
                        label.Text = textField.Text;
StephaneLenclud@172
  1830
                        label.TextAlign = textField.Alignment;
sl@68
  1831
                    }
StephaneLenclud@176
  1832
                    else if (aField.IsBitmapField && ctrl is PictureBox)
sl@75
  1833
                    {
StephaneLenclud@223
  1834
                        BitmapField bitmapField = (BitmapField) aField;
StephaneLenclud@148
  1835
                        contentChanged = true; //TODO: Bitmap comp or should we leave that to clients?
sl@75
  1836
                        //Bitmap field control already in place just change the bitmap
StephaneLenclud@223
  1837
                        PictureBox pictureBox = (PictureBox) ctrl;
StephaneLenclud@172
  1838
                        pictureBox.Image = bitmapField.Bitmap;
sl@75
  1839
                    }
sl@68
  1840
                    else
sl@68
  1841
                    {
StephaneLenclud@141
  1842
                        layoutChanged = true;
sl@68
  1843
                    }
sl@30
  1844
                }
StephaneLenclud@141
  1845
            }
StephaneLenclud@141
  1846
            else
StephaneLenclud@223
  1847
            {
StephaneLenclud@141
  1848
                layoutChanged = true;
StephaneLenclud@141
  1849
            }
StephaneLenclud@141
  1850
StephaneLenclud@148
  1851
            //If either content or layout changed we need to update our tree view to reflect the changes
StephaneLenclud@148
  1852
            if (contentChanged || layoutChanged)
StephaneLenclud@141
  1853
            {
StephaneLenclud@141
  1854
                UpdateClientTreeViewNode(client);
StephaneLenclud@148
  1855
                //
StephaneLenclud@148
  1856
                if (layoutChanged)
sl@75
  1857
                {
StephaneLenclud@148
  1858
                    Debug.Print("Layout changed");
StephaneLenclud@148
  1859
                    //Our layout has changed, if we are already the current client we need to update our panel
StephaneLenclud@148
  1860
                    if (aSessionId == iCurrentClientSessionId)
StephaneLenclud@148
  1861
                    {
StephaneLenclud@148
  1862
                        //Apply layout and set data fields.
StephaneLenclud@148
  1863
                        UpdateTableLayoutPanel(iCurrentClientData);
StephaneLenclud@148
  1864
                    }
sl@75
  1865
                }
StephaneLenclud@158
  1866
                else
StephaneLenclud@158
  1867
                {
StephaneLenclud@158
  1868
                    Debug.Print("Layout has not changed.");
StephaneLenclud@158
  1869
                }
StephaneLenclud@158
  1870
            }
StephaneLenclud@158
  1871
            else
StephaneLenclud@158
  1872
            {
StephaneLenclud@158
  1873
                Debug.Print("WARNING: content and layout have not changed!");
StephaneLenclud@141
  1874
            }
sl@75
  1875
StephaneLenclud@141
  1876
            //When a client field is set we try switching to this client to present the new information to our user
StephaneLenclud@141
  1877
            SetCurrentClient(aSessionId);
sl@30
  1878
        }
sl@30
  1879
sl@30
  1880
        /// <summary>
sl@36
  1881
        ///
sl@30
  1882
        /// </summary>
sl@30
  1883
        /// <param name="aTexts"></param>
sl@75
  1884
        public void SetClientFieldsThreadSafe(string aSessionId, System.Collections.Generic.IList<DataField> aFields)
sl@30
  1885
        {
sl@33
  1886
            if (this.InvokeRequired)
sl@30
  1887
            {
sl@30
  1888
                //Not in the proper thread, invoke ourselves
sl@75
  1889
                SetFieldsDelegate d = new SetFieldsDelegate(SetClientFieldsThreadSafe);
StephaneLenclud@223
  1890
                this.Invoke(d, new object[] {aSessionId, aFields});
sl@30
  1891
            }
sl@30
  1892
            else
sl@30
  1893
            {
StephaneLenclud@175
  1894
                ClientData client = iClients[aSessionId];
StephaneLenclud@175
  1895
StephaneLenclud@175
  1896
                if (client.HasNewLayout)
sl@30
  1897
                {
StephaneLenclud@175
  1898
                    //TODO: Assert client.Count == 0
StephaneLenclud@175
  1899
                    //Our layout was just changed
StephaneLenclud@175
  1900
                    //Do some special handling to avoid re-creating our panel N times, once for each fields
StephaneLenclud@175
  1901
                    client.HasNewLayout = false;
StephaneLenclud@175
  1902
                    //Just set all our fields then
StephaneLenclud@175
  1903
                    client.Fields.AddRange(aFields);
StephaneLenclud@175
  1904
                    //Try switch to that client
StephaneLenclud@175
  1905
                    SetCurrentClient(aSessionId);
StephaneLenclud@175
  1906
StephaneLenclud@175
  1907
                    //If we are updating the current client update our panel
StephaneLenclud@175
  1908
                    if (aSessionId == iCurrentClientSessionId)
StephaneLenclud@175
  1909
                    {
StephaneLenclud@175
  1910
                        //Apply layout and set data fields.
StephaneLenclud@175
  1911
                        UpdateTableLayoutPanel(iCurrentClientData);
StephaneLenclud@175
  1912
                    }
StephaneLenclud@176
  1913
StephaneLenclud@176
  1914
                    UpdateClientTreeViewNode(client);
StephaneLenclud@175
  1915
                }
StephaneLenclud@175
  1916
                else
StephaneLenclud@175
  1917
                {
StephaneLenclud@175
  1918
                    //Put each our text fields in a label control
StephaneLenclud@175
  1919
                    foreach (DataField field in aFields)
StephaneLenclud@175
  1920
                    {
StephaneLenclud@175
  1921
                        SetClientField(aSessionId, field);
StephaneLenclud@175
  1922
                    }
sl@30
  1923
                }
sl@30
  1924
            }
sl@32
  1925
        }
sl@30
  1926
sl@67
  1927
        /// <summary>
sl@67
  1928
        ///
sl@67
  1929
        /// </summary>
sl@67
  1930
        /// <param name="aSessionId"></param>
sl@32
  1931
        /// <param name="aName"></param>
sl@32
  1932
        public void SetClientNameThreadSafe(string aSessionId, string aName)
sl@32
  1933
        {
sl@32
  1934
            if (this.InvokeRequired)
sl@32
  1935
            {
sl@32
  1936
                //Not in the proper thread, invoke ourselves
sl@32
  1937
                SetClientNameDelegate d = new SetClientNameDelegate(SetClientNameThreadSafe);
StephaneLenclud@223
  1938
                this.Invoke(d, new object[] {aSessionId, aName});
sl@32
  1939
            }
sl@32
  1940
            else
sl@32
  1941
            {
sl@32
  1942
                //We are in the proper thread
sl@33
  1943
                //Get our client
sl@33
  1944
                ClientData client = iClients[aSessionId];
sl@33
  1945
                if (client != null)
sl@32
  1946
                {
sl@33
  1947
                    //Set its name
sl@33
  1948
                    client.Name = aName;
sl@33
  1949
                    //Update our tree-view
sl@33
  1950
                    UpdateClientTreeViewNode(client);
sl@33
  1951
                }
sl@33
  1952
            }
sl@33
  1953
        }
sl@33
  1954
StephaneLenclud@184
  1955
        ///
StephaneLenclud@184
  1956
        public void SetClientPriorityThreadSafe(string aSessionId, uint aPriority)
StephaneLenclud@184
  1957
        {
StephaneLenclud@184
  1958
            if (this.InvokeRequired)
StephaneLenclud@184
  1959
            {
StephaneLenclud@184
  1960
                //Not in the proper thread, invoke ourselves
StephaneLenclud@184
  1961
                SetClientPriorityDelegate d = new SetClientPriorityDelegate(SetClientPriorityThreadSafe);
StephaneLenclud@223
  1962
                this.Invoke(d, new object[] {aSessionId, aPriority});
StephaneLenclud@184
  1963
            }
StephaneLenclud@184
  1964
            else
StephaneLenclud@184
  1965
            {
StephaneLenclud@184
  1966
                //We are in the proper thread
StephaneLenclud@184
  1967
                //Get our client
StephaneLenclud@184
  1968
                ClientData client = iClients[aSessionId];
StephaneLenclud@184
  1969
                if (client != null)
StephaneLenclud@184
  1970
                {
StephaneLenclud@184
  1971
                    //Set its name
StephaneLenclud@184
  1972
                    client.Priority = aPriority;
StephaneLenclud@184
  1973
                    //Update our tree-view
StephaneLenclud@184
  1974
                    UpdateClientTreeViewNode(client);
Stephane@186
  1975
                    //Change our current client as per new priority
Stephane@186
  1976
                    ClientData newCurrentClient = FindHighestPriorityClient();
StephaneLenclud@223
  1977
                    if (newCurrentClient != null)
Stephane@186
  1978
                    {
Stephane@186
  1979
                        SetCurrentClient(newCurrentClient.SessionId);
Stephane@186
  1980
                    }
StephaneLenclud@184
  1981
                }
StephaneLenclud@184
  1982
            }
StephaneLenclud@184
  1983
        }
StephaneLenclud@184
  1984
sl@33
  1985
        /// <summary>
StephaneLenclud@183
  1986
        /// 
StephaneLenclud@183
  1987
        /// </summary>
StephaneLenclud@183
  1988
        /// <param name="value"></param>
StephaneLenclud@183
  1989
        /// <param name="maxChars"></param>
StephaneLenclud@183
  1990
        /// <returns></returns>
StephaneLenclud@183
  1991
        public static string Truncate(string value, int maxChars)
StephaneLenclud@183
  1992
        {
StephaneLenclud@223
  1993
            return value.Length <= maxChars ? value : value.Substring(0, maxChars - 3) + "...";
StephaneLenclud@183
  1994
        }
StephaneLenclud@183
  1995
StephaneLenclud@183
  1996
        /// <summary>
StephaneLenclud@180
  1997
        /// Update our recording notification.
StephaneLenclud@180
  1998
        /// </summary>
StephaneLenclud@180
  1999
        private void UpdateRecordingNotification()
StephaneLenclud@180
  2000
        {
StephaneLenclud@180
  2001
            //Go through each 
StephaneLenclud@180
  2002
            bool activeRecording = false;
StephaneLenclud@223
  2003
            string text = "";
StephaneLenclud@223
  2004
            RecordingField recField = new RecordingField();
StephaneLenclud@180
  2005
            foreach (var client in iClients)
StephaneLenclud@180
  2006
            {
StephaneLenclud@223
  2007
                RecordingField rec = (RecordingField) client.Value.FindSameFieldAs(recField);
StephaneLenclud@223
  2008
                if (rec != null && rec.IsActive)
StephaneLenclud@180
  2009
                {
StephaneLenclud@180
  2010
                    activeRecording = true;
StephaneLenclud@183
  2011
                    //Don't break cause we are collecting the names/texts.
StephaneLenclud@183
  2012
                    if (!String.IsNullOrEmpty(rec.Text))
StephaneLenclud@183
  2013
                    {
StephaneLenclud@183
  2014
                        text += (rec.Text + "\n");
StephaneLenclud@183
  2015
                    }
StephaneLenclud@183
  2016
                    else
StephaneLenclud@183
  2017
                    {
StephaneLenclud@183
  2018
                        //Not text for that recording, use client name instead
StephaneLenclud@183
  2019
                        text += client.Value.Name + " recording\n";
StephaneLenclud@183
  2020
                    }
StephaneLenclud@223
  2021
StephaneLenclud@180
  2022
                }
StephaneLenclud@180
  2023
            }
StephaneLenclud@180
  2024
StephaneLenclud@183
  2025
            //Update our text no matter what, can't have more than 63 characters otherwise it throws an exception.
StephaneLenclud@223
  2026
            iRecordingNotification.Text = Truncate(text, 63);
StephaneLenclud@183
  2027
StephaneLenclud@180
  2028
            //Change visibility of notification if needed
StephaneLenclud@180
  2029
            if (iRecordingNotification.Visible != activeRecording)
StephaneLenclud@223
  2030
            {
StephaneLenclud@180
  2031
                iRecordingNotification.Visible = activeRecording;
Stephane@182
  2032
                //Assuming the notification icon is in sync with our display icon
Stephane@182
  2033
                //Take care of our REC icon
StephaneLenclud@183
  2034
                if (iDisplay.IsOpen())
StephaneLenclud@183
  2035
                {
StephaneLenclud@183
  2036
                    iDisplay.SetIconOnOff(MiniDisplay.IconType.Recording, activeRecording);
StephaneLenclud@223
  2037
                }
StephaneLenclud@180
  2038
            }
StephaneLenclud@180
  2039
        }
StephaneLenclud@180
  2040
StephaneLenclud@180
  2041
        /// <summary>
sl@36
  2042
        ///
sl@33
  2043
        /// </summary>
sl@33
  2044
        /// <param name="aClient"></param>
sl@33
  2045
        private void UpdateClientTreeViewNode(ClientData aClient)
sl@33
  2046
        {
StephaneLenclud@148
  2047
            Debug.Print("UpdateClientTreeViewNode");
StephaneLenclud@148
  2048
sl@33
  2049
            if (aClient == null)
sl@33
  2050
            {
sl@33
  2051
                return;
sl@33
  2052
            }
sl@33
  2053
StephaneLenclud@180
  2054
            //Hook in record icon update too
StephaneLenclud@180
  2055
            UpdateRecordingNotification();
StephaneLenclud@180
  2056
sl@33
  2057
            TreeNode node = null;
sl@33
  2058
            //Check that our client node already exists
sl@33
  2059
            //Get our client root node using its key which is our session ID
StephaneLenclud@188
  2060
            TreeNode[] nodes = iTreeViewClients.Nodes.Find(aClient.SessionId, false);
StephaneLenclud@223
  2061
            if (nodes.Count() > 0)
sl@33
  2062
            {
sl@33
  2063
                //We already have a node for that client
sl@33
  2064
                node = nodes[0];
sl@33
  2065
                //Clear children as we are going to recreate them below
sl@33
  2066
                node.Nodes.Clear();
sl@33
  2067
            }
sl@33
  2068
            else
sl@33
  2069
            {
sl@33
  2070
                //Client node does not exists create a new one
StephaneLenclud@188
  2071
                iTreeViewClients.Nodes.Add(aClient.SessionId, aClient.SessionId);
StephaneLenclud@188
  2072
                node = iTreeViewClients.Nodes.Find(aClient.SessionId, false)[0];
sl@33
  2073
            }
sl@33
  2074
sl@33
  2075
            if (node != null)
sl@33
  2076
            {
sl@33
  2077
                //Change its name
StephaneLenclud@184
  2078
                if (!String.IsNullOrEmpty(aClient.Name))
sl@33
  2079
                {
StephaneLenclud@184
  2080
                    //We have a name, use it as text for our root node
sl@33
  2081
                    node.Text = aClient.Name;
sl@32
  2082
                    //Add a child with SessionId
sl@33
  2083
                    node.Nodes.Add(new TreeNode(aClient.SessionId));
sl@33
  2084
                }
sl@33
  2085
                else
sl@33
  2086
                {
sl@33
  2087
                    //No name, use session ID instead
sl@33
  2088
                    node.Text = aClient.SessionId;
sl@33
  2089
                }
sl@36
  2090
StephaneLenclud@184
  2091
                //Display client priority
StephaneLenclud@184
  2092
                node.Nodes.Add(new TreeNode("Priority: " + aClient.Priority));
StephaneLenclud@184
  2093
sl@67
  2094
                if (aClient.Fields.Count > 0)
sl@33
  2095
                {
sl@33
  2096
                    //Create root node for our texts
sl@70
  2097
                    TreeNode textsRoot = new TreeNode("Fields");
sl@33
  2098
                    node.Nodes.Add(textsRoot);
sl@33
  2099
                    //For each text add a new entry
sl@67
  2100
                    foreach (DataField field in aClient.Fields)
sl@33
  2101
                    {
StephaneLenclud@172
  2102
                        if (field.IsTextField)
sl@67
  2103
                        {
StephaneLenclud@223
  2104
                            TextField textField = (TextField) field;
sl@70
  2105
                            textsRoot.Nodes.Add(new TreeNode("[Text]" + textField.Text));
sl@67
  2106
                        }
StephaneLenclud@172
  2107
                        else if (field.IsBitmapField)
sl@67
  2108
                        {
sl@72
  2109
                            textsRoot.Nodes.Add(new TreeNode("[Bitmap]"));
sl@70
  2110
                        }
StephaneLenclud@172
  2111
                        else if (field.IsRecordingField)
StephaneLenclud@172
  2112
                        {
StephaneLenclud@223
  2113
                            RecordingField recordingField = (RecordingField) field;
StephaneLenclud@177
  2114
                            textsRoot.Nodes.Add(new TreeNode("[Recording]" + recordingField.IsActive));
StephaneLenclud@172
  2115
                        }
sl@33
  2116
                    }
sl@32
  2117
                }
sl@34
  2118
sl@34
  2119
                node.ExpandAll();
sl@32
  2120
            }
sl@30
  2121
        }
sl@17
  2122
sl@60
  2123
        /// <summary>
sl@60
  2124
        /// Update our table layout row styles to make sure each rows have similar height
sl@60
  2125
        /// </summary>
sl@60
  2126
        private void UpdateTableLayoutRowStyles()
sl@60
  2127
        {
StephaneLenclud@175
  2128
            foreach (RowStyle rowStyle in iTableLayoutPanel.RowStyles)
sl@60
  2129
            {
sl@60
  2130
                rowStyle.SizeType = SizeType.Percent;
StephaneLenclud@223
  2131
                rowStyle.Height = 100/iTableLayoutPanel.RowCount;
sl@60
  2132
            }
sl@60
  2133
        }
sl@60
  2134
sl@63
  2135
        /// <summary>
sl@63
  2136
        /// Update our display table layout.
StephaneLenclud@175
  2137
        /// Will instanciated every field control as defined by our client.
StephaneLenclud@175
  2138
        /// Fields must be specified by rows from the left.
sl@63
  2139
        /// </summary>
sl@63
  2140
        /// <param name="aLayout"></param>
sl@65
  2141
        private void UpdateTableLayoutPanel(ClientData aClient)
sl@63
  2142
        {
StephaneLenclud@175
  2143
            Debug.Print("UpdateTableLayoutPanel");
StephaneLenclud@148
  2144
StephaneLenclud@223
  2145
            if (aClient == null)
StephaneLenclud@223
  2146
            {
StephaneLenclud@223
  2147
                //Just drop it
StephaneLenclud@223
  2148
                return;
StephaneLenclud@223
  2149
            }
StephaneLenclud@106
  2150
StephaneLenclud@106
  2151
sl@65
  2152
            TableLayout layout = aClient.Layout;
sl@70
  2153
StephaneLenclud@141
  2154
            //First clean our current panel
StephaneLenclud@175
  2155
            iTableLayoutPanel.Controls.Clear();
StephaneLenclud@175
  2156
            iTableLayoutPanel.RowStyles.Clear();
StephaneLenclud@175
  2157
            iTableLayoutPanel.ColumnStyles.Clear();
StephaneLenclud@175
  2158
            iTableLayoutPanel.RowCount = 0;
StephaneLenclud@175
  2159
            iTableLayoutPanel.ColumnCount = 0;
sl@63
  2160
StephaneLenclud@175
  2161
            //Then recreate our rows...
StephaneLenclud@175
  2162
            while (iTableLayoutPanel.RowCount < layout.Rows.Count)
sl@63
  2163
            {
StephaneLenclud@175
  2164
                iTableLayoutPanel.RowCount++;
sl@63
  2165
            }
sl@63
  2166
StephaneLenclud@175
  2167
            // ...and columns 
StephaneLenclud@175
  2168
            while (iTableLayoutPanel.ColumnCount < layout.Columns.Count)
sl@63
  2169
            {
StephaneLenclud@175
  2170
                iTableLayoutPanel.ColumnCount++;
sl@63
  2171
            }
sl@63
  2172
StephaneLenclud@175
  2173
            //For each column
StephaneLenclud@175
  2174
            for (int i = 0; i < iTableLayoutPanel.ColumnCount; i++)
sl@63
  2175
            {
sl@63
  2176
                //Create our column styles
StephaneLenclud@175
  2177
                this.iTableLayoutPanel.ColumnStyles.Add(layout.Columns[i]);
sl@63
  2178
StephaneLenclud@175
  2179
                //For each rows
StephaneLenclud@175
  2180
                for (int j = 0; j < iTableLayoutPanel.RowCount; j++)
sl@63
  2181
                {
sl@63
  2182
                    if (i == 0)
sl@63
  2183
                    {
sl@63
  2184
                        //Create our row styles
StephaneLenclud@175
  2185
                        this.iTableLayoutPanel.RowStyles.Add(layout.Rows[j]);
sl@63
  2186
                    }
StephaneLenclud@176
  2187
                    else
sl@70
  2188
                    {
sl@70
  2189
                        continue;
sl@70
  2190
                    }
sl@63
  2191
                }
sl@63
  2192
            }
sl@63
  2193
StephaneLenclud@176
  2194
            //For each field
StephaneLenclud@176
  2195
            foreach (DataField field in aClient.Fields)
sl@70
  2196
            {
StephaneLenclud@176
  2197
                if (!field.IsTableField)
StephaneLenclud@176
  2198
                {
StephaneLenclud@176
  2199
                    //That field is not taking part in our table layout skip it
StephaneLenclud@176
  2200
                    continue;
StephaneLenclud@176
  2201
                }
StephaneLenclud@176
  2202
StephaneLenclud@223
  2203
                TableField tableField = (TableField) field;
StephaneLenclud@176
  2204
StephaneLenclud@176
  2205
                //Create a control corresponding to the field specified for that cell
StephaneLenclud@176
  2206
                Control control = CreateControlForDataField(tableField);
StephaneLenclud@176
  2207
StephaneLenclud@176
  2208
                //Add newly created control to our table layout at the specified row and column
StephaneLenclud@176
  2209
                iTableLayoutPanel.Controls.Add(control, tableField.Column, tableField.Row);
StephaneLenclud@176
  2210
                //Make sure we specify column and row span for that new control
StephaneLenclud@176
  2211
                iTableLayoutPanel.SetColumnSpan(control, tableField.ColumnSpan);
StephaneLenclud@176
  2212
                iTableLayoutPanel.SetRowSpan(control, tableField.RowSpan);
sl@70
  2213
            }
sl@70
  2214
StephaneLenclud@176
  2215
sl@63
  2216
            CheckFontHeight();
sl@63
  2217
        }
sl@63
  2218
sl@68
  2219
        /// <summary>
sl@70
  2220
        /// Check our type of data field and create corresponding control
sl@68
  2221
        /// </summary>
sl@68
  2222
        /// <param name="aField"></param>
sl@69
  2223
        private Control CreateControlForDataField(DataField aField)
sl@68
  2224
        {
StephaneLenclud@223
  2225
            Control control = null;
StephaneLenclud@172
  2226
            if (aField.IsTextField)
sl@68
  2227
            {
sl@68
  2228
                MarqueeLabel label = new SharpDisplayManager.MarqueeLabel();
sl@68
  2229
                label.AutoEllipsis = true;
sl@68
  2230
                label.AutoSize = true;
sl@68
  2231
                label.BackColor = System.Drawing.Color.Transparent;
sl@68
  2232
                label.Dock = System.Windows.Forms.DockStyle.Fill;
sl@68
  2233
                label.Location = new System.Drawing.Point(1, 1);
sl@68
  2234
                label.Margin = new System.Windows.Forms.Padding(0);
StephaneLenclud@176
  2235
                label.Name = "marqueeLabel" + aField;
sl@68
  2236
                label.OwnTimer = false;
StephaneLenclud@106
  2237
                label.PixelsPerSecond = cds.ScrollingSpeedInPixelsPerSecond;
sl@100
  2238
                label.Separator = cds.Separator;
sl@100
  2239
                label.MinFontSize = cds.MinFontSize;
sl@100
  2240
                label.ScaleToFit = cds.ScaleToFit;
sl@68
  2241
                //control.Size = new System.Drawing.Size(254, 30);
sl@68
  2242
                //control.TabIndex = 2;
sl@68
  2243
                label.Font = cds.Font;
sl@68
  2244
StephaneLenclud@223
  2245
                TextField field = (TextField) aField;
StephaneLenclud@172
  2246
                label.TextAlign = field.Alignment;
sl@68
  2247
                label.UseCompatibleTextRendering = true;
StephaneLenclud@172
  2248
                label.Text = field.Text;
sl@68
  2249
                //
sl@68
  2250
                control = label;
sl@68
  2251
            }
StephaneLenclud@172
  2252
            else if (aField.IsBitmapField)
sl@68
  2253
            {
sl@68
  2254
                //Create picture box
sl@68
  2255
                PictureBox picture = new PictureBox();
sl@68
  2256
                picture.AutoSize = true;
sl@68
  2257
                picture.BackColor = System.Drawing.Color.Transparent;
sl@68
  2258
                picture.Dock = System.Windows.Forms.DockStyle.Fill;
sl@68
  2259
                picture.Location = new System.Drawing.Point(1, 1);
sl@68
  2260
                picture.Margin = new System.Windows.Forms.Padding(0);
sl@68
  2261
                picture.Name = "pictureBox" + aField;
sl@68
  2262
                //Set our image
StephaneLenclud@223
  2263
                BitmapField field = (BitmapField) aField;
StephaneLenclud@172
  2264
                picture.Image = field.Bitmap;
sl@68
  2265
                //
sl@68
  2266
                control = picture;
sl@68
  2267
            }
StephaneLenclud@172
  2268
            //TODO: Handle recording field?
sl@68
  2269
sl@69
  2270
            return control;
sl@68
  2271
        }
sl@68
  2272
StephaneLenclud@223
  2273
        /// <summary>
StephaneLenclud@223
  2274
        /// Called when the user selected a new display type.
StephaneLenclud@223
  2275
        /// </summary>
StephaneLenclud@223
  2276
        /// <param name="sender"></param>
StephaneLenclud@223
  2277
        /// <param name="e"></param>
sl@46
  2278
        private void comboBoxDisplayType_SelectedIndexChanged(object sender, EventArgs e)
sl@46
  2279
        {
StephaneLenclud@223
  2280
            //Store the selected display type in our settings
sl@48
  2281
            Properties.Settings.Default.CurrentDisplayIndex = comboBoxDisplayType.SelectedIndex;
sl@48
  2282
            cds.DisplayType = comboBoxDisplayType.SelectedIndex;
sl@46
  2283
            Properties.Settings.Default.Save();
StephaneLenclud@103
  2284
StephaneLenclud@223
  2285
            //Try re-opening the display connection if we were already connected.
StephaneLenclud@223
  2286
            //Otherwise just update our status to reflect display type change.
sl@51
  2287
            if (iDisplay.IsOpen())
sl@51
  2288
            {
sl@51
  2289
                OpenDisplayConnection();
sl@51
  2290
            }
sl@51
  2291
            else
sl@51
  2292
            {
sl@51
  2293
                UpdateStatus();
sl@51
  2294
            }
sl@46
  2295
        }
sl@46
  2296
sl@47
  2297
        private void maskedTextBoxTimerInterval_TextChanged(object sender, EventArgs e)
sl@47
  2298
        {
sl@47
  2299
            if (maskedTextBoxTimerInterval.Text != "")
sl@47
  2300
            {
sl@51
  2301
                int interval = Convert.ToInt32(maskedTextBoxTimerInterval.Text);
sl@51
  2302
sl@51
  2303
                if (interval > 0)
sl@51
  2304
                {
StephaneLenclud@270
  2305
                    iTimerDisplay.Interval = interval;
StephaneLenclud@270
  2306
                    cds.TimerInterval = iTimerDisplay.Interval;
sl@51
  2307
                    Properties.Settings.Default.Save();
sl@51
  2308
                }
sl@47
  2309
            }
sl@47
  2310
        }
sl@47
  2311
sl@100
  2312
        private void maskedTextBoxMinFontSize_TextChanged(object sender, EventArgs e)
sl@100
  2313
        {
sl@100
  2314
            if (maskedTextBoxMinFontSize.Text != "")
sl@100
  2315
            {
sl@100
  2316
                int minFontSize = Convert.ToInt32(maskedTextBoxMinFontSize.Text);
sl@100
  2317
sl@100
  2318
                if (minFontSize > 0)
sl@100
  2319
                {
sl@100
  2320
                    cds.MinFontSize = minFontSize;
sl@100
  2321
                    Properties.Settings.Default.Save();
StephaneLenclud@223
  2322
                    //We need to recreate our layout for that change to take effect
StephaneLenclud@223
  2323
                    UpdateTableLayoutPanel(iCurrentClientData);
sl@100
  2324
                }
sl@100
  2325
            }
sl@100
  2326
        }
sl@100
  2327
StephaneLenclud@106
  2328
StephaneLenclud@223
  2329
        private void maskedTextBoxScrollingSpeed_TextChanged(object sender, EventArgs e)
StephaneLenclud@223
  2330
        {
StephaneLenclud@223
  2331
            if (maskedTextBoxScrollingSpeed.Text != "")
StephaneLenclud@223
  2332
            {
StephaneLenclud@223
  2333
                int scrollingSpeed = Convert.ToInt32(maskedTextBoxScrollingSpeed.Text);
StephaneLenclud@223
  2334
StephaneLenclud@223
  2335
                if (scrollingSpeed > 0)
StephaneLenclud@223
  2336
                {
StephaneLenclud@223
  2337
                    cds.ScrollingSpeedInPixelsPerSecond = scrollingSpeed;
StephaneLenclud@223
  2338
                    Properties.Settings.Default.Save();
StephaneLenclud@223
  2339
                    //We need to recreate our layout for that change to take effect
StephaneLenclud@223
  2340
                    UpdateTableLayoutPanel(iCurrentClientData);
StephaneLenclud@223
  2341
                }
StephaneLenclud@223
  2342
            }
StephaneLenclud@223
  2343
        }
StephaneLenclud@106
  2344
sl@100
  2345
        private void textBoxScrollLoopSeparator_TextChanged(object sender, EventArgs e)
sl@100
  2346
        {
sl@100
  2347
            cds.Separator = textBoxScrollLoopSeparator.Text;
sl@100
  2348
            Properties.Settings.Default.Save();
StephaneLenclud@110
  2349
StephaneLenclud@223
  2350
            //Update our text fields
StephaneLenclud@223
  2351
            foreach (MarqueeLabel ctrl in iTableLayoutPanel.Controls)
StephaneLenclud@223
  2352
            {
StephaneLenclud@223
  2353
                ctrl.Separator = cds.Separator;
StephaneLenclud@223
  2354
            }
StephaneLenclud@110
  2355
sl@100
  2356
        }
sl@100
  2357
sl@52
  2358
        private void buttonPowerOn_Click(object sender, EventArgs e)
sl@52
  2359
        {
sl@52
  2360
            iDisplay.PowerOn();
sl@52
  2361
        }
sl@52
  2362
sl@52
  2363
        private void buttonPowerOff_Click(object sender, EventArgs e)
sl@52
  2364
        {
sl@52
  2365
            iDisplay.PowerOff();
sl@52
  2366
        }
sl@52
  2367
sl@53
  2368
        private void buttonShowClock_Click(object sender, EventArgs e)
sl@53
  2369
        {
StephaneLenclud@223
  2370
            ShowClock();
sl@53
  2371
        }
sl@53
  2372
sl@53
  2373
        private void buttonHideClock_Click(object sender, EventArgs e)
sl@53
  2374
        {
StephaneLenclud@223
  2375
            HideClock();
sl@53
  2376
        }
sl@88
  2377
sl@88
  2378
        private void buttonUpdate_Click(object sender, EventArgs e)
sl@88
  2379
        {
sl@88
  2380
            InstallUpdateSyncWithInfo();
sl@88
  2381
        }
sl@88
  2382
StephaneLenclud@223
  2383
        /// <summary>
StephaneLenclud@223
  2384
        /// 
StephaneLenclud@223
  2385
        /// </summary>
StephaneLenclud@223
  2386
        void ShowClock()
StephaneLenclud@223
  2387
        {
StephaneLenclud@223
  2388
            if (!iDisplay.IsOpen())
StephaneLenclud@223
  2389
            {
StephaneLenclud@223
  2390
                return;
StephaneLenclud@223
  2391
            }
StephaneLenclud@223
  2392
StephaneLenclud@223
  2393
            //Devices like MDM166AA don't support windowing and frame rendering must be stopped while showing our clock
StephaneLenclud@223
  2394
            iSkipFrameRendering = true;
StephaneLenclud@223
  2395
            //Clear our screen 
StephaneLenclud@223
  2396
            iDisplay.Clear();
StephaneLenclud@223
  2397
            iDisplay.SwapBuffers();
StephaneLenclud@223
  2398
            //Then show our clock
StephaneLenclud@223
  2399
            iDisplay.ShowClock();
StephaneLenclud@223
  2400
        }
StephaneLenclud@223
  2401
StephaneLenclud@223
  2402
        /// <summary>
StephaneLenclud@223
  2403
        /// 
StephaneLenclud@223
  2404
        /// </summary>
StephaneLenclud@223
  2405
        void HideClock()
StephaneLenclud@223
  2406
        {
StephaneLenclud@223
  2407
            if (!iDisplay.IsOpen())
StephaneLenclud@223
  2408
            {
StephaneLenclud@223
  2409
                return;
StephaneLenclud@223
  2410
            }
StephaneLenclud@223
  2411
StephaneLenclud@223
  2412
            //Devices like MDM166AA don't support windowing and frame rendering must be stopped while showing our clock
StephaneLenclud@223
  2413
            iSkipFrameRendering = false;
StephaneLenclud@223
  2414
            iDisplay.HideClock();
StephaneLenclud@223
  2415
        }
sl@88
  2416
sl@88
  2417
        private void InstallUpdateSyncWithInfo()
sl@88
  2418
        {
sl@88
  2419
            UpdateCheckInfo info = null;
sl@88
  2420
sl@88
  2421
            if (ApplicationDeployment.IsNetworkDeployed)
sl@88
  2422
            {
sl@88
  2423
                ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
sl@88
  2424
sl@88
  2425
                try
sl@88
  2426
                {
sl@88
  2427
                    info = ad.CheckForDetailedUpdate();
sl@88
  2428
sl@88
  2429
                }
sl@88
  2430
                catch (DeploymentDownloadException dde)
sl@88
  2431
                {
StephaneLenclud@223
  2432
                    MessageBox.Show(
StephaneLenclud@223
  2433
                        "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
  2434
                        dde.Message);
sl@88
  2435
                    return;
sl@88
  2436
                }
sl@88
  2437
                catch (InvalidDeploymentException ide)
sl@88
  2438
                {
StephaneLenclud@223
  2439
                    MessageBox.Show(
StephaneLenclud@223
  2440
                        "Cannot check for a new version of the application. The ClickOnce deployment is corrupt. Please redeploy the application and try again. Error: " +
StephaneLenclud@223
  2441
                        ide.Message);
sl@88
  2442
                    return;
sl@88
  2443
                }
sl@88
  2444
                catch (InvalidOperationException ioe)
sl@88
  2445
                {
StephaneLenclud@223
  2446
                    MessageBox.Show(
StephaneLenclud@223
  2447
                        "This application cannot be updated. It is likely not a ClickOnce application. Error: " +
StephaneLenclud@223
  2448
                        ioe.Message);
sl@88
  2449
                    return;
sl@88
  2450
                }
sl@88
  2451
StephaneLenclud@223
  2452
                if (info.UpdateAvailable)
StephaneLenclud@223
  2453
                {
StephaneLenclud@223
  2454
                    Boolean doUpdate = true;
StephaneLenclud@223
  2455
StephaneLenclud@223
  2456
                    if (!info.IsUpdateRequired)
StephaneLenclud@223
  2457
                    {
StephaneLenclud@223
  2458
                        DialogResult dr =
StephaneLenclud@223
  2459
                            MessageBox.Show("An update is available. Would you like to update the application now?",
StephaneLenclud@223
  2460
                                "Update Available", MessageBoxButtons.OKCancel);
StephaneLenclud@223
  2461
                        if (!(DialogResult.OK == dr))
StephaneLenclud@223
  2462
                        {
StephaneLenclud@223
  2463
                            doUpdate = false;
StephaneLenclud@223
  2464
                        }
StephaneLenclud@223
  2465
                    }
StephaneLenclud@223
  2466
                    else
StephaneLenclud@223
  2467
                    {
StephaneLenclud@223
  2468
                        // Display a message that the application MUST reboot. Display the minimum required version.
StephaneLenclud@223
  2469
                        MessageBox.Show("This application has detected a mandatory update from your current " +
StephaneLenclud@223
  2470
                                        "version to version " + info.MinimumRequiredVersion.ToString() +
StephaneLenclud@223
  2471
                                        ". The application will now install the update and restart.",
StephaneLenclud@223
  2472
                            "Update Available", MessageBoxButtons.OK,
StephaneLenclud@223
  2473
                            MessageBoxIcon.Information);
StephaneLenclud@223
  2474
                    }
StephaneLenclud@223
  2475
StephaneLenclud@223
  2476
                    if (doUpdate)
StephaneLenclud@223
  2477
                    {
StephaneLenclud@223
  2478
                        try
StephaneLenclud@223
  2479
                        {
StephaneLenclud@223
  2480
                            ad.Update();
StephaneLenclud@223
  2481
                            MessageBox.Show("The application has been upgraded, and will now restart.");
StephaneLenclud@223
  2482
                            Application.Restart();
StephaneLenclud@223
  2483
                        }
StephaneLenclud@223
  2484
                        catch (DeploymentDownloadException dde)
StephaneLenclud@223
  2485
                        {
StephaneLenclud@223
  2486
                            MessageBox.Show(
StephaneLenclud@223
  2487
                                "Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " +
StephaneLenclud@223
  2488
                                dde);
StephaneLenclud@223
  2489
                            return;
StephaneLenclud@223
  2490
                        }
StephaneLenclud@223
  2491
                    }
StephaneLenclud@223
  2492
                }
StephaneLenclud@223
  2493
                else
StephaneLenclud@223
  2494
                {
StephaneLenclud@223
  2495
                    MessageBox.Show("You are already running the latest version.", "Application up-to-date");
StephaneLenclud@223
  2496
                }
sl@88
  2497
            }
sl@88
  2498
        }
sl@92
  2499
sl@94
  2500
StephaneLenclud@223
  2501
        /// <summary>
StephaneLenclud@223
  2502
        /// Used to
StephaneLenclud@223
  2503
        /// </summary>
StephaneLenclud@223
  2504
        private void SysTrayHideShow()
StephaneLenclud@223
  2505
        {
StephaneLenclud@223
  2506
            Visible = !Visible;
StephaneLenclud@223
  2507
            if (Visible)
StephaneLenclud@223
  2508
            {
StephaneLenclud@223
  2509
                Activate();
StephaneLenclud@223
  2510
                WindowState = FormWindowState.Normal;
StephaneLenclud@223
  2511
            }
StephaneLenclud@223
  2512
        }
StephaneLenclud@223
  2513
StephaneLenclud@223
  2514
        /// <summary>
StephaneLenclud@223
  2515
        /// Use to handle minimize events.
StephaneLenclud@223
  2516
        /// </summary>
StephaneLenclud@223
  2517
        /// <param name="sender"></param>
StephaneLenclud@223
  2518
        /// <param name="e"></param>
StephaneLenclud@223
  2519
        private void MainForm_SizeChanged(object sender, EventArgs e)
StephaneLenclud@223
  2520
        {
StephaneLenclud@223
  2521
            if (WindowState == FormWindowState.Minimized && Properties.Settings.Default.MinimizeToTray)
StephaneLenclud@223
  2522
            {
StephaneLenclud@223
  2523
                if (Visible)
StephaneLenclud@223
  2524
                {
StephaneLenclud@223
  2525
                    SysTrayHideShow();
StephaneLenclud@223
  2526
                }
StephaneLenclud@223
  2527
            }
StephaneLenclud@223
  2528
        }
StephaneLenclud@223
  2529
StephaneLenclud@223
  2530
        /// <summary>
StephaneLenclud@223
  2531
        /// 
StephaneLenclud@223
  2532
        /// </summary>
StephaneLenclud@223
  2533
        /// <param name="sender"></param>
StephaneLenclud@223
  2534
        /// <param name="e"></param>
StephaneLenclud@223
  2535
        private void tableLayoutPanel_SizeChanged(object sender, EventArgs e)
StephaneLenclud@223
  2536
        {
StephaneLenclud@223
  2537
            //Our table layout size has changed which means our display size has changed.
StephaneLenclud@223
  2538
            //We need to re-create our bitmap.
StephaneLenclud@223
  2539
            iCreateBitmap = true;
StephaneLenclud@223
  2540
        }
StephaneLenclud@223
  2541
StephaneLenclud@223
  2542
        /// <summary>
StephaneLenclud@167
  2543
        /// Broadcast messages to subscribers.
StephaneLenclud@167
  2544
        /// </summary>
StephaneLenclud@167
  2545
        /// <param name="message"></param>
StephaneLenclud@167
  2546
        protected override void WndProc(ref Message aMessage)
StephaneLenclud@167
  2547
        {
StephaneLenclud@223
  2548
            if (OnWndProc != null)
StephaneLenclud@167
  2549
            {
StephaneLenclud@167
  2550
                OnWndProc(ref aMessage);
StephaneLenclud@167
  2551
            }
StephaneLenclud@223
  2552
StephaneLenclud@167
  2553
            base.WndProc(ref aMessage);
StephaneLenclud@167
  2554
        }
StephaneLenclud@168
  2555
Stephane@252
  2556
        private void iCheckBoxCecEnabled_CheckedChanged(object sender, EventArgs e)
StephaneLenclud@168
  2557
        {
StephaneLenclud@168
  2558
            //
StephaneLenclud@168
  2559
            ResetCec();
StephaneLenclud@168
  2560
        }
StephaneLenclud@168
  2561
StephaneLenclud@168
  2562
        private void comboBoxHdmiPort_SelectedIndexChanged(object sender, EventArgs e)
StephaneLenclud@168
  2563
        {
StephaneLenclud@168
  2564
            //Save CEC HDMI port
StephaneLenclud@168
  2565
            Properties.Settings.Default.CecHdmiPort = Convert.ToByte(comboBoxHdmiPort.SelectedIndex);
StephaneLenclud@168
  2566
            Properties.Settings.Default.CecHdmiPort++;
StephaneLenclud@168
  2567
            Properties.Settings.Default.Save();
StephaneLenclud@168
  2568
            //
StephaneLenclud@168
  2569
            ResetCec();
StephaneLenclud@168
  2570
        }
StephaneLenclud@168
  2571
StephaneLenclud@168
  2572
        /// <summary>
StephaneLenclud@168
  2573
        /// 
StephaneLenclud@168
  2574
        /// </summary>
StephaneLenclud@168
  2575
        private void ResetCec()
StephaneLenclud@168
  2576
        {
StephaneLenclud@223
  2577
            if (iCecManager == null)
StephaneLenclud@168
  2578
            {
StephaneLenclud@168
  2579
                //Thus skipping initial UI setup
StephaneLenclud@168
  2580
                return;
StephaneLenclud@168
  2581
            }
StephaneLenclud@168
  2582
StephaneLenclud@168
  2583
            iCecManager.Stop();
StephaneLenclud@168
  2584
            //
StephaneLenclud@168
  2585
            if (Properties.Settings.Default.CecEnabled)
StephaneLenclud@168
  2586
            {
StephaneLenclud@168
  2587
                iCecManager.Start(Handle, "CEC",
StephaneLenclud@223
  2588
                    Properties.Settings.Default.CecHdmiPort);
StephaneLenclud@206
  2589
Stephane@207
  2590
                SetupCecLogLevel();
Stephane@207
  2591
            }
Stephane@207
  2592
        }
StephaneLenclud@206
  2593
Stephane@207
  2594
        /// <summary>
Stephane@207
  2595
        /// 
Stephane@207
  2596
        /// </summary>
StephaneLenclud@255
  2597
        private async void ResetHarmonyAsync(bool aForceAuth=false)
StephaneLenclud@233
  2598
        {
StephaneLenclud@233
  2599
            // ConnectAsync already if we have an existing session cookie
Stephane@252
  2600
            if (Properties.Settings.Default.HarmonyEnabled)
StephaneLenclud@233
  2601
            {
StephaneLenclud@233
  2602
                try
StephaneLenclud@233
  2603
                {
StephaneLenclud@255
  2604
                    iButtonHarmonyConnect.Enabled = false;
Stephane@252
  2605
                    await ConnectHarmonyAsync(aForceAuth);
StephaneLenclud@233
  2606
                }
Stephane@252
  2607
                catch (Exception ex)
StephaneLenclud@233
  2608
                {
StephaneLenclud@253
  2609
                    Trace.WriteLine("Exception thrown by ConnectHarmonyAsync");
StephaneLenclud@253
  2610
                    Trace.WriteLine(ex.ToString());
StephaneLenclud@233
  2611
                }
StephaneLenclud@255
  2612
                finally
StephaneLenclud@255
  2613
                {
StephaneLenclud@255
  2614
                    iButtonHarmonyConnect.Enabled = true;
StephaneLenclud@255
  2615
                }
StephaneLenclud@233
  2616
            }
StephaneLenclud@233
  2617
        }
StephaneLenclud@233
  2618
StephaneLenclud@233
  2619
        /// <summary>
StephaneLenclud@233
  2620
        /// 
StephaneLenclud@233
  2621
        /// </summary>
Stephane@252
  2622
        /// <param name="sender"></param>
Stephane@252
  2623
        /// <param name="e"></param>
Stephane@252
  2624
        private void iButtonHarmonyConnect_Click(object sender, EventArgs e)
Stephane@252
  2625
        {
Stephane@252
  2626
            // User is explicitaly trying to connect
Stephane@252
  2627
            //Reset Harmony Hub connection forcing authentication
StephaneLenclud@255
  2628
            ResetHarmonyAsync(true);
Stephane@252
  2629
        }
Stephane@252
  2630
Stephane@252
  2631
        /// <summary>
Stephane@252
  2632
        /// 
Stephane@252
  2633
        /// </summary>
Stephane@252
  2634
        /// <param name="sender"></param>
Stephane@252
  2635
        /// <param name="e"></param>
Stephane@252
  2636
        private void iCheckBoxHarmonyEnabled_CheckedChanged(object sender, EventArgs e)
Stephane@252
  2637
        {
Stephane@252
  2638
            iButtonHarmonyConnect.Enabled = iCheckBoxHarmonyEnabled.Checked;
Stephane@252
  2639
        }
Stephane@252
  2640
Stephane@252
  2641
        /// <summary>
Stephane@252
  2642
        /// 
Stephane@252
  2643
        /// </summary>
Stephane@207
  2644
        private void SetupCecLogLevel()
Stephane@207
  2645
        {
Stephane@207
  2646
            //Setup log level
Stephane@207
  2647
            iCecManager.Client.LogLevel = 0;
StephaneLenclud@206
  2648
Stephane@207
  2649
            if (checkBoxCecLogError.Checked)
StephaneLenclud@223
  2650
                iCecManager.Client.LogLevel |= (int) CecLogLevel.Error;
StephaneLenclud@206
  2651
Stephane@207
  2652
            if (checkBoxCecLogWarning.Checked)
StephaneLenclud@223
  2653
                iCecManager.Client.LogLevel |= (int) CecLogLevel.Warning;
StephaneLenclud@206
  2654
Stephane@207
  2655
            if (checkBoxCecLogNotice.Checked)
StephaneLenclud@223
  2656
                iCecManager.Client.LogLevel |= (int) CecLogLevel.Notice;
StephaneLenclud@206
  2657
Stephane@207
  2658
            if (checkBoxCecLogTraffic.Checked)
StephaneLenclud@223
  2659
                iCecManager.Client.LogLevel |= (int) CecLogLevel.Traffic;
StephaneLenclud@206
  2660
Stephane@207
  2661
            if (checkBoxCecLogDebug.Checked)
StephaneLenclud@223
  2662
                iCecManager.Client.LogLevel |= (int) CecLogLevel.Debug;
StephaneLenclud@206
  2663
Stephane@207
  2664
            iCecManager.Client.FilterOutPollLogs = checkBoxCecLogNoPoll.Checked;
Stephane@207
  2665
StephaneLenclud@168
  2666
        }
StephaneLenclud@189
  2667
StephaneLenclud@189
  2668
        private void ButtonStartIdleClient_Click(object sender, EventArgs e)
StephaneLenclud@189
  2669
        {
StephaneLenclud@189
  2670
            StartIdleClient();
StephaneLenclud@189
  2671
        }
StephaneLenclud@204
  2672
StephaneLenclud@206
  2673
        private void buttonClearLogs_Click(object sender, EventArgs e)
StephaneLenclud@206
  2674
        {
StephaneLenclud@206
  2675
            richTextBoxLogs.Clear();
StephaneLenclud@206
  2676
        }
StephaneLenclud@204
  2677
StephaneLenclud@206
  2678
        private void checkBoxCecLogs_CheckedChanged(object sender, EventArgs e)
StephaneLenclud@206
  2679
        {
Stephane@207
  2680
            SetupCecLogLevel();
StephaneLenclud@206
  2681
        }
StephaneLenclud@211
  2682
StephaneLenclud@223
  2683
StephaneLenclud@218
  2684
StephaneLenclud@219
  2685
StephaneLenclud@219
  2686
StephaneLenclud@217
  2687
        /// <summary>
StephaneLenclud@219
  2688
        /// Get the current event based on event tree view selection.
StephaneLenclud@217
  2689
        /// </summary>
StephaneLenclud@217
  2690
        /// <returns></returns>
StephaneLenclud@234
  2691
        private Ear.Event CurrentEvent()
StephaneLenclud@217
  2692
        {
StephaneLenclud@217
  2693
            //Walk up the tree from the selected node to find our event
StephaneLenclud@217
  2694
            TreeNode node = iTreeViewEvents.SelectedNode;
StephaneLenclud@234
  2695
            Ear.Event selectedEvent = null;
StephaneLenclud@217
  2696
            while (node != null)
StephaneLenclud@217
  2697
            {
StephaneLenclud@234
  2698
                if (node.Tag is Ear.Event)
StephaneLenclud@217
  2699
                {
StephaneLenclud@234
  2700
                    selectedEvent = (Ear.Event) node.Tag;
StephaneLenclud@217
  2701
                    break;
StephaneLenclud@217
  2702
                }
StephaneLenclud@217
  2703
                node = node.Parent;
StephaneLenclud@217
  2704
            }
StephaneLenclud@217
  2705
StephaneLenclud@217
  2706
            return selectedEvent;
StephaneLenclud@217
  2707
        }
StephaneLenclud@217
  2708
StephaneLenclud@217
  2709
        /// <summary>
StephaneLenclud@219
  2710
        /// Get the current action based on event tree view selection
StephaneLenclud@217
  2711
        /// </summary>
StephaneLenclud@217
  2712
        /// <returns></returns>
StephaneLenclud@234
  2713
        private Ear.Action CurrentAction()
StephaneLenclud@217
  2714
        {
StephaneLenclud@217
  2715
            TreeNode node = iTreeViewEvents.SelectedNode;
StephaneLenclud@234
  2716
            if (node != null && node.Tag is Ear.Action)
StephaneLenclud@217
  2717
            {
StephaneLenclud@234
  2718
                return (Ear.Action) node.Tag;
StephaneLenclud@217
  2719
            }
StephaneLenclud@217
  2720
StephaneLenclud@217
  2721
            return null;
StephaneLenclud@217
  2722
        }
StephaneLenclud@217
  2723
StephaneLenclud@217
  2724
        /// <summary>
StephaneLenclud@217
  2725
        /// 
StephaneLenclud@217
  2726
        /// </summary>
StephaneLenclud@265
  2727
        /// <returns></returns>
StephaneLenclud@265
  2728
        private Ear.Object CurrentEarObject()
StephaneLenclud@265
  2729
        {
StephaneLenclud@265
  2730
            Ear.Action a = CurrentAction();
StephaneLenclud@265
  2731
            Ear.Event e = CurrentEvent();
StephaneLenclud@265
  2732
StephaneLenclud@265
  2733
            if (a != null)
StephaneLenclud@265
  2734
            {
StephaneLenclud@265
  2735
                return a;
StephaneLenclud@265
  2736
            }
StephaneLenclud@265
  2737
StephaneLenclud@265
  2738
            return e;
StephaneLenclud@265
  2739
        }
StephaneLenclud@265
  2740
StephaneLenclud@265
  2741
        /// <summary>
StephaneLenclud@265
  2742
        /// Get the current action based on event tree view selection
StephaneLenclud@265
  2743
        /// </summary>
StephaneLenclud@265
  2744
        /// <returns></returns>
StephaneLenclud@265
  2745
        private Ear.Object CurrentEarParent()
StephaneLenclud@265
  2746
        {
StephaneLenclud@265
  2747
            TreeNode node = iTreeViewEvents.SelectedNode;
StephaneLenclud@265
  2748
            if (node == null || node.Parent == null)
StephaneLenclud@265
  2749
            {
StephaneLenclud@265
  2750
                return null;
StephaneLenclud@265
  2751
            }
StephaneLenclud@265
  2752
StephaneLenclud@265
  2753
            if (node.Parent.Tag is Ear.Object)
StephaneLenclud@265
  2754
            {
StephaneLenclud@265
  2755
                return (Ear.Object)node.Parent.Tag;
StephaneLenclud@265
  2756
            }
StephaneLenclud@265
  2757
StephaneLenclud@265
  2758
            if (node.Parent.Parent != null && node.Parent.Parent.Tag is Ear.Object)
StephaneLenclud@265
  2759
            {
StephaneLenclud@265
  2760
                //Can be the case for events
StephaneLenclud@265
  2761
                return (Ear.Object)node.Parent.Parent.Tag;
StephaneLenclud@265
  2762
            }
StephaneLenclud@265
  2763
StephaneLenclud@265
  2764
            return null;
StephaneLenclud@265
  2765
        }
StephaneLenclud@265
  2766
StephaneLenclud@265
  2767
StephaneLenclud@265
  2768
        /// <summary>
StephaneLenclud@265
  2769
        /// 
StephaneLenclud@265
  2770
        /// </summary>
StephaneLenclud@217
  2771
        /// <param name="sender"></param>
StephaneLenclud@217
  2772
        /// <param name="e"></param>
StephaneLenclud@227
  2773
        private void buttonActionAdd_Click(object sender, EventArgs e)
StephaneLenclud@211
  2774
        {
StephaneLenclud@265
  2775
            Ear.Object parent = CurrentEarObject();
StephaneLenclud@265
  2776
            if (parent == null )
Stephane@212
  2777
            {
StephaneLenclud@265
  2778
                //We did not find a corresponding event or action
StephaneLenclud@211
  2779
                return;
StephaneLenclud@211
  2780
            }
StephaneLenclud@211
  2781
StephaneLenclud@234
  2782
            FormEditObject<Ear.Action> ea = new FormEditObject<Ear.Action>();
StephaneLenclud@228
  2783
            ea.Text = "Add action";
StephaneLenclud@211
  2784
            DialogResult res = CodeProject.Dialog.DlgBox.ShowDialog(ea);
StephaneLenclud@211
  2785
            if (res == DialogResult.OK)
StephaneLenclud@211
  2786
            {
StephaneLenclud@265
  2787
                parent.Objects.Add(ea.Object);               
Stephane@212
  2788
                Properties.Settings.Default.Save();
StephaneLenclud@266
  2789
                // We want to select the parent so that one can easily add another action to the same collection
StephaneLenclud@266
  2790
                PopulateTreeViewEvents(parent);
StephaneLenclud@211
  2791
            }
StephaneLenclud@211
  2792
        }
StephaneLenclud@214
  2793
StephaneLenclud@217
  2794
        /// <summary>
StephaneLenclud@217
  2795
        /// 
StephaneLenclud@217
  2796
        /// </summary>
StephaneLenclud@217
  2797
        /// <param name="sender"></param>
StephaneLenclud@217
  2798
        /// <param name="e"></param>
StephaneLenclud@227
  2799
        private void buttonActionEdit_Click(object sender, EventArgs e)
StephaneLenclud@227
  2800
        {
StephaneLenclud@234
  2801
            Ear.Action selectedAction = CurrentAction();
StephaneLenclud@265
  2802
            Ear.Object parent = CurrentEarParent()
StephaneLenclud@265
  2803
            ;
StephaneLenclud@265
  2804
            if (parent == null || selectedAction == null)
StephaneLenclud@227
  2805
            {
StephaneLenclud@265
  2806
                //We did not find a corresponding parent
StephaneLenclud@227
  2807
                return;
StephaneLenclud@227
  2808
            }
StephaneLenclud@227
  2809
StephaneLenclud@234
  2810
            FormEditObject<Ear.Action> ea = new FormEditObject<Ear.Action>();
StephaneLenclud@228
  2811
            ea.Text = "Edit action";
StephaneLenclud@231
  2812
            ea.Object = selectedAction;
StephaneLenclud@227
  2813
            int actionIndex = iTreeViewEvents.SelectedNode.Index;
StephaneLenclud@227
  2814
            DialogResult res = CodeProject.Dialog.DlgBox.ShowDialog(ea);
StephaneLenclud@227
  2815
            if (res == DialogResult.OK)
StephaneLenclud@227
  2816
            {
StephaneLenclud@265
  2817
                //Make sure we keep the same children as before
StephaneLenclud@265
  2818
                ea.Object.Objects = parent.Objects[actionIndex].Objects;
StephaneLenclud@227
  2819
                //Update our action
StephaneLenclud@265
  2820
                parent.Objects[actionIndex]=ea.Object;
StephaneLenclud@227
  2821
                //Save and rebuild our event tree view
StephaneLenclud@227
  2822
                Properties.Settings.Default.Save();
StephaneLenclud@266
  2823
                PopulateTreeViewEvents(ea.Object);
StephaneLenclud@227
  2824
            }
StephaneLenclud@227
  2825
        }
StephaneLenclud@227
  2826
StephaneLenclud@227
  2827
        /// <summary>
StephaneLenclud@227
  2828
        /// 
StephaneLenclud@227
  2829
        /// </summary>
StephaneLenclud@227
  2830
        /// <param name="sender"></param>
StephaneLenclud@227
  2831
        /// <param name="e"></param>
StephaneLenclud@227
  2832
        private void buttonActionDelete_Click(object sender, EventArgs e)
StephaneLenclud@214
  2833
        {
StephaneLenclud@234
  2834
            Ear.Action action = CurrentAction();
StephaneLenclud@214
  2835
            if (action == null)
StephaneLenclud@214
  2836
            {
StephaneLenclud@214
  2837
                //Must select action node
StephaneLenclud@214
  2838
                return;
StephaneLenclud@214
  2839
            }
StephaneLenclud@214
  2840
StephaneLenclud@235
  2841
            Properties.Settings.Default.EarManager.RemoveAction(action);
StephaneLenclud@214
  2842
            Properties.Settings.Default.Save();
StephaneLenclud@260
  2843
            PopulateTreeViewEvents();
StephaneLenclud@214
  2844
        }
StephaneLenclud@217
  2845
StephaneLenclud@223
  2846
        /// <summary>
StephaneLenclud@223
  2847
        /// 
StephaneLenclud@223
  2848
        /// </summary>
StephaneLenclud@223
  2849
        /// <param name="sender"></param>
StephaneLenclud@223
  2850
        /// <param name="e"></param>
StephaneLenclud@227
  2851
        private void buttonActionTest_Click(object sender, EventArgs e)
StephaneLenclud@223
  2852
        {
StephaneLenclud@234
  2853
            Ear.Action a = CurrentAction();
StephaneLenclud@223
  2854
            if (a != null)
StephaneLenclud@223
  2855
            {
StephaneLenclud@231
  2856
                a.Test();
StephaneLenclud@223
  2857
            }
StephaneLenclud@223
  2858
            iTreeViewEvents.Focus();
StephaneLenclud@223
  2859
        }
StephaneLenclud@223
  2860
StephaneLenclud@223
  2861
        /// <summary>
StephaneLenclud@223
  2862
        /// 
StephaneLenclud@223
  2863
        /// </summary>
StephaneLenclud@223
  2864
        /// <param name="sender"></param>
StephaneLenclud@223
  2865
        /// <param name="e"></param>
StephaneLenclud@223
  2866
        private void buttonActionMoveUp_Click(object sender, EventArgs e)
StephaneLenclud@223
  2867
        {
StephaneLenclud@234
  2868
            Ear.Action a = CurrentAction();
StephaneLenclud@223
  2869
            if (a == null || 
StephaneLenclud@223
  2870
                //Action already at the top of the list
StephaneLenclud@223
  2871
                iTreeViewEvents.SelectedNode.Index == 0)
StephaneLenclud@223
  2872
            {
StephaneLenclud@223
  2873
                return;
StephaneLenclud@223
  2874
            }
StephaneLenclud@223
  2875
StephaneLenclud@223
  2876
            //Swap actions in event's action list
StephaneLenclud@265
  2877
            Ear.Object parent = CurrentEarParent();
StephaneLenclud@223
  2878
            int currentIndex = iTreeViewEvents.SelectedNode.Index;
StephaneLenclud@265
  2879
            Ear.Action movingUp = parent.Objects[currentIndex] as Ear.Action;
StephaneLenclud@265
  2880
            Ear.Action movingDown = parent.Objects[currentIndex-1] as Ear.Action;
StephaneLenclud@265
  2881
            parent.Objects[currentIndex] = movingDown;
StephaneLenclud@265
  2882
            parent.Objects[currentIndex-1] = movingUp;
StephaneLenclud@223
  2883
StephaneLenclud@223
  2884
            //Save and populate our tree again
StephaneLenclud@223
  2885
            Properties.Settings.Default.Save();
StephaneLenclud@266
  2886
            PopulateTreeViewEvents(a);
StephaneLenclud@223
  2887
        }
StephaneLenclud@223
  2888
StephaneLenclud@223
  2889
        /// <summary>
StephaneLenclud@223
  2890
        /// 
StephaneLenclud@223
  2891
        /// </summary>
StephaneLenclud@223
  2892
        /// <param name="sender"></param>
StephaneLenclud@223
  2893
        /// <param name="e"></param>
StephaneLenclud@223
  2894
        private void buttonActionMoveDown_Click(object sender, EventArgs e)
StephaneLenclud@223
  2895
        {
StephaneLenclud@234
  2896
            Ear.Action a = CurrentAction();
StephaneLenclud@223
  2897
            if (a == null ||
StephaneLenclud@223
  2898
                //Action already at the bottom of the list
StephaneLenclud@223
  2899
                iTreeViewEvents.SelectedNode.Index == iTreeViewEvents.SelectedNode.Parent.Nodes.Count - 1)
StephaneLenclud@223
  2900
            {
StephaneLenclud@223
  2901
                return;
StephaneLenclud@223
  2902
            }
StephaneLenclud@223
  2903
StephaneLenclud@223
  2904
            //Swap actions in event's action list
StephaneLenclud@265
  2905
            Ear.Object parent = CurrentEarParent();
StephaneLenclud@223
  2906
            int currentIndex = iTreeViewEvents.SelectedNode.Index;
StephaneLenclud@265
  2907
            Ear.Action movingDown = parent.Objects[currentIndex] as Ear.Action;
StephaneLenclud@265
  2908
            Ear.Action movingUp = parent.Objects[currentIndex + 1] as Ear.Action;
StephaneLenclud@265
  2909
            parent.Objects[currentIndex] = movingUp;
StephaneLenclud@265
  2910
            parent.Objects[currentIndex + 1] = movingDown;
StephaneLenclud@223
  2911
StephaneLenclud@223
  2912
            //Save and populate our tree again
StephaneLenclud@223
  2913
            Properties.Settings.Default.Save();
StephaneLenclud@266
  2914
            PopulateTreeViewEvents(a);
StephaneLenclud@217
  2915
        }
StephaneLenclud@227
  2916
StephaneLenclud@227
  2917
StephaneLenclud@227
  2918
        /// <summary>
StephaneLenclud@229
  2919
        /// 
StephaneLenclud@229
  2920
        /// </summary>
StephaneLenclud@229
  2921
        /// <param name="sender"></param>
StephaneLenclud@229
  2922
        /// <param name="e"></param>
StephaneLenclud@229
  2923
        private void buttonEventTest_Click(object sender, EventArgs e)
StephaneLenclud@229
  2924
        {
StephaneLenclud@234
  2925
            Ear.Event earEvent = CurrentEvent();
StephaneLenclud@229
  2926
            if (earEvent != null)
StephaneLenclud@229
  2927
            {
StephaneLenclud@231
  2928
                earEvent.Test();
StephaneLenclud@229
  2929
            }
StephaneLenclud@229
  2930
        }
StephaneLenclud@229
  2931
StephaneLenclud@229
  2932
        /// <summary>
StephaneLenclud@227
  2933
        /// Manages events and actions buttons according to selected item in event tree.
StephaneLenclud@227
  2934
        /// </summary>
StephaneLenclud@227
  2935
        /// <param name="sender"></param>
StephaneLenclud@227
  2936
        /// <param name="e"></param>
StephaneLenclud@227
  2937
        private void iTreeViewEvents_AfterSelect(object sender, TreeViewEventArgs e)
StephaneLenclud@227
  2938
        {
StephaneLenclud@231
  2939
            UpdateEventView();
StephaneLenclud@231
  2940
        }
StephaneLenclud@231
  2941
StephaneLenclud@231
  2942
        /// <summary>
StephaneLenclud@231
  2943
        /// 
StephaneLenclud@231
  2944
        /// </summary>
StephaneLenclud@231
  2945
        private void UpdateEventView()
StephaneLenclud@231
  2946
        {
StephaneLenclud@231
  2947
            //One can always add an event
StephaneLenclud@231
  2948
            buttonEventAdd.Enabled = true;
StephaneLenclud@231
  2949
StephaneLenclud@227
  2950
            //Enable buttons according to selected item
StephaneLenclud@229
  2951
            buttonActionAdd.Enabled =
StephaneLenclud@229
  2952
            buttonEventTest.Enabled =
StephaneLenclud@231
  2953
            buttonEventDelete.Enabled =
StephaneLenclud@231
  2954
            buttonEventEdit.Enabled =
StephaneLenclud@229
  2955
                CurrentEvent() != null;
StephaneLenclud@227
  2956
StephaneLenclud@234
  2957
            Ear.Action currentAction = CurrentAction();
StephaneLenclud@227
  2958
            //If an action is selected enable the following buttons
StephaneLenclud@227
  2959
            buttonActionTest.Enabled =
StephaneLenclud@227
  2960
            buttonActionDelete.Enabled =
StephaneLenclud@227
  2961
            buttonActionMoveUp.Enabled =
StephaneLenclud@227
  2962
            buttonActionMoveDown.Enabled =
StephaneLenclud@231
  2963
            buttonActionEdit.Enabled =
StephaneLenclud@227
  2964
                    currentAction != null;
StephaneLenclud@227
  2965
StephaneLenclud@227
  2966
            if (currentAction != null)
StephaneLenclud@227
  2967
            {
StephaneLenclud@227
  2968
                //If an action is selected enable move buttons if needed
StephaneLenclud@227
  2969
                buttonActionMoveUp.Enabled = iTreeViewEvents.SelectedNode.Index != 0;
StephaneLenclud@227
  2970
                buttonActionMoveDown.Enabled = iTreeViewEvents.SelectedNode.Index <
StephaneLenclud@227
  2971
                                               iTreeViewEvents.SelectedNode.Parent.Nodes.Count - 1;
StephaneLenclud@227
  2972
            }
StephaneLenclud@227
  2973
        }
StephaneLenclud@227
  2974
StephaneLenclud@250
  2975
        /// <summary>
StephaneLenclud@250
  2976
        /// 
StephaneLenclud@250
  2977
        /// </summary>
StephaneLenclud@250
  2978
        /// <param name="sender"></param>
StephaneLenclud@250
  2979
        /// <param name="e"></param>
StephaneLenclud@231
  2980
        private void buttonEventAdd_Click(object sender, EventArgs e)
StephaneLenclud@231
  2981
        {
StephaneLenclud@234
  2982
            FormEditObject<Ear.Event> ea = new FormEditObject<Ear.Event>();
StephaneLenclud@231
  2983
            ea.Text = "Add event";
StephaneLenclud@231
  2984
            DialogResult res = CodeProject.Dialog.DlgBox.ShowDialog(ea);
StephaneLenclud@231
  2985
            if (res == DialogResult.OK)
StephaneLenclud@231
  2986
            {
StephaneLenclud@235
  2987
                Properties.Settings.Default.EarManager.Events.Add(ea.Object);
StephaneLenclud@231
  2988
                Properties.Settings.Default.Save();
StephaneLenclud@266
  2989
                PopulateTreeViewEvents(ea.Object);
StephaneLenclud@231
  2990
            }
StephaneLenclud@231
  2991
        }
StephaneLenclud@231
  2992
StephaneLenclud@250
  2993
        /// <summary>
StephaneLenclud@250
  2994
        /// 
StephaneLenclud@250
  2995
        /// </summary>
StephaneLenclud@250
  2996
        /// <param name="sender"></param>
StephaneLenclud@250
  2997
        /// <param name="e"></param>
StephaneLenclud@231
  2998
        private void buttonEventDelete_Click(object sender, EventArgs e)
StephaneLenclud@231
  2999
        {
StephaneLenclud@234
  3000
            Ear.Event currentEvent = CurrentEvent();
StephaneLenclud@231
  3001
            if (currentEvent == null)
StephaneLenclud@231
  3002
            {
StephaneLenclud@231
  3003
                //Must select action node
StephaneLenclud@231
  3004
                return;
StephaneLenclud@231
  3005
            }
StephaneLenclud@231
  3006
StephaneLenclud@235
  3007
            Properties.Settings.Default.EarManager.Events.Remove(currentEvent);
StephaneLenclud@231
  3008
            Properties.Settings.Default.Save();
StephaneLenclud@260
  3009
            PopulateTreeViewEvents();
StephaneLenclud@231
  3010
        }
StephaneLenclud@231
  3011
StephaneLenclud@250
  3012
        /// <summary>
StephaneLenclud@250
  3013
        /// 
StephaneLenclud@250
  3014
        /// </summary>
StephaneLenclud@250
  3015
        /// <param name="sender"></param>
StephaneLenclud@250
  3016
        /// <param name="e"></param>
StephaneLenclud@231
  3017
        private void buttonEventEdit_Click(object sender, EventArgs e)
StephaneLenclud@231
  3018
        {
StephaneLenclud@234
  3019
            Ear.Event selectedEvent = CurrentEvent();
StephaneLenclud@231
  3020
            if (selectedEvent == null)
StephaneLenclud@231
  3021
            {
StephaneLenclud@231
  3022
                //We did not find a corresponding event
StephaneLenclud@231
  3023
                return;
StephaneLenclud@231
  3024
            }
StephaneLenclud@231
  3025
StephaneLenclud@234
  3026
            FormEditObject<Ear.Event> ea = new FormEditObject<Ear.Event>();
StephaneLenclud@231
  3027
            ea.Text = "Edit event";
StephaneLenclud@231
  3028
            ea.Object = selectedEvent;
StephaneLenclud@248
  3029
            int index = iTreeViewEvents.SelectedNode.Index;
StephaneLenclud@231
  3030
            DialogResult res = CodeProject.Dialog.DlgBox.ShowDialog(ea);
StephaneLenclud@231
  3031
            if (res == DialogResult.OK)
StephaneLenclud@248
  3032
            {                
StephaneLenclud@248
  3033
                //Make sure we keep the same actions as before
StephaneLenclud@265
  3034
                ea.Object.Objects = Properties.Settings.Default.EarManager.Events[index].Objects;
StephaneLenclud@248
  3035
                //Update our event
StephaneLenclud@248
  3036
                Properties.Settings.Default.EarManager.Events[index] = ea.Object;
StephaneLenclud@231
  3037
                //Save and rebuild our event tree view
StephaneLenclud@231
  3038
                Properties.Settings.Default.Save();
StephaneLenclud@266
  3039
                PopulateTreeViewEvents(ea.Object);
StephaneLenclud@231
  3040
            }
StephaneLenclud@231
  3041
        }
StephaneLenclud@231
  3042
StephaneLenclud@250
  3043
        /// <summary>
StephaneLenclud@250
  3044
        /// 
StephaneLenclud@250
  3045
        /// </summary>
StephaneLenclud@250
  3046
        /// <param name="sender"></param>
StephaneLenclud@250
  3047
        /// <param name="e"></param>
StephaneLenclud@231
  3048
        private void iTreeViewEvents_Leave(object sender, EventArgs e)
StephaneLenclud@231
  3049
        {
StephaneLenclud@231
  3050
            //Make sure our event tree never looses focus
StephaneLenclud@231
  3051
            ((TreeView) sender).Focus();
StephaneLenclud@231
  3052
        }
StephaneLenclud@233
  3053
StephaneLenclud@250
  3054
        /// <summary>
StephaneLenclud@256
  3055
        /// Called whenever we loose connection with our HarmonyHub.
StephaneLenclud@256
  3056
        /// </summary>
StephaneLenclud@256
  3057
        /// <param name="aRequestWasCancelled"></param>
St?phane@271
  3058
        private void HarmonyConnectionClosed(object aSender, bool aClosedByServer)
StephaneLenclud@256
  3059
        {
St?phane@271
  3060
            if (aClosedByServer)
St?phane@271
  3061
            {
St?phane@271
  3062
                //Try reconnect then
StephaneLenclud@256
  3063
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
St?phane@271
  3064
                BeginInvoke(new MethodInvoker(delegate () { ResetHarmonyAsync(); }));
StephaneLenclud@256
  3065
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
St?phane@271
  3066
            }
StephaneLenclud@256
  3067
        }
StephaneLenclud@256
  3068
StephaneLenclud@270
  3069
StephaneLenclud@270
  3070
StephaneLenclud@270
  3071
        int iHarmonyReconnectTries = 0;
StephaneLenclud@270
  3072
        const int KHarmonyMaxReconnectTries = 10;
StephaneLenclud@270
  3073
StephaneLenclud@256
  3074
        /// <summary>
StephaneLenclud@250
  3075
        /// 
StephaneLenclud@250
  3076
        /// </summary>
StephaneLenclud@250
  3077
        /// <returns></returns>
Stephane@252
  3078
        private async Task ConnectHarmonyAsync(bool aForceAuth=false)
StephaneLenclud@233
  3079
        {
StephaneLenclud@236
  3080
            if (Program.HarmonyClient != null)
StephaneLenclud@236
  3081
            {
StephaneLenclud@254
  3082
                await Program.HarmonyClient.CloseAsync();
StephaneLenclud@236
  3083
            }
StephaneLenclud@236
  3084
StephaneLenclud@270
  3085
            bool success = false;
StephaneLenclud@270
  3086
StephaneLenclud@236
  3087
            //Reset Harmony client & config
StephaneLenclud@236
  3088
            Program.HarmonyClient = null;
StephaneLenclud@236
  3089
            Program.HarmonyConfig = null;
StephaneLenclud@270
  3090
            iTreeViewHarmony.Nodes.Clear();
StephaneLenclud@236
  3091
StephaneLenclud@253
  3092
            Trace.WriteLine("Harmony: Connecting... ");
StephaneLenclud@256
  3093
            //First create our client and login
StephaneLenclud@259
  3094
            //Tip: Set keep-alive to false when testing reconnection process
StephaneLenclud@259
  3095
            Program.HarmonyClient = new HarmonyHub.Client(iTextBoxHarmonyHubAddress.Text, true);
St?phane@271
  3096
            Program.HarmonyClient.OnConnectionClosed += HarmonyConnectionClosed;
StephaneLenclud@266
  3097
StephaneLenclud@266
  3098
            string authToken = Properties.Settings.Default.LogitechAuthToken;
StephaneLenclud@266
  3099
            if (!string.IsNullOrEmpty(authToken) && !aForceAuth)
StephaneLenclud@233
  3100
            {
StephaneLenclud@266
  3101
                Trace.WriteLine("Harmony: Reusing token: {0}", authToken);
StephaneLenclud@270
  3102
                success = await Program.HarmonyClient.TryOpenAsync(authToken);
StephaneLenclud@233
  3103
            }
StephaneLenclud@256
  3104
StephaneLenclud@270
  3105
            if (!Program.HarmonyClient.IsReady || !success 
StephaneLenclud@270
  3106
                // Only first failure triggers new Harmony server AUTH
StephaneLenclud@270
  3107
                // That's to avoid calling upon Logitech servers too often
StephaneLenclud@270
  3108
                && iHarmonyReconnectTries == 0 )
StephaneLenclud@233
  3109
            {
StephaneLenclud@256
  3110
                //We failed to connect using our token
StephaneLenclud@256
  3111
                //Delete it then
StephaneLenclud@270
  3112
                Trace.WriteLine("Harmony: Reseting authentication token!");
StephaneLenclud@266
  3113
                Properties.Settings.Default.LogitechAuthToken = "";
StephaneLenclud@266
  3114
                Properties.Settings.Default.Save();
StephaneLenclud@256
  3115
StephaneLenclud@253
  3116
                Trace.WriteLine("Harmony: Authenticating with Logitech servers...");
St?phane@271
  3117
                success = await Program.HarmonyClient.TryOpenAsync();
StephaneLenclud@266
  3118
                //Persist our authentication token in our setting
StephaneLenclud@270
  3119
                if (success)
StephaneLenclud@270
  3120
                {
StephaneLenclud@270
  3121
                    Trace.WriteLine("Harmony: Saving authentication token.");
StephaneLenclud@270
  3122
                    Properties.Settings.Default.LogitechAuthToken = Program.HarmonyClient.Token;
StephaneLenclud@270
  3123
                    Properties.Settings.Default.Save();
StephaneLenclud@270
  3124
                }
StephaneLenclud@233
  3125
            }
StephaneLenclud@270
  3126
           
StephaneLenclud@270
  3127
            // I've seen this failing with "Policy lookup failed on server".
StephaneLenclud@270
  3128
            Program.HarmonyConfig = await Program.HarmonyClient.TryGetConfigAsync();
StephaneLenclud@270
  3129
            if (Program.HarmonyConfig == null)
StephaneLenclud@270
  3130
            {
StephaneLenclud@270
  3131
                success = false;
StephaneLenclud@270
  3132
            }
StephaneLenclud@270
  3133
            else
StephaneLenclud@270
  3134
            {
StephaneLenclud@270
  3135
                // So we now have our Harmony Configuration
StephaneLenclud@270
  3136
                PopulateTreeViewHarmony(Program.HarmonyConfig);
StephaneLenclud@270
  3137
                // Make sure harmony command actions are showing device name instead of device id
StephaneLenclud@270
  3138
                PopulateTreeViewEvents(CurrentEarObject());
StephaneLenclud@270
  3139
            }
StephaneLenclud@270
  3140
StephaneLenclud@270
  3141
            // TODO: Consider putting the retry logic one level higher in ResetHarmonyAsync
StephaneLenclud@270
  3142
            if (!success)
StephaneLenclud@270
  3143
            {
StephaneLenclud@270
  3144
                // See if we need to keep trying 
StephaneLenclud@270
  3145
                if (iHarmonyReconnectTries < KHarmonyMaxReconnectTries)
StephaneLenclud@270
  3146
                {
StephaneLenclud@270
  3147
                    iHarmonyReconnectTries++;
StephaneLenclud@270
  3148
                    Trace.WriteLine("Harmony: Failed to connect, try again: " + iHarmonyReconnectTries);
StephaneLenclud@270
  3149
                    await ConnectHarmonyAsync();
StephaneLenclud@270
  3150
                }
StephaneLenclud@270
  3151
                else
StephaneLenclud@270
  3152
                {
StephaneLenclud@270
  3153
                    Trace.WriteLine("Harmony: Failed to connect, giving up!");
StephaneLenclud@270
  3154
                    iHarmonyReconnectTries = 0;
StephaneLenclud@270
  3155
                    // TODO: Could use a data member as timer rather than a new instance.
StephaneLenclud@270
  3156
                    // Try that again in 5 minutes then.
StephaneLenclud@270
  3157
                    // Using Windows Form timer to make sure we run in the UI thread.
StephaneLenclud@270
  3158
                    System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
StephaneLenclud@270
  3159
                    timer.Tick += async delegate (object sender, EventArgs e)
StephaneLenclud@270
  3160
                    {
StephaneLenclud@270
  3161
                        // Stop our timer first as we won't need it anymore
StephaneLenclud@270
  3162
                        (sender as System.Windows.Forms.Timer).Stop();
StephaneLenclud@270
  3163
                        // Then try to connect again
StephaneLenclud@270
  3164
                        await ConnectHarmonyAsync();
StephaneLenclud@270
  3165
                    };
StephaneLenclud@270
  3166
                    timer.Interval = 300000;
StephaneLenclud@270
  3167
                    timer.Start();
StephaneLenclud@270
  3168
                }
StephaneLenclud@270
  3169
            }
StephaneLenclud@270
  3170
            else
StephaneLenclud@270
  3171
            {
StephaneLenclud@270
  3172
                // We are connected with a valid Harmony Configuration
StephaneLenclud@270
  3173
                // Reset our tries counter then    
StephaneLenclud@270
  3174
                iHarmonyReconnectTries = 0;
StephaneLenclud@270
  3175
            }
StephaneLenclud@233
  3176
        }
StephaneLenclud@233
  3177
StephaneLenclud@233
  3178
        /// <summary>
StephaneLenclud@233
  3179
        /// 
StephaneLenclud@233
  3180
        /// </summary>
StephaneLenclud@233
  3181
        /// <param name="aConfig"></param>
StephaneLenclud@236
  3182
        private void PopulateTreeViewHarmony(HarmonyHub.Config aConfig)
StephaneLenclud@233
  3183
        {
StephaneLenclud@233
  3184
            iTreeViewHarmony.Nodes.Clear();
StephaneLenclud@233
  3185
            //Add our devices
StephaneLenclud@236
  3186
            foreach (HarmonyHub.Device device in aConfig.Devices)
StephaneLenclud@233
  3187
            {
StephaneLenclud@233
  3188
                TreeNode deviceNode = iTreeViewHarmony.Nodes.Add(device.Id, $"{device.Label} ({device.DeviceTypeDisplayName}/{device.Model})");
StephaneLenclud@233
  3189
                deviceNode.Tag = device;
StephaneLenclud@233
  3190
StephaneLenclud@236
  3191
                foreach (HarmonyHub.ControlGroup cg in device.ControlGroups)
StephaneLenclud@233
  3192
                {
StephaneLenclud@233
  3193
                    TreeNode cgNode = deviceNode.Nodes.Add(cg.Name);
StephaneLenclud@233
  3194
                    cgNode.Tag = cg;
StephaneLenclud@233
  3195
StephaneLenclud@236
  3196
                    foreach (HarmonyHub.Function f in cg.Functions)
StephaneLenclud@233
  3197
                    {
StephaneLenclud@257
  3198
                        TreeNode fNode = cgNode.Nodes.Add(f.Label);
StephaneLenclud@233
  3199
                        fNode.Tag = f;
StephaneLenclud@233
  3200
                    }
StephaneLenclud@233
  3201
                }
StephaneLenclud@233
  3202
            }
StephaneLenclud@233
  3203
StephaneLenclud@233
  3204
            //treeViewConfig.ExpandAll();
StephaneLenclud@233
  3205
        }
StephaneLenclud@233
  3206
StephaneLenclud@233
  3207
        private async void iTreeViewHarmony_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
StephaneLenclud@233
  3208
        {
StephaneLenclud@233
  3209
            //Upon function node double click we execute it
StephaneLenclud@236
  3210
            var tag = e.Node.Tag as HarmonyHub.Function;
StephaneLenclud@236
  3211
            if (tag != null && e.Node.Parent.Parent.Tag is HarmonyHub.Device)
StephaneLenclud@233
  3212
            {
StephaneLenclud@236
  3213
                HarmonyHub.Function f = tag;
StephaneLenclud@236
  3214
                HarmonyHub.Device d = (HarmonyHub.Device)e.Node.Parent.Parent.Tag;
StephaneLenclud@233
  3215
StephaneLenclud@257
  3216
                Trace.WriteLine($"Harmony: Sending {f.Label} to {d.Label}...");
StephaneLenclud@257
  3217
StephaneLenclud@257
  3218
                await Program.HarmonyClient.TrySendKeyPressAsync(d.Id, f.Action.Command);
StephaneLenclud@233
  3219
            }
StephaneLenclud@233
  3220
        }
Stephane@252
  3221
sl@0
  3222
    }
sl@0
  3223
}