Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7927 was 7927, checked in by jkarder, 12 years ago

#1711:

  • removed HiveResourceSelector property in HiveResourceSelectorDialog
  • added View and Content attributes to HiveResourceSelector
  • added check if Content is null in OnContentChanged in HiveResourceSelector
File size: 12.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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
45    private ISet<Resource> selectedResources;
46    public ISet<Resource> SelectedResources {
47      get { return selectedResources; }
48      set { selectedResources = value; }
49    }
50
51    private ProgressView progressView;
52    public ProgressView ProgressView {
53      get { return progressView; }
54      set { progressView = value; }
55    }
56
57    public new IItemList<Resource> Content {
58      get { return (IItemList<Resource>)base.Content; }
59      set { base.Content = value; }
60    }
61
62    public HiveResourceSelector() {
63      InitializeComponent();
64      mainTreeNodes = new HashSet<TreeNode>();
65      filteredTreeNodes = new HashSet<TreeNode>();
66      nodeStore = new HashSet<TreeNode>();
67      selectedResources = new HashSet<Resource>();
68      imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.MonitorLarge);
69      imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.NetworkCenterLarge);
70    }
71
72    public void StartProgressView() {
73      if (InvokeRequired) {
74        Invoke(new Action(StartProgressView));
75      } else {
76        if (progressView == null) {
77          IProgress prog = new Progress();
78          prog.Status = "Downloading resources. Please be patient.";
79          progressView = new ProgressView(this, prog);
80        }
81      }
82    }
83
84    public void FinishProgressView() {
85      if (InvokeRequired) {
86        Invoke(new Action(FinishProgressView));
87      } else {
88        if (progressView != null) {
89          progressView.Finish();
90          progressView = null;
91          SetEnabledStateOfControls();
92        }
93      }
94    }
95
96    protected override void OnContentChanged() {
97      if (Content != null) {
98        base.OnContentChanged();
99        selectedResources = new HashSet<Resource>(Content.Where(x => selectedResources.Any(y => x.Id == y.Id)));
100      }
101      UpdateMainTree();
102      ExtractStatistics();
103    }
104
105    #region MainTree Methods
106    private void UpdateMainTree() {
107      mainTreeNodes.Clear();
108
109      foreach (Resource g in Content) {
110        if (g.GetType() == typeof(SlaveGroup)) {
111          //root node
112          if (g.ParentResourceId == null) {
113            TreeNode tn = new TreeNode();
114            tn.ImageIndex = slaveGroupImageIndex;
115            tn.SelectedImageIndex = tn.ImageIndex;
116
117            tn.Tag = g;
118            tn.Text = g.Name;
119            tn.Checked = selectedResources.Any(x => x.Id == g.Id);
120
121            BuildMainTree(tn);
122            mainTreeNodes.Add(tn);
123          }
124        }
125      }
126      UpdateFilteredTree();
127    }
128
129    private void BuildMainTree(TreeNode tn) {
130      foreach (Resource r in Content.Where(s => s.ParentResourceId != null && s.ParentResourceId == ((Resource)tn.Tag).Id)) {
131        TreeNode stn = new TreeNode(r.Name);
132        if (r is Slave) stn.ImageIndex = slaveImageIndex;
133        else if (r is SlaveGroup) stn.ImageIndex = slaveGroupImageIndex;
134        stn.SelectedImageIndex = stn.ImageIndex;
135        stn.Tag = r;
136        stn.Checked = selectedResources.Any(x => x.Id == r.Id);
137        tn.Nodes.Add(stn);
138        mainTreeNodes.Add(stn);
139
140        BuildMainTree(stn);
141      }
142    }
143    #endregion
144
145    #region FilteredTree Methods
146    private void UpdateFilteredTree() {
147      filteredTreeNodes.Clear();
148      foreach (TreeNode n in mainTreeNodes) {
149        n.BackColor = SystemColors.Window;
150        if (currentSearchString == null || ((Resource)n.Tag).Name.ToLower().Contains(currentSearchString)) {
151          n.BackColor = string.IsNullOrEmpty(currentSearchString) ? SystemColors.Window : Color.LightBlue;
152          filteredTreeNodes.Add(n);
153          TraverseParentNodes(n);
154        }
155      }
156      UpdateResourceTree();
157    }
158
159    private void TraverseParentNodes(TreeNode node) {
160      if (node != null) {
161        for (TreeNode parent = node.Parent; parent != null; parent = parent.Parent)
162          filteredTreeNodes.Add(parent);
163      }
164    }
165    #endregion
166
167    #region ResourceTree Methods
168    private void UpdateResourceTree() {
169      resourcesTreeView.Nodes.Clear();
170      nodeStore.Clear();
171
172      foreach (TreeNode node in filteredTreeNodes) {
173        var clone = nodeStore.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)node.Tag).Id);
174        if (clone == null) {
175          clone = (TreeNode)node.Clone();
176          nodeStore.Add(clone);
177          clone.Nodes.Clear();
178        }
179        foreach (TreeNode child in node.Nodes)
180          if (filteredTreeNodes.Any(x => ((Resource)x.Tag).Id == ((Resource)child.Tag).Id)) {
181            var childClone = nodeStore.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)child.Tag).Id);
182            if (childClone == null) {
183              childClone = (TreeNode)child.Clone();
184              nodeStore.Add(childClone);
185              childClone.Nodes.Clear();
186            }
187            clone.Nodes.Add(childClone);
188          }
189      }
190      resourcesTreeView.Nodes.AddRange(nodeStore.Where(x => ((Resource)x.Tag).ParentResourceId == null).ToArray());
191      if (string.IsNullOrEmpty(currentSearchString)) ExpandSlaveGroupNodes();
192      else resourcesTreeView.ExpandAll();
193    }
194    #endregion
195
196    #region Events
197    private void resourcesTreeView_AfterCheck(object sender, TreeViewEventArgs e) {
198      if (e.Action != TreeViewAction.Unknown) {
199        if (e.Node.Checked) {
200          IncludeChildNodes(mainTreeNodes.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)e.Node.Tag).Id));
201          IncludeParentNodes(mainTreeNodes.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)e.Node.Tag).Id));
202        } else {
203          ExcludeChildNodes(mainTreeNodes.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)e.Node.Tag).Id));
204          ExcludeParentNodes(mainTreeNodes.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)e.Node.Tag).Id));
205        }
206        ExtractStatistics();
207      }
208    }
209
210    private void resourcesTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
211      if (e.Action != TreeViewAction.Unknown) {
212        ExtractStatistics(e.Node);
213      }
214    }
215
216    private void searchTextBox_TextChanged(object sender, System.EventArgs e) {
217      currentSearchString = searchTextBox.Text.ToLower();
218      UpdateFilteredTree();
219    }
220    #endregion
221
222    #region Helpers
223    private void IncludeChildNodes(TreeNode node) {
224      if (node != null) {
225        node.Checked = true;
226        selectedResources.Add((Resource)node.Tag);
227        AdjustNodeCheckedState(node);
228        foreach (TreeNode n in node.Nodes) IncludeChildNodes(n);
229      }
230    }
231
232    private void IncludeParentNodes(TreeNode node) {
233      if (node != null && node.Parent != null) {
234        TreeNode parent = node.Parent;
235        if (parent.Nodes.OfType<TreeNode>().All(x => x.Checked)) {
236          parent.Checked = true;
237          selectedResources.Add((Resource)parent.Tag);
238          AdjustNodeCheckedState(parent);
239          IncludeParentNodes(parent);
240        }
241      }
242    }
243
244    private void ExcludeChildNodes(TreeNode node) {
245      if (node != null) {
246        node.Checked = false;
247        selectedResources.Remove((Resource)node.Tag);
248        AdjustNodeCheckedState(node);
249        foreach (TreeNode n in node.Nodes) ExcludeChildNodes(n);
250      }
251    }
252
253    private void ExcludeParentNodes(TreeNode node) {
254      if (node != null) {
255        node.Checked = false;
256        selectedResources.Remove((Resource)node.Tag);
257        AdjustNodeCheckedState(node);
258        ExcludeParentNodes(node.Parent);
259      }
260    }
261
262    private void AdjustNodeCheckedState(TreeNode node) {
263      var filterdNode = filteredTreeNodes.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)node.Tag).Id);
264      var storedNode = nodeStore.SingleOrDefault(x => ((Resource)x.Tag).Id == ((Resource)node.Tag).Id);
265      if (filterdNode != null) filterdNode.Checked = node.Checked;
266      if (storedNode != null) storedNode.Checked = node.Checked;
267    }
268
269    private void ExpandSlaveGroupNodes() {
270      foreach (TreeNode n in nodeStore.Where(x => x.Tag is SlaveGroup)) {
271        TreeNode[] children = new TreeNode[n.Nodes.Count];
272        n.Nodes.CopyTo(children, 0);
273        if (children.Any(x => x.Tag is SlaveGroup)) n.Expand();
274      }
275    }
276
277    private void ExtractStatistics(TreeNode treeNode = null) {
278      StringBuilder sb = new StringBuilder();
279      Resource resource = treeNode == null ? null : treeNode.Tag as Resource;
280      ISet<Resource> resources = treeNode == null ? selectedResources : new HashSet<Resource>(treeNode.DescendantNodes().Select(x => x.Tag as Resource)); ;
281      IEnumerable<SlaveGroup> slaveGroups = resources.OfType<SlaveGroup>();
282      IEnumerable<Slave> slaves = resources.OfType<Slave>();
283      int cpuSpeed = 0, cores = 0, freeCores = 0, memory = 0, freeMemory = 0;
284      string contextString = treeNode == null ? "Selected" : "Included";
285
286      if (resources.Any() || resource != null) {
287        foreach (Slave s in slaves) {
288          cpuSpeed += s.CpuSpeed.GetValueOrDefault();
289          cores += s.Cores.GetValueOrDefault();
290          freeCores += s.FreeCores.GetValueOrDefault();
291          memory += s.Memory.GetValueOrDefault();
292          freeMemory += s.FreeMemory.GetValueOrDefault();
293        }
294        if (resource != null) {
295          if (resource is SlaveGroup) sb.Append("Slave group: ");
296          else if (resource is Slave) {
297            sb.Append("Slave: ");
298            if (!resources.Any()) {
299              Slave s = resource as Slave;
300              cpuSpeed = s.CpuSpeed.GetValueOrDefault();
301              cores = s.Cores.GetValueOrDefault();
302              freeCores = s.FreeCores.GetValueOrDefault();
303              memory = s.Memory.GetValueOrDefault();
304              freeMemory = s.FreeMemory.GetValueOrDefault();
305            }
306          }
307          sb.AppendLine(string.Format("{0}", resource.Name));
308        }
309        if (resource == null || resource is SlaveGroup) {
310          if (resources.Any()) {
311            sb.AppendFormat("{0} slave groups ({1}): ", contextString, slaveGroups.Count());
312            foreach (SlaveGroup sg in slaveGroups) sb.AppendFormat("{0}; ", sg.Name);
313            sb.AppendLine();
314            sb.AppendFormat("{0} slaves ({1}): ", contextString, slaves.Count());
315            foreach (Slave s in slaves) sb.AppendFormat("{0}; ", s.Name);
316            sb.AppendLine();
317          } else {
318            sb.Append("The selection does not inlcude any further resources.");
319          }
320        }
321        sb.AppendLine();
322        sb.AppendLine(string.Format("CPU speed: {0} MHz", cpuSpeed));
323        if (resources.Any()) sb.AppendLine(string.Format("Avg. CPU speed: {0:0.00} MHz", (double)cpuSpeed / resources.Count()));
324        sb.AppendLine(string.Format("Cores: {0}", cores));
325        sb.AppendLine(string.Format("Free cores: {0}", freeCores));
326        if (resources.Any()) sb.AppendLine(string.Format("Avg. free cores: {0:0.00}", (double)freeCores / resources.Count()));
327        sb.AppendLine(string.Format("Memory: {0} MB", memory));
328        sb.AppendFormat("Free memory: {0} MB", freeMemory);
329        if (resources.Any()) sb.Append(string.Format("{0}Avg. free memory: {1:0.00} MB", Environment.NewLine, (double)freeMemory / resources.Count()));
330      } else {
331        sb.Append("No resources selected.");
332      }
333
334      descriptionTextBox.Text = sb.ToString();
335    }
336    #endregion
337  }
338}
Note: See TracBrowser for help on using the repository browser.