Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 8160 was 8160, checked in by ascheibe, 12 years ago

#1762 removed unnecessary SetEnabledStateOfControls calls

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