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