Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1689: Corrected ApplicationManagers by introducing a new parameter in the GetTypes method.

  • 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 = true;
136            valid = valid && (ShowNotInstantiableTypes || type.GetConstructor(Type.EmptyTypes) != null); //check for public default ctor
137            if (valid) {
138              TreeNode typeNode = new TreeNode();
139              string name = ItemAttribute.GetName(type);
140              typeNode.Text = name != null ? name : type.GetPrettyName();
141              typeNode.ImageIndex = 0;
142              if (type.IsInterface) typeNode.ImageIndex = 2;
143              else if (type.ContainsGenericParameters) typeNode.ImageIndex = 3;
144              else if (imageList.Images.ContainsKey(type.FullName)) typeNode.ImageIndex = imageList.Images.IndexOfKey(type.FullName);
145              else if (typeof(IItem).IsAssignableFrom(type) && !type.IsInterface && !type.IsAbstract && type.GetConstructor(Type.EmptyTypes) != null) {
146                IItem item = (IItem)Activator.CreateInstance(type);
147                imageList.Images.Add(type.FullName, item.ItemImage);
148                typeNode.ImageIndex = imageList.Images.IndexOfKey(type.FullName);
149              }
150              typeNode.SelectedImageIndex = typeNode.ImageIndex;
151              typeNode.Tag = type;
152              pluginNode.Nodes.Add(typeNode);
153              if (type.Equals(selectedType)) selectedTypeFound = true;
154            }
155          }
156          if (pluginNode.Nodes.Count > 0)
157            treeNodes.Add(pluginNode);
158        }
159        if (!selectedTypeFound) SelectedType = null;
160        foreach (TreeNode node in treeNodes)
161          typesTreeView.Nodes.Add((TreeNode)node.Clone());
162        RestoreSelectedNode(selectedNode);
163        Filter(searchTextBox.Text);
164
165        UpdateTypeParameters();
166      }
167    }
168
169    public virtual void Filter(string searchString) {
170      if (InvokeRequired)
171        Invoke(new Action<string>(Filter), searchString);
172      else {
173        searchString = searchString.ToLower();
174
175        if (!searchString.Contains(currentSearchString)) {
176          typesTreeView.BeginUpdate();
177          // expand search -> restore all tree nodes
178          TreeNode selectedNode = typesTreeView.SelectedNode;
179          typesTreeView.Nodes.Clear();
180          foreach (TreeNode node in treeNodes)
181            typesTreeView.Nodes.Add((TreeNode)node.Clone());
182          RestoreSelectedNode(selectedNode);
183          typesTreeView.EndUpdate();
184        }
185
186
187        // remove nodes
188        typesTreeView.BeginUpdate();
189        int i = 0;
190        while (i < typesTreeView.Nodes.Count) {
191          int j = 0;
192          while (j < typesTreeView.Nodes[i].Nodes.Count) {
193            if (!typesTreeView.Nodes[i].Nodes[j].Text.ToLower().Contains(searchString)) {
194              if ((typesTreeView.Nodes[i].Nodes[j].Tag as Type).Equals(selectedType))
195                SelectedType = null;
196              typesTreeView.Nodes[i].Nodes[j].Remove();
197            } else
198              j++;
199          }
200          if (typesTreeView.Nodes[i].Nodes.Count == 0)
201            typesTreeView.Nodes[i].Remove();
202          else
203            i++;
204        }
205        typesTreeView.EndUpdate();
206        currentSearchString = searchString;
207
208        // if there is just one type node left, select by default
209        if (typesTreeView.Nodes.Count == 1) {
210          if (typesTreeView.Nodes[0].Nodes.Count == 1) {
211            typesTreeView.SelectedNode = typesTreeView.Nodes[0].Nodes[0];
212          }
213        }
214
215        if (typesTreeView.Nodes.Count == 0) {
216          SelectedType = null;
217          typesTreeView.Enabled = false;
218        } else {
219          SetTreeNodeVisibility();
220          typesTreeView.Enabled = true;
221        }
222        UpdateDescription();
223      }
224    }
225
226    public virtual object CreateInstanceOfSelectedType(params object[] args) {
227      if (SelectedType == null)
228        throw new InvalidOperationException("No type selected.");
229      else
230        return Activator.CreateInstance(SelectedType, args);
231    }
232
233    protected virtual void UpdateTypeParameters() {
234      typeParametersListView.Items.Clear();
235      if ((SelectedType == null) || !SelectedType.ContainsGenericParameters) {
236        typeParametersGroupBox.Enabled = false;
237        typeParametersSplitContainer.Panel2Collapsed = true;
238      } else {
239        typeParametersGroupBox.Enabled = true;
240        typeParametersSplitContainer.Panel2Collapsed = false;
241        setTypeParameterButton.Enabled = false;
242
243        foreach (Type param in SelectedType.GetGenericArguments()) {
244          if (param.IsGenericParameter) {
245            ListViewItem item = new ListViewItem();
246            item.Text = param.Name;
247
248            item.ToolTipText = "Constraints:";
249            Type[] constraints = param.GetGenericParameterConstraints();
250            if (constraints.Length == 0) {
251              item.ToolTipText += " none";
252            } else {
253              foreach (Type constraint in constraints)
254                item.ToolTipText += " " + constraint.GetPrettyName();
255            }
256
257            item.Tag = param;
258            typeParametersListView.Items.Add(item);
259          }
260        }
261        typeParametersListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
262      }
263    }
264
265    protected virtual void SetTypeParameter() {
266      if (typeSelectorDialog == null) {
267        typeSelectorDialog = new TypeSelectorDialog();
268        typeSelectorDialog.Caption = "Select Type of Generic Type Parameter";
269      }
270      Type param = typeParametersListView.SelectedItems[0].Tag as Type;
271      Type[] constraints = param.GetGenericParameterConstraints();
272      bool showNotInstantiableTypes = !param.GenericParameterAttributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint);
273      typeSelectorDialog.TypeSelector.Configure(constraints, showNotInstantiableTypes, true, true);
274
275      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
276        Type selected = typeSelectorDialog.TypeSelector.SelectedType;
277        Type[] parameters = SelectedType.GetGenericArguments();
278        parameters[param.GenericParameterPosition] = selected;
279        SelectedType = SelectedType.GetGenericTypeDefinition().MakeGenericType(parameters);
280
281        typeParametersListView.SelectedItems[0].Text = param.Name + ": " + selected.GetPrettyName();
282        typeParametersListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
283      }
284    }
285
286    protected virtual void UpdateDescription() {
287      descriptionTextBox.Text = string.Empty;
288
289      if (typesTreeView.SelectedNode != null) {
290        IPluginDescription plugin = typesTreeView.SelectedNode.Tag as IPluginDescription;
291        if (plugin != null) {
292          StringBuilder sb = new StringBuilder();
293          sb.Append("Plugin: ").Append(plugin.Name).Append(Environment.NewLine);
294          sb.Append("Version: ").Append(plugin.Version.ToString()).Append(Environment.NewLine);
295          descriptionTextBox.Text = sb.ToString();
296        }
297        Type type = typesTreeView.SelectedNode.Tag as Type;
298        if (type != null) {
299          string description = ItemAttribute.GetDescription(type);
300          if (description != null)
301            descriptionTextBox.Text = description;
302        }
303      } else if (typesTreeView.Nodes.Count == 0) {
304        descriptionTextBox.Text = "No types found";
305      }
306    }
307
308    #region Events
309    public event EventHandler SelectedTypeChanged;
310    protected virtual void OnSelectedTypeChanged() {
311      if (SelectedTypeChanged != null)
312        SelectedTypeChanged(this, EventArgs.Empty);
313    }
314    #endregion
315
316    #region Control Events
317    protected virtual void searchTextBox_TextChanged(object sender, System.EventArgs e) {
318      Filter(searchTextBox.Text);
319    }
320
321    protected virtual void typesTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
322      if (typesTreeView.SelectedNode == null) SelectedType = null;
323      else SelectedType = typesTreeView.SelectedNode.Tag as Type;
324      UpdateTypeParameters();
325      UpdateDescription();
326    }
327    protected virtual void typesTreeView_ItemDrag(object sender, ItemDragEventArgs e) {
328      TreeNode node = (TreeNode)e.Item;
329      Type type = node.Tag as Type;
330      if ((type != null) && (!type.IsInterface) && (!type.IsAbstract) && (!type.HasElementType) && (!type.ContainsGenericParameters)) {
331        object o = Activator.CreateInstance(type);
332        DataObject data = new DataObject();
333        data.SetData(HeuristicLab.Common.Constants.DragDropDataFormat, o);
334        DoDragDrop(data, DragDropEffects.Copy);
335      }
336    }
337    protected virtual void typesTreeView_VisibleChanged(object sender, EventArgs e) {
338      if (Visible) SetTreeNodeVisibility();
339    }
340
341    protected virtual void typeParametersListView_SelectedIndexChanged(object sender, EventArgs e) {
342      setTypeParameterButton.Enabled = typeParametersListView.SelectedItems.Count == 1;
343    }
344    protected virtual void typeParametersListView_DoubleClick(object sender, EventArgs e) {
345      if (typeParametersListView.SelectedItems.Count == 1)
346        SetTypeParameter();
347    }
348
349    protected virtual void setTypeParameterButton_Click(object sender, EventArgs e) {
350      SetTypeParameter();
351    }
352    #endregion
353
354    #region Helpers
355    private void RestoreSelectedNode(TreeNode selectedNode) {
356      if (selectedNode != null) {
357        foreach (TreeNode node in typesTreeView.Nodes) {
358          if (node.Text.Equals(selectedNode.Text)) typesTreeView.SelectedNode = node;
359          foreach (TreeNode child in node.Nodes) {
360            if ((child.Text.Equals(selectedNode.Text)) && (child.Tag == selectedNode.Tag))
361              typesTreeView.SelectedNode = child;
362          }
363        }
364        if (typesTreeView.SelectedNode == null) SelectedType = null;
365      }
366    }
367    private void SetTreeNodeVisibility() {
368      TreeNode selectedNode = typesTreeView.SelectedNode;
369      if (string.IsNullOrEmpty(currentSearchString) && (typesTreeView.Nodes.Count > 1)) {
370        typesTreeView.CollapseAll();
371        if (selectedNode != null) typesTreeView.SelectedNode = selectedNode;
372      } else {
373        typesTreeView.ExpandAll();
374      }
375      if (selectedNode != null) selectedNode.EnsureVisible();
376    }
377    #endregion
378  }
379}
Note: See TracBrowser for help on using the repository browser.