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