Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3528 was 3528, checked in by swagner, 14 years ago

Implemented reviewers' comments (#893)

File size: 10.9 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.Linq;
24using System.Text;
25using System.Windows.Forms;
26using HeuristicLab.Common;
27using HeuristicLab.PluginInfrastructure;
28using System.Collections.Generic;
29
30namespace HeuristicLab.Core.Views {
31  public partial class TypeSelector : UserControl {
32    protected List<TreeNode> treeNodes;
33    protected string currentSearchString;
34
35    protected Type baseType;
36    public Type BaseType {
37      get { return baseType; }
38    }
39    protected bool showNotInstantiableTypes;
40    public bool ShowNotInstantiableTypes {
41      get { return showNotInstantiableTypes; }
42    }
43    protected bool showGenericTypes;
44    public bool ShowGenericTypes {
45      get { return showGenericTypes; }
46    }
47    public string Caption {
48      get { return typesGroupBox.Text; }
49      set {
50        if (InvokeRequired)
51          Invoke(new Action<string>(delegate(string s) { Caption = s; }), value);
52        else
53          typesGroupBox.Text = value;
54      }
55    }
56    public TreeView TypesTreeView {
57      get { return typesTreeView; }
58    }
59    protected Type selectedType;
60    public Type SelectedType {
61      get { return selectedType; }
62      private set {
63        if (value != selectedType) {
64          selectedType = value;
65          OnSelectedTypeChanged();
66        }
67      }
68    }
69
70    public TypeSelector() {
71      InitializeComponent();
72      treeNodes = new List<TreeNode>();
73      currentSearchString = string.Empty;
74      selectedType = null;
75    }
76
77    public virtual void Configure(Type baseType, bool showNotInstantiableTypes, bool showGenericTypes) {
78      if (baseType == null) throw new ArgumentNullException();
79      if (InvokeRequired)
80        Invoke(new Action<Type, bool, bool>(Configure), baseType, showNotInstantiableTypes, showGenericTypes);
81      else {
82        this.baseType = baseType;
83        this.showNotInstantiableTypes = showNotInstantiableTypes;
84        this.showGenericTypes = showGenericTypes;
85
86        TreeNode selectedNode = typesTreeView.SelectedNode;
87        typesTreeView.Nodes.Clear();
88        treeNodes.Clear();
89        imageList.Images.Clear();
90        imageList.Images.Add(HeuristicLab.Common.Resources.VS2008ImageLibrary.Class);      // default icon
91        imageList.Images.Add(HeuristicLab.Common.Resources.VS2008ImageLibrary.Namespace);  // plugins
92        imageList.Images.Add(HeuristicLab.Common.Resources.VS2008ImageLibrary.Interface);  // interfaces
93        imageList.Images.Add(HeuristicLab.Common.Resources.VS2008ImageLibrary.Template);   // generic types
94
95        var plugins = from p in ApplicationManager.Manager.Plugins
96                      orderby p.Name, p.Version ascending
97                      select p;
98        foreach (IPluginDescription plugin in plugins) {
99          TreeNode pluginNode = new TreeNode();
100          pluginNode.Text = plugin.Name;
101          pluginNode.ImageIndex = 1;
102          pluginNode.SelectedImageIndex = pluginNode.ImageIndex;
103          pluginNode.Tag = plugin;
104
105          var types = from t in ApplicationManager.Manager.GetTypes(BaseType, plugin, false)
106                      orderby t.Name ascending
107                      select t;
108          foreach (Type type in types) {
109            bool valid = true;
110            valid = valid && (ShowGenericTypes || !type.ContainsGenericParameters);
111            valid = valid && (ShowNotInstantiableTypes || !type.IsAbstract);
112            valid = valid && (ShowNotInstantiableTypes || !type.IsInterface);
113            valid = valid && (ShowNotInstantiableTypes || !type.HasElementType);
114            if (valid) {
115              TreeNode typeNode = new TreeNode();
116              string name = ItemAttribute.GetName(type);
117              typeNode.Text = name != null ? name : type.GetPrettyName();
118              typeNode.ImageIndex = 0;
119              if (type.IsInterface) typeNode.ImageIndex = 2;
120              else if (type.ContainsGenericParameters) typeNode.ImageIndex = 3;
121              else if (imageList.Images.ContainsKey(type.FullName)) typeNode.ImageIndex = imageList.Images.IndexOfKey(type.FullName);
122              else if (typeof(IItem).IsAssignableFrom(type)) {
123                try {
124                  IItem item = (IItem)Activator.CreateInstance(type);
125                  imageList.Images.Add(type.FullName, item.ItemImage);
126                  typeNode.ImageIndex = imageList.Images.IndexOfKey(type.FullName);
127                }
128                catch (Exception) { }
129              }
130              typeNode.SelectedImageIndex = typeNode.ImageIndex;
131              typeNode.Tag = type;
132              pluginNode.Nodes.Add(typeNode);
133            }
134          }
135          if (pluginNode.Nodes.Count > 0)
136            treeNodes.Add(pluginNode);
137        }
138        foreach (TreeNode node in treeNodes)
139          typesTreeView.Nodes.Add((TreeNode)node.Clone());
140        RestoreSelectedNode(selectedNode);
141        Filter(searchTextBox.Text);
142      }
143    }
144
145    public virtual void Filter(string searchString) {
146      if (InvokeRequired)
147        Invoke(new Action<string>(Filter), searchString);
148      else {
149        searchString = searchString.ToLower();
150        typesTreeView.BeginUpdate();
151        if (!searchString.Contains(currentSearchString)) {
152          // expand search -> restore all tree nodes
153          TreeNode selectedNode = typesTreeView.SelectedNode;
154          typesTreeView.Nodes.Clear();
155          foreach (TreeNode node in treeNodes)
156            typesTreeView.Nodes.Add((TreeNode)node.Clone());
157          RestoreSelectedNode(selectedNode);
158        }
159
160        // remove nodes
161        int i = 0;
162        while (i < typesTreeView.Nodes.Count) {
163          int j = 0;
164          while (j < typesTreeView.Nodes[i].Nodes.Count) {
165            if (!typesTreeView.Nodes[i].Nodes[j].Text.ToLower().Contains(searchString))
166              typesTreeView.Nodes[i].Nodes[j].Remove();
167            else
168              j++;
169          }
170          if (typesTreeView.Nodes[i].Nodes.Count == 0)
171            typesTreeView.Nodes[i].Remove();
172          else
173            i++;
174        }
175        typesTreeView.EndUpdate();
176        currentSearchString = searchString;
177
178        // if there is just one type node left, select by default
179        if (typesTreeView.Nodes.Count == 1) {
180          if (typesTreeView.Nodes[0].Nodes.Count == 1) {
181            typesTreeView.SelectedNode = typesTreeView.Nodes[0].Nodes[0];
182          }
183        }
184
185        if (typesTreeView.Nodes.Count == 0) {
186          SelectedType = null;
187          typesTreeView.Enabled = false;
188        } else {
189          SetTreeNodeVisibility();
190          typesTreeView.Enabled = true;
191        }
192        UpdateDescription();
193      }
194    }
195
196    public virtual object CreateInstanceOfSelectedType(params object[] args) {
197      if (SelectedType == null)
198        throw new InvalidOperationException("No type selected.");
199      else
200        return Activator.CreateInstance(SelectedType, args);
201    }
202
203    public event EventHandler SelectedTypeChanged;
204    protected virtual void OnSelectedTypeChanged() {
205      if (SelectedTypeChanged != null)
206        SelectedTypeChanged(this, EventArgs.Empty);
207    }
208
209    protected virtual void UpdateDescription() {
210      descriptionTextBox.Text = string.Empty;
211
212      if (typesTreeView.SelectedNode != null) {
213        IPluginDescription plugin = typesTreeView.SelectedNode.Tag as IPluginDescription;
214        if (plugin != null) {
215          StringBuilder sb = new StringBuilder();
216          sb.Append("Plugin: ").Append(plugin.Name).Append(Environment.NewLine);
217          sb.Append("Version: ").Append(plugin.Version.ToString()).Append(Environment.NewLine);
218          descriptionTextBox.Text = sb.ToString();
219        }
220        Type type = typesTreeView.SelectedNode.Tag as Type;
221        if (type != null) {
222          string description = ItemAttribute.GetDescription(type);
223          if (description != null)
224            descriptionTextBox.Text = description;
225        }
226      } else if (typesTreeView.Nodes.Count == 0) {
227        descriptionTextBox.Text = "No types found";
228      }
229    }
230
231    protected virtual void searchTextBox_TextChanged(object sender, System.EventArgs e) {
232      Filter(searchTextBox.Text);
233    }
234
235    protected virtual void typesTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
236      if (typesTreeView.SelectedNode == null) SelectedType = null;
237      else SelectedType = typesTreeView.SelectedNode.Tag as Type;
238      UpdateDescription();
239    }
240
241    protected virtual void typesTreeView_ItemDrag(object sender, ItemDragEventArgs e) {
242      TreeNode node = (TreeNode)e.Item;
243      Type type = node.Tag as Type;
244      if ((type != null) && (!type.IsInterface) && (!type.IsAbstract) && (!type.HasElementType) && (!type.ContainsGenericParameters)) {
245        object o = Activator.CreateInstance(type);
246        DataObject data = new DataObject();
247        data.SetData("Type", type);
248        data.SetData("Value", o);
249        DoDragDrop(data, DragDropEffects.Copy);
250      }
251    }
252
253    protected virtual void typesTreeView_VisibleChanged(object sender, EventArgs e) {
254      if (Visible) SetTreeNodeVisibility();
255    }
256
257    #region Helpers
258    private void RestoreSelectedNode(TreeNode selectedNode) {
259      if (selectedNode != null) {
260        foreach (TreeNode node in typesTreeView.Nodes) {
261          if (node.Text.Equals(selectedNode.Text)) typesTreeView.SelectedNode = node;
262          foreach (TreeNode child in node.Nodes) {
263            if ((child.Text.Equals(selectedNode.Text)) && (child.Tag == selectedNode.Tag))
264              typesTreeView.SelectedNode = child;
265          }
266        }
267        if (typesTreeView.SelectedNode == null) SelectedType = null;
268      }
269    }
270    private void SetTreeNodeVisibility() {
271      TreeNode selectedNode = typesTreeView.SelectedNode;
272      if (string.IsNullOrEmpty(currentSearchString) && (typesTreeView.Nodes.Count > 1)) {
273        typesTreeView.CollapseAll();
274        if (selectedNode != null) typesTreeView.SelectedNode = selectedNode;
275      } else {
276        typesTreeView.ExpandAll();
277      }
278      if (selectedNode != null) selectedNode.EnsureVisible();
279    }
280    #endregion
281  }
282}
Note: See TracBrowser for help on using the repository browser.