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