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