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