Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4300 was 4261, checked in by mkommend, 14 years ago

Added a check for a public default ctor in the TypeSelectorDialog (ticket #1162).

File size: 14.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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    public virtual void Configure(Type baseType, bool showNotInstantiableTypes, bool showGenericTypes) {
79      if (baseType == null) throw new ArgumentNullException();
80      if (InvokeRequired)
81        Invoke(new Action<Type, bool, bool>(Configure), baseType, showNotInstantiableTypes, showGenericTypes);
82      else {
83        this.baseType = baseType;
84        this.showNotInstantiableTypes = showNotInstantiableTypes;
85        this.showGenericTypes = showGenericTypes;
86
87        typeParametersSplitContainer.Panel2Collapsed = !showGenericTypes;
88
89        TreeNode selectedNode = typesTreeView.SelectedNode;
90        typesTreeView.Nodes.Clear();
91        treeNodes.Clear();
92        imageList.Images.Clear();
93        imageList.Images.Add(HeuristicLab.Common.Resources.VS2008ImageLibrary.Class);      // default icon
94        imageList.Images.Add(HeuristicLab.Common.Resources.VS2008ImageLibrary.Namespace);  // plugins
95        imageList.Images.Add(HeuristicLab.Common.Resources.VS2008ImageLibrary.Interface);  // interfaces
96        imageList.Images.Add(HeuristicLab.Common.Resources.VS2008ImageLibrary.Template);   // generic types
97
98        var plugins = from p in ApplicationManager.Manager.Plugins
99                      orderby p.Name, p.Version ascending
100                      select p;
101        foreach (IPluginDescription plugin in plugins) {
102          TreeNode pluginNode = new TreeNode();
103          pluginNode.Text = plugin.Name;
104          pluginNode.ImageIndex = 1;
105          pluginNode.SelectedImageIndex = pluginNode.ImageIndex;
106          pluginNode.Tag = plugin;
107
108          var types = from t in ApplicationManager.Manager.GetTypes(BaseType, plugin, false)
109                      orderby t.Name ascending
110                      select t;
111          foreach (Type type in types) {
112            bool valid = true;
113            valid = valid && (ShowGenericTypes || !type.ContainsGenericParameters);
114            valid = valid && (ShowNotInstantiableTypes || !type.IsAbstract);
115            valid = valid && (ShowNotInstantiableTypes || !type.IsInterface);
116            valid = valid && (ShowNotInstantiableTypes || !type.HasElementType);
117            valid = valid && (ShowNotInstantiableTypes || type.GetConstructor(Type.EmptyTypes) != null); //check for public default ctor
118            if (valid) {
119              TreeNode typeNode = new TreeNode();
120              string name = ItemAttribute.GetName(type);
121              typeNode.Text = name != null ? name : type.GetPrettyName();
122              typeNode.ImageIndex = 0;
123              if (type.IsInterface) typeNode.ImageIndex = 2;
124              else if (type.ContainsGenericParameters) typeNode.ImageIndex = 3;
125              else if (imageList.Images.ContainsKey(type.FullName)) typeNode.ImageIndex = imageList.Images.IndexOfKey(type.FullName);
126              else if (typeof(IItem).IsAssignableFrom(type) && !type.IsInterface && !type.IsAbstract) {
127                try {
128                  IItem item = (IItem)Activator.CreateInstance(type);
129                  imageList.Images.Add(type.FullName, item.ItemImage);
130                  typeNode.ImageIndex = imageList.Images.IndexOfKey(type.FullName);
131                }
132                catch (Exception) { }
133              }
134              typeNode.SelectedImageIndex = typeNode.ImageIndex;
135              typeNode.Tag = type;
136              pluginNode.Nodes.Add(typeNode);
137            }
138          }
139          if (pluginNode.Nodes.Count > 0)
140            treeNodes.Add(pluginNode);
141        }
142        foreach (TreeNode node in treeNodes)
143          typesTreeView.Nodes.Add((TreeNode)node.Clone());
144        RestoreSelectedNode(selectedNode);
145        Filter(searchTextBox.Text);
146
147        UpdateTypeParameters();
148      }
149    }
150
151    public virtual void Filter(string searchString) {
152      if (InvokeRequired)
153        Invoke(new Action<string>(Filter), searchString);
154      else {
155        searchString = searchString.ToLower();
156        typesTreeView.BeginUpdate();
157        if (!searchString.Contains(currentSearchString)) {
158          // expand search -> restore all tree nodes
159          TreeNode selectedNode = typesTreeView.SelectedNode;
160          typesTreeView.Nodes.Clear();
161          foreach (TreeNode node in treeNodes)
162            typesTreeView.Nodes.Add((TreeNode)node.Clone());
163          RestoreSelectedNode(selectedNode);
164        }
165
166        // remove nodes
167        int i = 0;
168        while (i < typesTreeView.Nodes.Count) {
169          int j = 0;
170          while (j < typesTreeView.Nodes[i].Nodes.Count) {
171            if (!typesTreeView.Nodes[i].Nodes[j].Text.ToLower().Contains(searchString))
172              typesTreeView.Nodes[i].Nodes[j].Remove();
173            else
174              j++;
175          }
176          if (typesTreeView.Nodes[i].Nodes.Count == 0)
177            typesTreeView.Nodes[i].Remove();
178          else
179            i++;
180        }
181        typesTreeView.EndUpdate();
182        currentSearchString = searchString;
183
184        // if there is just one type node left, select by default
185        if (typesTreeView.Nodes.Count == 1) {
186          if (typesTreeView.Nodes[0].Nodes.Count == 1) {
187            typesTreeView.SelectedNode = typesTreeView.Nodes[0].Nodes[0];
188          }
189        }
190
191        if (typesTreeView.Nodes.Count == 0) {
192          SelectedType = null;
193          typesTreeView.Enabled = false;
194        } else {
195          SetTreeNodeVisibility();
196          typesTreeView.Enabled = true;
197        }
198        UpdateDescription();
199      }
200    }
201
202    public virtual object CreateInstanceOfSelectedType(params object[] args) {
203      if (SelectedType == null)
204        throw new InvalidOperationException("No type selected.");
205      else
206        return Activator.CreateInstance(SelectedType, args);
207    }
208
209    protected virtual void UpdateTypeParameters() {
210      typeParametersListView.Items.Clear();
211      if ((SelectedType == null) || !SelectedType.ContainsGenericParameters) {
212        typeParametersGroupBox.Enabled = false;
213        typeParametersSplitContainer.Panel2Collapsed = true;
214      } else {
215        typeParametersGroupBox.Enabled = true;
216        typeParametersSplitContainer.Panel2Collapsed = false;
217        setTypeParameterButton.Enabled = false;
218
219        foreach (Type param in SelectedType.GetGenericArguments()) {
220          if (param.IsGenericParameter) {
221            ListViewItem item = new ListViewItem();
222            item.Text = param.Name;
223
224            item.ToolTipText = "Constraints:";
225            Type[] constraints = param.GetGenericParameterConstraints();
226            if (constraints.Length == 0) {
227              item.ToolTipText += " none";
228            } else {
229              foreach (Type constraint in constraints)
230                item.ToolTipText += " " + constraint.GetPrettyName();
231            }
232
233            item.Tag = param;
234            typeParametersListView.Items.Add(item);
235          }
236        }
237        typeParametersListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
238      }
239    }
240
241    protected virtual void SetTypeParameter() {
242      if (typeSelectorDialog == null) {
243        typeSelectorDialog = new TypeSelectorDialog();
244        typeSelectorDialog.Caption = "Select Type of Generic Type Parameter";
245      }
246      Type param = typeParametersListView.SelectedItems[0].Tag as Type;
247      Type[] contraints = param.GetGenericParameterConstraints();
248      typeSelectorDialog.TypeSelector.Configure(typeof(IItem), true, true);
249
250      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
251        Type selected = typeSelectorDialog.TypeSelector.SelectedType;
252        Type[] parameters = SelectedType.GetGenericArguments();
253        parameters[param.GenericParameterPosition] = selected;
254        SelectedType = SelectedType.GetGenericTypeDefinition().MakeGenericType(parameters);
255
256        typeParametersListView.SelectedItems[0].Text = param.Name + ": " + selected.GetPrettyName();
257        typeParametersListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
258      }
259    }
260
261    protected virtual void UpdateDescription() {
262      descriptionTextBox.Text = string.Empty;
263
264      if (typesTreeView.SelectedNode != null) {
265        IPluginDescription plugin = typesTreeView.SelectedNode.Tag as IPluginDescription;
266        if (plugin != null) {
267          StringBuilder sb = new StringBuilder();
268          sb.Append("Plugin: ").Append(plugin.Name).Append(Environment.NewLine);
269          sb.Append("Version: ").Append(plugin.Version.ToString()).Append(Environment.NewLine);
270          descriptionTextBox.Text = sb.ToString();
271        }
272        Type type = typesTreeView.SelectedNode.Tag as Type;
273        if (type != null) {
274          string description = ItemAttribute.GetDescription(type);
275          if (description != null)
276            descriptionTextBox.Text = description;
277        }
278      } else if (typesTreeView.Nodes.Count == 0) {
279        descriptionTextBox.Text = "No types found";
280      }
281    }
282
283    #region Events
284    public event EventHandler SelectedTypeChanged;
285    protected virtual void OnSelectedTypeChanged() {
286      if (SelectedTypeChanged != null)
287        SelectedTypeChanged(this, EventArgs.Empty);
288    }
289    #endregion
290
291    #region Control Events
292    protected virtual void searchTextBox_TextChanged(object sender, System.EventArgs e) {
293      Filter(searchTextBox.Text);
294    }
295
296    protected virtual void typesTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
297      if (typesTreeView.SelectedNode == null) SelectedType = null;
298      else SelectedType = typesTreeView.SelectedNode.Tag as Type;
299      UpdateTypeParameters();
300      UpdateDescription();
301    }
302    protected virtual void typesTreeView_ItemDrag(object sender, ItemDragEventArgs e) {
303      TreeNode node = (TreeNode)e.Item;
304      Type type = node.Tag as Type;
305      if ((type != null) && (!type.IsInterface) && (!type.IsAbstract) && (!type.HasElementType) && (!type.ContainsGenericParameters)) {
306        object o = Activator.CreateInstance(type);
307        DataObject data = new DataObject();
308        data.SetData("Type", type);
309        data.SetData("Value", o);
310        DoDragDrop(data, DragDropEffects.Copy);
311      }
312    }
313    protected virtual void typesTreeView_VisibleChanged(object sender, EventArgs e) {
314      if (Visible) SetTreeNodeVisibility();
315    }
316
317    protected virtual void typeParametersListView_SelectedIndexChanged(object sender, EventArgs e) {
318      setTypeParameterButton.Enabled = typeParametersListView.SelectedItems.Count == 1;
319    }
320    protected virtual void typeParametersListView_DoubleClick(object sender, EventArgs e) {
321      if (typeParametersListView.SelectedItems.Count == 1)
322        SetTypeParameter();
323    }
324
325    protected virtual void setTypeParameterButton_Click(object sender, EventArgs e) {
326      SetTypeParameter();
327    }
328    #endregion
329
330    #region Helpers
331    private void RestoreSelectedNode(TreeNode selectedNode) {
332      if (selectedNode != null) {
333        foreach (TreeNode node in typesTreeView.Nodes) {
334          if (node.Text.Equals(selectedNode.Text)) typesTreeView.SelectedNode = node;
335          foreach (TreeNode child in node.Nodes) {
336            if ((child.Text.Equals(selectedNode.Text)) && (child.Tag == selectedNode.Tag))
337              typesTreeView.SelectedNode = child;
338          }
339        }
340        if (typesTreeView.SelectedNode == null) SelectedType = null;
341      }
342    }
343    private void SetTreeNodeVisibility() {
344      TreeNode selectedNode = typesTreeView.SelectedNode;
345      if (string.IsNullOrEmpty(currentSearchString) && (typesTreeView.Nodes.Count > 1)) {
346        typesTreeView.CollapseAll();
347        if (selectedNode != null) typesTreeView.SelectedNode = selectedNode;
348      } else {
349        typesTreeView.ExpandAll();
350      }
351      if (selectedNode != null) selectedNode.EnsureVisible();
352    }
353    #endregion
354  }
355}
Note: See TracBrowser for help on using the repository browser.