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

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

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

File size: 14.7 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(new List<Type>() { baseType }, showNotInstantiableTypes, showGenericTypes, true);
89    }
90
91    public virtual void Configure(IEnumerable<Type> baseTypes, bool showNotInstantiableTypes, bool showGenericTypes, bool allTypes) {
92      if (baseTypes == null) throw new ArgumentNullException();
93      if (InvokeRequired)
94        Invoke(new Action<IEnumerable<Type>, bool, bool, bool>(Configure), baseTypes, showNotInstantiableTypes, showGenericTypes, allTypes);
95      else {
96        this.baseTypes = baseTypes;
97        this.showNotInstantiableTypes = showNotInstantiableTypes;
98        this.showGenericTypes = showGenericTypes;
99
100        typeParametersSplitContainer.Panel2Collapsed = !showGenericTypes;
101
102        TreeNode selectedNode = typesTreeView.SelectedNode;
103        typesTreeView.Nodes.Clear();
104        treeNodes.Clear();
105        imageList.Images.Clear();
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
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();
116          pluginNode.Text = string.Format("{0} {1}.{2}", plugin.Name, plugin.Version.Major, plugin.Version.Minor);
117          pluginNode.ImageIndex = 1;
118          pluginNode.SelectedImageIndex = pluginNode.ImageIndex;
119          pluginNode.Tag = plugin;
120
121          var types = from t in ApplicationManager.Manager.GetTypes(BaseTypes, plugin, ShowNotInstantiableTypes, allTypes)
122                      orderby t.Name ascending
123                      select t;
124          foreach (Type type in types) {
125            bool valid = true;
126            valid = valid && (ShowGenericTypes || !type.ContainsGenericParameters);
127            valid = valid && (ShowNotInstantiableTypes || type.GetConstructor(Type.EmptyTypes) != null); //check for public default ctor
128            if (valid) {
129              TreeNode typeNode = new TreeNode();
130              string name = ItemAttribute.GetName(type);
131              typeNode.Text = name != null ? name : type.GetPrettyName();
132              typeNode.ImageIndex = 0;
133              if (type.IsInterface) typeNode.ImageIndex = 2;
134              else if (type.ContainsGenericParameters) typeNode.ImageIndex = 3;
135              else if (imageList.Images.ContainsKey(type.FullName)) typeNode.ImageIndex = imageList.Images.IndexOfKey(type.FullName);
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);
140              }
141              typeNode.SelectedImageIndex = typeNode.ImageIndex;
142              typeNode.Tag = type;
143              pluginNode.Nodes.Add(typeNode);
144            }
145          }
146          if (pluginNode.Nodes.Count > 0)
147            treeNodes.Add(pluginNode);
148        }
149        foreach (TreeNode node in treeNodes)
150          typesTreeView.Nodes.Add((TreeNode)node.Clone());
151        RestoreSelectedNode(selectedNode);
152        Filter(searchTextBox.Text);
153
154        UpdateTypeParameters();
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();
163
164        if (!searchString.Contains(currentSearchString)) {
165          typesTreeView.BeginUpdate();
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);
172          typesTreeView.EndUpdate();
173        }
174
175
176        // remove nodes
177        typesTreeView.BeginUpdate();
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        }
192        typesTreeView.EndUpdate();
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
202        if (typesTreeView.Nodes.Count == 0) {
203          SelectedType = null;
204          typesTreeView.Enabled = false;
205        } else {
206          SetTreeNodeVisibility();
207          typesTreeView.Enabled = true;
208        }
209        UpdateDescription();
210      }
211    }
212
213    public virtual object CreateInstanceOfSelectedType(params object[] args) {
214      if (SelectedType == null)
215        throw new InvalidOperationException("No type selected.");
216      else
217        return Activator.CreateInstance(SelectedType, args);
218    }
219
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      }
250    }
251
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;
258      Type[] constraints = param.GetGenericParameterConstraints();
259      bool showNotInstantiableTypes = !param.GenericParameterAttributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint);
260      typeSelectorDialog.TypeSelector.Configure(constraints, showNotInstantiableTypes, true, true);
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
273    protected virtual void UpdateDescription() {
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        }
290      } else if (typesTreeView.Nodes.Count == 0) {
291        descriptionTextBox.Text = "No types found";
292      }
293    }
294
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
304    protected virtual void searchTextBox_TextChanged(object sender, System.EventArgs e) {
305      Filter(searchTextBox.Text);
306    }
307
308    protected virtual void typesTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
309      if (typesTreeView.SelectedNode == null) SelectedType = null;
310      else SelectedType = typesTreeView.SelectedNode.Tag as Type;
311      UpdateTypeParameters();
312      UpdateDescription();
313    }
314    protected virtual void typesTreeView_ItemDrag(object sender, ItemDragEventArgs e) {
315      TreeNode node = (TreeNode)e.Item;
316      Type type = node.Tag as Type;
317      if ((type != null) && (!type.IsInterface) && (!type.IsAbstract) && (!type.HasElementType) && (!type.ContainsGenericParameters)) {
318        object o = Activator.CreateInstance(type);
319        DataObject data = new DataObject();
320        data.SetData(HeuristicLab.Common.Constants.DragDropDataFormat, o);
321        DoDragDrop(data, DragDropEffects.Copy);
322      }
323    }
324    protected virtual void typesTreeView_VisibleChanged(object sender, EventArgs e) {
325      if (Visible) SetTreeNodeVisibility();
326    }
327
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
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;
356      if (string.IsNullOrEmpty(currentSearchString) && (typesTreeView.Nodes.Count > 1)) {
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
365  }
366}
Note: See TracBrowser for help on using the repository browser.