Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5524 was 5445, checked in by swagner, 13 years ago

Updated year of copyrights (#1406)

File size: 14.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.Text;
26using System.Windows.Forms;
27using HeuristicLab.Common;
28using HeuristicLab.PluginInfrastructure;
29
30namespace HeuristicLab.Core.Views {
31  public partial class TypeSelector : UserControl {
32    protected List<TreeNode> treeNodes;
33    protected string currentSearchString;
34    protected TypeSelectorDialog typeSelectorDialog;
35
36    protected Type baseType;
37    public Type BaseType {
38      get { return baseType; }
39    }
40    protected bool showNotInstantiableTypes;
41    public bool ShowNotInstantiableTypes {
42      get { return showNotInstantiableTypes; }
43    }
44    protected bool showGenericTypes;
45    public bool ShowGenericTypes {
46      get { return showGenericTypes; }
47    }
48    public string Caption {
49      get { return typesGroupBox.Text; }
50      set {
51        if (InvokeRequired)
52          Invoke(new Action<string>(delegate(string s) { Caption = s; }), value);
53        else
54          typesGroupBox.Text = value;
55      }
56    }
57    public TreeView TypesTreeView {
58      get { return typesTreeView; }
59    }
60    protected Type selectedType;
61    public Type SelectedType {
62      get { return selectedType; }
63      private set {
64        if (value != selectedType) {
65          selectedType = value;
66          OnSelectedTypeChanged();
67        }
68      }
69    }
70
71    public TypeSelector() {
72      InitializeComponent();
73      treeNodes = new List<TreeNode>();
74      currentSearchString = string.Empty;
75      selectedType = null;
76    }
77
78    protected override void Dispose(bool disposing) {
79      if (disposing) {
80        if (typeSelectorDialog != null) typeSelectorDialog.Dispose();
81        if (components != null) components.Dispose();
82      }
83      base.Dispose(disposing);
84    }
85
86    public virtual void Configure(Type baseType, bool showNotInstantiableTypes, bool showGenericTypes) {
87      if (baseType == null) throw new ArgumentNullException();
88      if (InvokeRequired)
89        Invoke(new Action<Type, bool, bool>(Configure), baseType, showNotInstantiableTypes, showGenericTypes);
90      else {
91        this.baseType = baseType;
92        this.showNotInstantiableTypes = showNotInstantiableTypes;
93        this.showGenericTypes = showGenericTypes;
94
95        typeParametersSplitContainer.Panel2Collapsed = !showGenericTypes;
96
97        TreeNode selectedNode = typesTreeView.SelectedNode;
98        typesTreeView.Nodes.Clear();
99        treeNodes.Clear();
100        imageList.Images.Clear();
101        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Class);      // default icon
102        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Namespace);  // plugins
103        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Interface);  // interfaces
104        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Template);   // generic types
105
106        var plugins = from p in ApplicationManager.Manager.Plugins
107                      orderby p.Name, p.Version ascending
108                      select p;
109        foreach (IPluginDescription plugin in plugins) {
110          TreeNode pluginNode = new TreeNode();
111          pluginNode.Text = plugin.Name;
112          pluginNode.ImageIndex = 1;
113          pluginNode.SelectedImageIndex = pluginNode.ImageIndex;
114          pluginNode.Tag = plugin;
115
116          var types = from t in ApplicationManager.Manager.GetTypes(BaseType, plugin, false)
117                      orderby t.Name ascending
118                      select t;
119          foreach (Type type in types) {
120            bool valid = true;
121            valid = valid && (ShowGenericTypes || !type.ContainsGenericParameters);
122            valid = valid && (ShowNotInstantiableTypes || !type.IsAbstract);
123            valid = valid && (ShowNotInstantiableTypes || !type.IsInterface);
124            valid = valid && (ShowNotInstantiableTypes || !type.HasElementType);
125            valid = valid && (ShowNotInstantiableTypes || type.GetConstructor(Type.EmptyTypes) != null); //check for public default ctor
126            if (valid) {
127              TreeNode typeNode = new TreeNode();
128              string name = ItemAttribute.GetName(type);
129              typeNode.Text = name != null ? name : type.GetPrettyName();
130              typeNode.ImageIndex = 0;
131              if (type.IsInterface) typeNode.ImageIndex = 2;
132              else if (type.ContainsGenericParameters) typeNode.ImageIndex = 3;
133              else if (imageList.Images.ContainsKey(type.FullName)) typeNode.ImageIndex = imageList.Images.IndexOfKey(type.FullName);
134              else if (typeof(IItem).IsAssignableFrom(type) && !type.IsInterface && !type.IsAbstract) {
135                try {
136                  IItem item = (IItem)Activator.CreateInstance(type);
137                  imageList.Images.Add(type.FullName, item.ItemImage);
138                  typeNode.ImageIndex = imageList.Images.IndexOfKey(type.FullName);
139                } catch (Exception) { }
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[] contraints = param.GetGenericParameterConstraints();
259      typeSelectorDialog.TypeSelector.Configure(typeof(IItem), true, true);
260
261      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
262        Type selected = typeSelectorDialog.TypeSelector.SelectedType;
263        Type[] parameters = SelectedType.GetGenericArguments();
264        parameters[param.GenericParameterPosition] = selected;
265        SelectedType = SelectedType.GetGenericTypeDefinition().MakeGenericType(parameters);
266
267        typeParametersListView.SelectedItems[0].Text = param.Name + ": " + selected.GetPrettyName();
268        typeParametersListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
269      }
270    }
271
272    protected virtual void UpdateDescription() {
273      descriptionTextBox.Text = string.Empty;
274
275      if (typesTreeView.SelectedNode != null) {
276        IPluginDescription plugin = typesTreeView.SelectedNode.Tag as IPluginDescription;
277        if (plugin != null) {
278          StringBuilder sb = new StringBuilder();
279          sb.Append("Plugin: ").Append(plugin.Name).Append(Environment.NewLine);
280          sb.Append("Version: ").Append(plugin.Version.ToString()).Append(Environment.NewLine);
281          descriptionTextBox.Text = sb.ToString();
282        }
283        Type type = typesTreeView.SelectedNode.Tag as Type;
284        if (type != null) {
285          string description = ItemAttribute.GetDescription(type);
286          if (description != null)
287            descriptionTextBox.Text = description;
288        }
289      } else if (typesTreeView.Nodes.Count == 0) {
290        descriptionTextBox.Text = "No types found";
291      }
292    }
293
294    #region Events
295    public event EventHandler SelectedTypeChanged;
296    protected virtual void OnSelectedTypeChanged() {
297      if (SelectedTypeChanged != null)
298        SelectedTypeChanged(this, EventArgs.Empty);
299    }
300    #endregion
301
302    #region Control Events
303    protected virtual void searchTextBox_TextChanged(object sender, System.EventArgs e) {
304      Filter(searchTextBox.Text);
305    }
306
307    protected virtual void typesTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
308      if (typesTreeView.SelectedNode == null) SelectedType = null;
309      else SelectedType = typesTreeView.SelectedNode.Tag as Type;
310      UpdateTypeParameters();
311      UpdateDescription();
312    }
313    protected virtual void typesTreeView_ItemDrag(object sender, ItemDragEventArgs e) {
314      TreeNode node = (TreeNode)e.Item;
315      Type type = node.Tag as Type;
316      if ((type != null) && (!type.IsInterface) && (!type.IsAbstract) && (!type.HasElementType) && (!type.ContainsGenericParameters)) {
317        object o = Activator.CreateInstance(type);
318        DataObject data = new DataObject();
319        data.SetData("Type", type);
320        data.SetData("Value", 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.