source: branches/2839_HiveProjectManagement/HeuristicLab.Clients.Hive.Administrator/3.3/Views/ProjectResourcesView.cs @ 15922

Last change on this file since 15922 was 15922, checked in by jzenisek, 16 months ago

#2839:

  • replaced use of TreeView with NoDoubleClickTreeView everywhere allegedly reasonable for Hive
  • updated genealogy computation for HiveAdminClient and corresponding views (ResourcesView & ProjectResourcesView)
File size: 15.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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.Clients.Access;
28using HeuristicLab.Common.Resources;
29using HeuristicLab.Core.Views;
30using HeuristicLab.MainForm;
31using System.Collections;
32
33namespace HeuristicLab.Clients.Hive.Administrator.Views {
34  [View("ProjectView")]
35  [Content(typeof(Project), IsDefaultView = false)]
36  public partial class ProjectResourcesView : ItemView {
37    private const int slaveImageIndex = 0;
38    private const int slaveGroupImageIndex = 1;
39    public const string UNGROUPED_GROUP_NAME = "UNGROUPED";
40    public const string UNGROUPED_GROUP_DESCRIPTION = "Contains slaves that are not assigned to any group.";
41    public const string IMMUTABLE_TAG = " [assigned, immutable]";
42    public const string INCLUDED_TAG = " [included]";
43    public const string ADDED_ASSIGNMENT_TAG = " [added assignment]";
44    public const string REMOVED_ASSIGNMENT_TAG = " [removed assignment]";
45    public const string ADDED_INCLUDE_TAG = " [added include]";
46    public const string REMOVED_INCLUDE_TAG = " [removed include]";
47
48    private readonly HashSet<Resource> assignedResources = new HashSet<Resource>();
49    private readonly HashSet<Resource> newAssignedResources = new HashSet<Resource>();
50    private readonly HashSet<Resource> includedResources = new HashSet<Resource>();
51    private readonly HashSet<Resource> newIncludedResources = new HashSet<Resource>();
52
53    private readonly Color addedAssignmentColor = Color.FromArgb(255, 87, 191, 193); // #57bfc1
54    private readonly Color removedAssignmentColor = Color.FromArgb(255, 236, 159, 72); // #ec9f48
55    private readonly Color addedIncludeColor = Color.FromArgb(25, 169, 221, 221); // #a9dddd
56    private readonly Color removedIncludeColor = Color.FromArgb(25, 249, 210, 145); // #f9d291
57
58    private HashSet<Resource> projectExclusiveResources = new HashSet<Resource>();
59    private TreeNode ungroupedGroupNode;
60
61    public new Project Content {
62      get { return (Project)base.Content; }
63      set { base.Content = value; }
64    }
65
66    public ProjectResourcesView() {
67      InitializeComponent();
68
69      treeView.ImageList.Images.Add(VSImageLibrary.MonitorLarge);
70      treeView.ImageList.Images.Add(VSImageLibrary.NetworkCenterLarge);
71    }
72
73    #region Overrides
74    protected override void OnContentChanged() {
75      base.OnContentChanged();
76      if (Content == null) {
77        assignedResources.Clear();
78        newAssignedResources.Clear();
79        includedResources.Clear();
80        treeView.Nodes.Clear();
81        detailsViewHost.Content = null;
82      } else {
83        UpdateAssignedResources();
84        UpdateIncludedResources();
85        var top = BuildResourceTree(HiveAdminClient.Instance.Resources);
86        detailsViewHost.Content = top;
87      }
88    }
89
90    protected override void SetEnabledStateOfControls() {
91      base.SetEnabledStateOfControls();
92      bool enabled = Content != null && !Locked && !ReadOnly;
93
94      inheritButton.Enabled = enabled;
95      saveButton.Enabled = enabled;
96      treeView.Enabled = enabled;
97    }
98    #endregion
99
100    #region Event Handlers
101    private void ProjectResourcesView_Load(object sender, EventArgs e) {
102
103    }
104
105    private void refreshButton_Click(object sender, EventArgs e) {
106      HiveAdminClient.Instance.Refresh();
107      UpdateAssignedResources();
108      UpdateIncludedResources();
109      var top = BuildResourceTree(HiveAdminClient.Instance.Resources);
110      detailsViewHost.Content = top;
111    }
112
113    private async void inheritButton_Click(object sender, EventArgs e) {
114      await SecurityExceptionUtil.TryAsyncAndReportSecurityExceptions(
115        action: () => {
116          SetAssignedProjectResources(Content.Id, newAssignedResources.Select(x => x.Id), false, true, false);
117        });
118      UpdateResourceTree();
119    }
120
121    private async void saveButton_Click(object sender, EventArgs e) {
122      await SecurityExceptionUtil.TryAsyncAndReportSecurityExceptions(
123        action: () => {
124          SetAssignedProjectResources(Content.Id, newAssignedResources.Select(x => x.Id), false, false, false);
125        });
126      UpdateResourceTree();
127    }
128
129    private void treeView_AfterSelect(object sender, TreeViewEventArgs e) {
130      var selectedResource = (Resource)e.Node.Tag;
131      detailsViewHost.Content = selectedResource;
132    }
133
134    private void treeView_BeforeCheck(object sender, TreeViewCancelEventArgs e) {
135      var checkedResource = (Resource)e.Node.Tag;
136      if (newIncludedResources.Contains(checkedResource) || checkedResource.Id == Guid.Empty || e.Node == ungroupedGroupNode) {
137        e.Cancel = true;
138      } else if (!HiveRoles.CheckAdminUserPermissions()) {
139          if (!HiveAdminClient.Instance.GetAvailableProjectAncestors(Content.Id).Any() || projectExclusiveResources.Contains(checkedResource)) {
140            e.Cancel = true;
141          }
142      }
143    }
144
145    private void treeView_AfterCheck(object sender, TreeViewEventArgs e) {
146      var checkedResource = (Resource)e.Node.Tag;
147      if (e.Node.Checked) {
148        newAssignedResources.Add(checkedResource);
149      } else {
150        newAssignedResources.Remove(checkedResource);
151      }
152
153      UpdateNewResourceTree();
154    }
155    #endregion
156
157    #region Helpers
158
159    private void UpdateResourceTree() {
160      UpdateAssignedResources();
161      UpdateIncludedResources();
162
163      var top = BuildResourceTree(HiveAdminClient.Instance.Resources);
164      detailsViewHost.Content = top;
165    }
166
167    private void UpdateNewResourceTree() {
168      UpdateNewAssignedResources();
169      UpdateNewIncludedResources();
170      var top = BuildResourceTree(HiveAdminClient.Instance.Resources);
171      detailsViewHost.Content = top;
172    }
173
174    private IEnumerable<Resource> GetAvailableResourcesForProjectAdministration(Guid projectId) {
175      projectExclusiveResources.Clear();
176      if (projectId == Guid.Empty) return Enumerable.Empty<Resource>();
177      var resources = HiveAdminClient.Instance.Resources.Where(x => x.Id != Guid.Empty);
178      if (!resources.Any()) return resources;
179      if (IsAdmin()) return resources;
180
181      // get project specific assigned resources
182      var projectResources = resources.Where(x => 
183        HiveAdminClient.Instance.ProjectResourceAssignments
184          .Where(a => a.ProjectId == projectId)
185          .Select(a => a.ResourceId)
186        .Contains(x.Id));
187
188      // look up for assignments of ancestor projects
189      var projectIds = new HashSet<Guid>();
190      HiveClient.Instance.GetAvailableProjectAncestors(projectId).ToList().ForEach(x => projectIds.Add(x.Id));
191
192      var ancestorProjectResources = resources.Where(x => 
193        HiveAdminClient.Instance.ProjectResourceAssignments
194          .Where(a => projectIds.Contains(a.ProjectId))
195          .Select(a => a.ResourceId)
196        .Contains(x.Id));
197
198      // look down for included resources of ancestor projects
199      HashSet<Resource> availableResources = new HashSet<Resource>(ancestorProjectResources);
200      foreach (var r in ancestorProjectResources) {
201        foreach(var d in HiveAdminClient.Instance.GetAvailableResourceDescendants(r.Id)) {
202          availableResources.Add(d);
203        }
204      }
205
206      // determine resources, which are exclusively assigned to the currently selected project
207      projectResources
208        .Except(availableResources)
209        .ToList()
210        .ForEach(x => projectExclusiveResources.Add(x));
211
212      // look down for included resources of currently selected project
213      if (projectExclusiveResources.Any()) {
214        foreach (var r in projectExclusiveResources.ToArray()) {
215          foreach (var d in HiveAdminClient.Instance.GetAvailableResourceDescendants(r.Id)) {
216            projectExclusiveResources.Add(d);
217          } 
218        }
219      }
220
221      return availableResources.Union(projectExclusiveResources);
222    }
223
224    private IEnumerable<Resource> GetAssignedResourcesForProject(Guid projectId) {
225      if (projectId == Guid.Empty) return Enumerable.Empty<Resource>();
226      return HiveAdminClient.Instance.Resources.Where(x =>
227        HiveAdminClient.Instance.ProjectResourceAssignments
228          .Where(a => a.ProjectId == projectId)
229          .Select(a => a.ResourceId)
230        .Contains(x.Id));
231    }
232
233    private void SetAssignedProjectResources(Guid projectId, IEnumerable<Guid> resourceIds, bool reassign, bool cascading, bool reassignCascading) {
234      if (projectId == null || resourceIds == null) return;
235      HiveServiceLocator.Instance.CallHiveService(s => {
236       s.SaveProjectResourceAssignments(projectId, resourceIds.ToList(), reassign, cascading, reassignCascading);
237      });
238    }
239
240    private void UpdateNewAssignedResources() {
241      for(int i = newAssignedResources.Count -1; i >= 0; i--) {
242        if(newAssignedResources.Intersect(HiveAdminClient.Instance.GetAvailableResourceAncestors(newAssignedResources.ElementAt(i).Id)).Any()) {
243          newAssignedResources.Remove(newAssignedResources.ElementAt(i));
244        }
245      }
246    }
247
248    private void UpdateAssignedResources() {
249      assignedResources.Clear();
250      newAssignedResources.Clear();
251      foreach (var r in GetAssignedResourcesForProject(Content.Id)) {
252        assignedResources.Add(r);
253        newAssignedResources.Add(r);
254      }
255    }
256
257    private void UpdateIncludedResources() {
258      includedResources.Clear();
259      newIncludedResources.Clear();
260      foreach (var a in assignedResources) {
261        foreach (var r in HiveAdminClient.Instance.GetAvailableResourceDescendants(a.Id)) {
262          includedResources.Add(r);
263          newIncludedResources.Add(r);
264        }
265      }
266    }
267
268    private void UpdateNewIncludedResources() {
269      newIncludedResources.Clear();
270      foreach (var a in newAssignedResources) {
271        foreach (var r in HiveAdminClient.Instance.GetAvailableResourceDescendants(a.Id)) {
272          newIncludedResources.Add(r);
273        }
274      }
275    }
276
277    private Resource BuildResourceTree(IEnumerable<Resource> resources) {
278      treeView.Nodes.Clear();
279      if (!resources.Any()) return null;
280
281      treeView.BeforeCheck -= treeView_BeforeCheck;
282      treeView.AfterCheck -= treeView_AfterCheck;
283
284      resources = GetAvailableResourcesForProjectAdministration(Content.Id);
285
286      var mainResources = new HashSet<Resource>(resources.OfType<SlaveGroup>().Where(x => x.ParentResourceId == null));
287      var parentedMainResources = new HashSet<Resource>(resources.OfType<SlaveGroup>()
288        .Where(x => x.ParentResourceId.HasValue && !resources.Select(y => y.Id).Contains(x.ParentResourceId.Value)));
289      mainResources.UnionWith(parentedMainResources);
290      var subResources = new HashSet<Resource>(resources.Except(mainResources));
291
292      var stack = new Stack<Resource>(mainResources.OrderByDescending(x => x.Name));
293      Resource top = null;
294
295      TreeNode currentNode = null;
296      Resource currentResource = null;
297
298      var addedAssignments = newAssignedResources.Except(assignedResources);
299      var removedAssignments = assignedResources.Except(newAssignedResources);
300      var addedIncludes = newIncludedResources.Except(includedResources);
301      var removedIncludes = includedResources.Except(newIncludedResources);
302
303      while (stack.Any()) {
304        if(top == null)  top = stack.Peek();
305        var newResource = stack.Pop();
306        var newNode = new TreeNode(newResource.Name) { Tag = newResource };
307
308        // search for parent node of newNode and save in currentNode
309        // necessary since newNodes (stack top items) might be siblings
310        // or grand..grandparents of previous node (currentNode)
311        while (currentNode != null && newResource.ParentResourceId != currentResource.Id) {
312          currentNode = currentNode.Parent;
313          currentResource = currentNode == null ? null : (Resource)currentNode.Tag;
314        }
315
316        if (currentNode == null) {
317          treeView.Nodes.Add(newNode);
318        } else {
319          currentNode.Nodes.Add(newNode);
320        }
321
322        if (newAssignedResources.Contains(newResource)) {
323          newNode.Checked = true;
324          if(!HiveRoles.CheckAdminUserPermissions()) {
325            if (!HiveAdminClient.Instance.GetAvailableProjectAncestors(Content.Id).Any() 
326              || projectExclusiveResources.Contains(newResource)) {
327              newNode.ForeColor = SystemColors.GrayText;
328              newNode.Text += IMMUTABLE_TAG;
329            }
330          }
331
332        } else if (newIncludedResources.Contains(newResource)) {
333          newNode.Checked = true;
334          newNode.ForeColor = SystemColors.GrayText;
335        }
336
337          if (includedResources.Contains(newResource) && newIncludedResources.Contains(newResource)) {
338          newNode.Text += INCLUDED_TAG;
339        } else if (addedIncludes.Contains(newResource)) {
340          newNode.BackColor = addedIncludeColor;
341          newNode.ForeColor = SystemColors.GrayText;
342          newNode.Text += ADDED_INCLUDE_TAG;
343        } else if (removedIncludes.Contains(newResource)) {
344          newNode.BackColor = removedIncludeColor;
345          newNode.Text += REMOVED_INCLUDE_TAG;
346        }
347
348        if (addedAssignments.Contains(newResource)) {
349          newNode.BackColor = addedAssignmentColor;
350          newNode.ForeColor = SystemColors.ControlText;
351          newNode.Text += ADDED_ASSIGNMENT_TAG;
352        } else if (removedAssignments.Contains(newResource)) {
353          newNode.BackColor = removedAssignmentColor;
354          newNode.ForeColor = SystemColors.ControlText;
355          newNode.Text += REMOVED_ASSIGNMENT_TAG;
356        }
357
358        if (newResource is Slave) {
359          newNode.ImageIndex = slaveImageIndex;
360        } else {
361          newNode.ImageIndex = slaveGroupImageIndex;
362
363          var childResources = subResources.Where(x => x.ParentResourceId == newResource.Id);
364          if (childResources.Any()) {
365            foreach (var resource in childResources.OrderByDescending(x => x.Name)) {
366              subResources.Remove(resource);
367              stack.Push(resource);
368            }
369            currentNode = newNode;
370            currentResource = newResource;
371          }
372        }
373        newNode.SelectedImageIndex = newNode.ImageIndex;
374      }
375
376      var ungroupedSlaves = subResources.OfType<Slave>().OrderBy(x => x.Name);
377      if(ungroupedSlaves.Any()) {
378        ungroupedGroupNode = new TreeNode(UNGROUPED_GROUP_NAME) {
379          ForeColor = SystemColors.GrayText,
380          Tag = new SlaveGroup() {
381            Name = UNGROUPED_GROUP_NAME,
382            Description = UNGROUPED_GROUP_DESCRIPTION
383          }
384        };
385
386        foreach (var slave in ungroupedSlaves) {
387          var slaveNode = new TreeNode(slave.Name) { Tag = slave };
388          ungroupedGroupNode.Nodes.Add(slaveNode);
389        }
390        treeView.Nodes.Add(ungroupedGroupNode);
391      } else {
392        ungroupedGroupNode?.Nodes.Clear();
393      }
394
395      treeView.BeforeCheck += treeView_BeforeCheck;
396      treeView.AfterCheck += treeView_AfterCheck;
397      treeView.ExpandAll();
398
399      return top;
400    }
401
402    private bool IsAdmin() {
403      return HiveRoles.CheckAdminUserPermissions();
404    }
405
406    #endregion
407  }
408}
Note: See TracBrowser for help on using the repository browser.