Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2845_EnhancedProgress/HeuristicLab.Clients.Hive.JobManager/3.3/Views/HiveResourceSelector.cs @ 16317

Last change on this file since 16317 was 16311, checked in by pfleck, 6 years ago

#2845 Merged trunk changes into branch (15406-15681, 15683-16308)

File size: 33.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2017 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.Windows.Forms;
27using HeuristicLab.Collections;
28using HeuristicLab.Common;
29using HeuristicLab.Common.Resources;
30using HeuristicLab.Core;
31using HeuristicLab.Core.Views;
32using HeuristicLab.MainForm;
33using HeuristicLab.MainForm.WindowsForms;
34
35namespace HeuristicLab.Clients.Hive.JobManager.Views {
36  [View("Hive Project Selector View")]
37  [Content(typeof(IItemList<Project>), true)]
38  public partial class HiveProjectSelector : ItemView, IDisposable {
39    private const int greenFlagImageIndex = 0;
40    private const int redFlagImageIndex = 1;
41    private const int slaveImageIndex = 0;
42    private const int slaveGroupImageIndex = 1;
43    public const string additionalSlavesGroupName = "Additional Slaves";
44    public const string additionalSlavesGroupDescription = "Contains additional slaves which are either ungrouped or the parenting slave group is not assigned to the selected project.";
45
46    private const string CURRENT_SELECTION_TAG = " [current assignment]";
47    private const string NEW_SELECTION_TAG = " [new assignment]";
48    private const string CHANGED_SELECTION_TAG = " [changed assignment]";
49    private const string ADDED_SELECTION_TAG = " [added assignment]";
50    private const string REMOVED_SELECTION_TAG = " [removed assignment]";
51    private const string SELECTED_TAG = " [assigned]";
52    private const string INCLUDED_TAG = " [included]";
53    private const string ADDED_INCLUDE_TAG = " [added include]";
54    private const string REMOVED_INCLUDE_TAG = " [removed include]";
55
56    private TreeNode additionalNode;
57
58    private readonly HashSet<TreeNode> mainTreeNodes = new HashSet<TreeNode>();
59    private readonly HashSet<TreeNode> filteredTreeNodes = new HashSet<TreeNode>();
60
61    private readonly HashSet<Resource> availableResources = new HashSet<Resource>();
62    private readonly HashSet<Resource> assignedResources = new HashSet<Resource>();
63    private readonly HashSet<Resource> includedResources = new HashSet<Resource>();
64    private readonly HashSet<Resource> newAssignedResources = new HashSet<Resource>();
65    private readonly HashSet<Resource> newIncludedResources = new HashSet<Resource>();
66
67    private readonly Color addedAssignmentColor = Color.FromArgb(255, 87, 191, 193); // #57bfc1
68    private readonly Color removedAssignmentColor = Color.FromArgb(255, 236, 159, 72); // #ec9f48
69    private readonly Color addedIncludeColor = Color.FromArgb(25, 169, 221, 221); // #a9dddd
70    private readonly Color removedIncludeColor = Color.FromArgb(25, 249, 210, 145); // #f9d291
71    private readonly Color selectedBackColor = Color.DodgerBlue;
72    private readonly Color selectedForeColor = Color.White;
73    private readonly Color controlTextColor = SystemColors.ControlText;
74    private readonly Color grayTextColor = SystemColors.GrayText;
75
76    private string currentSearchString;
77
78    private void resetHiveResourceSelector() {
79      lastSelectedProject = null;
80      selectedProject = null;
81      projectId = null;
82    }
83
84    private Guid jobId;
85    public Guid JobId {
86      get { return jobId; }
87      set {
88        if (jobId == value) return;
89        jobId = value;
90        resetHiveResourceSelector();
91      }
92    }
93
94    private Guid? projectId;
95    public Guid? ProjectId {
96      get { return projectId; }
97      set {
98        if (projectId == value) return;
99        projectId = value;
100      }
101    }
102
103    private Guid? selectedProjectId;
104    public Guid? SelectedProjectId {
105      get { return selectedProjectId; }
106      set {
107        if (selectedProjectId == value) return;
108        selectedProjectId = value;
109      }
110    }
111
112    private IEnumerable<Guid> selectedResourceIds;
113    public IEnumerable<Guid> SelectedResourceIds {
114      get { return selectedResourceIds; }
115      set {
116        if (selectedResourceIds == value) return;
117        selectedResourceIds = value;
118      }
119    }
120
121    public bool ChangedProjectSelection {
122      get {
123        if ((lastSelectedProject == null && selectedProject != null)
124          || (lastSelectedProject != null && selectedProject == null)
125          || (lastSelectedProject != null && selectedProject != null && lastSelectedProject.Id != selectedProject.Id))
126          return true;
127        else return false;
128      }
129    }
130
131    public bool ChangedResources {
132      get { return !assignedResources.SetEquals(newAssignedResources); }
133    }
134
135    private Project lastSelectedProject;
136    private Project selectedProject;
137    public Project SelectedProject {
138      get { return selectedProject; }
139      set {
140        if (selectedProject == value) return;
141
142        if ((JobId == Guid.Empty || JobId == null)
143          && (value == null || SelectedProject == null || value.Id != SelectedProject.Id)) selectedResourceIds = null;
144        lastSelectedProject = selectedProject;
145        selectedProject = value;
146
147        UpdateResourceTree();
148        ExtractStatistics();
149        OnSelectedProjectChanged();
150      }
151    }
152
153    public int AssignedCores {
154      get {
155        HashSet<Slave> newAssignedSlaves = new HashSet<Slave>(newAssignedResources.OfType<Slave>());
156        foreach(var slaveGroup in newAssignedResources.OfType<SlaveGroup>()) {
157          foreach(var slave in HiveClient.Instance.GetAvailableResourceDescendants(slaveGroup.Id).OfType<Slave>()) {
158            newAssignedSlaves.Add(slave);
159          }
160        }
161        return newAssignedSlaves.Sum(x => x.Cores.GetValueOrDefault());
162      }
163    }
164
165    public IEnumerable<Resource> AssignedResources {
166      get { return newAssignedResources; }
167      set {
168        if (newAssignedResources == value) return;
169        newAssignedResources.Clear();
170        foreach(var resource in value) {
171          newAssignedResources.Add(resource);
172        }
173      }
174    }
175
176
177    public new IItemList<Project> Content {
178      get { return (IItemList<Project>)base.Content; }
179      set { base.Content = value; }
180    }
181
182    public HiveProjectSelector() {
183      InitializeComponent();
184
185      projectsImageList.Images.Add(VSImageLibrary.FlagGreen);
186      projectsImageList.Images.Add(VSImageLibrary.FlagRed);
187      resourcesImageList.Images.Add(VSImageLibrary.MonitorLarge);
188      resourcesImageList.Images.Add(VSImageLibrary.NetworkCenterLarge);
189    }
190
191    #region Overrides
192    protected override void OnContentChanged() {
193      base.OnContentChanged();
194
195      if (Content != null) {               
196        if (SelectedProjectId.HasValue && SelectedProjectId.Value != Guid.Empty) {
197          SelectedProject = GetSelectedProjectById(SelectedProjectId.Value);
198        } else {
199          SelectedProject = null;
200        }
201        //ExtractStatistics();
202        UpdateProjectTree();
203
204      } else {
205        lastSelectedProject = null;
206        selectedProject = null;
207        selectedProjectId = null;
208        projectsTreeView.Nodes.Clear();
209        resourcesTreeView.Nodes.Clear();
210      }
211    }
212
213    #endregion
214
215    #region Event Handlers
216    private void HiveProjectSelector_Load(object sender, EventArgs e) {
217      projectsTreeView.Nodes.Clear();
218      resourcesTreeView.Nodes.Clear();
219    }
220
221    private void searchTextBox_TextChanged(object sender, EventArgs e) {
222      currentSearchString = searchTextBox.Text.ToLower();
223      //UpdateFilteredTree();
224      UpdateProjectTree();
225    }
226
227    private void projectsTreeView_MouseDoubleClick(object sender, MouseEventArgs e) {
228      OnProjectsTreeViewDoubleClicked();
229    }
230
231    private void projectsTreeView_BeforeSelect(object sender, TreeViewCancelEventArgs e) {
232      var node = (Project)e.Node.Tag;
233      if (HiveClient.Instance.DisabledParentProjects.Contains(node)) {
234        e.Cancel = true;
235      }
236    }
237
238    private void projectsTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
239      var node = (Project)e.Node.Tag;
240
241      if (node == null) {
242        projectsTreeView.SelectedNode = null;
243      } else if (HiveClient.Instance.DisabledParentProjects.Contains(node)) {
244        return;
245      } else {
246        ResetTreeNodes(projectsTreeView.Nodes);
247        e.Node.BackColor = selectedBackColor;
248        e.Node.ForeColor = selectedForeColor;
249
250        if (node.Id == projectId) {
251          e.Node.Text += CURRENT_SELECTION_TAG;
252        } else if (projectId == null || projectId == Guid.Empty) {
253          e.Node.Text += NEW_SELECTION_TAG;
254        } else {
255          e.Node.Text += CHANGED_SELECTION_TAG;
256        }
257
258
259      }
260      SelectedProject = node;
261    }
262
263    private void resourcesTreeView_MouseDown(object sender, MouseEventArgs e) {
264      var node = resourcesTreeView.GetNodeAt(new Point(e.X, e.Y));
265
266      if (node == null && e.Button == MouseButtons.Left) {
267        resourcesTreeView.SelectedNode = null;
268        ExtractStatistics();
269      }
270    }
271
272    private void resourcesTreeView_BeforeSelect(object sender, TreeViewCancelEventArgs e) {
273      if(e.Node == null) {
274        e.Cancel = true;
275        resourcesTreeView.SelectedNode = null;
276        ExtractStatistics();
277      } else if (e.Node == additionalNode) {
278        e.Cancel = true;
279      } else {
280        var r = (Resource)e.Node.Tag;
281        if(r != null && !HiveClient.Instance.DisabledParentResources.Contains(r)) {
282          ExtractStatistics(r);
283        } else {
284          e.Cancel = true;
285        }
286      }
287    }
288
289    private void resourcesTreeView_BeforeCheck(object sender, TreeViewCancelEventArgs e) {
290      if(e.Node == null || e.Node == additionalNode) {
291        e.Cancel = true;
292      } else {
293        var checkedResource = (Resource)e.Node.Tag;
294        if (checkedResource == null
295          || checkedResource.Id == Guid.Empty
296          || HiveClient.Instance.DisabledParentResources.Contains(checkedResource)
297          || newIncludedResources.Contains(checkedResource)) {
298          e.Cancel = true;
299        }
300      }
301    }
302
303    private void resourcesTreeView_AfterCheck(object sender, TreeViewEventArgs e) {
304      var checkedResource = (Resource)e.Node.Tag;
305      if (e.Node.Checked) {
306        newAssignedResources.Add(checkedResource);
307      } else {
308        newAssignedResources.Remove(checkedResource);
309      }
310
311      UpdateResourceTreeAfterCheck();
312      if(resourcesTreeView.SelectedNode == null)
313        ExtractStatistics();
314      OnAssignedResourcesChanged();
315    }
316
317    private void resourcesTreeView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) {
318      return;
319    }
320    #endregion
321
322    #region Helpers
323
324    private Project GetSelectedProjectById(Guid projectId) {
325      return Content.Where(x => x.Id == projectId).SingleOrDefault();
326    }
327
328    private void UpdateProjectTree() {
329
330      if (string.IsNullOrEmpty(currentSearchString)) {
331        BuildProjectTree(Content);
332      } else {
333        HashSet<Project> filteredProjects = new HashSet<Project>();
334        foreach(var project in Content) {
335          if(project.Name.ToLower().Contains(currentSearchString.ToLower())) {
336            filteredProjects.Add(project);
337            filteredProjects.UnionWith(Content.Where(p => HiveClient.Instance.GetAvailableProjectAncestors(project.Id).Select(x => x.Id).Contains(p.Id)));
338          }
339        }
340        BuildProjectTree(filteredProjects);
341      }
342    }
343
344    private void BuildProjectTree(IEnumerable<Project> projects) {
345      projectsTreeView.Nodes.Clear();
346      if (!projects.Any()) return;
347
348      var disabledParentProjects = HiveClient.Instance.DisabledParentProjects;
349      // select all top level projects (withouth parent, or without any ancestor within current project collection)
350      var mainProjects = new HashSet<Project>(projects.Where(x => x.ParentProjectId == null));
351      //var parentedMainProjects = new HashSet<Project>(projects
352      //  .Where(x => x.ParentProjectId.HasValue
353      //  && !projects.Select(y => y.Id).Contains(x.ParentProjectId.Value)
354      //  && !projects.SelectMany(y => HiveClient.Instance.ProjectAncestors[y.Id]).Contains(x.ParentProjectId.Value)));
355      //mainProjects.UnionWith(parentedMainProjects);
356      var mainDisabledParentProjects = new HashSet<Project>(disabledParentProjects.Where(x => x.ParentProjectId == null || x.ParentProjectId == Guid.Empty));
357      mainProjects.UnionWith(mainDisabledParentProjects);
358      var subProbjects = new HashSet<Project>(projects.Union(disabledParentProjects).Except(mainProjects));
359      //foreach (var p in subProbjects) {
360      //  p.ParentProjectId = HiveClient.Instance.ProjectAncestors[p.Id].Where(x => projects.Select(y => y.Id).Contains(x)).FirstOrDefault();
361      //}
362
363      var stack = new Stack<Project>(mainProjects.OrderByDescending(x => x.Name));
364
365      TreeNode currentNode = null;
366      Project currentProject = null;
367
368      while(stack.Any()) {
369        var newProject = stack.Pop();
370        var newNode = new TreeNode(newProject.Name) { Tag = newProject };
371
372        while (currentNode != null && newProject.ParentProjectId != currentProject.Id) {
373          currentNode = currentNode.Parent;
374          currentProject = currentNode == null ? null : (Project)currentNode.Tag;
375        }
376
377        if (currentNode == null) {
378          projectsTreeView.Nodes.Add(newNode);
379          newNode.ImageIndex = greenFlagImageIndex;
380        } else {
381          currentNode.Nodes.Add(newNode);
382          newNode.ImageIndex = redFlagImageIndex;
383        }
384
385        newNode.SelectedImageIndex = newNode.ImageIndex;
386
387        if(disabledParentProjects.Contains(newProject)) {
388          newNode.Checked = false;
389          newNode.ForeColor = grayTextColor;
390        }
391        else if (SelectedProject != null && SelectedProject.Id.Equals(newProject.Id)) {
392          newNode.BackColor = selectedBackColor;
393          newNode.ForeColor = selectedForeColor;
394          if(SelectedProject.Id == projectId) {
395            newNode.Text += CURRENT_SELECTION_TAG;
396          } else if (projectId == null || projectId == Guid.Empty) {
397            newNode.Text += NEW_SELECTION_TAG;
398          } else {
399            newNode.Text += CHANGED_SELECTION_TAG;
400          }
401        }
402
403        if (!string.IsNullOrEmpty(currentSearchString) && newProject.Name.ToLower().Contains(currentSearchString.ToLower())) {
404          newNode.BackColor = Color.LightBlue;
405        }
406
407        var childProjects = subProbjects.Where(x => x.ParentProjectId == newProject.Id);
408        if (childProjects.Any()) {
409          foreach (var project in childProjects.OrderByDescending(x => x.Name)) {
410            subProbjects.Remove(project);
411            stack.Push(project);
412          }
413          currentNode = newNode;
414          currentProject = newProject;
415        }
416      }
417
418      projectsTreeView.ExpandAll();
419    }
420
421    private static IEnumerable<Resource> GetAssignedResourcesForProject(Guid projectId) {
422      var assignedProjectResources = HiveServiceLocator.Instance.CallHiveService(s => s.GetAssignedResourcesForProject(projectId));
423      return HiveClient.Instance.Resources.Where(x => assignedProjectResources.Select(y => y.ResourceId).Contains(x.Id));
424    }
425
426    private static IEnumerable<Resource> GetAssignedResourcesForJob(Guid jobId) {
427      var assignedJobResources = HiveServiceLocator.Instance.CallHiveService(s => s.GetAssignedResourcesForJob(jobId));
428      return HiveClient.Instance.Resources.Where(x => assignedJobResources.Select(y => y.ResourceId).Contains(x.Id));
429    }
430
431    private void UpdateResourceTree() {
432      UpdateAvailableResources();
433      UpdateAssignedResources();
434      UpdateIncludedResources();
435      BuildResourceTree(availableResources);
436    }
437
438    private void UpdateResourceTreeAfterCheck() {
439      resourcesTreeView.BeforeCheck -= resourcesTreeView_BeforeCheck;
440      resourcesTreeView.AfterCheck -= resourcesTreeView_AfterCheck;
441      UpdateNewAssignedResources();
442      UpdateNewIncludedResources();
443      SetTreeNodes(resourcesTreeView.Nodes);
444      resourcesTreeView.BeforeCheck += resourcesTreeView_BeforeCheck;
445      resourcesTreeView.AfterCheck += resourcesTreeView_AfterCheck;
446    }
447
448    private void UpdateAvailableResources() {
449      availableResources.Clear();
450      if (selectedProject != null) {
451        var assignedProjectResources = GetAssignedResourcesForProject(selectedProject.Id);
452        foreach (var resource in assignedProjectResources) {
453          availableResources.Add(resource);
454          foreach(var descendant in HiveClient.Instance.Resources.Where(x => HiveClient.Instance.ResourceDescendants[resource.Id].Contains(x.Id))) {
455            availableResources.Add(descendant);
456          }
457        }
458      }
459      //ExtractStatistics();
460      //OnAssignedResourcesChanged();
461    }
462
463    private void UpdateAssignedResources() {
464      assignedResources.Clear();
465      newAssignedResources.Clear();
466
467      if (JobId == Guid.Empty || JobId == null) { // new, unchanged jobs get all avaialable resources
468        // update new assigned resources
469        if(selectedResourceIds == null) {
470          foreach (var resource in availableResources
471            .Where(x => !x.ParentResourceId.HasValue
472            || !availableResources.Select(y => y.Id).Contains(x.ParentResourceId.Value))) {
473            newAssignedResources.Add(resource);
474          }
475        } else {
476          foreach(var resource in availableResources.Where(x => selectedResourceIds.Contains(x.Id))) {
477            newAssignedResources.Add(resource);
478          }
479        }
480      } else if(selectedProject.Id == projectId) { // existent, unchanged jobs get all assigned resources
481        // update assigned resources
482        var assignedJobResources = GetAssignedResourcesForJob(JobId);
483        foreach (var resource in assignedJobResources) {
484          assignedResources.Add(resource);
485          if (selectedResourceIds == null) {
486            newAssignedResources.Add(resource);
487          }
488        }
489
490        if(selectedResourceIds != null) {
491          foreach (var resource in availableResources.Where(x => selectedResourceIds.Contains(x.Id))) {
492            newAssignedResources.Add(resource);
493          }
494        }
495      }
496
497      //ExtractStatistics();
498      OnAssignedResourcesChanged();
499    }
500
501    private void UpdateNewAssignedResources() {
502      for(int i = newAssignedResources.Count-1; i>=0; i--) {
503        if(newAssignedResources.Intersect(HiveClient.Instance.GetAvailableResourceAncestors(newAssignedResources.ElementAt(i).Id)).Any()) {
504          newAssignedResources.Remove(newAssignedResources.ElementAt(i));
505        }
506      }
507    }
508
509    private void UpdateIncludedResources() {
510      includedResources.Clear();
511      newIncludedResources.Clear();
512
513      if (JobId != Guid.Empty) {
514        foreach (var item in assignedResources) {
515          foreach (var descendant in HiveClient.Instance.GetAvailableResourceDescendants(item.Id)) {
516            includedResources.Add(descendant);
517          }
518        }
519      }
520
521      foreach (var item in newAssignedResources) {
522        foreach (var descendant in HiveClient.Instance.GetAvailableResourceDescendants(item.Id)) {
523          newIncludedResources.Add(descendant);
524        }
525      }
526    }
527
528    private void UpdateNewIncludedResources() {
529      newIncludedResources.Clear();
530      foreach (var item in newAssignedResources) {
531        foreach (var descendant in HiveClient.Instance.GetAvailableResourceDescendants(item.Id)) {
532          newIncludedResources.Add(descendant);
533        }
534      }
535    }
536
537    private void BuildResourceTree(IEnumerable<Resource> resources) {
538      resourcesTreeView.Nodes.Clear();
539      if (!resources.Any()) return;
540
541      resourcesTreeView.BeforeCheck -= resourcesTreeView_BeforeCheck;
542      resourcesTreeView.AfterCheck -= resourcesTreeView_AfterCheck;
543
544      //var disabledParentResources = HiveClient.Instance.DisabledParentResources;
545      var disabledParentResources = HiveClient.Instance.GetDisabledResourceAncestors(resources);
546      var mainResources = new HashSet<Resource>(resources.OfType<SlaveGroup>().Where(x => x.ParentResourceId == null));
547      //var parentedMainResources = new HashSet<Resource>(resources.OfType<SlaveGroup>()
548      //  .Where(x => x.ParentResourceId.HasValue && !resources.Select(y => y.Id).Contains(x.ParentResourceId.Value)));
549      //mainResources.UnionWith(parentedMainResources);
550      //var subResources = new HashSet<Resource>(resources.Except(mainResources));
551      var mainDisabledParentResources = new HashSet<Resource>(disabledParentResources.Where(x => x.ParentResourceId == null || x.ParentResourceId == Guid.Empty));
552      mainResources.UnionWith(mainDisabledParentResources);
553      var subResources = new HashSet<Resource>(resources.Union(disabledParentResources).Except(mainResources).OrderByDescending(x => x.Name));
554
555      var addedAssignments = newAssignedResources.Except(assignedResources);
556      var removedAssignments = assignedResources.Except(newAssignedResources);
557      var addedIncludes = newIncludedResources.Except(includedResources);
558      var removedIncludes = includedResources.Except(newIncludedResources);
559
560      TreeNode currentNode = null;
561      Resource currentResource = null;
562
563      var stack = new Stack<Resource>(mainResources.OrderByDescending(x => x.Name));
564
565      while (stack.Any()) {
566        var newResource = stack.Pop();
567        var newNode = new TreeNode(newResource.Name) { Tag = newResource };
568
569        // search for parent node of newNode and save in currentNode
570        // necessary since newNodes (stack top items) might be siblings
571        // or grand..grandparents of previous node (currentNode)
572        while (currentNode != null && newResource.ParentResourceId != currentResource.Id) {
573          currentNode = currentNode.Parent;
574          currentResource = currentNode == null ? null : (Resource)currentNode.Tag;
575        }
576
577        if (currentNode == null) {
578          resourcesTreeView.Nodes.Add(newNode);
579        } else {
580          currentNode.Nodes.Add(newNode);
581        }
582
583        if (disabledParentResources.Contains(newResource)) {
584          newNode.Checked = false;
585          newNode.ForeColor = grayTextColor;
586        } else if (newAssignedResources.Select(x => x.Id).Contains(newResource.Id)) {
587          newNode.Checked = true;
588          if(!addedAssignments.Select(x => x.Id).Contains(newResource.Id) && !removedAssignments.Select(x => x.Id).Contains(newResource.Id)) {
589            newNode.Text += SELECTED_TAG;
590          }
591        } else if (newIncludedResources.Select(x => x.Id).Contains(newResource.Id)) {
592          newNode.Checked = true;
593          newNode.ForeColor = grayTextColor;
594        }
595
596        if (includedResources.Select(x => x.Id).Contains(newResource.Id) && newIncludedResources.Select(x => x.Id).Contains(newResource.Id)) {
597          newNode.Text += INCLUDED_TAG;
598        } else if (addedIncludes.Select(x => x.Id).Contains(newResource.Id)) {
599          newNode.BackColor = addedIncludeColor;
600          newNode.ForeColor = grayTextColor;
601          newNode.Text += ADDED_INCLUDE_TAG;
602        } else if (removedIncludes.Select(x => x.Id).Contains(newResource.Id)) {
603          newNode.BackColor = removedIncludeColor;
604          newNode.Text += REMOVED_INCLUDE_TAG;
605        }
606
607        if (addedAssignments.Select(x => x.Id).Contains(newResource.Id)) {
608          newNode.BackColor = addedAssignmentColor;
609          newNode.ForeColor = controlTextColor;
610          newNode.Text += ADDED_SELECTION_TAG;
611        } else if (removedAssignments.Select(x => x.Id).Contains(newResource.Id)) {
612          newNode.BackColor = removedAssignmentColor;
613          newNode.ForeColor = controlTextColor;
614          newNode.Text += REMOVED_SELECTION_TAG;
615        }
616
617        if (newResource is Slave) {
618          newNode.ImageIndex = slaveImageIndex;
619        } else {
620          newNode.ImageIndex = slaveGroupImageIndex;
621
622          var childResources = subResources.Where(x => x.ParentResourceId == newResource.Id);
623          if (childResources.Any()) {
624            foreach (var resource in childResources.OrderByDescending(x => x.Name)) {
625              subResources.Remove(resource);
626              stack.Push(resource);
627            }
628            currentNode = newNode;
629            currentResource = newResource;
630          }
631        }
632        newNode.SelectedImageIndex = newNode.ImageIndex;
633      }
634
635      var singleSlaves = subResources.OfType<Slave>();
636      if (singleSlaves.Any()) {
637
638        additionalNode = new TreeNode(additionalSlavesGroupName) {
639          ForeColor = SystemColors.GrayText,
640          ImageIndex = slaveGroupImageIndex,
641          Tag = new SlaveGroup() {
642            Name = additionalSlavesGroupName,
643            Description = additionalSlavesGroupDescription
644          }
645        };
646
647        foreach (var slave in singleSlaves.OrderBy(x => x.Name)) {
648          var slaveNode = new TreeNode(slave.Name) { Tag = slave };
649
650          if (newAssignedResources.Select(x => x.Id).Contains(slave.Id)) {
651            slaveNode.Checked = true;
652            if (!addedAssignments.Select(x => x.Id).Contains(slave.Id) &&
653                !removedAssignments.Select(x => x.Id).Contains(slave.Id)) {
654              slaveNode.Text += SELECTED_TAG;
655            }
656          }
657
658          if (addedAssignments.Select(x => x.Id).Contains(slave.Id)) {
659            slaveNode.BackColor = addedAssignmentColor;
660            slaveNode.ForeColor = controlTextColor;
661            slaveNode.Text += ADDED_SELECTION_TAG;
662          } else if (removedAssignments.Select(x => x.Id).Contains(slave.Id)) {
663            slaveNode.BackColor = removedAssignmentColor;
664            slaveNode.ForeColor = controlTextColor;
665            slaveNode.Text += REMOVED_SELECTION_TAG;
666          }
667
668          additionalNode.Nodes.Add(slaveNode);
669        }
670
671        resourcesTreeView.Nodes.Add(additionalNode);
672      }
673
674      ExpandResourceNodesOfInterest(resourcesTreeView.Nodes);
675
676      resourcesTreeView.BeforeCheck += resourcesTreeView_BeforeCheck;
677      resourcesTreeView.AfterCheck += resourcesTreeView_AfterCheck;
678    }
679
680    private void ExpandResourceNodesOfInterest(TreeNodeCollection nodes) {
681      foreach(TreeNode n in nodes) {
682        Resource r = (Resource)n.Tag;
683        if(n.Nodes.Count > 0) {
684          if(HiveClient.Instance.GetAvailableResourceDescendants(r.Id).OfType<SlaveGroup>().Any()           
685            || HiveClient.Instance.GetAvailableResourceDescendants(r.Id).OfType<Slave>().Intersect(assignedResources.Union(newAssignedResources)).Any()
686            || (n == additionalNode && additionalNode.Nodes.Count > 0 && additionalNode.Nodes.Cast<TreeNode>().Any(x => x.Checked))) {
687            n.Expand();
688            ExpandResourceNodesOfInterest(n.Nodes);
689          } else {
690            n.Collapse();
691          }   
692        } else {
693          n.Collapse();
694        }
695      }
696    }
697
698    private void CollapseSlaveOnlyNodes(TreeNode tn) {
699      if (!(tn.Tag is Resource)) return;
700
701      Resource r = (Resource)tn.Tag;
702      if (HiveClient.Instance.GetAvailableResourceDescendants(r.Id).OfType<SlaveGroup>().Any()) {
703        tn.Expand();
704        foreach (TreeNode n in tn.Nodes) CollapseSlaveOnlyNodes(n);
705      } else {
706        tn.Collapse();
707      }
708    }
709
710    private void ExtractStatistics(Resource resource = null) {
711      HashSet<Slave> newAssignedSlaves = new HashSet<Slave>(newAssignedResources.OfType<Slave>());
712      foreach (var slaveGroup in newAssignedResources.OfType<SlaveGroup>()) {
713        foreach (var slave in HiveClient.Instance.GetAvailableResourceDescendants(slaveGroup.Id).OfType<Slave>()) {
714          newAssignedSlaves.Add(slave);
715        }
716      }
717
718      HashSet<Slave> selectedSlaves = null;
719
720      if (resource != null) {
721        var slaveGroup = resource as SlaveGroup;
722        if (slaveGroup != null) {
723          selectedSlaves = new HashSet<Slave>(HiveClient.Instance.GetAvailableResourceDescendants(slaveGroup.Id).OfType<Slave>());
724        } else {
725          selectedSlaves = new HashSet<Slave>(new[] { resource as Slave });
726        }
727      } else {
728        selectedSlaves = newAssignedSlaves;
729      }
730
731      int sumCores = selectedSlaves.Sum(x => x.Cores.GetValueOrDefault());
732      int sumFreeCores = selectedSlaves.Sum(x => x.FreeCores.GetValueOrDefault());
733      double sumMemory = selectedSlaves.Sum(x => x.Memory.GetValueOrDefault()) / 1024.0;
734      double sumFreeMemory = selectedSlaves.Sum(x => x.FreeMemory.GetValueOrDefault()) / 1024.0;
735
736      coresSummaryLabel.Text = string.Format("{0} Total ({1} Free / {2} Used)", sumCores, sumFreeCores, sumCores - sumFreeCores);
737      memorySummaryLabel.Text = string.Format("{0:0.00} GB Total ({1:0.00} GB Free / {2:0.00} GB Used)", sumMemory, sumFreeMemory, sumMemory - sumFreeMemory);
738    }
739
740    private void StyleTreeNode(TreeNode n, string name) {
741      n.Text = name;
742      n.BackColor = Color.Transparent;
743      n.ForeColor = Color.Black;
744
745      if(n.Tag is Project) {
746        var p = (Project)n.Tag;
747        if(HiveClient.Instance.DisabledParentProjects.Select(x => x.Id).Contains(p.Id)) {
748          n.Checked = false;
749          n.ForeColor = grayTextColor;
750        }
751      } else if(n.Tag is Resource) {
752        var r = (Resource)n.Tag;
753        if(HiveClient.Instance.DisabledParentResources.Select(x => x.Id).Contains(r.Id) || n == additionalNode) {
754          n.Checked = false;
755          n.ForeColor = grayTextColor;
756        }
757      }
758    }
759
760    private void ResetTreeNodes(TreeNodeCollection nodes) {
761      foreach (TreeNode n in nodes) {
762        string name = "";
763        if (n.Tag is Project) name = ((Project)n.Tag).Name;
764        else if (n.Tag is Resource) name = ((Resource)n.Tag).Name;
765        StyleTreeNode(n, name);
766        if (n.Nodes.Count > 0) {
767          ResetTreeNodes(n.Nodes);
768        }
769      }
770    }
771
772    private void SetTreeNodes(TreeNodeCollection nodes) {
773      var addedAssignments = newAssignedResources.Except(assignedResources);
774      var removedAssignments = assignedResources.Except(newAssignedResources);
775      var addedIncludes = newIncludedResources.Except(includedResources);
776      var removedIncludes = includedResources.Except(newIncludedResources);
777
778      foreach (TreeNode n in nodes) {
779
780        if(n.Tag is Resource) {
781          // reset
782          var resource = (Resource)n.Tag;
783          n.Text = resource.Name;
784          n.BackColor = Color.Transparent;
785          n.ForeColor = Color.Black;
786          n.Checked = false;
787
788          if (HiveClient.Instance.DisabledParentResources.Select(x => x.Id).Contains(resource.Id) || n == additionalNode) {
789            n.ForeColor = grayTextColor;
790          }
791
792          // add additional info
793          if (newAssignedResources.Select(x => x.Id).Contains(resource.Id)) {
794            n.Checked = true;
795            if (!addedAssignments.Select(x => x.Id).Contains(resource.Id) && !removedAssignments.Select(x => x.Id).Contains(resource.Id)) {
796              n.Text += SELECTED_TAG;
797            }
798          } else if (newIncludedResources.Select(x => x.Id).Contains(resource.Id)) {
799            n.Checked = true;
800            n.ForeColor = grayTextColor;
801          }
802
803          if (includedResources.Select(x => x.Id).Contains(resource.Id) && newIncludedResources.Select(x => x.Id).Contains(resource.Id)) {
804            n.Text += INCLUDED_TAG;
805          } else if (addedIncludes.Select(x => x.Id).Contains(resource.Id)) {
806            n.BackColor = addedIncludeColor;
807            n.ForeColor = grayTextColor;
808            n.Text += ADDED_INCLUDE_TAG;
809          } else if (removedIncludes.Select(x => x.Id).Contains(resource.Id)) {
810            n.BackColor = removedIncludeColor;
811            n.Text += REMOVED_INCLUDE_TAG;
812          }
813
814          if (addedAssignments.Select(x => x.Id).Contains(resource.Id)) {
815            n.BackColor = addedAssignmentColor;
816            n.ForeColor = controlTextColor;
817            n.Text += ADDED_SELECTION_TAG;
818          } else if (removedAssignments.Select(x => x.Id).Contains(resource.Id)) {
819            n.BackColor = removedAssignmentColor;
820            n.ForeColor = controlTextColor;
821            n.Text += REMOVED_SELECTION_TAG;
822          }
823        }
824
825        if(n.Nodes.Count > 0) {
826          SetTreeNodes(n.Nodes);
827        }
828      }
829    }
830
831    #endregion
832
833    #region Events
834    public event EventHandler SelectedProjectChanged;
835    private void OnSelectedProjectChanged() {
836      var handler = SelectedProjectChanged;
837      if (handler != null) handler(this, EventArgs.Empty);
838    }
839
840    public event EventHandler AssignedResourcesChanged;
841    private void OnAssignedResourcesChanged() {
842      var handler = AssignedResourcesChanged;
843      if (handler != null) handler(this, EventArgs.Empty);
844    }
845
846    public event EventHandler ProjectsTreeViewDoubleClicked;
847    private void OnProjectsTreeViewDoubleClicked() {
848      var handler = ProjectsTreeViewDoubleClicked;
849      if (handler != null) handler(this, EventArgs.Empty);
850    }
851    #endregion
852  }
853}
Note: See TracBrowser for help on using the repository browser.