Free cookie consent management tool by TermsFeed Policy Generator

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

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

Fixed exception handling in TypeSelector (#906)

File size: 11.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.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.OrgChart);   // abstract types
94        imageList.Images.Add(HeuristicLab.Common.Resources.VS2008ImageLibrary.Template);   // generic types
95
96        var plugins = from p in ApplicationManager.Manager.Plugins
97                      orderby p.Name, p.Version ascending
98                      select p;
99        foreach (IPluginDescription plugin in plugins) {
100          TreeNode pluginNode = new TreeNode();
101          pluginNode.Text = plugin.Name;
102          pluginNode.ImageIndex = 1;
103          pluginNode.SelectedImageIndex = pluginNode.ImageIndex;
104          pluginNode.Tag = plugin;
105
106          var types = from t in ApplicationManager.Manager.GetTypes(BaseType, plugin, false)
107                      orderby t.Name ascending
108                      select t;
109          foreach (Type type in types) {
110            bool valid = true;
111            valid = valid && (ShowGenericTypes || !type.ContainsGenericParameters);
112            valid = valid && (ShowNotInstantiableTypes || !type.IsAbstract);
113            valid = valid && (ShowNotInstantiableTypes || !type.IsInterface);
114            valid = valid && (ShowNotInstantiableTypes || !type.HasElementType);
115            if (valid) {
116              TreeNode typeNode = new TreeNode();
117              string name = ItemAttribute.GetName(type);
118              typeNode.Text = name != null ? name : type.GetPrettyName();
119              typeNode.ImageIndex = 0;
120              if (type.IsInterface) typeNode.ImageIndex = 2;
121              else if (type.IsAbstract) typeNode.ImageIndex = 3;
122              else if (type.ContainsGenericParameters) typeNode.ImageIndex = 4;
123              else if (imageList.Images.ContainsKey(type.FullName)) typeNode.ImageIndex = imageList.Images.IndexOfKey(type.FullName);
124              else if (typeof(IItem).IsAssignableFrom(type)) {
125                try {
126                  IItem item = (IItem)Activator.CreateInstance(type);
127                  imageList.Images.Add(type.FullName, item.ItemImage);
128                  typeNode.ImageIndex = imageList.Images.IndexOfKey(type.FullName);
129                }
130                catch (Exception) { }
131              }
132              typeNode.SelectedImageIndex = typeNode.ImageIndex;
133              typeNode.Tag = type;
134              pluginNode.Nodes.Add(typeNode);
135            }
136          }
137          if (pluginNode.Nodes.Count > 0)
138            treeNodes.Add(pluginNode);
139        }
140        foreach (TreeNode node in treeNodes)
141          typesTreeView.Nodes.Add((TreeNode)node.Clone());
142        RestoreSelectedNode(selectedNode);
143        Filter(searchTextBox.Text);
144      }
145    }
146
147    public virtual void Filter(string searchString) {
148      if (InvokeRequired)
149        Invoke(new Action<string>(Filter), searchString);
150      else {
151        searchString = searchString.ToLower();
152
153        typesTreeView.BeginUpdate();
154        if (!searchString.Contains(currentSearchString)) {
155          // expand search -> restore all tree nodes
156          TreeNode selectedNode = typesTreeView.SelectedNode;
157          typesTreeView.Nodes.Clear();
158          foreach (TreeNode node in treeNodes)
159            typesTreeView.Nodes.Add((TreeNode)node.Clone());
160          RestoreSelectedNode(selectedNode);
161        }
162
163        // remove nodes
164        int i = 0;
165        while (i < typesTreeView.Nodes.Count) {
166          int j = 0;
167          while (j < typesTreeView.Nodes[i].Nodes.Count) {
168            if (!typesTreeView.Nodes[i].Nodes[j].Text.ToLower().Contains(searchString))
169              typesTreeView.Nodes[i].Nodes[j].Remove();
170            else
171              j++;
172          }
173          if (typesTreeView.Nodes[i].Nodes.Count == 0)
174            typesTreeView.Nodes[i].Remove();
175          else
176            i++;
177        }
178        currentSearchString = searchString;
179
180        // if there is just one type node left, select by default
181        if (typesTreeView.Nodes.Count == 1) {
182          if (typesTreeView.Nodes[0].Nodes.Count == 1) {
183            typesTreeView.SelectedNode = typesTreeView.Nodes[0].Nodes[0];
184          }
185        }
186
187        if (typesTreeView.Nodes.Count == 0) {
188          SelectedType = null;
189          typesTreeView.Enabled = false;
190        } else {
191          SetTreeNodeVisibility();
192          typesTreeView.Enabled = true;
193        }
194        UpdateDescription();
195        typesTreeView.EndUpdate();
196      }
197    }
198
199    public virtual object CreateInstanceOfSelectedType(params object[] args) {
200      if (SelectedType == null)
201        throw new InvalidOperationException("No type selected.");
202      else
203        return Activator.CreateInstance(SelectedType, args);
204    }
205
206    public event EventHandler SelectedTypeChanged;
207    protected virtual void OnSelectedTypeChanged() {
208      if (SelectedTypeChanged != null)
209        SelectedTypeChanged(this, EventArgs.Empty);
210    }
211
212    protected virtual void UpdateDescription() {
213      descriptionTextBox.Text = string.Empty;
214
215      if (typesTreeView.SelectedNode != null) {
216        IPluginDescription plugin = typesTreeView.SelectedNode.Tag as IPluginDescription;
217        if (plugin != null) {
218          StringBuilder sb = new StringBuilder();
219          sb.Append("Plugin: ").Append(plugin.Name).Append(Environment.NewLine);
220          sb.Append("Version: ").Append(plugin.Version.ToString()).Append(Environment.NewLine);
221          descriptionTextBox.Text = sb.ToString();
222        }
223        Type type = typesTreeView.SelectedNode.Tag as Type;
224        if (type != null) {
225          string description = ItemAttribute.GetDescription(type);
226          if (description != null)
227            descriptionTextBox.Text = description;
228        }
229      } else if (typesTreeView.Nodes.Count == 0) {
230        descriptionTextBox.Text = "No types found";
231      }
232    }
233
234    protected virtual void searchTextBox_TextChanged(object sender, System.EventArgs e) {
235      Filter(searchTextBox.Text);
236    }
237
238    protected virtual void typesTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
239      if (typesTreeView.SelectedNode == null) SelectedType = null;
240      else SelectedType = typesTreeView.SelectedNode.Tag as Type;
241      UpdateDescription();
242    }
243
244    protected virtual void typesTreeView_ItemDrag(object sender, ItemDragEventArgs e) {
245      TreeNode node = (TreeNode)e.Item;
246      Type type = node.Tag as Type;
247      if ((type != null) && (!type.IsInterface) && (!type.IsAbstract) && (!type.HasElementType) && (!type.ContainsGenericParameters)) {
248        object o = Activator.CreateInstance(type);
249        DataObject data = new DataObject();
250        data.SetData("Type", type);
251        data.SetData("Value", o);
252        DoDragDrop(data, DragDropEffects.Copy);
253      }
254    }
255
256    protected virtual void typesTreeView_VisibleChanged(object sender, EventArgs e) {
257      if (Visible) SetTreeNodeVisibility();
258    }
259
260    #region Helpers
261    private void RestoreSelectedNode(TreeNode selectedNode) {
262      if (selectedNode != null) {
263        foreach (TreeNode node in typesTreeView.Nodes) {
264          if (node.Text.Equals(selectedNode.Text)) typesTreeView.SelectedNode = node;
265          foreach (TreeNode child in node.Nodes) {
266            if ((child.Text.Equals(selectedNode.Text)) && (child.Tag == selectedNode.Tag))
267              typesTreeView.SelectedNode = child;
268          }
269        }
270        if (typesTreeView.SelectedNode == null) SelectedType = null;
271      }
272    }
273    private void SetTreeNodeVisibility() {
274      TreeNode selectedNode = typesTreeView.SelectedNode;
275      if (string.IsNullOrEmpty(currentSearchString) && (typesTreeView.Nodes.Count > 1)) {
276        typesTreeView.CollapseAll();
277        if (selectedNode != null) typesTreeView.SelectedNode = selectedNode;
278      } else {
279        typesTreeView.ExpandAll();
280      }
281      if (selectedNode != null) selectedNode.EnsureVisible();
282    }
283    #endregion
284  }
285}
Note: See TracBrowser for help on using the repository browser.