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