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