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