Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Optimization.Views/3.3/ExperimentTreeView.cs @ 6524

Last change on this file since 6524 was 6524, checked in by mkommend, 12 years ago

#1555: ExperimentTreeView

  • Corrected flickering during item image update
  • Corrected state of details view host during algorithm execution (readonly, locked)
  • Added algorithm child nodes (problem, parameters, results)
File size: 36.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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;
24using System.Collections.Generic;
25using System.Drawing;
26using System.Linq;
27using System.Windows.Forms;
28using HeuristicLab.Collections;
29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.Core.Views;
32using HeuristicLab.MainForm;
33using HeuristicLab.PluginInfrastructure;
34
35namespace HeuristicLab.Optimization.Views {
36  public sealed partial class ExperimentTreeView : ItemView {
37    private TypeSelectorDialog typeSelectorDialog;
38    private Dictionary<INamedItem, List<TreeNode>> treeNodeTagMapping;
39
40    public ExperimentTreeView() {
41      InitializeComponent();
42      treeNodeTagMapping = new Dictionary<INamedItem, List<TreeNode>>();
43    }
44
45    protected override void Dispose(bool disposing) {
46      if (disposing) {
47        if (typeSelectorDialog != null) typeSelectorDialog.Dispose();
48        if (components != null) components.Dispose();
49      }
50      base.Dispose(disposing);
51    }
52
53    #region necessary code to handle dock correctly regarding the expanded nodes
54    bool[] expandendedState;
55    protected override void OnHandleCreated(EventArgs e) {
56      base.OnHandleCreated(e);
57      if (expandendedState == null) return;
58      var nodes = IterateTreeNodes().ToList();
59      for (int i = 0; i < nodes.Count; i++)
60        if (expandendedState[i]) nodes[i].Expand();
61    }
62    protected override void OnHandleDestroyed(EventArgs e) {
63      base.OnHandleDestroyed(e);
64      var nodes = IterateTreeNodes().ToList();
65      expandendedState = new bool[nodes.Count];
66      for (int i = 0; i < nodes.Count; i++)
67        expandendedState[i] = nodes[i].IsExpanded;
68    }
69    #endregion
70
71    public new Experiment Content {
72      get { return (Experiment)base.Content; }
73      set { base.Content = value; }
74    }
75
76    #region events registration
77    protected override void RegisterContentEvents() {
78      base.RegisterContentEvents();
79      Content.ExecutionStateChanged += new EventHandler(Content_ExecutionStateChanged);
80      Content.Optimizers.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsAdded);
81      Content.Optimizers.ItemsMoved += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsMoved);
82      Content.Optimizers.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsRemoved);
83      Content.Optimizers.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsReplaced);
84      Content.Optimizers.CollectionReset += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_CollectionReset);
85    }
86
87    protected override void DeregisterContentEvents() {
88      Content.ExecutionStateChanged -= new EventHandler(Content_ExecutionStateChanged);
89      Content.Optimizers.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsAdded);
90      Content.Optimizers.ItemsMoved -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsMoved);
91      Content.Optimizers.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsRemoved);
92      Content.Optimizers.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsReplaced);
93      Content.Optimizers.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_CollectionReset);
94      foreach (var optimizer in treeNodeTagMapping.Keys)
95        DeregisterNamedItemEvents(optimizer);
96      base.DeregisterContentEvents();
97    }
98
99    private void RegisterNamedItemEvents(INamedItem namedItem) {
100      namedItem.ToStringChanged += new EventHandler(namedItem_ToStringChanged);
101      namedItem.ItemImageChanged += new EventHandler(namedItem_ItemImageChanged);
102
103      var algorithm = namedItem as IAlgorithm;
104      var batchRun = namedItem as BatchRun;
105      var experiment = namedItem as Experiment;
106
107      if (algorithm != null) {
108        algorithm.ProblemChanged += new EventHandler(algorithm_ProblemChanged);
109      } else if (batchRun != null) {
110        batchRun.OptimizerChanged += new EventHandler(batchRun_OptimizerChanged);
111      } else if (experiment != null) {
112        experiment.Optimizers.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsAdded);
113        experiment.Optimizers.ItemsMoved += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsMoved);
114        experiment.Optimizers.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsRemoved);
115        experiment.Optimizers.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsReplaced);
116        experiment.Optimizers.CollectionReset += new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_CollectionReset);
117      }
118    }
119
120
121
122    private void DeregisterNamedItemEvents(INamedItem namedItem) {
123      namedItem.ToStringChanged -= new EventHandler(namedItem_ToStringChanged);
124      namedItem.ItemImageChanged -= new EventHandler(namedItem_ItemImageChanged);
125
126      var algorithm = namedItem as IAlgorithm;
127      var batchRun = namedItem as BatchRun;
128      var experiment = namedItem as Experiment;
129      if (algorithm != null) {
130        algorithm.ProblemChanged -= new EventHandler(algorithm_ProblemChanged);
131      } else if (batchRun != null) {
132        batchRun.OptimizerChanged -= new EventHandler(batchRun_OptimizerChanged);
133      } else if (experiment != null) {
134        experiment.Optimizers.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsAdded);
135        experiment.Optimizers.ItemsMoved -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsMoved);
136        experiment.Optimizers.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsRemoved);
137        experiment.Optimizers.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_ItemsReplaced);
138        experiment.Optimizers.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedItem<IOptimizer>>(Optimizers_CollectionReset);
139      }
140    }
141    #endregion
142
143    protected override void OnContentChanged() {
144      base.OnContentChanged();
145      if (Content == null) {
146        treeView.Nodes.Clear();
147      } else {
148        UpdateOptimizerTreeView();
149        treeView.ExpandAll();
150      }
151    }
152
153    #region content events
154    private void Content_ExecutionStateChanged(object sender, EventArgs e) {
155      if (InvokeRequired) {
156        Invoke((Action<object, EventArgs>)Content_ExecutionStateChanged, sender, e);
157        return;
158      }
159      SetEnabledStateOfControls();
160    }
161
162    private void algorithm_ProblemChanged(object sender, EventArgs e) {
163      if (InvokeRequired) {
164        Invoke((Action<object, EventArgs>)algorithm_ProblemChanged, sender, e);
165        return;
166      }
167
168      var algorithm = (IAlgorithm)sender;
169      foreach (TreeNode node in treeNodeTagMapping[algorithm]) {
170        foreach (TreeNode childNode in node.Nodes.OfType<TreeNode>().ToList()) {
171          DisposeTreeNode(childNode);
172          childNode.Remove();
173        }
174        foreach (TreeNode childNode in CreateAlgorithmChildNodes(algorithm))
175          node.Nodes.Add(childNode);
176        node.Expand();
177      }
178
179      RebuildImageList();
180      UpdateDetailsViewHost();
181    }
182
183    private void batchRun_OptimizerChanged(object sender, EventArgs e) {
184      if (InvokeRequired) {
185        Invoke((Action<object, EventArgs>)batchRun_OptimizerChanged, sender, e);
186        return;
187      }
188      var batchRun = (BatchRun)sender;
189      foreach (TreeNode node in treeNodeTagMapping[batchRun]) {
190        foreach (TreeNode childNode in node.Nodes.OfType<TreeNode>().ToList()) {
191          DisposeTreeNode(childNode);
192          childNode.Remove();
193        }
194
195        if (batchRun.Optimizer != null) {
196          UpdateChildTreeNodes(node.Nodes, batchRun);
197          node.Expand();
198        }
199      }
200      RebuildImageList();
201      UpdateDetailsViewHost();
202    }
203
204    private void Optimizers_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>> e) {
205      if (InvokeRequired) {
206        Invoke((Action<object, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>>>)Optimizers_ItemsAdded, sender, e);
207        return;
208      }
209
210      var optimizerList = (OptimizerList)sender;
211      IEnumerable<TreeNodeCollection> parentNodes;
212      if (optimizerList == Content.Optimizers) parentNodes = new List<TreeNodeCollection>() { treeView.Nodes };
213      else {
214        Experiment experiment = treeNodeTagMapping.Keys.OfType<Experiment>().Where(exp => exp.Optimizers == optimizerList).First();
215        parentNodes = treeNodeTagMapping[experiment].Select(node => node.Nodes);
216      }
217
218      foreach (TreeNodeCollection parentNode in parentNodes) {
219        foreach (var childOptimizer in e.Items) {
220          TreeNode childNode = CreateTreeNode(childOptimizer.Value);
221          UpdateChildTreeNodes(childNode.Nodes, childOptimizer.Value);
222          parentNode.Insert(childOptimizer.Index, childNode);
223          childNode.ExpandAll();
224          if (childNode.Parent != null) childNode.Parent.ExpandAll();
225        }
226      }
227      RebuildImageList();
228    }
229    private void Optimizers_ItemsMoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>> e) {
230      if (InvokeRequired) {
231        Invoke((Action<object, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>>>)Optimizers_ItemsMoved, sender, e);
232        return;
233      }
234
235      var optimizerList = (OptimizerList)sender;
236      IEnumerable<TreeNodeCollection> parentNodes;
237      if (optimizerList == Content.Optimizers) parentNodes = new List<TreeNodeCollection>() { treeView.Nodes };
238      else {
239        Experiment experiment = treeNodeTagMapping.Keys.OfType<Experiment>().Where(exp => exp.Optimizers == optimizerList).First();
240        parentNodes = treeNodeTagMapping[experiment].Select(node => node.Nodes);
241      }
242
243      foreach (TreeNodeCollection parentNode in parentNodes) {
244        //get all effected child nodes
245        foreach (TreeNode childNode in parentNode.OfType<TreeNode>()
246          .Where(n => e.OldItems.Select(x => x.Value).Contains((IOptimizer)n.Tag)).ToList()) {
247          DisposeTreeNode(childNode);
248          childNode.Remove();
249        }
250
251        foreach (var childOptimizer in e.Items) {
252          TreeNode childNode = CreateTreeNode(childOptimizer.Value);
253          UpdateChildTreeNodes(childNode.Nodes, childOptimizer.Value);
254          childNode.ExpandAll();
255          parentNode.Insert(childOptimizer.Index, childNode);
256        }
257      }
258      RebuildImageList();
259      UpdateDetailsViewHost();
260    }
261    private void Optimizers_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>> e) {
262      if (InvokeRequired) {
263        Invoke((Action<object, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>>>)Optimizers_ItemsRemoved, sender, e);
264        return;
265      }
266
267      var optimizerList = (OptimizerList)sender;
268      IEnumerable<TreeNodeCollection> parentNodes;
269      if (optimizerList == Content.Optimizers) parentNodes = new List<TreeNodeCollection>() { treeView.Nodes };
270      else {
271        Experiment experiment = treeNodeTagMapping.Keys.OfType<Experiment>().Where(exp => exp.Optimizers == optimizerList).First();
272        parentNodes = treeNodeTagMapping[experiment].Select(node => node.Nodes);
273      }
274
275      foreach (TreeNodeCollection parentNode in parentNodes) {
276        foreach (var childOptimizer in e.Items) {
277          TreeNode childNode = parentNode[childOptimizer.Index];
278          DisposeTreeNode(childNode);
279          childNode.Remove();
280        }
281      }
282      RebuildImageList();
283      UpdateDetailsViewHost();
284    }
285    private void Optimizers_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>> e) {
286      if (InvokeRequired) {
287        Invoke((Action<object, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>>>)Optimizers_ItemsReplaced, sender, e);
288        return;
289      }
290
291      var optimizerList = (OptimizerList)sender;
292      IEnumerable<TreeNodeCollection> parentNodes;
293      if (optimizerList == Content.Optimizers) parentNodes = new List<TreeNodeCollection>() { treeView.Nodes };
294      else {
295        Experiment experiment = treeNodeTagMapping.Keys.OfType<Experiment>().Where(exp => exp.Optimizers == optimizerList).First();
296        parentNodes = treeNodeTagMapping[experiment].Select(node => node.Nodes);
297      }
298
299      foreach (TreeNodeCollection parentNode in parentNodes) {
300        foreach (var childOptimizer in e.OldItems) {
301          TreeNode childNode = parentNode.Cast<TreeNode>().Where(n => n.Tag == childOptimizer.Value && n.Index == childOptimizer.Index).First();
302          DisposeTreeNode(childNode);
303          childNode.Remove();
304        }
305        foreach (var childOptimizer in e.Items) {
306          TreeNode childNode = CreateTreeNode(childOptimizer.Value);
307          UpdateChildTreeNodes(childNode.Nodes, childOptimizer.Value);
308          parentNode.Insert(childOptimizer.Index, childNode);
309        }
310      }
311      RebuildImageList();
312      UpdateDetailsViewHost();
313    }
314    private void Optimizers_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>> e) {
315      if (InvokeRequired) {
316        Invoke((Action<object, CollectionItemsChangedEventArgs<IndexedItem<IOptimizer>>>)Optimizers_CollectionReset, sender, e);
317        return;
318      }
319
320      var optimizerList = (OptimizerList)sender;
321      IEnumerable<TreeNodeCollection> parentNodes;
322      if (optimizerList == Content.Optimizers) parentNodes = new List<TreeNodeCollection>() { treeView.Nodes };
323      else {
324        Experiment experiment = treeNodeTagMapping.Keys.OfType<Experiment>().Where(exp => exp.Optimizers == optimizerList).First();
325        parentNodes = treeNodeTagMapping[experiment].Select(node => node.Nodes);
326      }
327
328      foreach (TreeNodeCollection parentNode in parentNodes) {
329        foreach (var childOptimizer in e.OldItems) {
330          TreeNode childNode = parentNode.Cast<TreeNode>().Where(n => n.Tag == childOptimizer.Value && n.Index == childOptimizer.Index).First();
331          DisposeTreeNode(childNode);
332          childNode.Remove();
333        }
334        foreach (var childOptimizer in e.Items) {
335          TreeNode childNode = CreateTreeNode(childOptimizer.Value);
336          UpdateChildTreeNodes(childNode.Nodes, childOptimizer.Value);
337          parentNode.Insert(childOptimizer.Index, childNode);
338        }
339      }
340      RebuildImageList();
341      UpdateDetailsViewHost();
342    }
343
344    private void namedItem_ToStringChanged(object sender, EventArgs e) {
345      if (InvokeRequired) {
346        Invoke((Action<object, EventArgs>)namedItem_ToStringChanged, sender, e);
347        return;
348      }
349      var namedItem = (INamedItem)sender;
350      foreach (TreeNode node in treeNodeTagMapping[namedItem])
351        node.Text = namedItem.ToString();
352    }
353
354    private void namedItem_ItemImageChanged(object sender, EventArgs e) {
355      if (InvokeRequired) {
356        Invoke((Action<object, EventArgs>)namedItem_ItemImageChanged, sender, e);
357        return;
358      }
359      INamedItem namedItem = (INamedItem)sender;
360      foreach (TreeNode node in treeNodeTagMapping[namedItem]) {
361        treeView.ImageList.Images[node.ImageIndex] = namedItem.ItemImage;
362        node.ImageIndex = node.ImageIndex;
363      }
364      SetEnabledStateOfControls();
365    }
366    #endregion
367
368    protected override void PropagateStateChanges(Control control, Type type, System.Reflection.PropertyInfo propertyInfo) {
369      return;
370    }
371
372    protected override void SetEnabledStateOfControls() {
373      base.SetEnabledStateOfControls();
374      IOptimizer optimizer = null;
375      IAlgorithm algorithm = null;
376      BatchRun batchRun = null;
377      Experiment experiment = null;
378
379      IOptimizer parentOptimizer = null;
380      Experiment parentExperiment = null;
381
382      if (treeView.SelectedNode != null) {
383        optimizer = treeView.SelectedNode.Tag as IOptimizer;
384        algorithm = optimizer as IAlgorithm;
385        batchRun = optimizer as BatchRun;
386        experiment = optimizer as Experiment;
387
388        if (treeView.SelectedNode.Parent != null) parentOptimizer = treeView.SelectedNode.Parent.Tag as IOptimizer;
389        else parentOptimizer = Content;
390
391        parentExperiment = parentOptimizer as Experiment;
392      }
393
394      treeView.Enabled = Content != null;
395      if (parentOptimizer != null) {
396        detailsViewHost.ReadOnly = parentOptimizer.ExecutionState == ExecutionState.Started;
397        detailsViewHost.Locked = parentOptimizer.ExecutionState == ExecutionState.Started;
398      }
399
400      addButton.Enabled = Content != null && !Locked && !ReadOnly &&
401        (treeView.SelectedNode == null || experiment != null || (batchRun != null && batchRun.Optimizer == null) || (algorithm != null && algorithm.Problem == null));
402      moveUpButton.Enabled = Content != null && !Locked && !ReadOnly &&
403        treeView.SelectedNode != null && treeView.SelectedNode.PrevNode != null && parentExperiment != null;
404      moveDownButton.Enabled = Content != null && !Locked && !ReadOnly &&
405        treeView.SelectedNode != null && treeView.SelectedNode.NextNode != null && parentExperiment != null;
406      removeButton.Enabled = Content != null && !Locked && !ReadOnly && optimizer != null;
407    }
408
409    private void UpdateOptimizerTreeView() {
410      treeView.Nodes.Clear();
411      UpdateChildTreeNodes(treeView.Nodes, Content);
412      RebuildImageList();
413    }
414
415    private void UpdateChildTreeNodes(TreeNodeCollection collection, IOptimizer optimizer) {
416      var batchRun = optimizer as BatchRun;
417      var experiment = optimizer as Experiment;
418
419      if (batchRun != null && batchRun.Optimizer != null) UpdateChildTreeNodes(collection, new List<IOptimizer>() { batchRun.Optimizer });
420      else if (experiment != null) UpdateChildTreeNodes(collection, experiment.Optimizers);
421    }
422    private void UpdateChildTreeNodes(TreeNodeCollection collection, IEnumerable<IOptimizer> optimizers) {
423      foreach (IOptimizer optimizer in optimizers) {
424        var node = CreateTreeNode(optimizer);
425        collection.Add(node);
426        UpdateChildTreeNodes(node.Nodes, optimizer);
427      }
428    }
429
430
431    #region drag & drop
432    private void optimizerTreeView_ItemDrag(object sender, ItemDragEventArgs e) {
433      if (Locked) return;
434
435      TreeNode selectedNode = (TreeNode)e.Item;
436      var item = (IItem)selectedNode.Tag;
437      DataObject data = new DataObject();
438      data.SetData(HeuristicLab.Common.Constants.DragDropDataFormat, item);
439      validDragOperation = true;
440
441      if (ReadOnly || !(item is IOptimizer)) {
442        DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link);
443      } else {
444        DragDropEffects result = DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link | DragDropEffects.Move);
445        if ((result & DragDropEffects.Move) == DragDropEffects.Move) {
446          var optimizer = (IOptimizer)item;
447          if (selectedNode.Parent == null) Content.Optimizers.Remove(optimizer);
448          else {
449            var parentOptimizer = (IOptimizer)selectedNode.Parent.Tag;
450            var parentBatchRun = parentOptimizer as BatchRun;
451            var parentExperiment = parentOptimizer as Experiment;
452            if (parentBatchRun != null) parentBatchRun.Optimizer = null;
453            else if (parentExperiment != null) parentExperiment.Optimizers.Remove(optimizer);
454            else throw new NotSupportedException("Handling for specific type not implemented" + parentOptimizer.GetType());
455          }
456          SetEnabledStateOfControls();
457          UpdateDetailsViewHost();
458          RebuildImageList();
459        }
460      }
461    }
462
463    private bool validDragOperation = false;
464    private void optimizerTreeView_DragEnter(object sender, DragEventArgs e) {
465      validDragOperation = false;
466      if (!ReadOnly) {
467        if ((e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) is IOptimizer)) validDragOperation = true;
468        else if (e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) is IEnumerable) {
469          validDragOperation = true;
470          IEnumerable items = (IEnumerable)e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
471          foreach (object item in items)
472            validDragOperation = validDragOperation && (item is IOptimizer);
473        }
474      }
475    }
476    private void optimizerTreeView_DragOver(object sender, DragEventArgs e) {
477      e.Effect = DragDropEffects.None;
478      if (validDragOperation) {
479        Point coordinates = treeView.PointToClient(new Point(e.X, e.Y));
480        TreeNode node = treeView.GetNodeAt(coordinates);
481        Experiment experiment = null;
482        BatchRun batchRun = null;
483
484        if (node == null) experiment = Content;
485        else {
486          experiment = node.Tag as Experiment;
487          batchRun = node.Tag as BatchRun;
488        }
489
490        if (batchRun == null && experiment == null) return;
491        if (batchRun != null) {
492          var optimizer = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) as IOptimizer;
493          if (optimizer == null) return;
494          if (batchRun.Optimizer != null) return;
495          if (optimizer.GetObjectGraphObjects().OfType<IOptimizer>().Contains(batchRun)) return;
496        }
497
498        //do not allow recursive nesting of contents
499        if (experiment != null) {
500          var optimizer = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) as IOptimizer;
501          IEnumerable<IOptimizer> optimizers = null;
502          var enumerable = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) as IEnumerable;
503          if (enumerable != null) optimizers = enumerable.Cast<IOptimizer>();
504
505          if (optimizer != null && optimizer.GetObjectGraphObjects().OfType<IOptimizer>().Contains(experiment)) return;
506          if (optimizers != null && optimizers.GetObjectGraphObjects().OfType<IOptimizer>().Contains(experiment)) return;
507        }
508
509        if ((e.KeyState & 32) == 32) e.Effect = DragDropEffects.Link;  // ALT key
510        else if ((e.KeyState & 4) == 4) e.Effect = DragDropEffects.Move;  // SHIFT key
511        else if (e.AllowedEffect.HasFlag(DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy;
512        else if (e.AllowedEffect.HasFlag(DragDropEffects.Move)) e.Effect = DragDropEffects.Move;
513        else if (e.AllowedEffect.HasFlag(DragDropEffects.Link)) e.Effect = DragDropEffects.Link;
514      }
515    }
516    private void optimizerTreeView_DragDrop(object sender, DragEventArgs e) {
517      Point coordinates = treeView.PointToClient(new Point(e.X, e.Y));
518      TreeNode node = treeView.GetNodeAt(coordinates);
519      Experiment experiment = null;
520      BatchRun batchRun = null;
521
522      if (node == null) experiment = Content;
523      else {
524        experiment = node.Tag as Experiment;
525        batchRun = node.Tag as BatchRun;
526      }
527
528      if (e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) is IOptimizer) {
529        IOptimizer optimizer = (IOptimizer)e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
530        if (e.Effect.HasFlag(DragDropEffects.Copy)) optimizer = (IOptimizer)optimizer.Clone();
531        if (batchRun != null) batchRun.Optimizer = optimizer;
532        else if (experiment != null) experiment.Optimizers.Add(optimizer);
533        else throw new NotSupportedException("Handling for specific type not implemented" + node.Tag.GetType());
534      } else if (e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) is IEnumerable) {
535        IEnumerable<IOptimizer> optimizers = ((IEnumerable)e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat)).Cast<IOptimizer>();
536        if (e.Effect.HasFlag(DragDropEffects.Copy)) {
537          Cloner cloner = new Cloner();
538          optimizers = optimizers.Select(o => (IOptimizer)o.Clone(cloner));
539        }
540        if (experiment != null) experiment.Optimizers.AddRange(optimizers);
541        else throw new NotSupportedException("Handling for specific type not implemented" + node.Tag.GetType());
542      }
543    }
544    #endregion
545
546    #region control events
547    private void optimizerTreeView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) {
548      if (rightClickOccured) return;
549      if (e.X < e.Node.Bounds.Left || e.X > e.Node.Bounds.Right) return;
550      e.Node.Toggle();
551      IContent optimizer = (IContent)e.Node.Tag;
552      MainFormManager.MainForm.ShowContent(optimizer);
553    }
554    private void optimizerTreeview_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
555      if (e.X < e.Node.Bounds.Left || e.X > e.Node.Bounds.Right) return;
556      treeView.SelectedNode = e.Node;
557      detailsViewHost.Content = (IContent)e.Node.Tag;
558      SetEnabledStateOfControls();
559    }
560    private void optimizerTreeView_MouseDown(object sender, MouseEventArgs e) {
561      // enables deselection of treeNodes
562      if (e.Button != MouseButtons.Right) rightClickOccured = false;
563      if (treeView.SelectedNode == null) return;
564      Point coordinates = new Point(e.X, e.Y);
565      TreeNode node = treeView.GetNodeAt(coordinates);
566      if (node == null || coordinates.X < node.Bounds.Left || coordinates.X > node.Bounds.Right) {
567        treeView.SelectedNode = null;
568        detailsViewHost.Content = null;
569        SetEnabledStateOfControls();
570      }
571    }
572
573
574    private void optimizerTreeView_KeyDown(object sender, KeyEventArgs e) {
575      if (ReadOnly) return;
576      if (e.KeyCode != Keys.Delete) return;
577      if (treeView.SelectedNode == null) return;
578      if (!(treeView.SelectedNode.Tag is IOptimizer)) return;
579
580      var treeNode = treeView.SelectedNode;
581      var optimizer = (IOptimizer)treeNode.Tag;
582
583      if (treeNode.Parent == null)
584        Content.Optimizers.Remove(optimizer);
585      else {
586        var batchRun = treeNode.Parent.Tag as BatchRun;
587        var experiment = treeNode.Parent.Tag as Experiment;
588        if (batchRun != null) batchRun.Optimizer = null;
589        else if (experiment != null) experiment.Optimizers.Remove(optimizer);
590        else throw new NotSupportedException("Handling for specific type not implemented" + treeView.SelectedNode.Tag.GetType());
591      }
592      SetEnabledStateOfControls();
593      UpdateDetailsViewHost();
594      RebuildImageList();
595    }
596
597    private bool rightClickOccured = true;
598    private TreeNode toolStripMenuNode = null;
599    private void optimizerTreeView_RightClick(object sender, EventArgs e) {
600      rightClickOccured = true;
601      Point coordinates = treeView.PointToClient(Cursor.Position);
602      toolStripMenuNode = treeView.GetNodeAt(coordinates);
603
604      if (toolStripMenuNode != null && coordinates.X >= toolStripMenuNode.Bounds.Left && coordinates.X <= toolStripMenuNode.Bounds.Right) {
605        treeView.SelectedNode = toolStripMenuNode;
606        detailsViewHost.Content = (IContent)toolStripMenuNode.Tag;
607        SetEnabledStateOfControls();
608
609        ExpandToolStripMenuItem.Enabled = !toolStripMenuNode.IsExpanded && toolStripMenuNode.Nodes.Count > 0;
610        ExpandToolStripMenuItem.Visible = !toolStripMenuNode.IsExpanded && toolStripMenuNode.Nodes.Count > 0;
611        CollapseToolStripMenuItem.Enabled = toolStripMenuNode.IsExpanded;
612        CollapseToolStripMenuItem.Visible = toolStripMenuNode.IsExpanded;
613        if (contextMenuStrip.Items.Cast<ToolStripMenuItem>().Any(item => item.Enabled))
614          contextMenuStrip.Show(Cursor.Position);
615      }
616    }
617
618    private void ExpandToolStripMenuItem_Click(object sender, EventArgs e) {
619      if (toolStripMenuNode != null) toolStripMenuNode.ExpandAll();
620    }
621    private void CollapseToolStripMenuItem_Click(object sender, EventArgs e) {
622      if (toolStripMenuNode != null) toolStripMenuNode.Collapse();
623    }
624
625    private void addButton_Click(object sender, System.EventArgs e) {
626      if (typeSelectorDialog == null) typeSelectorDialog = new TypeSelectorDialog();
627
628      IAlgorithm algorithm = null;
629      if (treeView.SelectedNode != null && (treeView.SelectedNode.Tag is IAlgorithm))
630        algorithm = (IAlgorithm)treeView.SelectedNode.Tag;
631
632      if (algorithm == null) {
633        typeSelectorDialog.Caption = "Select Optimizer";
634        typeSelectorDialog.TypeSelector.Caption = "Available Optimizers";
635        typeSelectorDialog.TypeSelector.Configure(typeof(IOptimizer), false, true);
636      } else {
637        typeSelectorDialog.Caption = "Select Problem";
638        typeSelectorDialog.TypeSelector.Caption = "Available Problems";
639        typeSelectorDialog.TypeSelector.Configure(algorithm.ProblemType, false, true);
640      }
641
642      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
643        try {
644          if (algorithm == null) {
645            IOptimizer optimizer = (IOptimizer)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
646            if (treeView.SelectedNode == null) Content.Optimizers.Add(optimizer);
647            else {
648              var batchRun = treeView.SelectedNode.Tag as BatchRun;
649              var experiment = treeView.SelectedNode.Tag as Experiment;
650              if (batchRun != null) batchRun.Optimizer = optimizer;
651              else if (experiment != null) experiment.Optimizers.Add(optimizer);
652              else throw new NotSupportedException("Handling for specific type not implemented" + treeView.SelectedNode.Tag.GetType());
653            }
654          } else {
655            IProblem problem = (IProblem)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
656            algorithm.Problem = problem;
657          }
658        }
659        catch (Exception ex) {
660          ErrorHandling.ShowErrorDialog(this, ex);
661        }
662      }
663    }
664
665    private void moveUpButton_Click(object sender, EventArgs e) {
666      var optimizer = (IOptimizer)treeView.SelectedNode.Tag;
667      Experiment experiment = null;
668      if (treeView.SelectedNode.Parent == null) experiment = Content;
669      else experiment = (Experiment)treeView.SelectedNode.Parent.Tag;
670
671      int index = treeView.SelectedNode.Index;
672      experiment.Optimizers.Reverse(index - 1, 2);
673      treeView.SelectedNode = treeNodeTagMapping[optimizer].First();
674      SetEnabledStateOfControls();
675      UpdateDetailsViewHost();
676      RebuildImageList();
677    }
678    private void moveDownButton_Click(object sender, EventArgs e) {
679      var optimizer = (IOptimizer)treeView.SelectedNode.Tag;
680      Experiment experiment = null;
681      if (treeView.SelectedNode.Parent == null) experiment = Content;
682      else experiment = (Experiment)treeView.SelectedNode.Parent.Tag;
683
684      int index = treeView.SelectedNode.Index;
685      experiment.Optimizers.Reverse(index, 2);
686      treeView.SelectedNode = treeNodeTagMapping[optimizer].First();
687      SetEnabledStateOfControls();
688      UpdateDetailsViewHost();
689      RebuildImageList();
690    }
691
692    private void removeButton_Click(object sender, EventArgs e) {
693      var treeNode = treeView.SelectedNode;
694      var optimizer = treeNode.Tag as IOptimizer;
695
696      if (treeNode.Parent == null)
697        Content.Optimizers.Remove(optimizer);
698      else {
699        var batchRun = treeNode.Parent.Tag as BatchRun;
700        var experiment = treeNode.Parent.Tag as Experiment;
701        if (batchRun != null) batchRun.Optimizer = null;
702        else if (experiment != null) experiment.Optimizers.Remove(optimizer);
703        else throw new NotSupportedException("Handling for specific type not implemented" + treeView.SelectedNode.Tag.GetType());
704      }
705      SetEnabledStateOfControls();
706      UpdateDetailsViewHost();
707      RebuildImageList();
708    }
709
710    private void showDetailsCheckBox_CheckedChanged(object sender, System.EventArgs e) {
711      if (showDetailsCheckBox.Checked) {
712        splitContainer.Panel2Collapsed = false;
713        detailsGroupBox.Enabled = treeView.SelectedNode != null;
714        detailsViewHost.Content = treeView.SelectedNode != null ? (IContent)treeView.SelectedNode.Tag : null;
715      } else {
716        splitContainer.Panel2Collapsed = true;
717        detailsViewHost.Content = null;
718      }
719    }
720    #endregion
721
722    #region helpers
723    private void UpdateDetailsViewHost() {
724      if (treeView.SelectedNode != null)
725        detailsViewHost.Content = (IContent)treeView.SelectedNode.Tag;
726      else
727        detailsViewHost.Content = null;
728    }
729
730    private TreeNode CreateTreeNode(IOptimizer optimizer) {
731      TreeNode node = new TreeNode(optimizer.ToString());
732      node.Tag = optimizer;
733
734      var algorithm = optimizer as IAlgorithm;
735      if (algorithm != null) {
736        foreach (TreeNode childNode in CreateAlgorithmChildNodes(algorithm))
737          node.Nodes.Add(childNode);
738      }
739
740      List<TreeNode> nodes;
741      if (!treeNodeTagMapping.TryGetValue(optimizer, out nodes)) {
742        nodes = new List<TreeNode>();
743        treeNodeTagMapping.Add(optimizer, nodes);
744        RegisterNamedItemEvents(optimizer);
745      }
746      nodes.Add(node);
747
748      foreach (TreeNode childNode in node.Nodes) {
749        NamedItem namedItem = childNode.Tag as NamedItem;
750        if (namedItem != null) {
751          if (!treeNodeTagMapping.TryGetValue(namedItem, out nodes)) {
752            nodes = new List<TreeNode>();
753            treeNodeTagMapping.Add(namedItem, nodes);
754            RegisterNamedItemEvents(namedItem);
755          }
756          nodes.Add(childNode);
757        }
758      }
759      return node;
760    }
761
762    private IEnumerable<TreeNode> CreateAlgorithmChildNodes(IAlgorithm algorithm) {
763      TreeNode problemNode;
764      if (algorithm.Problem != null) {
765        problemNode = new TreeNode(algorithm.Problem.Name);
766        problemNode.Tag = algorithm.Problem;
767      } else {
768        problemNode = new TreeNode("No Problem");
769        problemNode.Tag = null;
770      }
771      TreeNode parametersNode = new TreeNode("Parameters");
772      parametersNode.Tag = algorithm.Parameters;
773      TreeNode resultsNode = new TreeNode("Results");
774      resultsNode.Tag = algorithm.Results;
775
776      yield return problemNode;
777      yield return parametersNode;
778      yield return resultsNode;
779    }
780
781    private void DisposeTreeNode(TreeNode node) {
782      var namedItem = node.Tag as INamedItem;
783      if (namedItem == null) return;
784
785      List<TreeNode> nodes;
786      if (!treeNodeTagMapping.TryGetValue(namedItem, out nodes))
787        throw new ArgumentException();
788      nodes.Remove(node);
789      if (nodes.Count == 0) {
790        treeNodeTagMapping.Remove(namedItem);
791        DeregisterNamedItemEvents(namedItem);
792      }
793    }
794
795    private IEnumerable<TreeNode> IterateTreeNodes(TreeNode node = null) {
796      TreeNodeCollection nodes;
797      if (node == null)
798        nodes = treeView.Nodes;
799      else {
800        nodes = node.Nodes;
801        yield return node;
802      }
803
804      foreach (var childNode in nodes.OfType<TreeNode>())
805        foreach (var n in IterateTreeNodes(childNode))
806          yield return n;
807    }
808
809    private void RebuildImageList() {
810      if (InvokeRequired) {
811        Invoke((Action)RebuildImageList);
812        return;
813      }
814
815      treeView.ImageList.Images.Clear();
816      foreach (TreeNode treeNode in IterateTreeNodes()) {
817        var item = (IItem)treeNode.Tag;
818        treeView.ImageList.Images.Add(item == null ? HeuristicLab.Common.Resources.VSImageLibrary.Nothing : item.ItemImage);
819        treeNode.ImageIndex = treeView.ImageList.Images.Count - 1;
820        treeNode.SelectedImageIndex = treeNode.ImageIndex;
821      }
822    }
823    #endregion
824
825
826    public sealed class CustomTreeView : System.Windows.Forms.TreeView {
827      protected override void WndProc(ref System.Windows.Forms.Message m) {
828        const int WM_RBUTTONDOWN = 0x204;
829        if (m.Msg == WM_RBUTTONDOWN) {
830          //Raise your custom event right click event to prevent node highlighting
831          OnRightClick();
832          return;
833        }
834        base.WndProc(ref m);
835      }
836
837      public event EventHandler RightClick;
838      private void OnRightClick() {
839        var handler = RightClick;
840        if (handler != null) RightClick(this, EventArgs.Empty);
841      }
842    }
843  }
844}
Note: See TracBrowser for help on using the repository browser.