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