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