Free cookie consent management tool by TermsFeed Policy Generator

source: tags/3.3.2/HeuristicLab.Core.Views/3.3/TypeSelector.cs @ 8072

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

Set initial focus in TypeSelector to search text box (#1241)

File size: 14.2 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
157        if (!searchString.Contains(currentSearchString)) {
158          typesTreeView.BeginUpdate();
159          // expand search -> restore all tree nodes
160          TreeNode selectedNode = typesTreeView.SelectedNode;
161          typesTreeView.Nodes.Clear();
162          foreach (TreeNode node in treeNodes)
163            typesTreeView.Nodes.Add((TreeNode)node.Clone());
164          RestoreSelectedNode(selectedNode);
165          typesTreeView.EndUpdate();
166        }
167
168
169        // remove nodes
170        typesTreeView.BeginUpdate();
171        int i = 0;
172        while (i < typesTreeView.Nodes.Count) {
173          int j = 0;
174          while (j < typesTreeView.Nodes[i].Nodes.Count) {
175            if (!typesTreeView.Nodes[i].Nodes[j].Text.ToLower().Contains(searchString))
176              typesTreeView.Nodes[i].Nodes[j].Remove();
177            else
178              j++;
179          }
180          if (typesTreeView.Nodes[i].Nodes.Count == 0)
181            typesTreeView.Nodes[i].Remove();
182          else
183            i++;
184        }
185        typesTreeView.EndUpdate();
186        currentSearchString = searchString;
187
188        // if there is just one type node left, select by default
189        if (typesTreeView.Nodes.Count == 1) {
190          if (typesTreeView.Nodes[0].Nodes.Count == 1) {
191            typesTreeView.SelectedNode = typesTreeView.Nodes[0].Nodes[0];
192          }
193        }
194
195        if (typesTreeView.Nodes.Count == 0) {
196          SelectedType = null;
197          typesTreeView.Enabled = false;
198        } else {
199          SetTreeNodeVisibility();
200          typesTreeView.Enabled = true;
201        }
202        UpdateDescription();
203      }
204    }
205
206    public virtual object CreateInstanceOfSelectedType(params object[] args) {
207      if (SelectedType == null)
208        throw new InvalidOperationException("No type selected.");
209      else
210        return Activator.CreateInstance(SelectedType, args);
211    }
212
213    protected virtual void UpdateTypeParameters() {
214      typeParametersListView.Items.Clear();
215      if ((SelectedType == null) || !SelectedType.ContainsGenericParameters) {
216        typeParametersGroupBox.Enabled = false;
217        typeParametersSplitContainer.Panel2Collapsed = true;
218      } else {
219        typeParametersGroupBox.Enabled = true;
220        typeParametersSplitContainer.Panel2Collapsed = false;
221        setTypeParameterButton.Enabled = false;
222
223        foreach (Type param in SelectedType.GetGenericArguments()) {
224          if (param.IsGenericParameter) {
225            ListViewItem item = new ListViewItem();
226            item.Text = param.Name;
227
228            item.ToolTipText = "Constraints:";
229            Type[] constraints = param.GetGenericParameterConstraints();
230            if (constraints.Length == 0) {
231              item.ToolTipText += " none";
232            } else {
233              foreach (Type constraint in constraints)
234                item.ToolTipText += " " + constraint.GetPrettyName();
235            }
236
237            item.Tag = param;
238            typeParametersListView.Items.Add(item);
239          }
240        }
241        typeParametersListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
242      }
243    }
244
245    protected virtual void SetTypeParameter() {
246      if (typeSelectorDialog == null) {
247        typeSelectorDialog = new TypeSelectorDialog();
248        typeSelectorDialog.Caption = "Select Type of Generic Type Parameter";
249      }
250      Type param = typeParametersListView.SelectedItems[0].Tag as Type;
251      Type[] contraints = param.GetGenericParameterConstraints();
252      typeSelectorDialog.TypeSelector.Configure(typeof(IItem), true, true);
253
254      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
255        Type selected = typeSelectorDialog.TypeSelector.SelectedType;
256        Type[] parameters = SelectedType.GetGenericArguments();
257        parameters[param.GenericParameterPosition] = selected;
258        SelectedType = SelectedType.GetGenericTypeDefinition().MakeGenericType(parameters);
259
260        typeParametersListView.SelectedItems[0].Text = param.Name + ": " + selected.GetPrettyName();
261        typeParametersListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
262      }
263    }
264
265    protected virtual void UpdateDescription() {
266      descriptionTextBox.Text = string.Empty;
267
268      if (typesTreeView.SelectedNode != null) {
269        IPluginDescription plugin = typesTreeView.SelectedNode.Tag as IPluginDescription;
270        if (plugin != null) {
271          StringBuilder sb = new StringBuilder();
272          sb.Append("Plugin: ").Append(plugin.Name).Append(Environment.NewLine);
273          sb.Append("Version: ").Append(plugin.Version.ToString()).Append(Environment.NewLine);
274          descriptionTextBox.Text = sb.ToString();
275        }
276        Type type = typesTreeView.SelectedNode.Tag as Type;
277        if (type != null) {
278          string description = ItemAttribute.GetDescription(type);
279          if (description != null)
280            descriptionTextBox.Text = description;
281        }
282      } else if (typesTreeView.Nodes.Count == 0) {
283        descriptionTextBox.Text = "No types found";
284      }
285    }
286
287    #region Events
288    public event EventHandler SelectedTypeChanged;
289    protected virtual void OnSelectedTypeChanged() {
290      if (SelectedTypeChanged != null)
291        SelectedTypeChanged(this, EventArgs.Empty);
292    }
293    #endregion
294
295    #region Control Events
296    protected virtual void searchTextBox_TextChanged(object sender, System.EventArgs e) {
297      Filter(searchTextBox.Text);
298    }
299
300    protected virtual void typesTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
301      if (typesTreeView.SelectedNode == null) SelectedType = null;
302      else SelectedType = typesTreeView.SelectedNode.Tag as Type;
303      UpdateTypeParameters();
304      UpdateDescription();
305    }
306    protected virtual void typesTreeView_ItemDrag(object sender, ItemDragEventArgs e) {
307      TreeNode node = (TreeNode)e.Item;
308      Type type = node.Tag as Type;
309      if ((type != null) && (!type.IsInterface) && (!type.IsAbstract) && (!type.HasElementType) && (!type.ContainsGenericParameters)) {
310        object o = Activator.CreateInstance(type);
311        DataObject data = new DataObject();
312        data.SetData("Type", type);
313        data.SetData("Value", o);
314        DoDragDrop(data, DragDropEffects.Copy);
315      }
316    }
317    protected virtual void typesTreeView_VisibleChanged(object sender, EventArgs e) {
318      if (Visible) SetTreeNodeVisibility();
319    }
320
321    protected virtual void typeParametersListView_SelectedIndexChanged(object sender, EventArgs e) {
322      setTypeParameterButton.Enabled = typeParametersListView.SelectedItems.Count == 1;
323    }
324    protected virtual void typeParametersListView_DoubleClick(object sender, EventArgs e) {
325      if (typeParametersListView.SelectedItems.Count == 1)
326        SetTypeParameter();
327    }
328
329    protected virtual void setTypeParameterButton_Click(object sender, EventArgs e) {
330      SetTypeParameter();
331    }
332    #endregion
333
334    #region Helpers
335    private void RestoreSelectedNode(TreeNode selectedNode) {
336      if (selectedNode != null) {
337        foreach (TreeNode node in typesTreeView.Nodes) {
338          if (node.Text.Equals(selectedNode.Text)) typesTreeView.SelectedNode = node;
339          foreach (TreeNode child in node.Nodes) {
340            if ((child.Text.Equals(selectedNode.Text)) && (child.Tag == selectedNode.Tag))
341              typesTreeView.SelectedNode = child;
342          }
343        }
344        if (typesTreeView.SelectedNode == null) SelectedType = null;
345      }
346    }
347    private void SetTreeNodeVisibility() {
348      TreeNode selectedNode = typesTreeView.SelectedNode;
349      if (string.IsNullOrEmpty(currentSearchString) && (typesTreeView.Nodes.Count > 1)) {
350        typesTreeView.CollapseAll();
351        if (selectedNode != null) typesTreeView.SelectedNode = selectedNode;
352      } else {
353        typesTreeView.ExpandAll();
354      }
355      if (selectedNode != null) selectedNode.EnsureVisible();
356    }
357    #endregion
358  }
359}
Note: See TracBrowser for help on using the repository browser.