Free cookie consent management tool by TermsFeed Policy Generator

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

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

Worked on UI support for choosing generic type parameters (#42)

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