Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1454: Updated TypeSelector to handle logical connection operators when discovering multiple types.

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