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