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