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