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