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