Server/MainForm.cs
author sl
Thu, 14 Aug 2014 09:11:27 +0200
changeset 22 cac466b1b6e6
parent 21 274a6b27c3f9
child 25 6f10207a89a8
permissions -rw-r--r--
Adding interface library.
     1 using System;
     2 using System.Collections.Generic;
     3 using System.ComponentModel;
     4 using System.Data;
     5 using System.Drawing;
     6 using System.Linq;
     7 using System.Text;
     8 using System.Threading.Tasks;
     9 using System.Windows.Forms;
    10 using System.IO;
    11 using CodeProject.Dialog;
    12 using System.Drawing.Imaging;
    13 using System.ServiceModel;
    14 using SharpDisplayInterface;
    15 
    16 
    17 namespace SharpDisplayManager
    18 {
    19     public partial class MainForm : Form
    20     {
    21         DateTime LastTickTime;
    22         Display iDisplay;
    23         System.Drawing.Bitmap iBmp;
    24         bool iCreateBitmap; //Workaround render to bitmap issues when minimized
    25         ServiceHost iServiceHost;
    26         /// <summary>
    27         /// Our collection of clients
    28         /// </summary>
    29         public Dictionary<string, IDisplayServiceCallback> iClients;
    30 
    31         public MainForm()
    32         {
    33             LastTickTime = DateTime.Now;
    34             iDisplay = new Display();
    35             iClients = new Dictionary<string, IDisplayServiceCallback>();
    36 
    37             InitializeComponent();
    38             UpdateStatus();
    39 
    40             //Load settings
    41             marqueeLabelTop.Font = Properties.Settings.Default.DisplayFont;
    42             marqueeLabelBottom.Font = Properties.Settings.Default.DisplayFont;
    43             checkBoxShowBorders.Checked = Properties.Settings.Default.DisplayShowBorders;
    44             checkBoxConnectOnStartup.Checked = Properties.Settings.Default.DisplayConnectOnStartup;
    45             checkBoxReverseScreen.Checked = Properties.Settings.Default.DisplayReverseScreen;
    46             //
    47             tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
    48             //We have a bug when drawing minimized and reusing our bitmap
    49             iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
    50             iCreateBitmap = false;
    51         }
    52 
    53         private void MainForm_Load(object sender, EventArgs e)
    54         {
    55             StartServer();
    56 
    57             if (Properties.Settings.Default.DisplayConnectOnStartup)
    58             {
    59                 iDisplay.Open();
    60                 UpdateStatus();
    61             }
    62         }
    63 
    64 
    65         private void buttonFont_Click(object sender, EventArgs e)
    66         {
    67             //fontDialog.ShowColor = true;
    68             //fontDialog.ShowApply = true;
    69             fontDialog.ShowEffects = true;
    70             fontDialog.Font = marqueeLabelTop.Font;
    71             //fontDialog.ShowHelp = true;
    72 
    73             //fontDlg.MaxSize = 40;
    74             //fontDlg.MinSize = 22;
    75 
    76             //fontDialog.Parent = this;
    77             //fontDialog.StartPosition = FormStartPosition.CenterParent;
    78 
    79             //DlgBox.ShowDialog(fontDialog);
    80 
    81             //if (fontDialog.ShowDialog(this) != DialogResult.Cancel)
    82             if (DlgBox.ShowDialog(fontDialog) != DialogResult.Cancel)
    83             {
    84 
    85                 //MsgBox.Show("MessageBox MsgBox", "MsgBox caption");
    86 
    87                 //MessageBox.Show("Ok");
    88                 marqueeLabelTop.Font = fontDialog.Font;
    89                 marqueeLabelBottom.Font = fontDialog.Font;
    90                 Properties.Settings.Default.DisplayFont = fontDialog.Font;
    91                 Properties.Settings.Default.Save();
    92                 //label1.Font = fontDlg.Font;
    93                 //textBox1.BackColor = fontDlg.Color;
    94                 //label1.ForeColor = fontDlg.Color;
    95             }
    96         }
    97 
    98         private void buttonCapture_Click(object sender, EventArgs e)
    99         {
   100             System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height);
   101             tableLayoutPanel.DrawToBitmap(bmp, tableLayoutPanel.ClientRectangle);
   102             //Bitmap bmpToSave = new Bitmap(bmp);
   103             bmp.Save("D:\\capture.png");
   104 
   105             marqueeLabelTop.Text = "Sweet";
   106 
   107             /*
   108             string outputFileName = "d:\\capture.png";
   109             using (MemoryStream memory = new MemoryStream())
   110             {
   111                 using (FileStream fs = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
   112                 {
   113                     bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
   114                     byte[] bytes = memory.ToArray();
   115                     fs.Write(bytes, 0, bytes.Length);
   116                 }
   117             }
   118              */
   119 
   120         }
   121 
   122         private void CheckForRequestResults()
   123         {
   124             if (iDisplay.IsRequestPending())
   125             {
   126                 switch (iDisplay.AttemptRequestCompletion())
   127                 {
   128                     case Display.TMiniDisplayRequest.EMiniDisplayRequestPowerSupplyStatus:
   129                         if (iDisplay.PowerSupplyStatus())
   130                         {
   131                             toolStripStatusLabelPower.Text = "ON";
   132                         }
   133                         else
   134                         {
   135                             toolStripStatusLabelPower.Text = "OFF";
   136                         }
   137                         //Issue next request then
   138                         iDisplay.RequestDeviceId();
   139                         break;
   140 
   141                     case Display.TMiniDisplayRequest.EMiniDisplayRequestDeviceId:
   142                         toolStripStatusLabelConnect.Text += " - " + iDisplay.DeviceId();
   143                         //Issue next request then
   144                         iDisplay.RequestFirmwareRevision();
   145                         break;
   146 
   147                     case Display.TMiniDisplayRequest.EMiniDisplayRequestFirmwareRevision:
   148                         toolStripStatusLabelConnect.Text += " v" + iDisplay.FirmwareRevision();
   149                         //No more request to issue
   150                         break;
   151                 }
   152             }
   153         }
   154 
   155 
   156         public delegate int CoordinateTranslationDelegate(System.Drawing.Bitmap aBmp, int aInt);
   157 
   158 
   159         public static int ScreenReversedX(System.Drawing.Bitmap aBmp, int aX)
   160         {
   161             return aBmp.Width - aX - 1;
   162         }
   163 
   164         public int ScreenReversedY(System.Drawing.Bitmap aBmp, int aY)
   165         {
   166             return iBmp.Height - aY - 1;
   167         }
   168 
   169         public int ScreenX(System.Drawing.Bitmap aBmp, int aX)
   170         {
   171             return aX;
   172         }
   173 
   174         public int ScreenY(System.Drawing.Bitmap aBmp, int aY)
   175         {
   176             return aY;
   177         }
   178 
   179 
   180         //This is our timer tick responsible to perform our render
   181         private void timer_Tick(object sender, EventArgs e)
   182         {
   183             //Update our animations
   184             DateTime NewTickTime = DateTime.Now;
   185 
   186             marqueeLabelTop.UpdateAnimation(LastTickTime, NewTickTime);
   187             marqueeLabelBottom.UpdateAnimation(LastTickTime, NewTickTime);
   188 
   189             //Update our display
   190             if (iDisplay.IsOpen())
   191             {
   192                 CheckForRequestResults();
   193 
   194                 //Draw to bitmap
   195                 if (iCreateBitmap)
   196                 {
   197                     iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
   198                 }
   199                 tableLayoutPanel.DrawToBitmap(iBmp, tableLayoutPanel.ClientRectangle);
   200                 //iBmp.Save("D:\\capture.png");
   201 
   202                 //Select proper coordinate translation functions
   203                 //We used delegate/function pointer to support reverse screen without doing an extra test on each pixels
   204                 CoordinateTranslationDelegate screenX;
   205                 CoordinateTranslationDelegate screenY;
   206 
   207                 if (Properties.Settings.Default.DisplayReverseScreen)
   208                 {
   209                     screenX = ScreenReversedX;
   210                     screenY = ScreenReversedY;
   211                 }
   212                 else
   213                 {
   214                     screenX = ScreenX;
   215                     screenY = ScreenY;
   216                 }
   217 
   218                 //Send it to our display
   219                 for (int i = 0; i < iBmp.Width; i++)
   220                 {
   221                     for (int j = 0; j < iBmp.Height; j++)
   222                     {
   223                         unchecked
   224                         {
   225                             uint color = (uint)iBmp.GetPixel(i, j).ToArgb();
   226                             //For some reason when the app is minimized in the task bar only the alpha of our color is set.
   227                             //Thus that strange test for rendering to work both when the app is in the task bar and when it isn't.
   228                             iDisplay.SetPixel(screenX(iBmp, i), screenY(iBmp, j), Convert.ToInt32(!(color != 0xFF000000)));
   229                         }
   230                     }
   231                 }
   232 
   233                 iDisplay.SwapBuffers();
   234 
   235             }
   236 
   237             //Compute instant FPS
   238             toolStripStatusLabelFps.Text = (1.0/NewTickTime.Subtract(LastTickTime).TotalSeconds).ToString("F0") + " FPS";
   239 
   240             LastTickTime = NewTickTime;
   241 
   242         }
   243 
   244         private void buttonOpen_Click(object sender, EventArgs e)
   245         {
   246             if (iDisplay.Open())
   247             {
   248                 UpdateStatus();
   249                 iDisplay.RequestPowerSupplyStatus();
   250             }
   251             else
   252             {
   253                 UpdateStatus();
   254                 toolStripStatusLabelConnect.Text = "Connection error";
   255             }
   256 
   257         }
   258 
   259         private void buttonClose_Click(object sender, EventArgs e)
   260         {
   261             iDisplay.Close();
   262             UpdateStatus();
   263         }
   264 
   265         private void buttonClear_Click(object sender, EventArgs e)
   266         {
   267             iDisplay.Clear();
   268             iDisplay.SwapBuffers();
   269         }
   270 
   271         private void buttonFill_Click(object sender, EventArgs e)
   272         {
   273             iDisplay.Fill();
   274             iDisplay.SwapBuffers();
   275         }
   276 
   277         private void trackBarBrightness_Scroll(object sender, EventArgs e)
   278         {
   279             Properties.Settings.Default.DisplayBrightness = trackBarBrightness.Value;
   280             Properties.Settings.Default.Save();
   281             iDisplay.SetBrightness(trackBarBrightness.Value);
   282 
   283         }
   284 
   285         private void UpdateStatus()
   286         {
   287             if (iDisplay.IsOpen())
   288             {
   289                 buttonFill.Enabled = true;
   290                 buttonClear.Enabled = true;
   291                 buttonOpen.Enabled = false;
   292                 buttonClose.Enabled = true;
   293                 trackBarBrightness.Enabled = true;
   294                 trackBarBrightness.Minimum = iDisplay.MinBrightness();
   295                 trackBarBrightness.Maximum = iDisplay.MaxBrightness();
   296                 trackBarBrightness.Value = Properties.Settings.Default.DisplayBrightness;
   297                 trackBarBrightness.LargeChange = Math.Max(1,(iDisplay.MaxBrightness() - iDisplay.MinBrightness())/5);
   298                 trackBarBrightness.SmallChange = 1;
   299                 iDisplay.SetBrightness(Properties.Settings.Default.DisplayBrightness);
   300 
   301                 toolStripStatusLabelConnect.Text = "Connected - " + iDisplay.Vendor() + " - " + iDisplay.Product();
   302                 //+ " - " + iDisplay.SerialNumber();
   303             }
   304             else
   305             {
   306                 buttonFill.Enabled = false;
   307                 buttonClear.Enabled = false;
   308                 buttonOpen.Enabled = true;
   309                 buttonClose.Enabled = false;
   310                 trackBarBrightness.Enabled = false;
   311                 toolStripStatusLabelConnect.Text = "Disconnected";
   312             }
   313         }
   314 
   315 
   316 
   317         private void checkBoxShowBorders_CheckedChanged(object sender, EventArgs e)
   318         {
   319             //Save our show borders setting
   320             tableLayoutPanel.CellBorderStyle = (checkBoxShowBorders.Checked ? TableLayoutPanelCellBorderStyle.Single : TableLayoutPanelCellBorderStyle.None);
   321             Properties.Settings.Default.DisplayShowBorders = checkBoxShowBorders.Checked;
   322             Properties.Settings.Default.Save();
   323         }
   324 
   325         private void checkBoxConnectOnStartup_CheckedChanged(object sender, EventArgs e)
   326         {
   327             //Save our connect on startup setting
   328             Properties.Settings.Default.DisplayConnectOnStartup = checkBoxConnectOnStartup.Checked;
   329             Properties.Settings.Default.Save();
   330         }
   331 
   332         private void checkBoxReverseScreen_CheckedChanged(object sender, EventArgs e)
   333         {
   334             //Save our reverse screen setting
   335             Properties.Settings.Default.DisplayReverseScreen = checkBoxReverseScreen.Checked;
   336             Properties.Settings.Default.Save();
   337         }
   338 
   339         private void MainForm_Resize(object sender, EventArgs e)
   340         {
   341             if (WindowState == FormWindowState.Minimized)
   342             {
   343                 // Do some stuff
   344                 //iBmp = new System.Drawing.Bitmap(tableLayoutPanel.Width, tableLayoutPanel.Height, PixelFormat.Format32bppArgb);
   345                 iCreateBitmap = true;
   346             }
   347         }
   348 
   349         private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
   350         {
   351             StopServer();
   352         }
   353 
   354         public void StartServer()
   355         {
   356             iServiceHost = new ServiceHost
   357                 (
   358                     typeof(DisplayServer),
   359                     new Uri[] { new Uri("net.tcp://localhost:8001/") }
   360                 );
   361 
   362             iServiceHost.AddServiceEndpoint(typeof(IDisplayService), new NetTcpBinding(), "DisplayService");
   363             iServiceHost.Open();
   364         }
   365 
   366         public void StopServer()
   367         {
   368             //Tell connected client first? Is that possible?
   369             BroadcastCloseEvent();
   370             iServiceHost.Close();
   371         }
   372 
   373         public void BroadcastCloseEvent()
   374         {
   375             var inactiveClients = new List<string>();
   376             foreach (var client in iClients)
   377             {
   378                 //if (client.Key != eventData.ClientName)
   379                 {
   380                     try
   381                     {
   382                         client.Value.OnServerClosing(/*eventData*/);
   383                     }
   384                     catch (Exception ex)
   385                     {
   386                         inactiveClients.Add(client.Key);
   387                     }
   388                 }
   389             }
   390 
   391             if (inactiveClients.Count > 0)
   392             {
   393                 foreach (var client in inactiveClients)
   394                 {
   395                     iClients.Remove(client);
   396                 }
   397             }
   398         }
   399 
   400 
   401 
   402     }
   403 }