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