GUI/MainForm.cs
author moel.mich
Wed, 25 Jul 2012 18:10:10 +0000
changeset 375 01d283b11596
parent 362 1dfe9dac1651
child 378 64d3ddf8d73b
permissions -rw-r--r--
Updated the version.
     1 /*
     2  
     3   This Source Code Form is subject to the terms of the Mozilla Public
     4   License, v. 2.0. If a copy of the MPL was not distributed with this
     5   file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  
     7   Copyright (C) 2009-2012 Michael Möller <mmoeller@openhardwaremonitor.org>
     8 	Copyright (C) 2010 Paul Werelds <paul@werelds.net>
     9 	Copyright (C) 2012 Prince Samuel <prince.samuel@gmail.com>
    10 
    11 */
    12 
    13 using System;
    14 using System.Collections.Generic;
    15 using System.Collections.ObjectModel;
    16 using System.ComponentModel;
    17 using System.Drawing;
    18 using System.IO;
    19 using System.Reflection;
    20 using System.Windows.Forms;
    21 using Aga.Controls.Tree;
    22 using Aga.Controls.Tree.NodeControls;
    23 using OpenHardwareMonitor.Hardware;
    24 using OpenHardwareMonitor.WMI;
    25 using OpenHardwareMonitor.Utilities;
    26 
    27 namespace OpenHardwareMonitor.GUI {
    28   public partial class MainForm : Form {
    29 
    30     private PersistentSettings settings;
    31     private UnitManager unitManager;
    32     private Computer computer;
    33     private Node root;
    34     private TreeModel treeModel;
    35     private IDictionary<ISensor, Color> sensorPlotColors = 
    36       new Dictionary<ISensor, Color>();
    37     private Color[] plotColorPalette;
    38     private SystemTray systemTray;    
    39     private StartupManager startupManager = new StartupManager();
    40     private UpdateVisitor updateVisitor = new UpdateVisitor();
    41     private SensorGadget gadget;
    42     private Form plotForm;
    43     private PlotPanel plotPanel;
    44 
    45     private UserOption showHiddenSensors;
    46     private UserOption showPlot;
    47     private UserOption showValue;
    48     private UserOption showMin;
    49     private UserOption showMax;
    50     private UserOption startMinimized;
    51     private UserOption minimizeToTray;
    52     private UserOption minimizeOnClose;
    53     private UserOption autoStart;
    54 
    55     private UserOption readMainboardSensors;
    56     private UserOption readCpuSensors;
    57     private UserOption readRamSensors;
    58     private UserOption readGpuSensors;
    59     private UserOption readFanControllersSensors;
    60     private UserOption readHddSensors;
    61 
    62     private UserOption showGadget;
    63     private UserRadioGroup plotLocation;
    64     private WmiProvider wmiProvider;
    65 
    66     private UserOption runWebServer;
    67     private HttpServer server;
    68 
    69     private bool selectionDragging = false;
    70 
    71     public MainForm() {      
    72       InitializeComponent();
    73 
    74       // check if the OpenHardwareMonitorLib assembly has the correct version
    75       if (Assembly.GetAssembly(typeof(Computer)).GetName().Version !=
    76         Assembly.GetExecutingAssembly().GetName().Version) {
    77         MessageBox.Show(
    78           "The version of the file OpenHardwareMonitorLib.dll is incompatible.",
    79           "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    80         Environment.Exit(0);
    81       }
    82 
    83       this.settings = new PersistentSettings();      
    84       this.settings.Load(Path.ChangeExtension(
    85         Application.ExecutablePath, ".config"));
    86 
    87       this.unitManager = new UnitManager(settings);
    88 
    89       // make sure the buffers used for double buffering are not disposed 
    90       // after each draw call
    91       BufferedGraphicsManager.Current.MaximumBuffer =
    92         Screen.PrimaryScreen.Bounds.Size;  
    93 
    94       // set the DockStyle here, to avoid conflicts with the MainMenu
    95       this.splitContainer.Dock = DockStyle.Fill;
    96             
    97       this.Font = SystemFonts.MessageBoxFont;
    98       treeView.Font = SystemFonts.MessageBoxFont;
    99 
   100       plotPanel = new PlotPanel(settings);
   101       plotPanel.Font = SystemFonts.MessageBoxFont;
   102       plotPanel.Dock = DockStyle.Fill;
   103       
   104       nodeCheckBox.IsVisibleValueNeeded += nodeCheckBox_IsVisibleValueNeeded;
   105       nodeTextBoxText.DrawText += nodeTextBoxText_DrawText;
   106       nodeTextBoxValue.DrawText += nodeTextBoxText_DrawText;
   107       nodeTextBoxMin.DrawText += nodeTextBoxText_DrawText;
   108       nodeTextBoxMax.DrawText += nodeTextBoxText_DrawText;
   109       nodeTextBoxText.EditorShowing += nodeTextBoxText_EditorShowing;
   110 
   111       foreach (TreeColumn column in treeView.Columns) 
   112         column.Width = Math.Max(20, Math.Min(400,
   113           settings.GetValue("treeView.Columns." + column.Header + ".Width",
   114           column.Width)));
   115 
   116       treeModel = new TreeModel();
   117       root = new Node(System.Environment.MachineName);
   118       root.Image = Utilities.EmbeddedResources.GetImage("computer.png");
   119       
   120       treeModel.Nodes.Add(root);
   121       treeView.Model = treeModel;
   122 
   123       this.computer = new Computer(settings);
   124 
   125       systemTray = new SystemTray(computer, settings, unitManager);
   126       systemTray.HideShowCommand += hideShowClick;
   127       systemTray.ExitCommand += exitClick;
   128 
   129       int p = (int)Environment.OSVersion.Platform;
   130       if ((p == 4) || (p == 128)) { // Unix
   131         treeView.RowHeight = Math.Max(treeView.RowHeight, 18); 
   132         splitContainer.BorderStyle = BorderStyle.None;
   133         splitContainer.Border3DStyle = Border3DStyle.Adjust;
   134         splitContainer.SplitterWidth = 4;
   135         treeView.BorderStyle = BorderStyle.Fixed3D;
   136         plotPanel.BorderStyle = BorderStyle.Fixed3D;
   137         gadgetMenuItem.Visible = false;
   138         minCloseMenuItem.Visible = false;
   139         minTrayMenuItem.Visible = false;
   140         startMinMenuItem.Visible = false;
   141       } else { // Windows
   142         treeView.RowHeight = Math.Max(treeView.Font.Height + 1, 18); 
   143 
   144         gadget = new SensorGadget(computer, settings, unitManager);
   145         gadget.HideShowCommand += hideShowClick;
   146 
   147         wmiProvider = new WmiProvider(computer);
   148       }
   149 
   150       plotColorPalette = new Color[13];
   151       plotColorPalette[0] = Color.Blue;
   152       plotColorPalette[1] = Color.OrangeRed;
   153       plotColorPalette[2] = Color.Green;
   154       plotColorPalette[3] = Color.LightSeaGreen;
   155       plotColorPalette[4] = Color.Goldenrod;
   156       plotColorPalette[5] = Color.DarkViolet;
   157       plotColorPalette[6] = Color.YellowGreen;
   158       plotColorPalette[7] = Color.SaddleBrown;
   159       plotColorPalette[8] = Color.RoyalBlue;
   160       plotColorPalette[9] = Color.DeepPink;
   161       plotColorPalette[10] = Color.MediumSeaGreen;
   162       plotColorPalette[11] = Color.Olive;
   163       plotColorPalette[12] = Color.Firebrick;
   164       
   165       computer.HardwareAdded += new HardwareEventHandler(HardwareAdded);
   166       computer.HardwareRemoved += new HardwareEventHandler(HardwareRemoved);        
   167 
   168       computer.Open();
   169 
   170       timer.Enabled = true;
   171 
   172       showHiddenSensors = new UserOption("hiddenMenuItem", false,
   173         hiddenMenuItem, settings);
   174       showHiddenSensors.Changed += delegate(object sender, EventArgs e) {
   175         treeModel.ForceVisible = showHiddenSensors.Value;
   176       };
   177 
   178       showValue = new UserOption("valueMenuItem", true, valueMenuItem,
   179         settings);
   180       showValue.Changed += delegate(object sender, EventArgs e) {
   181         treeView.Columns[1].IsVisible = showValue.Value;
   182       };
   183 
   184       showMin = new UserOption("minMenuItem", false, minMenuItem, settings);
   185       showMin.Changed += delegate(object sender, EventArgs e) {
   186         treeView.Columns[2].IsVisible = showMin.Value;
   187       };
   188 
   189       showMax = new UserOption("maxMenuItem", true, maxMenuItem, settings);
   190       showMax.Changed += delegate(object sender, EventArgs e) {
   191         treeView.Columns[3].IsVisible = showMax.Value;
   192       };
   193 
   194       startMinimized = new UserOption("startMinMenuItem", false,
   195         startMinMenuItem, settings);
   196 
   197       minimizeToTray = new UserOption("minTrayMenuItem", true,
   198         minTrayMenuItem, settings);
   199       minimizeToTray.Changed += delegate(object sender, EventArgs e) {
   200         systemTray.IsMainIconEnabled = minimizeToTray.Value;
   201       };
   202 
   203       minimizeOnClose = new UserOption("minCloseMenuItem", false,
   204         minCloseMenuItem, settings);
   205 
   206       autoStart = new UserOption(null, startupManager.Startup,
   207         startupMenuItem, settings);
   208       autoStart.Changed += delegate(object sender, EventArgs e) {
   209         try {
   210           startupManager.Startup = autoStart.Value;
   211         } catch (InvalidOperationException) {
   212           MessageBox.Show("Updating the auto-startup option failed.", "Error", 
   213             MessageBoxButtons.OK, MessageBoxIcon.Error);
   214           autoStart.Value = startupManager.Startup;
   215         }
   216       };
   217 
   218       readMainboardSensors = new UserOption("mainboardMenuItem", true, 
   219         mainboardMenuItem, settings);
   220       readMainboardSensors.Changed += delegate(object sender, EventArgs e) {
   221         computer.MainboardEnabled = readMainboardSensors.Value;
   222       };
   223 
   224       readCpuSensors = new UserOption("cpuMenuItem", true,
   225         cpuMenuItem, settings);
   226       readCpuSensors.Changed += delegate(object sender, EventArgs e) {
   227         computer.CPUEnabled = readCpuSensors.Value;
   228       };
   229 
   230       readRamSensors = new UserOption("ramMenuItem", true,
   231         ramMenuItem, settings);
   232       readRamSensors.Changed += delegate(object sender, EventArgs e) {
   233         computer.RAMEnabled = readRamSensors.Value;
   234       };
   235 
   236       readGpuSensors = new UserOption("gpuMenuItem", true,
   237         gpuMenuItem, settings);
   238       readGpuSensors.Changed += delegate(object sender, EventArgs e) {
   239         computer.GPUEnabled = readGpuSensors.Value;
   240       };
   241 
   242       readFanControllersSensors = new UserOption("fanControllerMenuItem", true,
   243         fanControllerMenuItem, settings);
   244       readFanControllersSensors.Changed += delegate(object sender, EventArgs e) {
   245         computer.FanControllerEnabled = readFanControllersSensors.Value;
   246       };
   247 
   248       readHddSensors = new UserOption("hddMenuItem", true, hddMenuItem,
   249         settings);
   250       readHddSensors.Changed += delegate(object sender, EventArgs e) {
   251         computer.HDDEnabled = readHddSensors.Value;
   252       };
   253 
   254       showGadget = new UserOption("gadgetMenuItem", false, gadgetMenuItem,
   255         settings);
   256       showGadget.Changed += delegate(object sender, EventArgs e) {
   257         if (gadget != null) 
   258           gadget.Visible = showGadget.Value;
   259       };
   260 
   261       celsiusMenuItem.Checked = 
   262         unitManager.TemperatureUnit == TemperatureUnit.Celsius;
   263       fahrenheitMenuItem.Checked = !celsiusMenuItem.Checked;
   264 
   265       server = new HttpServer(root, this.settings.GetValue("listenerPort", 8085));
   266       runWebServer = new UserOption("runWebServerMenuItem", false,
   267         runWebServerMenuItem, settings);
   268       runWebServer.Changed += delegate(object sender, EventArgs e) {
   269         if (runWebServer.Value)
   270           runWebServer.Value = server.startHTTPListener();
   271         else
   272           server.stopHTTPListener();
   273       };
   274 
   275       InitializePlotForm();
   276 
   277       startupMenuItem.Visible = startupManager.IsAvailable;
   278       
   279       if (startMinMenuItem.Checked) {
   280         if (!minTrayMenuItem.Checked) {
   281           WindowState = FormWindowState.Minimized;
   282           Show();
   283         }
   284       } else {
   285         Show();
   286       }
   287 
   288       // Create a handle, otherwise calling Close() does not fire FormClosed     
   289       IntPtr handle = Handle;
   290 
   291       // Make sure the settings are saved when the user logs off
   292       Microsoft.Win32.SystemEvents.SessionEnded += delegate {
   293         SaveConfiguration();
   294         if (runWebServer.Value) 
   295             server.Quit();
   296 
   297       };
   298     }
   299 
   300     private void InitializePlotForm() {
   301       plotForm = new Form();
   302       plotForm.FormBorderStyle = FormBorderStyle.SizableToolWindow;
   303       plotForm.ShowInTaskbar = false;
   304       plotForm.StartPosition = FormStartPosition.Manual;
   305       this.AddOwnedForm(plotForm);
   306       plotForm.Bounds = new Rectangle {
   307         X = settings.GetValue("plotForm.Location.X", -100000),
   308         Y = settings.GetValue("plotForm.Location.Y", 100),
   309         Width = settings.GetValue("plotForm.Width", 600),
   310         Height = settings.GetValue("plotForm.Height", 400)
   311       };
   312 
   313       showPlot = new UserOption("plotMenuItem", false, plotMenuItem, settings);
   314       plotLocation = new UserRadioGroup("plotLocation", 0,
   315         new[] { plotWindowMenuItem, plotBottomMenuItem, plotRightMenuItem },
   316         settings);
   317 
   318       showPlot.Changed += delegate(object sender, EventArgs e) {
   319         if (plotLocation.Value == 0) {
   320           if (showPlot.Value && this.Visible)
   321             plotForm.Show();
   322           else
   323             plotForm.Hide();
   324         } else {
   325           splitContainer.Panel2Collapsed = !showPlot.Value;
   326         }
   327         treeView.Invalidate();
   328       };
   329       plotLocation.Changed += delegate(object sender, EventArgs e) {
   330         switch (plotLocation.Value) {
   331           case 0:
   332             splitContainer.Panel2.Controls.Clear();
   333             splitContainer.Panel2Collapsed = true;
   334             plotForm.Controls.Add(plotPanel);
   335             if (showPlot.Value && this.Visible)
   336               plotForm.Show();
   337             break;
   338           case 1:
   339             plotForm.Controls.Clear();
   340             plotForm.Hide();
   341             splitContainer.Orientation = Orientation.Horizontal;
   342             splitContainer.Panel2.Controls.Add(plotPanel);
   343             splitContainer.Panel2Collapsed = !showPlot.Value;
   344             break;
   345           case 2:
   346             plotForm.Controls.Clear();
   347             plotForm.Hide();
   348             splitContainer.Orientation = Orientation.Vertical;
   349             splitContainer.Panel2.Controls.Add(plotPanel);
   350             splitContainer.Panel2Collapsed = !showPlot.Value;
   351             break;
   352         }
   353       };
   354 
   355       plotForm.FormClosing += delegate(object sender, FormClosingEventArgs e) {
   356         if (e.CloseReason == CloseReason.UserClosing) {
   357           // just switch off the plotting when the user closes the form
   358           if (plotLocation.Value == 0) {
   359             showPlot.Value = false;
   360           }
   361           e.Cancel = true;
   362         }
   363       };
   364 
   365       EventHandler moveOrResizePlotForm = delegate(object sender, EventArgs e) {
   366         if (plotForm.WindowState != FormWindowState.Minimized) {
   367           settings.SetValue("plotForm.Location.X", plotForm.Bounds.X);
   368           settings.SetValue("plotForm.Location.Y", plotForm.Bounds.Y);
   369           settings.SetValue("plotForm.Width", plotForm.Bounds.Width);
   370           settings.SetValue("plotForm.Height", plotForm.Bounds.Height);
   371         }
   372       };
   373       plotForm.Move += moveOrResizePlotForm;
   374       plotForm.Resize += moveOrResizePlotForm;
   375 
   376       plotForm.VisibleChanged += delegate(object sender, EventArgs e) {
   377         Rectangle bounds = new Rectangle(plotForm.Location, plotForm.Size);
   378         Screen screen = Screen.FromRectangle(bounds);
   379         Rectangle intersection =
   380           Rectangle.Intersect(screen.WorkingArea, bounds);
   381         if (intersection.Width < Math.Min(16, bounds.Width) ||
   382             intersection.Height < Math.Min(16, bounds.Height)) {
   383           plotForm.Location = new Point(
   384             screen.WorkingArea.Width / 2 - bounds.Width / 2,
   385             screen.WorkingArea.Height / 2 - bounds.Height / 2);
   386         }
   387       };
   388 
   389       this.VisibleChanged += delegate(object sender, EventArgs e) {
   390         if (this.Visible && showPlot.Value && plotLocation.Value == 0)
   391           plotForm.Show();
   392         else
   393           plotForm.Hide();
   394       };
   395     }
   396 
   397     private void InsertSorted(Collection<Node> nodes, HardwareNode node) {
   398       int i = 0;
   399       while (i < nodes.Count && nodes[i] is HardwareNode &&
   400         ((HardwareNode)nodes[i]).Hardware.HardwareType < 
   401           node.Hardware.HardwareType)
   402         i++;
   403       nodes.Insert(i, node);
   404     }
   405     
   406     private void SubHardwareAdded(IHardware hardware, Node node) {
   407       HardwareNode hardwareNode = 
   408         new HardwareNode(hardware, settings, unitManager);
   409       hardwareNode.PlotSelectionChanged += PlotSelectionChanged;
   410 
   411       InsertSorted(node.Nodes, hardwareNode);
   412 
   413       foreach (IHardware subHardware in hardware.SubHardware)
   414         SubHardwareAdded(subHardware, hardwareNode);  
   415     }
   416 
   417     private void HardwareAdded(IHardware hardware) {      
   418       SubHardwareAdded(hardware, root);
   419       PlotSelectionChanged(this, null);
   420     }
   421 
   422     private void HardwareRemoved(IHardware hardware) {
   423       List<HardwareNode> nodesToRemove = new List<HardwareNode>();
   424       foreach (Node node in root.Nodes) {
   425         HardwareNode hardwareNode = node as HardwareNode;
   426         if (hardwareNode != null && hardwareNode.Hardware == hardware)
   427           nodesToRemove.Add(hardwareNode);
   428       }
   429       foreach (HardwareNode hardwareNode in nodesToRemove) {
   430         root.Nodes.Remove(hardwareNode);
   431         hardwareNode.PlotSelectionChanged -= PlotSelectionChanged;
   432       }
   433       PlotSelectionChanged(this, null);
   434     }
   435 
   436     private void nodeTextBoxText_DrawText(object sender, DrawEventArgs e) {       
   437       Node node = e.Node.Tag as Node;
   438       if (node != null) {
   439         Color color;
   440         if (node.IsVisible) {
   441           SensorNode sensorNode = node as SensorNode;
   442           if (plotMenuItem.Checked && sensorNode != null &&
   443             sensorPlotColors.TryGetValue(sensorNode.Sensor, out color))
   444             e.TextColor = color;
   445         } else {
   446           e.TextColor = Color.DarkGray;
   447         }
   448       }
   449     }
   450 
   451     private void PlotSelectionChanged(object sender, EventArgs e) {
   452       List<ISensor> selected = new List<ISensor>();
   453       IDictionary<ISensor, Color> colors = new Dictionary<ISensor, Color>();
   454       int colorIndex = 0;
   455       foreach (TreeNodeAdv node in treeView.AllNodes) {
   456         SensorNode sensorNode = node.Tag as SensorNode;
   457         if (sensorNode != null &&
   458           sensorNode.Sensor.SensorType == SensorType.Temperature) {
   459           if (sensorNode.Plot) {
   460             colors.Add(sensorNode.Sensor,
   461               plotColorPalette[colorIndex % plotColorPalette.Length]);
   462             selected.Add(sensorNode.Sensor);
   463           }
   464           colorIndex++;
   465         }
   466       }
   467       sensorPlotColors = colors;
   468       plotPanel.SetSensors(selected, colors);
   469     }
   470 
   471     private void nodeTextBoxText_EditorShowing(object sender,
   472       CancelEventArgs e) 
   473     {
   474       e.Cancel = !(treeView.CurrentNode != null &&
   475         (treeView.CurrentNode.Tag is SensorNode || 
   476          treeView.CurrentNode.Tag is HardwareNode));
   477     }
   478 
   479     private void nodeCheckBox_IsVisibleValueNeeded(object sender, 
   480       NodeControlValueEventArgs e) {
   481       SensorNode node = e.Node.Tag as SensorNode;
   482       e.Value = (node != null) && 
   483         (node.Sensor.SensorType == SensorType.Temperature) && 
   484         plotMenuItem.Checked;
   485     }
   486 
   487     private void exitClick(object sender, EventArgs e) {
   488       Close();
   489     }
   490 
   491     private void timer_Tick(object sender, EventArgs e) {
   492       computer.Accept(updateVisitor);
   493       treeView.Invalidate();
   494       plotPanel.Invalidate();
   495       systemTray.Redraw();
   496       if (gadget != null)
   497         gadget.Redraw();
   498 
   499       if (wmiProvider != null)
   500         wmiProvider.Update();
   501     }
   502 
   503     private void SaveConfiguration() {
   504       foreach (TreeColumn column in treeView.Columns)
   505         settings.SetValue("treeView.Columns." + column.Header + ".Width",
   506           column.Width);
   507 
   508       this.settings.SetValue("listenerPort", server.ListenerPort);
   509 
   510       string fileName = Path.ChangeExtension(
   511           System.Windows.Forms.Application.ExecutablePath, ".config");
   512       try {
   513         settings.Save(fileName);
   514       } catch (UnauthorizedAccessException) {
   515         MessageBox.Show("Access to the path '" + fileName + "' is denied. " +
   516           "The current settings could not be saved.",
   517           "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   518       } catch (IOException) {
   519         MessageBox.Show("The path '" + fileName + "' is not writeable. " +
   520           "The current settings could not be saved.",
   521           "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   522       }
   523     }
   524 
   525     private void MainForm_Load(object sender, EventArgs e) {
   526       Rectangle newBounds = new Rectangle {
   527         X = settings.GetValue("mainForm.Location.X", Location.X),
   528         Y = settings.GetValue("mainForm.Location.Y", Location.Y),
   529         Width = settings.GetValue("mainForm.Width", 470),
   530         Height = settings.GetValue("mainForm.Height", 640)
   531       };
   532 
   533       Rectangle fullWorkingArea = new Rectangle(int.MaxValue, int.MaxValue,
   534         int.MinValue, int.MinValue);
   535 
   536       foreach (Screen screen in Screen.AllScreens)
   537         fullWorkingArea = Rectangle.Union(fullWorkingArea, screen.Bounds);
   538 
   539       Rectangle intersection = Rectangle.Intersect(fullWorkingArea, newBounds);
   540       if (intersection.Width < 20 || intersection.Height < 20 ||
   541         !settings.Contains("mainForm.Location.X")
   542       ) {
   543         newBounds.X = (Screen.PrimaryScreen.WorkingArea.Width / 2) -
   544                       (newBounds.Width/2);
   545 
   546         newBounds.Y = (Screen.PrimaryScreen.WorkingArea.Height / 2) -
   547                       (newBounds.Height / 2);
   548       }
   549 
   550       this.Bounds = newBounds;
   551     }
   552     
   553     private void MainForm_FormClosed(object sender, FormClosedEventArgs e) {
   554       Visible = false;      
   555       systemTray.IsMainIconEnabled = false;
   556       timer.Enabled = false;            
   557       computer.Close();
   558       SaveConfiguration();
   559       if (runWebServer.Value)
   560           server.Quit();
   561       systemTray.Dispose();
   562     }
   563 
   564     private void aboutMenuItem_Click(object sender, EventArgs e) {
   565       new AboutBox().ShowDialog();
   566     }
   567 
   568     private void treeView_Click(object sender, EventArgs e) {
   569 
   570       MouseEventArgs m = e as MouseEventArgs;
   571       if (m == null || m.Button != MouseButtons.Right)
   572         return;
   573 
   574       NodeControlInfo info = treeView.GetNodeControlInfoAt(
   575         new Point(m.X, m.Y)
   576       );
   577       treeView.SelectedNode = info.Node;
   578       if (info.Node != null) {
   579         SensorNode node = info.Node.Tag as SensorNode;
   580         if (node != null && node.Sensor != null) {
   581           treeContextMenu.MenuItems.Clear();
   582           if (node.Sensor.Parameters.Length > 0) {
   583             MenuItem item = new MenuItem("Parameters...");
   584             item.Click += delegate(object obj, EventArgs args) {
   585               ShowParameterForm(node.Sensor);
   586             };
   587             treeContextMenu.MenuItems.Add(item);
   588           }
   589           if (nodeTextBoxText.EditEnabled) {
   590             MenuItem item = new MenuItem("Rename");
   591             item.Click += delegate(object obj, EventArgs args) {
   592               nodeTextBoxText.BeginEdit();
   593             };
   594             treeContextMenu.MenuItems.Add(item);
   595           }
   596           if (node.IsVisible) {
   597             MenuItem item = new MenuItem("Hide");
   598             item.Click += delegate(object obj, EventArgs args) {
   599               node.IsVisible = false;
   600             };
   601             treeContextMenu.MenuItems.Add(item);
   602           } else {
   603             MenuItem item = new MenuItem("Unhide");
   604             item.Click += delegate(object obj, EventArgs args) {
   605               node.IsVisible = true;
   606             };
   607             treeContextMenu.MenuItems.Add(item);
   608           }
   609           treeContextMenu.MenuItems.Add(new MenuItem("-"));
   610           {
   611             MenuItem item = new MenuItem("Show in Tray");
   612             item.Checked = systemTray.Contains(node.Sensor);
   613             item.Click += delegate(object obj, EventArgs args) {
   614               if (item.Checked)
   615                 systemTray.Remove(node.Sensor);
   616               else
   617                 systemTray.Add(node.Sensor, true);
   618             };
   619             treeContextMenu.MenuItems.Add(item);
   620           }
   621           if (gadget != null) {
   622             MenuItem item = new MenuItem("Show in Gadget");
   623             item.Checked = gadget.Contains(node.Sensor);
   624             item.Click += delegate(object obj, EventArgs args) {
   625               if (item.Checked) {
   626                 gadget.Remove(node.Sensor);
   627               } else {
   628                 gadget.Add(node.Sensor);
   629               }
   630             };
   631             treeContextMenu.MenuItems.Add(item);
   632           }
   633           if (node.Sensor.Control != null) {
   634             treeContextMenu.MenuItems.Add(new MenuItem("-"));
   635             IControl control = node.Sensor.Control;
   636             MenuItem controlItem = new MenuItem("Control");
   637             MenuItem defaultItem = new MenuItem("Default");
   638             defaultItem.Checked = control.ControlMode == ControlMode.Default;
   639             controlItem.MenuItems.Add(defaultItem);
   640             defaultItem.Click += delegate(object obj, EventArgs args) {
   641               control.SetDefault();
   642             };
   643             MenuItem manualItem = new MenuItem("Manual");
   644             controlItem.MenuItems.Add(manualItem);
   645             manualItem.Checked = control.ControlMode == ControlMode.Software;
   646             for (int i = 0; i <= 100; i += 5) {
   647               if (i <= control.MaxSoftwareValue &&
   648                   i >= control.MinSoftwareValue) {
   649                 MenuItem item = new MenuItem(i + " %");
   650                 manualItem.MenuItems.Add(item);
   651                 item.Checked = control.ControlMode == ControlMode.Software &&
   652                   Math.Round(control.SoftwareValue) == i;
   653                 int softwareValue = i;
   654                 item.Click += delegate(object obj, EventArgs args) {
   655                   control.SetSoftware(softwareValue);
   656                 };
   657               }
   658             }
   659             treeContextMenu.MenuItems.Add(controlItem);
   660           }
   661 
   662           treeContextMenu.Show(treeView, new Point(m.X, m.Y));
   663         }
   664 
   665         HardwareNode hardwareNode = info.Node.Tag as HardwareNode;
   666         if (hardwareNode != null && hardwareNode.Hardware != null) {
   667           treeContextMenu.MenuItems.Clear();
   668 
   669           if (nodeTextBoxText.EditEnabled) {
   670             MenuItem item = new MenuItem("Rename");
   671             item.Click += delegate(object obj, EventArgs args) {
   672               nodeTextBoxText.BeginEdit();
   673             };
   674             treeContextMenu.MenuItems.Add(item);
   675           }
   676 
   677           treeContextMenu.Show(treeView, new Point(m.X, m.Y));
   678         }
   679       }
   680     }
   681 
   682     private void saveReportMenuItem_Click(object sender, EventArgs e) {
   683       string report = computer.GetReport();
   684       if (saveFileDialog.ShowDialog() == DialogResult.OK) {
   685         using (TextWriter w = new StreamWriter(saveFileDialog.FileName)) {
   686           w.Write(report);
   687         }
   688       }
   689     }
   690 
   691     private void SysTrayHideShow() {
   692       Visible = !Visible;
   693       if (Visible)
   694         Activate();    
   695     }
   696 
   697     protected override void WndProc(ref Message m) {
   698       const int WM_SYSCOMMAND = 0x112;
   699       const int SC_MINIMIZE = 0xF020;
   700       const int SC_CLOSE = 0xF060;
   701 
   702       if (minimizeToTray.Value && 
   703         m.Msg == WM_SYSCOMMAND && m.WParam.ToInt64() == SC_MINIMIZE) {
   704         SysTrayHideShow();
   705       } else if (minimizeOnClose.Value &&
   706         m.Msg == WM_SYSCOMMAND && m.WParam.ToInt64() == SC_CLOSE) {
   707         /*
   708          * Apparently the user wants to minimize rather than close
   709          * Now we still need to check if we're going to the tray or not
   710          * 
   711          * Note: the correct way to do this would be to send out SC_MINIMIZE,
   712          * but since the code here is so simple,
   713          * that would just be a waste of time.
   714          */
   715         if (minimizeToTray.Value)
   716           SysTrayHideShow();
   717         else
   718           WindowState = FormWindowState.Minimized;
   719       } else {      
   720         base.WndProc(ref m);
   721       }
   722     }
   723 
   724     private void hideShowClick(object sender, EventArgs e) {
   725       SysTrayHideShow();
   726     }
   727 
   728     private void ShowParameterForm(ISensor sensor) {
   729       ParameterForm form = new ParameterForm();
   730       form.Parameters = sensor.Parameters;
   731       form.captionLabel.Text = sensor.Name;
   732       form.ShowDialog();
   733     }
   734 
   735     private void treeView_NodeMouseDoubleClick(object sender, 
   736       TreeNodeAdvMouseEventArgs e) {
   737       SensorNode node = e.Node.Tag as SensorNode;
   738       if (node != null && node.Sensor != null && 
   739         node.Sensor.Parameters.Length > 0) {
   740         ShowParameterForm(node.Sensor);
   741       }
   742     }
   743 
   744     private void celsiusMenuItem_Click(object sender, EventArgs e) {
   745       celsiusMenuItem.Checked = true;
   746       fahrenheitMenuItem.Checked = false;
   747       unitManager.TemperatureUnit = TemperatureUnit.Celsius;
   748     }
   749 
   750     private void fahrenheitMenuItem_Click(object sender, EventArgs e) {
   751       celsiusMenuItem.Checked = false;
   752       fahrenheitMenuItem.Checked = true;
   753       unitManager.TemperatureUnit = TemperatureUnit.Fahrenheit;
   754     }
   755 
   756     private void sumbitReportMenuItem_Click(object sender, EventArgs e) 
   757     {
   758       ReportForm form = new ReportForm();
   759       form.Report = computer.GetReport();
   760       form.ShowDialog();      
   761     }
   762 
   763     private void resetMinMaxMenuItem_Click(object sender, EventArgs e) {
   764       computer.Accept(new SensorVisitor(delegate(ISensor sensor) {
   765         sensor.ResetMin();
   766         sensor.ResetMax();
   767       }));
   768     }
   769 
   770     private void MainForm_MoveOrResize(object sender, EventArgs e) {
   771       if (WindowState != FormWindowState.Minimized) {
   772         settings.SetValue("mainForm.Location.X", Bounds.X);
   773         settings.SetValue("mainForm.Location.Y", Bounds.Y);
   774         settings.SetValue("mainForm.Width", Bounds.Width);
   775         settings.SetValue("mainForm.Height", Bounds.Height);
   776       }
   777     }
   778 
   779     private void resetClick(object sender, EventArgs e) {
   780       // disable the fallback MainIcon during reset, otherwise icon visibility
   781       // might be lost 
   782       systemTray.IsMainIconEnabled = false;
   783       computer.Close();
   784       computer.Open();
   785       // restore the MainIcon setting
   786       systemTray.IsMainIconEnabled = minimizeToTray.Value;
   787     }
   788 
   789     private void treeView_MouseMove(object sender, MouseEventArgs e) {
   790       selectionDragging = selectionDragging &
   791         (e.Button & (MouseButtons.Left | MouseButtons.Right)) > 0; 
   792 
   793       if (selectionDragging)
   794         treeView.SelectedNode = treeView.GetNodeAt(e.Location);     
   795     }
   796 
   797     private void treeView_MouseDown(object sender, MouseEventArgs e) {
   798       selectionDragging = true;
   799     }
   800 
   801     private void treeView_MouseUp(object sender, MouseEventArgs e) {
   802       selectionDragging = false;
   803     }
   804 
   805     private void serverPortMenuItem_Click(object sender, EventArgs e) {
   806       new PortForm(this).ShowDialog();
   807     }
   808 
   809     public HttpServer Server {
   810       get { return server; }
   811     }
   812 
   813   }
   814 }