Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6529 was 6529, checked in by mkommend, 13 years ago

#1555: Corrected drag & drop in ExperimentTreeView.

File size: 37.9 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      if (item == null) return;
438
439      DataObject data = new DataObject();
440      data.SetData(HeuristicLab.Common.Constants.DragDropDataFormat, item);
441      validDragOperation = true;
442
443      if (ReadOnly || !(item is IOptimizer)) {
444        DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link);
445      } else {
446        DragDropEffects result = DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link | DragDropEffects.Move);
447        if ((result & DragDropEffects.Move) == DragDropEffects.Move) {
448          var optimizer = (IOptimizer)item;
449          if (selectedNode.Parent == null) Content.Optimizers.Remove(optimizer);
450          else {
451            var parentOptimizer = (IOptimizer)selectedNode.Parent.Tag;
452            var parentBatchRun = parentOptimizer as BatchRun;
453            var parentExperiment = parentOptimizer as Experiment;
454            if (parentBatchRun != null) parentBatchRun.Optimizer = null;
455            else if (parentExperiment != null) parentExperiment.Optimizers.Remove(optimizer);
456            else throw new NotSupportedException("Handling for specific type not implemented" + parentOptimizer.GetType());
457          }
458        }
459      }
460    }
461
462    private bool validDragOperation = false;
463    private void optimizerTreeView_DragEnter(object sender, DragEventArgs e) {
464      validDragOperation = false;
465      if (!ReadOnly) {
466        var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
467        if (data is IOptimizer) validDragOperation = true;
468        else if (data is IProblem) validDragOperation = true;
469        else if (data is IEnumerable) {
470          IEnumerable items = (IEnumerable)data;
471          validDragOperation = true;
472          foreach (object item in items)
473            validDragOperation = validDragOperation && (item is IOptimizer);
474        }
475      }
476    }
477    private void optimizerTreeView_DragOver(object sender, DragEventArgs e) {
478      e.Effect = DragDropEffects.None;
479      if (!validDragOperation) return;
480      Point coordinates = treeView.PointToClient(new Point(e.X, e.Y));
481      TreeNode node = treeView.GetNodeAt(coordinates);
482      Experiment experiment = null;
483      BatchRun batchRun = null;
484      Algorithm algorithm = null;
485
486      if (node == null) experiment = Content;
487      else {
488        experiment = node.Tag as Experiment;
489        batchRun = node.Tag as BatchRun;
490        algorithm = node.Tag as Algorithm;
491      }
492
493      if (batchRun == null && experiment == null && algorithm == null) return;
494
495      var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
496
497      if (algorithm != null) {
498        var problem = data as IProblem;
499        if (problem == null) return;
500        if (!algorithm.ProblemType.IsAssignableFrom(problem.GetType())) return;
501      } else if (batchRun != null) {
502        var optimizer = data as IOptimizer;
503        if (optimizer == null) return;
504        if (batchRun == optimizer) return;
505        if (optimizer.NestedOptimizers.Contains(batchRun)) return;
506      } //do not allow recursive nesting of contents
507      else if (experiment != null) {
508        var optimizer = data as IOptimizer;
509        IEnumerable<IOptimizer> optimizers = null;
510        var enumerable = data as IEnumerable;
511        if (enumerable != null) optimizers = enumerable.Cast<IOptimizer>();
512        if (experiment == optimizer) return;
513        if (optimizer != null && optimizer.NestedOptimizers.Contains(experiment)) return;
514        if (optimizers != null && optimizers.Any(x => x.NestedOptimizers.Contains(experiment))) return;
515      }
516
517      if ((e.KeyState & 32) == 32 && e.AllowedEffect.HasFlag(DragDropEffects.Link)) e.Effect = DragDropEffects.Link;  // ALT key
518      else if ((e.KeyState & 4) == 4 && e.AllowedEffect.HasFlag(DragDropEffects.Move)) e.Effect = DragDropEffects.Move;  // SHIFT key
519      else if (e.AllowedEffect.HasFlag(DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy;
520      else if (e.AllowedEffect.HasFlag(DragDropEffects.Move)) e.Effect = DragDropEffects.Move;
521      else if (e.AllowedEffect.HasFlag(DragDropEffects.Link)) e.Effect = DragDropEffects.Link;
522    }
523
524    private void optimizerTreeView_DragDrop(object sender, DragEventArgs e) {
525      Point coordinates = treeView.PointToClient(new Point(e.X, e.Y));
526      TreeNode node = treeView.GetNodeAt(coordinates);
527      Algorithm algorithm = null;
528      BatchRun batchRun = null;
529      Experiment experiment = null;
530
531      if (node == null) experiment = Content;
532      else {
533        algorithm = node.Tag as Algorithm;
534        batchRun = node.Tag as BatchRun;
535        experiment = node.Tag as Experiment;
536      }
537
538      var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
539      if (data is IProblem) {
540        var problem = (IProblem)data;
541        if (e.Effect.HasFlag(DragDropEffects.Copy)) problem = (IProblem)problem.Clone();
542        algorithm.Problem = problem;
543      } else if (data is IOptimizer) {
544        IOptimizer optimizer = (IOptimizer)data;
545        if (e.Effect.HasFlag(DragDropEffects.Copy)) optimizer = (IOptimizer)optimizer.Clone();
546        if (batchRun != null) batchRun.Optimizer = optimizer;
547        else if (experiment != null) experiment.Optimizers.Add(optimizer);
548        else throw new NotSupportedException("Handling for specific type not implemented" + node.Tag.GetType());
549      } else if (data is IEnumerable) {
550        IEnumerable<IOptimizer> optimizers = ((IEnumerable)data).Cast<IOptimizer>();
551        if (e.Effect.HasFlag(DragDropEffects.Copy)) {
552          Cloner cloner = new Cloner();
553          optimizers = optimizers.Select(o => cloner.Clone(o));
554        }
555        if (experiment != null) experiment.Optimizers.AddRange(optimizers);
556        else throw new NotSupportedException("Handling for specific type not implemented" + node.Tag.GetType());
557      }
558    }
559    #endregion
560
561    #region control events
562    private void optimizerTreeView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) {
563      if (rightClickOccured) return;
564      if (e.X < e.Node.Bounds.Left || e.X > e.Node.Bounds.Right) return;
565      e.Node.Toggle();
566      IContent optimizer = (IContent)e.Node.Tag;
567      MainFormManager.MainForm.ShowContent(optimizer);
568    }
569    private void optimizerTreeview_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
570      if (e.X < e.Node.Bounds.Left || e.X > e.Node.Bounds.Right) return;
571      treeView.SelectedNode = e.Node;
572      detailsViewHost.Content = (IContent)e.Node.Tag;
573      SetEnabledStateOfControls();
574    }
575    private void optimizerTreeView_MouseDown(object sender, MouseEventArgs e) {
576      // enables deselection of treeNodes
577      if (e.Button != MouseButtons.Right) rightClickOccured = false;
578      if (treeView.SelectedNode == null) return;
579      Point coordinates = new Point(e.X, e.Y);
580      TreeNode node = treeView.GetNodeAt(coordinates);
581      if (node == null || coordinates.X < node.Bounds.Left || coordinates.X > node.Bounds.Right) {
582        treeView.SelectedNode = null;
583        detailsViewHost.Content = null;
584        SetEnabledStateOfControls();
585      }
586    }
587
588
589    private void optimizerTreeView_KeyDown(object sender, KeyEventArgs e) {
590      if (ReadOnly) return;
591      if (e.KeyCode != Keys.Delete) return;
592      if (treeView.SelectedNode == null) return;
593      if (!(treeView.SelectedNode.Tag is IOptimizer)) return;
594
595      var treeNode = treeView.SelectedNode;
596      var optimizer = (IOptimizer)treeNode.Tag;
597
598      if (treeNode.Parent == null)
599        Content.Optimizers.Remove(optimizer);
600      else {
601        var batchRun = treeNode.Parent.Tag as BatchRun;
602        var experiment = treeNode.Parent.Tag as Experiment;
603        if (batchRun != null) batchRun.Optimizer = null;
604        else if (experiment != null) experiment.Optimizers.Remove(optimizer);
605        else throw new NotSupportedException("Handling for specific type not implemented" + treeView.SelectedNode.Tag.GetType());
606      }
607      SetEnabledStateOfControls();
608      UpdateDetailsViewHost();
609      RebuildImageList();
610    }
611
612    private bool rightClickOccured = true;
613    private TreeNode toolStripMenuNode = null;
614    private void optimizerTreeView_RightClick(object sender, EventArgs e) {
615      rightClickOccured = true;
616      Point coordinates = treeView.PointToClient(Cursor.Position);
617      toolStripMenuNode = treeView.GetNodeAt(coordinates);
618
619      if (toolStripMenuNode != null && coordinates.X >= toolStripMenuNode.Bounds.Left && coordinates.X <= toolStripMenuNode.Bounds.Right) {
620        treeView.SelectedNode = toolStripMenuNode;
621        detailsViewHost.Content = (IContent)toolStripMenuNode.Tag;
622        SetEnabledStateOfControls();
623
624        ExpandToolStripMenuItem.Enabled = !toolStripMenuNode.IsExpanded && toolStripMenuNode.Nodes.Count > 0;
625        ExpandToolStripMenuItem.Visible = !toolStripMenuNode.IsExpanded && toolStripMenuNode.Nodes.Count > 0;
626        CollapseToolStripMenuItem.Enabled = toolStripMenuNode.IsExpanded;
627        CollapseToolStripMenuItem.Visible = toolStripMenuNode.IsExpanded;
628        EditNodeLabelToolStripMenuItem.Enabled = toolStripMenuNode.Tag != null && toolStripMenuNode.Tag is INamedItem;
629        EditNodeLabelToolStripMenuItem.Visible = toolStripMenuNode.Tag != null && toolStripMenuNode.Tag is INamedItem;
630        if (contextMenuStrip.Items.Cast<ToolStripMenuItem>().Any(item => item.Enabled))
631          contextMenuStrip.Show(Cursor.Position);
632      }
633    }
634
635    private void ExpandToolStripMenuItem_Click(object sender, EventArgs e) {
636      if (toolStripMenuNode != null) toolStripMenuNode.ExpandAll();
637    }
638    private void CollapseToolStripMenuItem_Click(object sender, EventArgs e) {
639      if (toolStripMenuNode != null) toolStripMenuNode.Collapse();
640    }
641    private void EditNodeLabelToolStripMenuItem_Click(object sender, EventArgs e) {
642      if (toolStripMenuNode != null) {
643        if (!toolStripMenuNode.IsEditing) toolStripMenuNode.BeginEdit();
644      }
645    }
646
647
648    private void treeView_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e) {
649      if (e.Node.Tag == null || !(e.Node.Tag is INamedItem)) {
650        e.CancelEdit = true;
651        return;
652      }
653    }
654    private void treeView_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) {
655      if (e.Label == null) return;
656
657      e.Node.EndEdit(false);
658      var namedItem = (INamedItem)e.Node.Tag;
659      namedItem.Name = e.Label;
660    }
661
662    private void addButton_Click(object sender, System.EventArgs e) {
663      if (typeSelectorDialog == null) typeSelectorDialog = new TypeSelectorDialog();
664
665      IAlgorithm algorithm = null;
666      if (treeView.SelectedNode != null && (treeView.SelectedNode.Tag is IAlgorithm))
667        algorithm = (IAlgorithm)treeView.SelectedNode.Tag;
668
669      if (algorithm == null) {
670        typeSelectorDialog.Caption = "Select Optimizer";
671        typeSelectorDialog.TypeSelector.Caption = "Available Optimizers";
672        typeSelectorDialog.TypeSelector.Configure(typeof(IOptimizer), false, true);
673      } else {
674        typeSelectorDialog.Caption = "Select Problem";
675        typeSelectorDialog.TypeSelector.Caption = "Available Problems";
676        typeSelectorDialog.TypeSelector.Configure(algorithm.ProblemType, false, true);
677      }
678
679      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
680        try {
681          if (algorithm == null) {
682            IOptimizer optimizer = (IOptimizer)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
683            if (treeView.SelectedNode == null) Content.Optimizers.Add(optimizer);
684            else {
685              var batchRun = treeView.SelectedNode.Tag as BatchRun;
686              var experiment = treeView.SelectedNode.Tag as Experiment;
687              if (batchRun != null) batchRun.Optimizer = optimizer;
688              else if (experiment != null) experiment.Optimizers.Add(optimizer);
689              else throw new NotSupportedException("Handling for specific type not implemented" + treeView.SelectedNode.Tag.GetType());
690            }
691          } else {
692            IProblem problem = (IProblem)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
693            algorithm.Problem = problem;
694          }
695        }
696        catch (Exception ex) {
697          ErrorHandling.ShowErrorDialog(this, ex);
698        }
699      }
700    }
701
702    private void moveUpButton_Click(object sender, EventArgs e) {
703      var optimizer = (IOptimizer)treeView.SelectedNode.Tag;
704      Experiment experiment = null;
705      if (treeView.SelectedNode.Parent == null) experiment = Content;
706      else experiment = (Experiment)treeView.SelectedNode.Parent.Tag;
707
708      int index = treeView.SelectedNode.Index;
709      experiment.Optimizers.Reverse(index - 1, 2);
710      treeView.SelectedNode = treeNodeTagMapping[optimizer].First();
711      SetEnabledStateOfControls();
712      UpdateDetailsViewHost();
713      RebuildImageList();
714    }
715    private void moveDownButton_Click(object sender, EventArgs e) {
716      var optimizer = (IOptimizer)treeView.SelectedNode.Tag;
717      Experiment experiment = null;
718      if (treeView.SelectedNode.Parent == null) experiment = Content;
719      else experiment = (Experiment)treeView.SelectedNode.Parent.Tag;
720
721      int index = treeView.SelectedNode.Index;
722      experiment.Optimizers.Reverse(index, 2);
723      treeView.SelectedNode = treeNodeTagMapping[optimizer].First();
724      SetEnabledStateOfControls();
725      UpdateDetailsViewHost();
726      RebuildImageList();
727    }
728
729    private void removeButton_Click(object sender, EventArgs e) {
730      var treeNode = treeView.SelectedNode;
731      var optimizer = treeNode.Tag as IOptimizer;
732
733      if (treeNode.Parent == null)
734        Content.Optimizers.Remove(optimizer);
735      else {
736        var batchRun = treeNode.Parent.Tag as BatchRun;
737        var experiment = treeNode.Parent.Tag as Experiment;
738        if (batchRun != null) batchRun.Optimizer = null;
739        else if (experiment != null) experiment.Optimizers.Remove(optimizer);
740        else throw new NotSupportedException("Handling for specific type not implemented" + treeView.SelectedNode.Tag.GetType());
741      }
742      SetEnabledStateOfControls();
743      UpdateDetailsViewHost();
744      RebuildImageList();
745    }
746
747    private void showDetailsCheckBox_CheckedChanged(object sender, System.EventArgs e) {
748      if (showDetailsCheckBox.Checked) {
749        splitContainer.Panel2Collapsed = false;
750        detailsGroupBox.Enabled = treeView.SelectedNode != null;
751        detailsViewHost.Content = treeView.SelectedNode != null ? (IContent)treeView.SelectedNode.Tag : null;
752      } else {
753        splitContainer.Panel2Collapsed = true;
754        detailsViewHost.Content = null;
755      }
756    }
757    #endregion
758
759    #region helpers
760    private void UpdateDetailsViewHost() {
761      if (treeView.SelectedNode != null)
762        detailsViewHost.Content = (IContent)treeView.SelectedNode.Tag;
763      else
764        detailsViewHost.Content = null;
765    }
766
767    private TreeNode CreateTreeNode(IOptimizer optimizer) {
768      TreeNode node = new TreeNode(optimizer.ToString());
769      node.Tag = optimizer;
770
771      var algorithm = optimizer as IAlgorithm;
772      if (algorithm != null) {
773        foreach (TreeNode childNode in CreateAlgorithmChildNodes(algorithm))
774          node.Nodes.Add(childNode);
775      }
776
777      List<TreeNode> nodes;
778      if (!treeNodeTagMapping.TryGetValue(optimizer, out nodes)) {
779        nodes = new List<TreeNode>();
780        treeNodeTagMapping.Add(optimizer, nodes);
781        RegisterNamedItemEvents(optimizer);
782      }
783      nodes.Add(node);
784
785      foreach (TreeNode childNode in node.Nodes) {
786        NamedItem namedItem = childNode.Tag as NamedItem;
787        if (namedItem != null) {
788          if (!treeNodeTagMapping.TryGetValue(namedItem, out nodes)) {
789            nodes = new List<TreeNode>();
790            treeNodeTagMapping.Add(namedItem, nodes);
791            RegisterNamedItemEvents(namedItem);
792          }
793          nodes.Add(childNode);
794        }
795      }
796      return node;
797    }
798
799    private IEnumerable<TreeNode> CreateAlgorithmChildNodes(IAlgorithm algorithm) {
800      TreeNode problemNode;
801      if (algorithm.Problem != null) {
802        problemNode = new TreeNode(algorithm.Problem.Name);
803        problemNode.Tag = algorithm.Problem;
804      } else {
805        problemNode = new TreeNode("No Problem");
806        problemNode.Tag = null;
807      }
808      TreeNode parametersNode = new TreeNode("Parameters");
809      parametersNode.Tag = algorithm.Parameters;
810      TreeNode resultsNode = new TreeNode("Results");
811      resultsNode.Tag = algorithm.Results;
812
813      yield return problemNode;
814      yield return parametersNode;
815      yield return resultsNode;
816    }
817
818    private void DisposeTreeNode(TreeNode node) {
819      var namedItem = node.Tag as INamedItem;
820      if (namedItem == null) return;
821
822      List<TreeNode> nodes;
823      if (!treeNodeTagMapping.TryGetValue(namedItem, out nodes))
824        throw new ArgumentException();
825      nodes.Remove(node);
826      if (nodes.Count == 0) {
827        treeNodeTagMapping.Remove(namedItem);
828        DeregisterNamedItemEvents(namedItem);
829      }
830    }
831
832    private IEnumerable<TreeNode> IterateTreeNodes(TreeNode node = null) {
833      TreeNodeCollection nodes;
834      if (node == null)
835        nodes = treeView.Nodes;
836      else {
837        nodes = node.Nodes;
838        yield return node;
839      }
840
841      foreach (var childNode in nodes.OfType<TreeNode>())
842        foreach (var n in IterateTreeNodes(childNode))
843          yield return n;
844    }
845
846    private void RebuildImageList() {
847      if (InvokeRequired) {
848        Invoke((Action)RebuildImageList);
849        return;
850      }
851
852      treeView.ImageList.Images.Clear();
853      foreach (TreeNode treeNode in IterateTreeNodes()) {
854        var item = (IItem)treeNode.Tag;
855        treeView.ImageList.Images.Add(item == null ? HeuristicLab.Common.Resources.VSImageLibrary.Nothing : item.ItemImage);
856        treeNode.ImageIndex = treeView.ImageList.Images.Count - 1;
857        treeNode.SelectedImageIndex = treeNode.ImageIndex;
858      }
859    }
860    #endregion
861
862
863    public sealed class CustomTreeView : System.Windows.Forms.TreeView {
864      protected override void WndProc(ref System.Windows.Forms.Message m) {
865        const int WM_RBUTTONDOWN = 0x204;
866        if (m.Msg == WM_RBUTTONDOWN) {
867          //Raise your custom event right click event to prevent node highlighting
868          OnRightClick();
869          return;
870        }
871        base.WndProc(ref m);
872      }
873
874      public event EventHandler RightClick;
875      private void OnRightClick() {
876        var handler = RightClick;
877        if (handler != null) RightClick(this, EventArgs.Empty);
878      }
879    }
880  }
881}
Note: See TracBrowser for help on using the repository browser.