GUI/MainForm.cs
author paulwerelds
Sun, 17 Oct 2010 19:25:50 +0000
changeset 233 c5139c236200
parent 227 97757a798918
child 241 52007c404f32
permissions -rw-r--r--
Updated attribute maps for the 4 SSD controllers we figured out so far.
Also switched back to an array of DriveAttribute rather than a generic list.
     1 /*
     2   
     3   Version: MPL 1.1/GPL 2.0/LGPL 2.1
     4 
     5   The contents of this file are subject to the Mozilla Public License Version
     6   1.1 (the "License"); you may not use this file except in compliance with
     7   the License. You may obtain a copy of the License at
     8  
     9   http://www.mozilla.org/MPL/
    10 
    11   Software distributed under the License is distributed on an "AS IS" basis,
    12   WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
    13   for the specific language governing rights and limitations under the License.
    14 
    15   The Original Code is the Open Hardware Monitor code.
    16 
    17   The Initial Developer of the Original Code is 
    18   Michael Möller <m.moeller@gmx.ch>.
    19   Portions created by the Initial Developer are Copyright (C) 2009-2010
    20   the Initial Developer. All Rights Reserved.
    21 
    22   Contributor(s): Paul Werelds
    23 
    24   Alternatively, the contents of this file may be used under the terms of
    25   either the GNU General Public License Version 2 or later (the "GPL"), or
    26   the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
    27   in which case the provisions of the GPL or the LGPL are applicable instead
    28   of those above. If you wish to allow use of your version of this file only
    29   under the terms of either the GPL or the LGPL, and not to allow others to
    30   use your version of this file under the terms of the MPL, indicate your
    31   decision by deleting the provisions above and replace them with the notice
    32   and other provisions required by the GPL or the LGPL. If you do not delete
    33   the provisions above, a recipient may use your version of this file under
    34   the terms of any one of the MPL, the GPL or the LGPL.
    35  
    36 */
    37 
    38 using System;
    39 using System.Collections.Generic;
    40 using System.ComponentModel;
    41 using System.Drawing;
    42 using System.IO;
    43 using System.Windows.Forms;
    44 using Aga.Controls.Tree;
    45 using Aga.Controls.Tree.NodeControls;
    46 using OpenHardwareMonitor.Hardware;
    47 using OpenHardwareMonitor.WMI;
    48 
    49 namespace OpenHardwareMonitor.GUI {
    50   public partial class MainForm : Form {
    51 
    52     private PersistentSettings settings;
    53     private UnitManager unitManager;
    54     private Computer computer;
    55     private Node root;
    56     private TreeModel treeModel;
    57     private IDictionary<ISensor, Color> sensorPlotColors = 
    58       new Dictionary<ISensor, Color>();
    59     private Color[] plotColorPalette;
    60     private SystemTray systemTray;    
    61     private StartupManager startupManager = new StartupManager();
    62     private UpdateVisitor updateVisitor = new UpdateVisitor();
    63     private SensorGadget gadget;
    64 
    65     private UserOption showHiddenSensors;
    66     private UserOption showPlot;
    67     private UserOption showValue;
    68     private UserOption showMin;
    69     private UserOption showMax;
    70     private UserOption startMinimized;
    71     private UserOption minimizeToTray;
    72     private UserOption minimizeOnClose;
    73     private UserOption autoStart;
    74     private UserOption readHddSensors;
    75     private UserOption showGadget;
    76 
    77     private WmiProvider wmiProvider;
    78 
    79     public MainForm() {      
    80       InitializeComponent();
    81 
    82       this.settings = new PersistentSettings();      
    83       this.settings.Load(Path.ChangeExtension(
    84         Application.ExecutablePath, ".config"));
    85 
    86       this.unitManager = new UnitManager(settings);
    87 
    88       // set the DockStyle here, to avoid conflicts with the MainMenu
    89       this.splitContainer.Dock = DockStyle.Fill;
    90             
    91       this.Font = SystemFonts.MessageBoxFont;
    92       treeView.Font = SystemFonts.MessageBoxFont;
    93       plotPanel.Font = SystemFonts.MessageBoxFont;
    94       
    95       nodeCheckBox.IsVisibleValueNeeded += nodeCheckBox_IsVisibleValueNeeded;
    96       nodeCheckBox.CheckStateChanged += UpdatePlotSelection;
    97       nodeTextBoxText.DrawText += nodeTextBoxText_DrawText;
    98       nodeTextBoxValue.DrawText += nodeTextBoxText_DrawText;
    99       nodeTextBoxMin.DrawText += nodeTextBoxText_DrawText;
   100       nodeTextBoxMax.DrawText += nodeTextBoxText_DrawText;
   101       nodeTextBoxText.EditorShowing += nodeTextBoxText_EditorShowing;
   102 
   103       foreach (TreeColumn column in treeView.Columns) 
   104         column.Width = Math.Max(20, Math.Min(400,
   105           settings.GetValue("treeView.Columns." + column.Header + ".Width",
   106           column.Width)));
   107 
   108       treeModel = new TreeModel();
   109       root = new Node(System.Environment.MachineName);
   110       root.Image = Utilities.EmbeddedResources.GetImage("computer.png");
   111       
   112       treeModel.Nodes.Add(root);
   113       treeView.Model = treeModel;
   114 
   115       this.computer = new Computer(settings);
   116 
   117       systemTray = new SystemTray(computer, settings);
   118       systemTray.HideShowCommand += hideShowClick;
   119       systemTray.ExitCommand += exitClick;
   120 
   121       int p = (int)Environment.OSVersion.Platform;
   122       if ((p == 4) || (p == 128)) { // Unix
   123         splitContainer.BorderStyle = BorderStyle.None;
   124         splitContainer.Border3DStyle = Border3DStyle.Adjust;
   125         splitContainer.SplitterWidth = 4;
   126         treeView.BorderStyle = BorderStyle.Fixed3D;
   127         plotPanel.BorderStyle = BorderStyle.Fixed3D;
   128         gadgetMenuItem.Visible = false;
   129         minCloseMenuItem.Visible = false;
   130       } else { // Windows
   131         gadget = new SensorGadget(computer, settings, unitManager);
   132         wmiProvider = new WmiProvider(computer);
   133       }          
   134 
   135       computer.HardwareAdded += new HardwareEventHandler(HardwareAdded);
   136       computer.HardwareRemoved += new HardwareEventHandler(HardwareRemoved);        
   137 
   138       computer.Open();
   139 
   140       timer.Enabled = true;
   141 
   142       plotColorPalette = new Color[13];
   143       plotColorPalette[0] = Color.Blue;
   144       plotColorPalette[1] = Color.OrangeRed;
   145       plotColorPalette[2] = Color.Green;
   146       plotColorPalette[3] = Color.LightSeaGreen;
   147       plotColorPalette[4] = Color.Goldenrod;
   148       plotColorPalette[5] = Color.DarkViolet;
   149       plotColorPalette[6] = Color.YellowGreen;
   150       plotColorPalette[7] = Color.SaddleBrown;
   151       plotColorPalette[8] = Color.RoyalBlue;
   152       plotColorPalette[9] = Color.DeepPink;
   153       plotColorPalette[10] = Color.MediumSeaGreen;
   154       plotColorPalette[11] = Color.Olive;
   155       plotColorPalette[12] = Color.Firebrick;
   156 
   157       showHiddenSensors = new UserOption("hiddenMenuItem", false,
   158         hiddenMenuItem, settings);
   159       showHiddenSensors.Changed += delegate(object sender, EventArgs e) {
   160         treeModel.ForceVisible = showHiddenSensors.Value;
   161       };
   162 
   163       showPlot = new UserOption("plotMenuItem", false, plotMenuItem, settings);
   164       showPlot.Changed += delegate(object sender, EventArgs e) {
   165         splitContainer.Panel2Collapsed = !showPlot.Value;
   166         treeView.Invalidate();
   167       };
   168 
   169       showValue = new UserOption("valueMenuItem", true, valueMenuItem,
   170         settings);
   171       showValue.Changed += delegate(object sender, EventArgs e) {
   172         treeView.Columns[1].IsVisible = showValue.Value;
   173       };
   174 
   175       showMin = new UserOption("minMenuItem", false, minMenuItem, settings);
   176       showMin.Changed += delegate(object sender, EventArgs e) {
   177         treeView.Columns[2].IsVisible = showMin.Value;
   178       };
   179 
   180       showMax = new UserOption("maxMenuItem", true, maxMenuItem, settings);
   181       showMax.Changed += delegate(object sender, EventArgs e) {
   182         treeView.Columns[3].IsVisible = showMax.Value;
   183       };
   184 
   185       startMinimized = new UserOption("startMinMenuItem", false,
   186         startMinMenuItem, settings);
   187 
   188       minimizeToTray = new UserOption("minTrayMenuItem", true,
   189         minTrayMenuItem, settings);
   190       minimizeToTray.Changed += delegate(object sender, EventArgs e) {
   191         systemTray.IsMainIconEnabled = minimizeToTray.Value;
   192       };
   193 
   194       minimizeOnClose = new UserOption("minCloseMenuItem", false,
   195         minCloseMenuItem, settings);
   196 
   197       autoStart = new UserOption(null, startupManager.Startup,
   198         startupMenuItem, settings);
   199       autoStart.Changed += delegate(object sender, EventArgs e) {
   200         try {
   201           startupManager.Startup = autoStart.Value;
   202         } catch (InvalidOperationException) {
   203           MessageBox.Show("Updating the auto-startup option failed.", "Error", 
   204             MessageBoxButtons.OK, MessageBoxIcon.Error);
   205           autoStart.Value = startupManager.Startup;
   206         }
   207       };
   208 
   209       readHddSensors = new UserOption("hddMenuItem", true, hddMenuItem,
   210         settings);
   211       readHddSensors.Changed += delegate(object sender, EventArgs e) {
   212         computer.HDDEnabled = readHddSensors.Value;
   213         UpdatePlotSelection(null, null);
   214       };
   215 
   216       showGadget = new UserOption("gadgetMenuItem", false, gadgetMenuItem,
   217         settings);
   218       showGadget.Changed += delegate(object sender, EventArgs e) {
   219         if (gadget != null) 
   220           gadget.Visible = showGadget.Value;
   221       };
   222 
   223       celciusMenuItem.Checked = 
   224         unitManager.TemperatureUnit == TemperatureUnit.Celcius;
   225       fahrenheitMenuItem.Checked = !celciusMenuItem.Checked;
   226 
   227       startupMenuItem.Visible = startupManager.IsAvailable;
   228       
   229       if (startMinMenuItem.Checked) {
   230         if (!minTrayMenuItem.Checked) {
   231           WindowState = FormWindowState.Minimized;
   232           Show();
   233         }
   234       } else {
   235         Show();
   236       }
   237 
   238       // Create a handle, otherwise calling Close() does not fire FormClosed     
   239       IntPtr handle = Handle;
   240 
   241       // Make sure the settings are saved when the user logs off
   242       Microsoft.Win32.SystemEvents.SessionEnded += delegate {
   243         SaveConfiguration();
   244       };  
   245     }
   246     
   247     private void SubHardwareAdded(IHardware hardware, Node node) {
   248       Node hardwareNode = new HardwareNode(hardware, settings, unitManager);
   249       node.Nodes.Add(hardwareNode);
   250       foreach (IHardware subHardware in hardware.SubHardware)
   251         SubHardwareAdded(subHardware, hardwareNode);  
   252     }
   253 
   254     private void HardwareAdded(IHardware hardware) {
   255       Node hardwareNode = new HardwareNode(hardware, settings, unitManager);
   256       root.Nodes.Add(hardwareNode);
   257       foreach (IHardware subHardware in hardware.SubHardware)
   258         SubHardwareAdded(subHardware, hardwareNode);     
   259     }
   260 
   261     private void HardwareRemoved(IHardware hardware) {      
   262       List<Node> nodesToRemove = new List<Node>();
   263       foreach (Node node in root.Nodes) {
   264         HardwareNode hardwareNode = node as HardwareNode;
   265         if (hardwareNode != null && hardwareNode.Hardware == hardware)
   266           nodesToRemove.Add(node);
   267       }
   268       foreach (Node node in nodesToRemove)
   269         root.Nodes.Remove(node);
   270     }
   271 
   272     private void nodeTextBoxText_DrawText(object sender, DrawEventArgs e) {       
   273       Node node = e.Node.Tag as Node;
   274       if (node != null) {
   275         Color color;
   276         if (node.IsVisible) {
   277           SensorNode sensorNode = node as SensorNode;
   278           if (plotMenuItem.Checked && sensorNode != null &&
   279             sensorPlotColors.TryGetValue(sensorNode.Sensor, out color))
   280             e.TextColor = color;
   281         } else {
   282           e.TextColor = Color.DarkGray;
   283         }
   284       }
   285     }
   286 
   287     private void UpdatePlotSelection(object sender, 
   288       TreePathEventArgs e) 
   289     {
   290       List<ISensor> selected = new List<ISensor>();
   291       IDictionary<ISensor, Color> colors = new Dictionary<ISensor, Color>();
   292       int colorIndex = 0;
   293       foreach (TreeNodeAdv node in treeView.AllNodes) {
   294         SensorNode sensorNode = node.Tag as SensorNode;
   295         if (sensorNode != null && 
   296           sensorNode.Sensor.SensorType == SensorType.Temperature) {
   297           if (sensorNode.Plot) {
   298             colors.Add(sensorNode.Sensor,
   299               plotColorPalette[colorIndex % plotColorPalette.Length]);
   300             selected.Add(sensorNode.Sensor);
   301           }
   302           colorIndex++;
   303         }
   304       }
   305       sensorPlotColors = colors;
   306       plotPanel.SetSensors(selected, colors);
   307     }
   308 
   309     private void nodeTextBoxText_EditorShowing(object sender,
   310       CancelEventArgs e) 
   311     {
   312       e.Cancel = !(treeView.CurrentNode != null &&
   313         treeView.CurrentNode.Tag is SensorNode);
   314     }
   315 
   316     private void nodeCheckBox_IsVisibleValueNeeded(object sender, 
   317       NodeControlValueEventArgs e) {
   318       SensorNode node = e.Node.Tag as SensorNode;
   319       e.Value = (node != null) && 
   320         (node.Sensor.SensorType == SensorType.Temperature) && 
   321         plotMenuItem.Checked;
   322     }
   323 
   324     private void exitClick(object sender, EventArgs e) {
   325       Close();
   326     }
   327 
   328     private void timer_Tick(object sender, EventArgs e) {
   329       computer.Accept(updateVisitor);
   330       treeView.Invalidate();
   331       plotPanel.Invalidate();
   332       systemTray.Redraw();
   333       if (gadget != null)
   334         gadget.Redraw();
   335 
   336       if (wmiProvider != null)
   337         wmiProvider.Update();
   338     }
   339 
   340     private void SaveConfiguration() {
   341       if (WindowState != FormWindowState.Minimized) {
   342         settings.SetValue("mainForm.Location.X", Bounds.X);
   343         settings.SetValue("mainForm.Location.Y", Bounds.Y);
   344         settings.SetValue("mainForm.Width", Bounds.Width);
   345         settings.SetValue("mainForm.Height", Bounds.Height);
   346       }
   347 
   348       foreach (TreeColumn column in treeView.Columns)
   349         settings.SetValue("treeView.Columns." + column.Header + ".Width",
   350           column.Width);
   351 
   352       string fileName = Path.ChangeExtension(
   353           System.Windows.Forms.Application.ExecutablePath, ".config");
   354       try {
   355         settings.Save(fileName);
   356       } catch (UnauthorizedAccessException) {
   357         MessageBox.Show("Access to the path '" + fileName + "' is denied. " +
   358           "The current seetings could not be saved.", 
   359           "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   360       }
   361     }
   362 
   363     private void MainForm_Load(object sender, EventArgs e) {
   364       Rectangle newBounds = new Rectangle {
   365         X = settings.GetValue("mainForm.Location.X", Location.X),
   366         Y = settings.GetValue("mainForm.Location.Y", Location.Y),
   367         Width = settings.GetValue("mainForm.Width", 470),
   368         Height = settings.GetValue("mainForm.Height", 640)
   369       };
   370 
   371       Rectangle fullWorkingArea = new Rectangle(int.MaxValue, int.MaxValue,
   372         int.MinValue, int.MinValue);
   373 
   374       foreach (Screen screen in Screen.AllScreens)
   375         fullWorkingArea = Rectangle.Union(fullWorkingArea, screen.Bounds);
   376 
   377       Rectangle intersection = Rectangle.Intersect(fullWorkingArea, newBounds);
   378       if (intersection.Width < 20 || intersection.Height < 20 ||
   379         !settings.Contains("mainForm.Location.X")
   380       ) {
   381         newBounds.X = (Screen.PrimaryScreen.WorkingArea.Width / 2) -
   382                       (newBounds.Width/2);
   383 
   384         newBounds.Y = (Screen.PrimaryScreen.WorkingArea.Height / 2) -
   385                       (newBounds.Height / 2);
   386       }
   387 
   388       this.Bounds = newBounds;
   389     }
   390     
   391     private void MainForm_FormClosed(object sender, FormClosedEventArgs e) {
   392       Visible = false;
   393       SaveConfiguration();
   394 
   395       timer.Enabled = false;
   396       systemTray.Dispose();      
   397       computer.Close();
   398     }
   399 
   400     private void aboutMenuItem_Click(object sender, EventArgs e) {
   401       new AboutBox().ShowDialog();
   402     }
   403 
   404     private void treeView_Click(object sender, EventArgs e) {
   405       
   406       MouseEventArgs m = e as MouseEventArgs;
   407       if (m == null || m.Button != MouseButtons.Right)
   408         return;
   409 
   410       NodeControlInfo info = treeView.GetNodeControlInfoAt(
   411         new Point(m.X, m.Y)
   412       );
   413       treeView.SelectedNode = info.Node;
   414       if (info.Node != null) {
   415         SensorNode node = info.Node.Tag as SensorNode;
   416         if (node != null && node.Sensor != null) {
   417           sensorContextMenu.MenuItems.Clear();
   418           if (node.Sensor.Parameters.Length > 0) {
   419             MenuItem item = new MenuItem("Parameters...");
   420             item.Click += delegate(object obj, EventArgs args) {
   421               ShowParameterForm(node.Sensor);
   422             };
   423             sensorContextMenu.MenuItems.Add(item);
   424           }
   425           if (nodeTextBoxText.EditEnabled) {
   426             MenuItem item = new MenuItem("Rename");
   427             item.Click += delegate(object obj, EventArgs args) {
   428               nodeTextBoxText.BeginEdit();
   429             };
   430             sensorContextMenu.MenuItems.Add(item);
   431           }
   432           if (node.IsVisible) {
   433             MenuItem item = new MenuItem("Hide");
   434             item.Click += delegate(object obj, EventArgs args) {
   435               node.IsVisible = false;
   436             };
   437             sensorContextMenu.MenuItems.Add(item);
   438           } else {
   439             MenuItem item = new MenuItem("Unhide");
   440             item.Click += delegate(object obj, EventArgs args) {
   441               node.IsVisible = true;
   442             };
   443             sensorContextMenu.MenuItems.Add(item);
   444           }
   445           sensorContextMenu.MenuItems.Add(new MenuItem("-"));
   446           {
   447             MenuItem item = new MenuItem("Show in Tray");
   448             item.Checked = systemTray.Contains(node.Sensor);
   449             item.Click += delegate(object obj, EventArgs args) {
   450               if (item.Checked)
   451                 systemTray.Remove(node.Sensor);
   452               else
   453                 systemTray.Add(node.Sensor, true);
   454             };
   455             sensorContextMenu.MenuItems.Add(item);
   456           }
   457           if (gadget != null) {
   458             MenuItem item = new MenuItem("Show in Gadget");
   459             item.Checked = gadget.Contains(node.Sensor);
   460             item.Click += delegate(object obj, EventArgs args) {
   461               if (item.Checked) {
   462                 gadget.Remove(node.Sensor);
   463               } else {
   464                 gadget.Add(node.Sensor);
   465               }
   466             };
   467             sensorContextMenu.MenuItems.Add(item);
   468           }
   469 
   470           sensorContextMenu.Show(treeView, new Point(m.X, m.Y));
   471         }
   472       }
   473     }
   474 
   475     private void saveReportMenuItem_Click(object sender, EventArgs e) {
   476       string report = computer.GetReport();
   477       if (saveFileDialog.ShowDialog() == DialogResult.OK) {
   478         using (TextWriter w = new StreamWriter(saveFileDialog.FileName)) {
   479           w.Write(report);
   480         }
   481       }
   482     }
   483 
   484     private void SysTrayHideShow() {
   485       Visible = !Visible;
   486       if (Visible)
   487         Activate();    
   488     }
   489 
   490     protected override void WndProc(ref Message m) {
   491       const int WM_SYSCOMMAND = 0x112;
   492       const int SC_MINIMIZE = 0xF020;
   493       const int SC_CLOSE = 0xF060;
   494 
   495       if (minimizeToTray.Value && 
   496         m.Msg == WM_SYSCOMMAND && m.WParam.ToInt32() == SC_MINIMIZE) {
   497         SysTrayHideShow();
   498       } else if(minimizeOnClose.Value && 
   499         m.Msg == WM_SYSCOMMAND && m.WParam.ToInt32() == SC_CLOSE) {
   500         /*
   501          * Apparently the user wants to minimize rather than close
   502          * Now we still need to check if we're going to the tray or not
   503          * 
   504          * Note: the correct way to do this would be to send out SC_MINIMIZE,
   505          * but since the code here is so simple,
   506          * that would just be a waste of time.
   507          */
   508         if (minimizeToTray.Value)
   509           SysTrayHideShow();
   510         else
   511           WindowState = FormWindowState.Minimized;
   512       } else {      
   513         base.WndProc(ref m);
   514       }
   515     }
   516 
   517     private void hideShowClick(object sender, EventArgs e) {
   518       SysTrayHideShow();
   519     }
   520 
   521     private void ShowParameterForm(ISensor sensor) {
   522       ParameterForm form = new ParameterForm();
   523       form.Parameters = sensor.Parameters;
   524       form.captionLabel.Text = sensor.Name;
   525       form.ShowDialog();
   526     }
   527 
   528     private void treeView_NodeMouseDoubleClick(object sender, 
   529       TreeNodeAdvMouseEventArgs e) {
   530       SensorNode node = e.Node.Tag as SensorNode;
   531       if (node != null && node.Sensor != null && 
   532         node.Sensor.Parameters.Length > 0) {
   533         ShowParameterForm(node.Sensor);
   534       }
   535     }
   536 
   537     private void celciusMenuItem_Click(object sender, EventArgs e) {
   538       celciusMenuItem.Checked = true;
   539       fahrenheitMenuItem.Checked = false;
   540       unitManager.TemperatureUnit = TemperatureUnit.Celcius;
   541     }
   542 
   543     private void fahrenheitMenuItem_Click(object sender, EventArgs e) {
   544       celciusMenuItem.Checked = false;
   545       fahrenheitMenuItem.Checked = true;
   546       unitManager.TemperatureUnit = TemperatureUnit.Fahrenheit;
   547     }
   548 
   549     private void sumbitReportMenuItem_Click(object sender, EventArgs e) 
   550     {
   551       ReportForm form = new ReportForm();
   552       form.Report = computer.GetReport();
   553       form.ShowDialog();      
   554     }
   555 
   556     private void resetMinMaxMenuItem_Click(object sender, EventArgs e) {
   557       computer.Accept(new SensorVisitor(delegate(ISensor sensor) {
   558         sensor.ResetMin();
   559         sensor.ResetMax();
   560       }));
   561     }
   562   }
   563 }