Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Core.Views/3.3/TypeSelector.cs @ 7123

Last change on this file since 7123 was 7123, checked in by abeham, 12 years ago

#1689

  • removed an unnecessary line
  • Property svn:mergeinfo set to (toggle deleted branches)
    /branches/CloningRefactoring/HeuristicLab.Core.Views/3.3/TypeSelector.cs4656-4721
    /branches/DataAnalysis Refactoring/HeuristicLab.Core.Views/3.3/TypeSelector.cs5471-5808
    /branches/DataAnalysis SolutionEnsembles/HeuristicLab.Core.Views/3.3/TypeSelector.cs5815-6180
    /branches/DataAnalysis/HeuristicLab.Core.Views/3.3/TypeSelector.cs4458-4459,​4462,​4464
    /branches/GP.Grammar.Editor/HeuristicLab.Core.Views/3.3/TypeSelector.cs6335
    /branches/GP.Symbols (TimeLag, Diff, Integral)/HeuristicLab.Core.Views/3.3/TypeSelector.cs5060
    /branches/NET40/sources/HeuristicLab.Core.Views/3.3/TypeSelector.cs5138-5162
    /branches/ParallelEngine/HeuristicLab.Core.Views/3.3/TypeSelector.cs5175-5192
    /branches/QAPAlgorithms/HeuristicLab.Core.Views/3.3/TypeSelector.cs6350-6627
    /branches/Restructure trunk solution/HeuristicLab.Core.Views/3.3/TypeSelector.cs6828
    /branches/SuccessProgressAnalysis/HeuristicLab.Core.Views/3.3/TypeSelector.cs5370-5682
    /branches/Trunk/HeuristicLab.Core.Views/3.3/TypeSelector.cs6829-6865
    /branches/VNS/HeuristicLab.Core.Views/3.3/TypeSelector.cs5594-5752
    /branches/histogram/HeuristicLab.Core.Views/3.3/TypeSelector.cs5959-6341
File size: 15.6 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.Generic;
24using System.Linq;
25using System.Reflection;
26using System.Text;
27using System.Windows.Forms;
28using HeuristicLab.Common;
29using HeuristicLab.PluginInfrastructure;
30
31namespace HeuristicLab.Core.Views {
32  public partial class TypeSelector : UserControl {
33    protected List<TreeNode> treeNodes;
34    protected string currentSearchString;
35    protected TypeSelectorDialog typeSelectorDialog;
36
37    protected IEnumerable<Type> baseTypes;
38    public IEnumerable<Type> BaseTypes {
39      get { return baseTypes; }
40    }
41    protected bool showNotInstantiableTypes;
42    public bool ShowNotInstantiableTypes {
43      get { return showNotInstantiableTypes; }
44    }
45    protected bool showGenericTypes;
46    public bool ShowGenericTypes {
47      get { return showGenericTypes; }
48    }
49    public string Caption {
50      get { return typesGroupBox.Text; }
51      set {
52        if (InvokeRequired)
53          Invoke(new Action<string>(delegate(string s) { Caption = s; }), value);
54        else
55          typesGroupBox.Text = value;
56      }
57    }
58    public TreeView TypesTreeView {
59      get { return typesTreeView; }
60    }
61    protected Type selectedType;
62    public Type SelectedType {
63      get { return selectedType; }
64      private set {
65        if (value != selectedType) {
66          selectedType = value;
67          OnSelectedTypeChanged();
68        }
69      }
70    }
71
72    public TypeSelector() {
73      InitializeComponent();
74      treeNodes = new List<TreeNode>();
75      currentSearchString = string.Empty;
76      selectedType = null;
77    }
78
79    protected override void Dispose(bool disposing) {
80      if (disposing) {
81        if (typeSelectorDialog != null) typeSelectorDialog.Dispose();
82        if (components != null) components.Dispose();
83      }
84      base.Dispose(disposing);
85    }
86
87    public virtual void Configure(Type baseType, bool showNotInstantiableTypes, bool showGenericTypes) {
88      Configure(baseType, showNotInstantiableTypes, showGenericTypes, (t) => true);
89    }
90
91    public virtual void Configure(Type baseType, bool showNotInstantiableTypes, bool showGenericTypes, Func<Type, bool> typeCondition) {
92      Configure(new List<Type>() { baseType }, showNotInstantiableTypes, showGenericTypes, true, typeCondition);
93    }
94
95    public virtual void Configure(IEnumerable<Type> baseTypes, bool showNotInstantiableTypes, bool showGenericTypes, bool assignableToAllTypes) {
96      Configure(baseTypes, showNotInstantiableTypes, showGenericTypes, assignableToAllTypes, (t) => { return true; });
97    }
98
99    public virtual void Configure(IEnumerable<Type> baseTypes, bool showNotInstantiableTypes, bool showGenericTypes, bool assignableToAllTypes, Func<Type, bool> typeCondition) {
100      if (baseTypes == null) throw new ArgumentNullException();
101      if (InvokeRequired)
102        Invoke(new Action<IEnumerable<Type>, bool, bool, bool, Func<Type, bool>>(Configure), baseTypes, showNotInstantiableTypes, showGenericTypes, assignableToAllTypes, typeCondition);
103      else {
104        this.baseTypes = baseTypes;
105        this.showNotInstantiableTypes = showNotInstantiableTypes;
106        this.showGenericTypes = showGenericTypes;
107        bool selectedTypeFound = false;
108
109        typeParametersSplitContainer.Panel2Collapsed = !showGenericTypes;
110
111        TreeNode selectedNode = typesTreeView.SelectedNode;
112        typesTreeView.Nodes.Clear();
113        treeNodes.Clear();
114        imageList.Images.Clear();
115        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Class);      // default icon
116        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Namespace);  // plugins
117        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Interface);  // interfaces
118        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Template);   // generic types
119
120        var plugins = from p in ApplicationManager.Manager.Plugins
121                      orderby p.Name, p.Version ascending
122                      select p;
123        foreach (IPluginDescription plugin in plugins) {
124          TreeNode pluginNode = new TreeNode();
125          pluginNode.Text = string.Format("{0} {1}.{2}", plugin.Name, plugin.Version.Major, plugin.Version.Minor);
126          pluginNode.ImageIndex = 1;
127          pluginNode.SelectedImageIndex = pluginNode.ImageIndex;
128          pluginNode.Tag = plugin;
129
130          var types = from t in ApplicationManager.Manager.GetTypes(BaseTypes, plugin, !ShowNotInstantiableTypes, ShowGenericTypes, assignableToAllTypes)
131                      where typeCondition(t)
132                      orderby t.Name ascending
133                      select t;
134          foreach (Type type in types) {
135            bool valid = (ShowNotInstantiableTypes || type.GetConstructor(Type.EmptyTypes) != null); //check for public default ctor
136            if (valid) {
137              TreeNode typeNode = new TreeNode();
138              string name = ItemAttribute.GetName(type);
139              typeNode.Text = name != null ? name : type.GetPrettyName();
140              typeNode.ImageIndex = 0;
141              if (type.IsInterface) typeNode.ImageIndex = 2;
142              else if (type.ContainsGenericParameters) typeNode.ImageIndex = 3;
143              else if (imageList.Images.ContainsKey(type.FullName)) typeNode.ImageIndex = imageList.Images.IndexOfKey(type.FullName);
144              else if (typeof(IItem).IsAssignableFrom(type) && !type.IsInterface && !type.IsAbstract && type.GetConstructor(Type.EmptyTypes) != null) {
145                IItem item = (IItem)Activator.CreateInstance(type);
146                imageList.Images.Add(type.FullName, item.ItemImage);
147                typeNode.ImageIndex = imageList.Images.IndexOfKey(type.FullName);
148              }
149              typeNode.SelectedImageIndex = typeNode.ImageIndex;
150              typeNode.Tag = type;
151              pluginNode.Nodes.Add(typeNode);
152              if (type.Equals(selectedType)) selectedTypeFound = true;
153            }
154          }
155          if (pluginNode.Nodes.Count > 0)
156            treeNodes.Add(pluginNode);
157        }
158        if (!selectedTypeFound) SelectedType = null;
159        foreach (TreeNode node in treeNodes)
160          typesTreeView.Nodes.Add((TreeNode)node.Clone());
161        RestoreSelectedNode(selectedNode);
162        Filter(searchTextBox.Text);
163
164        UpdateTypeParameters();
165      }
166    }
167
168    public virtual void Filter(string searchString) {
169      if (InvokeRequired)
170        Invoke(new Action<string>(Filter), searchString);
171      else {
172        searchString = searchString.ToLower();
173
174        if (!searchString.Contains(currentSearchString)) {
175          typesTreeView.BeginUpdate();
176          // expand search -> restore all tree nodes
177          TreeNode selectedNode = typesTreeView.SelectedNode;
178          typesTreeView.Nodes.Clear();
179          foreach (TreeNode node in treeNodes)
180            typesTreeView.Nodes.Add((TreeNode)node.Clone());
181          RestoreSelectedNode(selectedNode);
182          typesTreeView.EndUpdate();
183        }
184
185
186        // remove nodes
187        typesTreeView.BeginUpdate();
188        int i = 0;
189        while (i < typesTreeView.Nodes.Count) {
190          int j = 0;
191          while (j < typesTreeView.Nodes[i].Nodes.Count) {
192            if (!typesTreeView.Nodes[i].Nodes[j].Text.ToLower().Contains(searchString)) {
193              if ((typesTreeView.Nodes[i].Nodes[j].Tag as Type).Equals(selectedType))
194                SelectedType = null;
195              typesTreeView.Nodes[i].Nodes[j].Remove();
196            } else
197              j++;
198          }
199          if (typesTreeView.Nodes[i].Nodes.Count == 0)
200            typesTreeView.Nodes[i].Remove();
201          else
202            i++;
203        }
204        typesTreeView.EndUpdate();
205        currentSearchString = searchString;
206
207        // if there is just one type node left, select by default
208        if (typesTreeView.Nodes.Count == 1) {
209          if (typesTreeView.Nodes[0].Nodes.Count == 1) {
210            typesTreeView.SelectedNode = typesTreeView.Nodes[0].Nodes[0];
211          }
212        }
213
214        if (typesTreeView.Nodes.Count == 0) {
215          SelectedType = null;
216          typesTreeView.Enabled = false;
217        } else {
218          SetTreeNodeVisibility();
219          typesTreeView.Enabled = true;
220        }
221        UpdateDescription();
222      }
223    }
224
225    public virtual object CreateInstanceOfSelectedType(params object[] args) {
226      if (SelectedType == null)
227        throw new InvalidOperationException("No type selected.");
228      else
229        return Activator.CreateInstance(SelectedType, args);
230    }
231
232    protected virtual void UpdateTypeParameters() {
233      typeParametersListView.Items.Clear();
234      if ((SelectedType == null) || !SelectedType.ContainsGenericParameters) {
235        typeParametersGroupBox.Enabled = false;
236        typeParametersSplitContainer.Panel2Collapsed = true;
237      } else {
238        typeParametersGroupBox.Enabled = true;
239        typeParametersSplitContainer.Panel2Collapsed = false;
240        setTypeParameterButton.Enabled = false;
241
242        foreach (Type param in SelectedType.GetGenericArguments()) {
243          if (param.IsGenericParameter) {
244            ListViewItem item = new ListViewItem();
245            item.Text = param.Name;
246
247            item.ToolTipText = "Constraints:";
248            Type[] constraints = param.GetGenericParameterConstraints();
249            if (constraints.Length == 0) {
250              item.ToolTipText += " none";
251            } else {
252              foreach (Type constraint in constraints)
253                item.ToolTipText += " " + constraint.GetPrettyName();
254            }
255
256            item.Tag = param;
257            typeParametersListView.Items.Add(item);
258          }
259        }
260        typeParametersListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
261      }
262    }
263
264    protected virtual void SetTypeParameter() {
265      if (typeSelectorDialog == null) {
266        typeSelectorDialog = new TypeSelectorDialog();
267        typeSelectorDialog.Caption = "Select Type of Generic Type Parameter";
268      }
269      Type param = typeParametersListView.SelectedItems[0].Tag as Type;
270      Type[] constraints = param.GetGenericParameterConstraints();
271      bool showNotInstantiableTypes = !param.GenericParameterAttributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint);
272      typeSelectorDialog.TypeSelector.Configure(constraints, showNotInstantiableTypes, true, true);
273
274      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
275        Type selected = typeSelectorDialog.TypeSelector.SelectedType;
276        Type[] parameters = SelectedType.GetGenericArguments();
277        parameters[param.GenericParameterPosition] = selected;
278        SelectedType = SelectedType.GetGenericTypeDefinition().MakeGenericType(parameters);
279
280        typeParametersListView.SelectedItems[0].Text = param.Name + ": " + selected.GetPrettyName();
281        typeParametersListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
282      }
283    }
284
285    protected virtual void UpdateDescription() {
286      descriptionTextBox.Text = string.Empty;
287
288      if (typesTreeView.SelectedNode != null) {
289        IPluginDescription plugin = typesTreeView.SelectedNode.Tag as IPluginDescription;
290        if (plugin != null) {
291          StringBuilder sb = new StringBuilder();
292          sb.Append("Plugin: ").Append(plugin.Name).Append(Environment.NewLine);
293          sb.Append("Version: ").Append(plugin.Version.ToString()).Append(Environment.NewLine);
294          descriptionTextBox.Text = sb.ToString();
295        }
296        Type type = typesTreeView.SelectedNode.Tag as Type;
297        if (type != null) {
298          string description = ItemAttribute.GetDescription(type);
299          if (description != null)
300            descriptionTextBox.Text = description;
301        }
302      } else if (typesTreeView.Nodes.Count == 0) {
303        descriptionTextBox.Text = "No types found";
304      }
305    }
306
307    #region Events
308    public event EventHandler SelectedTypeChanged;
309    protected virtual void OnSelectedTypeChanged() {
310      if (SelectedTypeChanged != null)
311        SelectedTypeChanged(this, EventArgs.Empty);
312    }
313    #endregion
314
315    #region Control Events
316    protected virtual void searchTextBox_TextChanged(object sender, System.EventArgs e) {
317      Filter(searchTextBox.Text);
318    }
319
320    protected virtual void typesTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
321      if (typesTreeView.SelectedNode == null) SelectedType = null;
322      else SelectedType = typesTreeView.SelectedNode.Tag as Type;
323      UpdateTypeParameters();
324      UpdateDescription();
325    }
326    protected virtual void typesTreeView_ItemDrag(object sender, ItemDragEventArgs e) {
327      TreeNode node = (TreeNode)e.Item;
328      Type type = node.Tag as Type;
329      if ((type != null) && (!type.IsInterface) && (!type.IsAbstract) && (!type.HasElementType) && (!type.ContainsGenericParameters)) {
330        object o = Activator.CreateInstance(type);
331        DataObject data = new DataObject();
332        data.SetData(HeuristicLab.Common.Constants.DragDropDataFormat, o);
333        DoDragDrop(data, DragDropEffects.Copy);
334      }
335    }
336    protected virtual void typesTreeView_VisibleChanged(object sender, EventArgs e) {
337      if (Visible) SetTreeNodeVisibility();
338    }
339
340    protected virtual void typeParametersListView_SelectedIndexChanged(object sender, EventArgs e) {
341      setTypeParameterButton.Enabled = typeParametersListView.SelectedItems.Count == 1;
342    }
343    protected virtual void typeParametersListView_DoubleClick(object sender, EventArgs e) {
344      if (typeParametersListView.SelectedItems.Count == 1)
345        SetTypeParameter();
346    }
347
348    protected virtual void setTypeParameterButton_Click(object sender, EventArgs e) {
349      SetTypeParameter();
350    }
351    #endregion
352
353    #region Helpers
354    private void RestoreSelectedNode(TreeNode selectedNode) {
355      if (selectedNode != null) {
356        foreach (TreeNode node in typesTreeView.Nodes) {
357          if (node.Text.Equals(selectedNode.Text)) typesTreeView.SelectedNode = node;
358          foreach (TreeNode child in node.Nodes) {
359            if ((child.Text.Equals(selectedNode.Text)) && (child.Tag == selectedNode.Tag))
360              typesTreeView.SelectedNode = child;
361          }
362        }
363        if (typesTreeView.SelectedNode == null) SelectedType = null;
364      }
365    }
366    private void SetTreeNodeVisibility() {
367      TreeNode selectedNode = typesTreeView.SelectedNode;
368      if (string.IsNullOrEmpty(currentSearchString) && (typesTreeView.Nodes.Count > 1)) {
369        typesTreeView.CollapseAll();
370        if (selectedNode != null) typesTreeView.SelectedNode = selectedNode;
371      } else {
372        typesTreeView.ExpandAll();
373      }
374      if (selectedNode != null) selectedNode.EnsureVisible();
375    }
376    #endregion
377  }
378}
Note: See TracBrowser for help on using the repository browser.