Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Core.Views/3.3/OperatorTreeView.cs @ 3051

Last change on this file since 3051 was 2949, checked in by swagner, 15 years ago

Operator architecture refactoring (#95)

  • implemented reviewers' comments on version r2917.
File size: 18.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.ComponentModel;
25using System.Drawing;
26using System.Windows.Forms;
27using HeuristicLab.Collections;
28using HeuristicLab.MainForm;
29
30namespace HeuristicLab.Core.Views {
31  /// <summary>
32  /// The visual representation of an <see cref="OperatorGraph"/>.
33  /// </summary>
34  [View("Operator View (Successors)")]
35  [Content(typeof(IOperator), false)]
36  public sealed partial class OperatorTreeView : ItemView {
37    private Dictionary<IValueParameter<IOperator>, List<TreeNode>> opParamNodeTable;
38    private Dictionary<IOperator, List<TreeNode>> operatorNodeTable;
39    private Dictionary<IObservableKeyedCollection<string, IParameter>, IOperator> parametersOperatorTable;
40
41    /// <summary>
42    /// Gets or sets the operator graph to represent visually.
43    /// </summary>
44    /// <remarks>Uses property <see cref="ViewBase.Item"/> of base class <see cref="ViewBase"/>.
45    /// No own data storage present.</remarks>
46    public new IOperator Content {
47      get { return (IOperator)base.Content; }
48      set { base.Content = value; }
49    }
50
51    private IOperator selectedOperator;
52    public IOperator SelectedOperator {
53      get { return selectedOperator; }
54      private set {
55        if (value != selectedOperator) {
56          selectedOperator = value;
57          OnSelectedOperatorChanged();
58        }
59      }
60    }
61
62    /// <summary>
63    /// Initializes a new instance of <see cref="OperatorGraphView"/> with caption "Operator Graph".
64    /// </summary>
65    public OperatorTreeView() {
66      InitializeComponent();
67      graphTreeView.Sorted = true;
68      opParamNodeTable = new Dictionary<IValueParameter<IOperator>, List<TreeNode>>();
69      operatorNodeTable = new Dictionary<IOperator, List<TreeNode>>();
70      parametersOperatorTable = new Dictionary<IObservableKeyedCollection<string, IParameter>, IOperator>();
71      Caption = "Operator";
72    }
73    /// <summary>
74    /// Initializes a new instance of <see cref="OperatorGraphView"/>
75    /// with the given <paramref name="operatorGraph"/>.
76    /// </summary>
77    /// <remarks>Calls <see cref="OperatorGraphView()"/>.</remarks>
78    /// <param name="operatorGraph">The operator graph to represent visually.</param>
79    public OperatorTreeView(IOperator content)
80      : this() {
81      Content = content;
82    }
83
84    /// <summary>
85    /// Updates all controls with the latest data of the model.
86    /// </summary>
87    /// <remarks>Calls <see cref="ViewBase.UpdateControls"/> of base class <see cref="ViewBase"/>.</remarks>
88    protected override void OnContentChanged() {
89      base.OnContentChanged();
90      if (graphTreeView.Nodes.Count > 0)
91        RemoveTreeNode(graphTreeView.Nodes[0]);
92      graphTreeView.Enabled = false;
93      Caption = "Operator";
94      if (Content != null) {
95        Caption = Content.Name + " (" + Content.GetType().Name + ")";
96        TreeNode root = new TreeNode();
97        FillTreeNode(root, Content);
98        graphTreeView.Nodes.Add(root);
99        graphTreeView.Enabled = true;
100      }
101    }
102
103    public event EventHandler SelectedOperatorChanged;
104    private void OnSelectedOperatorChanged() {
105      if (SelectedOperatorChanged != null)
106        SelectedOperatorChanged(this, EventArgs.Empty);
107    }
108
109    #region TreeNode Management
110    private TreeNode CreateTreeNode(IValueParameter<IOperator> opParam) {
111      TreeNode node = new TreeNode();
112      node.Text = opParam.Name + ": ";
113      SetOperatorParameterTag(node, opParam);
114
115      if (!opParamNodeTable.ContainsKey(opParam)) {
116        opParamNodeTable.Add(opParam, new List<TreeNode>());
117        opParam.ValueChanged += new EventHandler(opParam_ValueChanged);
118      }
119      opParamNodeTable[opParam].Add(node);
120
121      IOperator op = opParam.Value;
122      if (op == null)
123        node.Text += "-";
124      else
125        FillTreeNode(node, op);
126
127      return node;
128    }
129    private void FillTreeNode(TreeNode node, IOperator op) {
130      if (!graphTreeView.ImageList.Images.ContainsKey(op.GetType().FullName))
131        graphTreeView.ImageList.Images.Add(op.GetType().FullName, op.ItemImage);
132
133      node.Text += op.Name;
134      node.ToolTipText = op.ItemName + ": " + op.ItemDescription;
135      node.ImageIndex = graphTreeView.ImageList.Images.IndexOfKey(op.GetType().FullName);
136      node.SelectedImageIndex = node.ImageIndex;
137      SetOperatorTag(node, op);
138
139      if (!operatorNodeTable.ContainsKey(op)) {
140        operatorNodeTable.Add(op, new List<TreeNode>());
141        op.NameChanged += new EventHandler(op_NameChanged);
142        op.BreakpointChanged += new EventHandler(op_BreakpointChanged);
143        parametersOperatorTable.Add(op.Parameters, op);
144        op.Parameters.ItemsAdded += new CollectionItemsChangedEventHandler<IParameter>(Parameters_ItemsAdded);
145        op.Parameters.ItemsRemoved += new CollectionItemsChangedEventHandler<IParameter>(Parameters_ItemsRemoved);
146        op.Parameters.ItemsReplaced += new CollectionItemsChangedEventHandler<IParameter>(Parameters_ItemsReplaced);
147        op.Parameters.CollectionReset += new CollectionItemsChangedEventHandler<IParameter>(Parameters_CollectionReset);
148      }
149      operatorNodeTable[op].Add(node);
150
151      if (op.Breakpoint)
152        node.ForeColor = Color.Red;
153
154      foreach (IParameter param in op.Parameters) {
155        if (param is IValueParameter<IOperator>)
156          node.Nodes.Add(new TreeNode());
157      }
158      node.Collapse();
159    }
160    private void ClearTreeNode(TreeNode node) {
161      while (node.Nodes.Count > 0)
162        RemoveTreeNode(node.Nodes[0]);
163
164      IOperator op = GetOperatorTag(node);
165      if (op != null) {
166        operatorNodeTable[op].Remove(node);
167        if (operatorNodeTable[op].Count == 0) {
168          op.NameChanged -= new EventHandler(op_NameChanged);
169          op.BreakpointChanged -= new EventHandler(op_BreakpointChanged);
170          operatorNodeTable.Remove(op);
171          op.Parameters.ItemsAdded -= new CollectionItemsChangedEventHandler<IParameter>(Parameters_ItemsAdded);
172          op.Parameters.ItemsRemoved -= new CollectionItemsChangedEventHandler<IParameter>(Parameters_ItemsRemoved);
173          op.Parameters.ItemsReplaced -= new CollectionItemsChangedEventHandler<IParameter>(Parameters_ItemsReplaced);
174          op.Parameters.CollectionReset -= new CollectionItemsChangedEventHandler<IParameter>(Parameters_CollectionReset);
175          parametersOperatorTable.Remove(op.Parameters);
176        }
177      }
178      SetOperatorTag(node, null);
179    }
180    private void RemoveTreeNode(TreeNode node) {
181      ClearTreeNode(node);
182
183      IValueParameter<IOperator> opParam = GetOperatorParameterTag(node);
184      if (opParam != null) {
185        opParamNodeTable[opParam].Remove(node);
186        if (opParamNodeTable[opParam].Count == 0) {
187          opParam.ValueChanged -= new EventHandler(opParam_ValueChanged);
188          opParamNodeTable.Remove(opParam);
189        }
190      }
191      SetOperatorParameterTag(node, null);
192      node.Remove();
193    }
194    private void AddParameterNodes(IOperator op, IEnumerable<IParameter> parameters) {
195      foreach (IParameter param in parameters) {
196        IValueParameter<IOperator> opParam = param as IValueParameter<IOperator>;
197        if (opParam != null) {
198          foreach (TreeNode node in operatorNodeTable[op])
199            node.Nodes.Add(CreateTreeNode(opParam));
200        }
201      }
202    }
203    private void RemoveParameterNodes(IEnumerable<IParameter> parameters) {
204      foreach (IParameter param in parameters) {
205        IValueParameter<IOperator> opParam = param as IValueParameter<IOperator>;
206        if (opParam != null) {
207          while (opParamNodeTable.ContainsKey(opParam))
208            RemoveTreeNode(opParamNodeTable[opParam][0]);
209        }
210      }
211    }
212    #endregion
213
214    #region Parameter and Operator Events
215    private void opParam_ValueChanged(object sender, EventArgs e) {
216      if (InvokeRequired)
217        Invoke(new EventHandler(opParam_ValueChanged), sender, e);
218      else {
219        IValueParameter<IOperator> opParam = (IValueParameter<IOperator>)sender;
220        foreach (TreeNode node in opParamNodeTable[opParam].ToArray())
221          ClearTreeNode(node);
222        foreach (TreeNode node in opParamNodeTable[opParam]) {
223          node.Text = opParam.Name + ": ";
224          if (opParam.Value == null)
225            node.Text += "-";
226          else
227            FillTreeNode(node, opParam.Value);
228        }
229      }
230    }
231    private void op_NameChanged(object sender, EventArgs e) {
232      if (InvokeRequired)
233        Invoke(new EventHandler(op_NameChanged), sender, e);
234      else {
235        IOperator op = (IOperator)sender;
236        foreach (TreeNode node in operatorNodeTable[op]) {
237          IValueParameter<IOperator> opParam = GetOperatorParameterTag(node);
238          if (opParam == null)
239            node.Text = op.Name + " (" + op.ItemName + ")";
240          else
241            node.Text = opParam.Name + ": " + op.Name;
242        }
243      }
244    }
245    private void op_BreakpointChanged(object sender, EventArgs e) {
246      if (InvokeRequired)
247        Invoke(new EventHandler(op_BreakpointChanged), sender, e);
248      else {
249        IOperator op = (IOperator)sender;
250        foreach (TreeNode node in operatorNodeTable[op]) {
251          if (op.Breakpoint)
252            node.ForeColor = Color.Red;
253          else
254            node.ForeColor = graphTreeView.ForeColor;
255        }
256      }
257    }
258
259    private void Parameters_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IParameter> e) {
260      if (InvokeRequired)
261        Invoke(new CollectionItemsChangedEventHandler<IParameter>(Parameters_ItemsAdded), sender, e);
262      else {
263        IObservableKeyedCollection<string, IParameter> coll = (IObservableKeyedCollection<string, IParameter>)sender;
264        IOperator op = parametersOperatorTable[coll];
265        AddParameterNodes(op, e.Items);
266      }
267    }
268    private void Parameters_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IParameter> e) {
269      if (InvokeRequired)
270        Invoke(new CollectionItemsChangedEventHandler<IParameter>(Parameters_ItemsRemoved), sender, e);
271      else
272        RemoveParameterNodes(e.Items);
273    }
274    private void Parameters_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IParameter> e) {
275      if (InvokeRequired)
276        Invoke(new CollectionItemsChangedEventHandler<IParameter>(Parameters_ItemsReplaced), sender, e);
277      else {
278        RemoveParameterNodes(e.Items);
279        IObservableKeyedCollection<string, IParameter> coll = (IObservableKeyedCollection<string, IParameter>)sender;
280        IOperator op = parametersOperatorTable[coll];
281        AddParameterNodes(op, e.Items);
282      }
283    }
284    private void Parameters_CollectionReset(object sender, CollectionItemsChangedEventArgs<IParameter> e) {
285      if (InvokeRequired)
286        Invoke(new CollectionItemsChangedEventHandler<IParameter>(Parameters_CollectionReset), sender, e);
287      else {
288        RemoveParameterNodes(e.Items);
289        IObservableKeyedCollection<string, IParameter> coll = (IObservableKeyedCollection<string, IParameter>)sender;
290        IOperator op = parametersOperatorTable[coll];
291        AddParameterNodes(op, e.Items);
292      }
293    }
294    #endregion
295
296    #region TreeView Events
297    private void graphTreeView_BeforeExpand(object sender, TreeViewCancelEventArgs e) {
298      TreeNode node = e.Node;
299      if ((node.Nodes.Count > 0) && (node.Nodes[0].Tag == null)) {
300        node.Nodes.Clear();
301        IOperator op = GetOperatorTag(node);
302        foreach (IParameter param in op.Parameters) {
303          IValueParameter<IOperator> opParam = param as IValueParameter<IOperator>;
304          if (opParam != null) node.Nodes.Add(CreateTreeNode(opParam));
305        }
306      }
307    }
308    private void graphTreeView_MouseDown(object sender, MouseEventArgs e) {
309      TreeNode node = graphTreeView.GetNodeAt(e.X, e.Y);
310      graphTreeView.SelectedNode = node;
311      graphTreeView.Refresh();
312    }
313    private void graphTreeView_KeyDown(object sender, KeyEventArgs e) {
314      if ((e.KeyCode == Keys.Delete) && (graphTreeView.SelectedNode != null)) {
315        IValueParameter<IOperator> opParam = GetOperatorParameterTag(graphTreeView.SelectedNode);
316        if (opParam != null) opParam.Value = null;
317      }
318    }
319    private void graphTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
320      SelectedOperator = graphTreeView.SelectedNode == null ? null : GetOperatorTag(graphTreeView.SelectedNode);
321    }
322    private void graphContextMenuStrip_Opening(object sender, CancelEventArgs e) {
323      viewToolStripMenuItem.Enabled = false;
324      breakpointToolStripMenuItem.Enabled = false;
325      breakpointToolStripMenuItem.Checked = false;
326      if (graphTreeView.SelectedNode != null) {
327        IOperator op = GetOperatorTag(graphTreeView.SelectedNode);
328        if (op != null) {
329          IView view = MainFormManager.CreateDefaultView(op);
330          if (view != null) {
331            viewToolStripMenuItem.Enabled = true;
332            viewToolStripMenuItem.Tag = view;
333          }
334          breakpointToolStripMenuItem.Enabled = true;
335          breakpointToolStripMenuItem.Tag = op;
336          if (op.Breakpoint)
337            breakpointToolStripMenuItem.Checked = true;
338        }
339      }
340    }
341    private void graphTreeView_ItemDrag(object sender, ItemDragEventArgs e) {
342      TreeNode node = (TreeNode)e.Item;
343      IValueParameter<IOperator> opParam = GetOperatorParameterTag(node);
344      IOperator op = GetOperatorTag(node);
345      DataObject data = new DataObject();
346      data.SetData("Type", op.GetType());
347      data.SetData("Value", op);
348      if (opParam == null) {
349        DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link);
350      } else {
351        DragDropEffects action = DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link | DragDropEffects.Move);
352        if ((action & DragDropEffects.Move) == DragDropEffects.Move)
353          opParam.Value = null;
354      }
355    }
356    private void graphTreeView_DragEnterOver(object sender, DragEventArgs e) {
357      e.Effect = DragDropEffects.None;
358      Type type = e.Data.GetData("Type") as Type;
359      if ((type != null) && (typeof(IOperator).IsAssignableFrom(type))) {
360        TreeNode node = graphTreeView.GetNodeAt(graphTreeView.PointToClient(new Point(e.X, e.Y)));
361        if ((node != null) && !node.IsExpanded) node.Expand();
362        if ((node != null) && (GetOperatorParameterTag(node) != null)) {
363          if ((e.KeyState & 8) == 8) e.Effect = DragDropEffects.Copy;  // CTRL key
364          else if ((e.KeyState & 4) == 4) e.Effect = DragDropEffects.Move;  // SHIFT key
365          else if ((e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link) e.Effect = DragDropEffects.Link;
366          else if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy) e.Effect = DragDropEffects.Copy;
367          else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move) e.Effect = DragDropEffects.Move;
368        }
369      }
370    }
371    private void graphTreeView_DragDrop(object sender, DragEventArgs e) {
372      if (e.Effect != DragDropEffects.None) {
373        IOperator op = e.Data.GetData("Value") as IOperator;
374        if ((e.Effect & DragDropEffects.Copy) == DragDropEffects.Copy) op = (IOperator)op.Clone();
375        TreeNode node = graphTreeView.GetNodeAt(graphTreeView.PointToClient(new Point(e.X, e.Y)));
376        IValueParameter<IOperator> opParam = GetOperatorParameterTag(node);
377        opParam.Value = op;
378      }
379    }
380    #endregion
381
382    #region Context Menu Events
383    private void viewToolStripMenuItem_Click(object sender, EventArgs e) {
384      IView view = ((ToolStripMenuItem)sender).Tag as IView;
385      if (view != null) view.Show();
386    }
387    private void breakpointToolStripMenuItem_Click(object sender, EventArgs e) {
388      IOperator op = (IOperator)breakpointToolStripMenuItem.Tag;
389      op.Breakpoint = breakpointToolStripMenuItem.Checked;
390    }
391    #endregion
392
393    #region Helpers
394    private class Tuple<T1, T2> {
395      public T1 Item1 { get; set; }
396      public T2 Item2 { get; set; }
397
398      public Tuple() {
399        Item1 = default(T1);
400        Item2 = default(T2);
401      }
402      public Tuple(T1 item1, T2 item2) {
403        Item1 = item1;
404        Item2 = item2;
405      }
406    }
407
408    private IValueParameter<IOperator> GetOperatorParameterTag(TreeNode node) {
409      if (node.Tag != null)
410        return ((Tuple<IValueParameter<IOperator>, IOperator>)node.Tag).Item1;
411      else
412        return null;
413    }
414    private void SetOperatorParameterTag(TreeNode node, IValueParameter<IOperator> opParam) {
415      if (node.Tag == null)
416        node.Tag = new Tuple<IValueParameter<IOperator>, IOperator>(opParam, null);
417      else
418        ((Tuple<IValueParameter<IOperator>, IOperator>)node.Tag).Item1 = opParam;
419    }
420    private IOperator GetOperatorTag(TreeNode node) {
421      if (node.Tag != null)
422        return ((Tuple<IValueParameter<IOperator>, IOperator>)node.Tag).Item2;
423      else
424        return null;
425    }
426    private void SetOperatorTag(TreeNode node, IOperator op) {
427      if (node.Tag == null)
428        node.Tag = new Tuple<IValueParameter<IOperator>, IOperator>(null, op);
429      else
430        ((Tuple<IValueParameter<IOperator>, IOperator>)node.Tag).Item2 = op;
431    }
432    #endregion
433  }
434}
Note: See TracBrowser for help on using the repository browser.