Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2839_HiveProjectManagement/HeuristicLab.Clients.Hive.JobManager/3.3/Views/HiveResourceSelector.cs @ 16094

Last change on this file since 16094 was 16094, checked in by jkarder, 6 years ago

#2839: worked on hive project management

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