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