Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1538: Merged r6335 into trunk.

  • Property svn:mergeinfo set to (toggle deleted branches)
    /branches/GP.Grammar.Editor/HeuristicLab.Core.Views/3.3/TypeSelector.csmergedeligible
    /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.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/SuccessProgressAnalysis/HeuristicLab.Core.Views/3.3/TypeSelector.cs5370-5682
    /branches/VNS/HeuristicLab.Core.Views/3.3/TypeSelector.cs5594-5752
    /branches/histogram/HeuristicLab.Core.Views/3.3/TypeSelector.cs5959-6341
File size: 15.4 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) => { return 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
108        typeParametersSplitContainer.Panel2Collapsed = !showGenericTypes;
109
110        TreeNode selectedNode = typesTreeView.SelectedNode;
111        typesTreeView.Nodes.Clear();
112        treeNodes.Clear();
113        imageList.Images.Clear();
114        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Class);      // default icon
115        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Namespace);  // plugins
116        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Interface);  // interfaces
117        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Template);   // generic types
118
119        var plugins = from p in ApplicationManager.Manager.Plugins
120                      orderby p.Name, p.Version ascending
121                      select p;
122        foreach (IPluginDescription plugin in plugins) {
123          TreeNode pluginNode = new TreeNode();
124          pluginNode.Text = string.Format("{0} {1}.{2}", plugin.Name, plugin.Version.Major, plugin.Version.Minor);
125          pluginNode.ImageIndex = 1;
126          pluginNode.SelectedImageIndex = pluginNode.ImageIndex;
127          pluginNode.Tag = plugin;
128
129          var types = from t in ApplicationManager.Manager.GetTypes(BaseTypes, plugin, !ShowNotInstantiableTypes, assignableToAllTypes)
130                      where typeCondition(t)
131                      orderby t.Name ascending
132                      select t;
133          foreach (Type type in types) {
134            bool valid = true;
135            valid = valid && (ShowGenericTypes || !type.ContainsGenericParameters);
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            }
154          }
155          if (pluginNode.Nodes.Count > 0)
156            treeNodes.Add(pluginNode);
157        }
158        foreach (TreeNode node in treeNodes)
159          typesTreeView.Nodes.Add((TreeNode)node.Clone());
160        RestoreSelectedNode(selectedNode);
161        Filter(searchTextBox.Text);
162
163        UpdateTypeParameters();
164      }
165    }
166
167    public virtual void Filter(string searchString) {
168      if (InvokeRequired)
169        Invoke(new Action<string>(Filter), searchString);
170      else {
171        searchString = searchString.ToLower();
172
173        if (!searchString.Contains(currentSearchString)) {
174          typesTreeView.BeginUpdate();
175          // expand search -> restore all tree nodes
176          TreeNode selectedNode = typesTreeView.SelectedNode;
177          typesTreeView.Nodes.Clear();
178          foreach (TreeNode node in treeNodes)
179            typesTreeView.Nodes.Add((TreeNode)node.Clone());
180          RestoreSelectedNode(selectedNode);
181          typesTreeView.EndUpdate();
182        }
183
184
185        // remove nodes
186        typesTreeView.BeginUpdate();
187        int i = 0;
188        while (i < typesTreeView.Nodes.Count) {
189          int j = 0;
190          while (j < typesTreeView.Nodes[i].Nodes.Count) {
191            if (!typesTreeView.Nodes[i].Nodes[j].Text.ToLower().Contains(searchString))
192              typesTreeView.Nodes[i].Nodes[j].Remove();
193            else
194              j++;
195          }
196          if (typesTreeView.Nodes[i].Nodes.Count == 0)
197            typesTreeView.Nodes[i].Remove();
198          else
199            i++;
200        }
201        typesTreeView.EndUpdate();
202        currentSearchString = searchString;
203
204        // if there is just one type node left, select by default
205        if (typesTreeView.Nodes.Count == 1) {
206          if (typesTreeView.Nodes[0].Nodes.Count == 1) {
207            typesTreeView.SelectedNode = typesTreeView.Nodes[0].Nodes[0];
208          }
209        }
210
211        if (typesTreeView.Nodes.Count == 0) {
212          SelectedType = null;
213          typesTreeView.Enabled = false;
214        } else {
215          SetTreeNodeVisibility();
216          typesTreeView.Enabled = true;
217        }
218        UpdateDescription();
219      }
220    }
221
222    public virtual object CreateInstanceOfSelectedType(params object[] args) {
223      if (SelectedType == null)
224        throw new InvalidOperationException("No type selected.");
225      else
226        return Activator.CreateInstance(SelectedType, args);
227    }
228
229    protected virtual void UpdateTypeParameters() {
230      typeParametersListView.Items.Clear();
231      if ((SelectedType == null) || !SelectedType.ContainsGenericParameters) {
232        typeParametersGroupBox.Enabled = false;
233        typeParametersSplitContainer.Panel2Collapsed = true;
234      } else {
235        typeParametersGroupBox.Enabled = true;
236        typeParametersSplitContainer.Panel2Collapsed = false;
237        setTypeParameterButton.Enabled = false;
238
239        foreach (Type param in SelectedType.GetGenericArguments()) {
240          if (param.IsGenericParameter) {
241            ListViewItem item = new ListViewItem();
242            item.Text = param.Name;
243
244            item.ToolTipText = "Constraints:";
245            Type[] constraints = param.GetGenericParameterConstraints();
246            if (constraints.Length == 0) {
247              item.ToolTipText += " none";
248            } else {
249              foreach (Type constraint in constraints)
250                item.ToolTipText += " " + constraint.GetPrettyName();
251            }
252
253            item.Tag = param;
254            typeParametersListView.Items.Add(item);
255          }
256        }
257        typeParametersListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
258      }
259    }
260
261    protected virtual void SetTypeParameter() {
262      if (typeSelectorDialog == null) {
263        typeSelectorDialog = new TypeSelectorDialog();
264        typeSelectorDialog.Caption = "Select Type of Generic Type Parameter";
265      }
266      Type param = typeParametersListView.SelectedItems[0].Tag as Type;
267      Type[] constraints = param.GetGenericParameterConstraints();
268      bool showNotInstantiableTypes = !param.GenericParameterAttributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint);
269      typeSelectorDialog.TypeSelector.Configure(constraints, showNotInstantiableTypes, true, true);
270
271      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
272        Type selected = typeSelectorDialog.TypeSelector.SelectedType;
273        Type[] parameters = SelectedType.GetGenericArguments();
274        parameters[param.GenericParameterPosition] = selected;
275        SelectedType = SelectedType.GetGenericTypeDefinition().MakeGenericType(parameters);
276
277        typeParametersListView.SelectedItems[0].Text = param.Name + ": " + selected.GetPrettyName();
278        typeParametersListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
279      }
280    }
281
282    protected virtual void UpdateDescription() {
283      descriptionTextBox.Text = string.Empty;
284
285      if (typesTreeView.SelectedNode != null) {
286        IPluginDescription plugin = typesTreeView.SelectedNode.Tag as IPluginDescription;
287        if (plugin != null) {
288          StringBuilder sb = new StringBuilder();
289          sb.Append("Plugin: ").Append(plugin.Name).Append(Environment.NewLine);
290          sb.Append("Version: ").Append(plugin.Version.ToString()).Append(Environment.NewLine);
291          descriptionTextBox.Text = sb.ToString();
292        }
293        Type type = typesTreeView.SelectedNode.Tag as Type;
294        if (type != null) {
295          string description = ItemAttribute.GetDescription(type);
296          if (description != null)
297            descriptionTextBox.Text = description;
298        }
299      } else if (typesTreeView.Nodes.Count == 0) {
300        descriptionTextBox.Text = "No types found";
301      }
302    }
303
304    #region Events
305    public event EventHandler SelectedTypeChanged;
306    protected virtual void OnSelectedTypeChanged() {
307      if (SelectedTypeChanged != null)
308        SelectedTypeChanged(this, EventArgs.Empty);
309    }
310    #endregion
311
312    #region Control Events
313    protected virtual void searchTextBox_TextChanged(object sender, System.EventArgs e) {
314      Filter(searchTextBox.Text);
315    }
316
317    protected virtual void typesTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
318      if (typesTreeView.SelectedNode == null) SelectedType = null;
319      else SelectedType = typesTreeView.SelectedNode.Tag as Type;
320      UpdateTypeParameters();
321      UpdateDescription();
322    }
323    protected virtual void typesTreeView_ItemDrag(object sender, ItemDragEventArgs e) {
324      TreeNode node = (TreeNode)e.Item;
325      Type type = node.Tag as Type;
326      if ((type != null) && (!type.IsInterface) && (!type.IsAbstract) && (!type.HasElementType) && (!type.ContainsGenericParameters)) {
327        object o = Activator.CreateInstance(type);
328        DataObject data = new DataObject();
329        data.SetData(HeuristicLab.Common.Constants.DragDropDataFormat, o);
330        DoDragDrop(data, DragDropEffects.Copy);
331      }
332    }
333    protected virtual void typesTreeView_VisibleChanged(object sender, EventArgs e) {
334      if (Visible) SetTreeNodeVisibility();
335    }
336
337    protected virtual void typeParametersListView_SelectedIndexChanged(object sender, EventArgs e) {
338      setTypeParameterButton.Enabled = typeParametersListView.SelectedItems.Count == 1;
339    }
340    protected virtual void typeParametersListView_DoubleClick(object sender, EventArgs e) {
341      if (typeParametersListView.SelectedItems.Count == 1)
342        SetTypeParameter();
343    }
344
345    protected virtual void setTypeParameterButton_Click(object sender, EventArgs e) {
346      SetTypeParameter();
347    }
348    #endregion
349
350    #region Helpers
351    private void RestoreSelectedNode(TreeNode selectedNode) {
352      if (selectedNode != null) {
353        foreach (TreeNode node in typesTreeView.Nodes) {
354          if (node.Text.Equals(selectedNode.Text)) typesTreeView.SelectedNode = node;
355          foreach (TreeNode child in node.Nodes) {
356            if ((child.Text.Equals(selectedNode.Text)) && (child.Tag == selectedNode.Tag))
357              typesTreeView.SelectedNode = child;
358          }
359        }
360        if (typesTreeView.SelectedNode == null) SelectedType = null;
361      }
362    }
363    private void SetTreeNodeVisibility() {
364      TreeNode selectedNode = typesTreeView.SelectedNode;
365      if (string.IsNullOrEmpty(currentSearchString) && (typesTreeView.Nodes.Count > 1)) {
366        typesTreeView.CollapseAll();
367        if (selectedNode != null) typesTreeView.SelectedNode = selectedNode;
368      } else {
369        typesTreeView.ExpandAll();
370      }
371      if (selectedNode != null) selectedNode.EnsureVisible();
372    }
373    #endregion
374  }
375}
Note: See TracBrowser for help on using the repository browser.