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