Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6703 was 6628, checked in by abeham, 13 years ago

#1541, #1603, #1606, #1607

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