Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Clients.Hive.JobManager/3.3/Views/HiveResourceSelector.cs @ 9893

Last change on this file since 9893 was 9893, checked in by ascheibe, 11 years ago

#1042

  • applied mkommends progress view patch
  • adapted Hive views accordingly
  • made some minor improvements (more to come...)
File size: 13.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Drawing;
25using System.Linq;
26using System.Text;
27using System.Windows.Forms;
28using HeuristicLab.Clients.Hive.JobManager.ExtensionMethods;
29using HeuristicLab.Core;
30using HeuristicLab.Core.Views;
31using HeuristicLab.MainForm;
32using HeuristicLab.MainForm.WindowsForms;
33
34namespace HeuristicLab.Clients.Hive.JobManager.Views {
35  [View("Hive Resource Selector View")]
36  [Content(typeof(IItemList<Resource>), true)]
37  public partial class HiveResourceSelector : ItemView, IDisposable {
38    private const int slaveImageIndex = 0;
39    private const int slaveGroupImageIndex = 1;
40    private string currentSearchString;
41    private ISet<TreeNode> mainTreeNodes;
42    private ISet<TreeNode> filteredTreeNodes;
43    private ISet<TreeNode> nodeStore;
44    private Progress progress;
45    private ProgressView progressView;
46
47    private ISet<Resource> selectedResources;
48    public ISet<Resource> SelectedResources {
49      get { return selectedResources; }
50      set { selectedResources = value; }
51    }
52
53    public new IItemList<Resource> Content {
54      get { return (IItemList<Resource>)base.Content; }
55      set { base.Content = value; }
56    }
57
58    public HiveResourceSelector() {
59      InitializeComponent();
60      mainTreeNodes = new HashSet<TreeNode>();
61      filteredTreeNodes = new HashSet<TreeNode>();
62      nodeStore = new HashSet<TreeNode>();
63      selectedResources = new HashSet<Resource>();
64      imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.MonitorLarge);
65      imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.NetworkCenterLarge);
66      progress = new Progress();
67    }
68
69    protected override void DeregisterContentEvents() {
70      if (progressView != null) {
71        progressView.Dispose();
72        progressView = null;
73      }
74      base.DeregisterContentEvents();
75    }
76
77    protected override void RegisterContentEvents() {
78      base.RegisterContentEvents();
79      progressView = new ProgressView(this, progress);
80    }
81
82    public void StartProgressView() {
83      if (InvokeRequired) {
84        Invoke(new Action(StartProgressView));
85      } else {
86        progress.Status = "Downloading resources. Please be patient.";
87        progress.ProgressState = ProgressState.Started;
88      }
89    }
90
91    public void FinishProgressView() {
92      if (InvokeRequired) {
93        Invoke(new Action(FinishProgressView));
94      } else {
95        progress.Finish();
96      }
97    }
98
99    protected override void OnContentChanged() {
100      base.OnContentChanged();
101
102      if (Content != null) {
103        selectedResources = new HashSet<Resource>(Content.Where(x => selectedResources.Any(y => x.Id == y.Id)));
104        UpdateMainTree();
105        ExtractStatistics();
106      } else {
107        mainTreeNodes.Clear();
108        UpdateFilteredTree();
109      }
110    }
111
112    #region MainTree Methods
113    private void UpdateMainTree() {
114      mainTreeNodes.Clear();
115
116      foreach (Resource g in Content) {
117        if (g.GetType() == typeof(SlaveGroup)) {
118          //root node
119          if (g.ParentResourceId == null) {
120            TreeNode tn = new TreeNode();
121            tn.ImageIndex = slaveGroupImageIndex;
122            tn.SelectedImageIndex = tn.ImageIndex;
123
124            tn.Tag = g;
125            tn.Text = g.Name;
126            tn.Checked = selectedResources.Any(x => x.Id == g.Id);
127
128            BuildMainTree(tn);
129            mainTreeNodes.Add(tn);
130          }
131        }
132      }
133      UpdateFilteredTree();
134    }
135
136    private void BuildMainTree(TreeNode tn) {
137      foreach (Resource r in Content.Where(s => s.ParentResourceId != null && s.ParentResourceId == ((Resource)tn.Tag).Id)) {
138        TreeNode stn = new TreeNode(r.Name);
139        if (r is Slave) stn.ImageIndex = slaveImageIndex;
140        else if (r is SlaveGroup) stn.ImageIndex = slaveGroupImageIndex;
141        stn.SelectedImageIndex = stn.ImageIndex;
142        stn.Tag = r;
143        stn.Checked = selectedResources.Any(x => x.Id == r.Id);
144        tn.Nodes.Add(stn);
145        mainTreeNodes.Add(stn);
146
147        BuildMainTree(stn);
148      }
149    }
150    #endregion
151
152    #region FilteredTree Methods
153    private void UpdateFilteredTree() {
154      filteredTreeNodes.Clear();
155      foreach (TreeNode n in mainTreeNodes) {
156        n.BackColor = SystemColors.Window;
157        if (currentSearchString == null || ((Resource)n.Tag).Name.ToLower().Contains(currentSearchString)) {
158          n.BackColor = string.IsNullOrEmpty(currentSearchString) ? SystemColors.Window : Color.LightBlue;
159          filteredTreeNodes.Add(n);
160          TraverseParentNodes(n);
161        }
162      }
163      UpdateResourceTree();
164    }
165
166    private void TraverseParentNodes(TreeNode node) {
167      if (node != null) {
168        for (TreeNode parent = node.Parent; parent != null; parent = parent.Parent)
169          filteredTreeNodes.Add(parent);
170      }
171    }
172    #endregion
173
174    #region ResourceTree Methods
175    private void UpdateResourceTree() {
176      resourcesTreeView.Nodes.Clear();
177      nodeStore.Clear();
178
179      foreach (TreeNode node in filteredTreeNodes) {
180        var clone = nodeStore.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)node.Tag).Id);
181        if (clone == null) {
182          clone = (TreeNode)node.Clone();
183          nodeStore.Add(clone);
184          clone.Nodes.Clear();
185        }
186        foreach (TreeNode child in node.Nodes)
187          if (filteredTreeNodes.Any(x => ((Resource)x.Tag).Id == ((Resource)child.Tag).Id)) {
188            var childClone = nodeStore.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)child.Tag).Id);
189            if (childClone == null) {
190              childClone = (TreeNode)child.Clone();
191              nodeStore.Add(childClone);
192              childClone.Nodes.Clear();
193            }
194            clone.Nodes.Add(childClone);
195          }
196      }
197      resourcesTreeView.Nodes.AddRange(nodeStore.Where(x => ((Resource)x.Tag).ParentResourceId == null).ToArray());
198      if (string.IsNullOrEmpty(currentSearchString)) ExpandSlaveGroupNodes();
199      else resourcesTreeView.ExpandAll();
200    }
201    #endregion
202
203    #region Events
204    private void resourcesTreeView_AfterCheck(object sender, TreeViewEventArgs e) {
205      if (e.Action != TreeViewAction.Unknown) {
206        if (e.Node.Checked) {
207          IncludeChildNodes(mainTreeNodes.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)e.Node.Tag).Id));
208          IncludeParentNodes(mainTreeNodes.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)e.Node.Tag).Id));
209        } else {
210          ExcludeChildNodes(mainTreeNodes.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)e.Node.Tag).Id));
211          ExcludeParentNodes(mainTreeNodes.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)e.Node.Tag).Id));
212        }
213        ExtractStatistics();
214      }
215    }
216
217    private void resourcesTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
218      if (e.Action != TreeViewAction.Unknown) {
219        ExtractStatistics(e.Node);
220      }
221    }
222
223    private void searchTextBox_TextChanged(object sender, System.EventArgs e) {
224      currentSearchString = searchTextBox.Text.ToLower();
225      UpdateFilteredTree();
226    }
227    #endregion
228
229    #region Helpers
230    private void IncludeChildNodes(TreeNode node) {
231      if (node != null) {
232        node.Checked = true;
233        selectedResources.Add((Resource)node.Tag);
234        AdjustNodeCheckedState(node);
235        foreach (TreeNode n in node.Nodes) IncludeChildNodes(n);
236      }
237    }
238
239    private void IncludeParentNodes(TreeNode node) {
240      if (node != null && node.Parent != null) {
241        TreeNode parent = node.Parent;
242        if (parent.Nodes.OfType<TreeNode>().All(x => x.Checked)) {
243          parent.Checked = true;
244          selectedResources.Add((Resource)parent.Tag);
245          AdjustNodeCheckedState(parent);
246          IncludeParentNodes(parent);
247        }
248      }
249    }
250
251    private void ExcludeChildNodes(TreeNode node) {
252      if (node != null) {
253        node.Checked = false;
254        selectedResources.Remove((Resource)node.Tag);
255        AdjustNodeCheckedState(node);
256        foreach (TreeNode n in node.Nodes) ExcludeChildNodes(n);
257      }
258    }
259
260    private void ExcludeParentNodes(TreeNode node) {
261      if (node != null) {
262        node.Checked = false;
263        selectedResources.Remove((Resource)node.Tag);
264        AdjustNodeCheckedState(node);
265        ExcludeParentNodes(node.Parent);
266      }
267    }
268
269    private void AdjustNodeCheckedState(TreeNode node) {
270      var filterdNode = filteredTreeNodes.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)node.Tag).Id);
271      var storedNode = nodeStore.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)node.Tag).Id);
272      if (filterdNode != null) filterdNode.Checked = node.Checked;
273      if (storedNode != null) storedNode.Checked = node.Checked;
274    }
275
276    private void ExpandSlaveGroupNodes() {
277      foreach (TreeNode n in nodeStore.Where(x => x.Tag is SlaveGroup)) {
278        TreeNode[] children = new TreeNode[n.Nodes.Count];
279        n.Nodes.CopyTo(children, 0);
280        if (children.Any(x => x.Tag is SlaveGroup)) n.Expand();
281      }
282    }
283
284    private void ExtractStatistics(TreeNode treeNode = null) {
285      StringBuilder sb = new StringBuilder();
286      Resource resource = treeNode == null ? null : treeNode.Tag as Resource;
287      ISet<Resource> resources = treeNode == null ? selectedResources : new HashSet<Resource>(treeNode.DescendantNodes().Select(x => x.Tag as Resource)); ;
288      IEnumerable<SlaveGroup> slaveGroups = resources.OfType<SlaveGroup>();
289      IEnumerable<Slave> slaves = resources.OfType<Slave>();
290      int cpuSpeed = 0, cores = 0, freeCores = 0, memory = 0, freeMemory = 0;
291      string contextString = treeNode == null ? "Selected" : "Included";
292
293      if (resources.Any() || resource != null) {
294        foreach (Slave s in slaves) {
295          cpuSpeed += s.CpuSpeed.GetValueOrDefault();
296          cores += s.Cores.GetValueOrDefault();
297          freeCores += s.FreeCores.GetValueOrDefault();
298          memory += s.Memory.GetValueOrDefault();
299          freeMemory += s.FreeMemory.GetValueOrDefault();
300        }
301        if (resource != null) {
302          if (resource is SlaveGroup) sb.Append("Slave group: ");
303          else if (resource is Slave) {
304            sb.Append("Slave: ");
305            if (!resources.Any()) {
306              Slave s = resource as Slave;
307              cpuSpeed = s.CpuSpeed.GetValueOrDefault();
308              cores = s.Cores.GetValueOrDefault();
309              freeCores = s.FreeCores.GetValueOrDefault();
310              memory = s.Memory.GetValueOrDefault();
311              freeMemory = s.FreeMemory.GetValueOrDefault();
312            }
313          }
314          sb.AppendLine(string.Format("{0}", resource.Name));
315        }
316        if (resource == null || resource is SlaveGroup) {
317          if (resources.Any()) {
318            sb.AppendFormat("{0} slave groups ({1}): ", contextString, slaveGroups.Count());
319            foreach (SlaveGroup sg in slaveGroups) sb.AppendFormat("{0}; ", sg.Name);
320            sb.AppendLine();
321            sb.AppendFormat("{0} slaves ({1}): ", contextString, slaves.Count());
322            foreach (Slave s in slaves) sb.AppendFormat("{0}; ", s.Name);
323            sb.AppendLine();
324          } else {
325            sb.Append("The selection does not inlcude any further resources.");
326          }
327        }
328        sb.AppendLine();
329        sb.AppendLine(string.Format("CPU speed: {0} MHz", cpuSpeed));
330        if (resources.Any()) sb.AppendLine(string.Format("Avg. CPU speed: {0:0.00} MHz", (double)cpuSpeed / resources.Count()));
331        sb.AppendLine(string.Format("Cores: {0}", cores));
332        sb.AppendLine(string.Format("Free cores: {0}", freeCores));
333        if (resources.Any()) sb.AppendLine(string.Format("Avg. free cores: {0:0.00}", (double)freeCores / resources.Count()));
334        sb.AppendLine(string.Format("Memory: {0} MB", memory));
335        sb.AppendFormat("Free memory: {0} MB", freeMemory);
336        if (resources.Any()) sb.Append(string.Format("{0}Avg. free memory: {1:0.00} MB", Environment.NewLine, (double)freeMemory / resources.Count()));
337      } else {
338        sb.Append("No resources selected.");
339      }
340
341      descriptionTextBox.Text = sb.ToString();
342    }
343    #endregion
344  }
345}
Note: See TracBrowser for help on using the repository browser.