Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 9755 was 9456, checked in by swagner, 11 years ago

Updated copyright year and added some missing license headers (#1889)

  • Property svn:mergeinfo set to (toggle deleted branches)
    /branches/CloningRefactoring/HeuristicLab.Core.Views/3.3/TypeSelector.cs4656-4721
    /branches/DataAnalysis Refactoring/HeuristicLab.Core.Views/3.3/TypeSelector.cs5471-5808
    /branches/DataAnalysis SolutionEnsembles/HeuristicLab.Core.Views/3.3/TypeSelector.cs5815-6180
    /branches/DataAnalysis/HeuristicLab.Core.Views/3.3/TypeSelector.cs4458-4459,​4462,​4464
    /branches/GP.Grammar.Editor/HeuristicLab.Core.Views/3.3/TypeSelector.cs6335
    /branches/GP.Symbols (TimeLag, Diff, Integral)/HeuristicLab.Core.Views/3.3/TypeSelector.cs5060
    /branches/NET40/sources/HeuristicLab.Core.Views/3.3/TypeSelector.cs5138-5162
    /branches/ParallelEngine/HeuristicLab.Core.Views/3.3/TypeSelector.cs5175-5192
    /branches/QAPAlgorithms/HeuristicLab.Core.Views/3.3/TypeSelector.cs6350-6627
    /branches/Restructure trunk solution/HeuristicLab.Core.Views/3.3/TypeSelector.cs6828
    /branches/SuccessProgressAnalysis/HeuristicLab.Core.Views/3.3/TypeSelector.cs5370-5682
    /branches/Trunk/HeuristicLab.Core.Views/3.3/TypeSelector.cs6829-6865
    /branches/VNS/HeuristicLab.Core.Views/3.3/TypeSelector.cs5594-5752
    /branches/histogram/HeuristicLab.Core.Views/3.3/TypeSelector.cs5959-6341
File size: 15.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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.Reflection;
26using System.Text;
27using System.Windows.Forms;
28using HeuristicLab.Common;
29using HeuristicLab.PluginInfrastructure;
30
31namespace HeuristicLab.Core.Views {
32  public partial class TypeSelector : UserControl {
33    protected List<TreeNode> treeNodes;
34    protected string currentSearchString;
35    protected TypeSelectorDialog typeSelectorDialog;
36
37    protected IEnumerable<Type> baseTypes;
38    public IEnumerable<Type> BaseTypes {
39      get { return baseTypes; }
40    }
41    protected bool showNotInstantiableTypes;
42    public bool ShowNotInstantiableTypes {
43      get { return showNotInstantiableTypes; }
44    }
45    protected bool showGenericTypes;
46    public bool ShowGenericTypes {
47      get { return showGenericTypes; }
48    }
49    public string Caption {
50      get { return typesGroupBox.Text; }
51      set {
52        if (InvokeRequired)
53          Invoke(new Action<string>(delegate(string s) { Caption = s; }), value);
54        else
55          typesGroupBox.Text = value;
56      }
57    }
58    public TreeView TypesTreeView {
59      get { return typesTreeView; }
60    }
61    protected Type selectedType;
62    public Type SelectedType {
63      get { return selectedType; }
64      private set {
65        if (value != selectedType) {
66          selectedType = value;
67          OnSelectedTypeChanged();
68        }
69      }
70    }
71
72    public TypeSelector() {
73      InitializeComponent();
74      treeNodes = new List<TreeNode>();
75      currentSearchString = string.Empty;
76      selectedType = null;
77    }
78
79    protected override void Dispose(bool disposing) {
80      if (disposing) {
81        if (typeSelectorDialog != null) typeSelectorDialog.Dispose();
82        if (components != null) components.Dispose();
83      }
84      base.Dispose(disposing);
85    }
86
87    public virtual void Configure(Type baseType, bool showNotInstantiableTypes, bool showGenericTypes) {
88      Configure(baseType, showNotInstantiableTypes, showGenericTypes, (t) => true);
89    }
90
91    public virtual void Configure(Type baseType, bool showNotInstantiableTypes, bool showGenericTypes, Func<Type, bool> typeCondition) {
92      Configure(new List<Type>() { baseType }, showNotInstantiableTypes, showGenericTypes, true, typeCondition);
93    }
94
95    public virtual void Configure(IEnumerable<Type> baseTypes, bool showNotInstantiableTypes, bool showGenericTypes, bool assignableToAllTypes) {
96      Configure(baseTypes, showNotInstantiableTypes, showGenericTypes, assignableToAllTypes, (t) => { return true; });
97    }
98
99    public virtual void Configure(IEnumerable<Type> baseTypes, bool showNotInstantiableTypes, bool showGenericTypes, bool assignableToAllTypes, Func<Type, bool> typeCondition) {
100      if (baseTypes == null) throw new ArgumentNullException();
101      if (InvokeRequired)
102        Invoke(new Action<IEnumerable<Type>, bool, bool, bool, Func<Type, bool>>(Configure), baseTypes, showNotInstantiableTypes, showGenericTypes, assignableToAllTypes, typeCondition);
103      else {
104        this.baseTypes = baseTypes;
105        this.showNotInstantiableTypes = showNotInstantiableTypes;
106        this.showGenericTypes = showGenericTypes;
107        bool selectedTypeFound = false;
108
109        typeParametersSplitContainer.Panel2Collapsed = !showGenericTypes;
110
111        TreeNode selectedNode = typesTreeView.SelectedNode;
112        typesTreeView.Nodes.Clear();
113        treeNodes.Clear();
114        imageList.Images.Clear();
115        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Class);      // default icon
116        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Namespace);  // plugins
117        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Interface);  // interfaces
118        imageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Template);   // generic types
119
120        var plugins = from p in ApplicationManager.Manager.Plugins
121                      orderby p.Name, p.Version ascending
122                      select p;
123        foreach (IPluginDescription plugin in plugins) {
124          TreeNode pluginNode = new TreeNode();
125          pluginNode.Text = string.Format("{0} {1}.{2}", plugin.Name, plugin.Version.Major, plugin.Version.Minor);
126          pluginNode.ImageIndex = 1;
127          pluginNode.SelectedImageIndex = pluginNode.ImageIndex;
128          pluginNode.Tag = plugin;
129
130          var types = from t in ApplicationManager.Manager.GetTypes(BaseTypes, plugin, !ShowNotInstantiableTypes, ShowGenericTypes, assignableToAllTypes)
131                      where typeCondition(t)
132                      orderby t.Name ascending
133                      select t;
134          foreach (Type type in types) {
135            bool valid = (ShowNotInstantiableTypes || type.GetConstructor(Type.EmptyTypes) != null); //check for public default ctor
136            if (valid) {
137              TreeNode typeNode = new TreeNode();
138              string name = ItemAttribute.GetName(type);
139              typeNode.Text = name != null ? name : type.GetPrettyName();
140              typeNode.ImageIndex = 0;
141              if (type.IsInterface) typeNode.ImageIndex = 2;
142              else if (type.ContainsGenericParameters) typeNode.ImageIndex = 3;
143              else if (imageList.Images.ContainsKey(type.FullName)) typeNode.ImageIndex = imageList.Images.IndexOfKey(type.FullName);
144              else {
145                var image = ItemAttribute.GetImage(type);
146                if (image != null) {
147                  imageList.Images.Add(type.FullName, image);
148                  typeNode.ImageIndex = imageList.Images.IndexOfKey(type.FullName);
149                }
150              }
151              typeNode.SelectedImageIndex = typeNode.ImageIndex;
152              typeNode.Tag = type;
153              pluginNode.Nodes.Add(typeNode);
154              if (type.Equals(selectedType)) selectedTypeFound = true;
155            }
156          }
157          if (pluginNode.Nodes.Count > 0)
158            treeNodes.Add(pluginNode);
159        }
160        if (!selectedTypeFound) SelectedType = null;
161        foreach (TreeNode node in treeNodes)
162          typesTreeView.Nodes.Add((TreeNode)node.Clone());
163        RestoreSelectedNode(selectedNode);
164        Filter(searchTextBox.Text);
165
166        UpdateTypeParameters();
167      }
168    }
169
170    public virtual void Filter(string searchString) {
171      if (InvokeRequired)
172        Invoke(new Action<string>(Filter), searchString);
173      else {
174        searchString = searchString.ToLower();
175
176        if (!searchString.Contains(currentSearchString)) {
177          typesTreeView.BeginUpdate();
178          // expand search -> restore all tree nodes
179          TreeNode selectedNode = typesTreeView.SelectedNode;
180          typesTreeView.Nodes.Clear();
181          foreach (TreeNode node in treeNodes)
182            typesTreeView.Nodes.Add((TreeNode)node.Clone());
183          RestoreSelectedNode(selectedNode);
184          typesTreeView.EndUpdate();
185        }
186
187
188        // remove nodes
189        typesTreeView.BeginUpdate();
190        int i = 0;
191        while (i < typesTreeView.Nodes.Count) {
192          int j = 0;
193          while (j < typesTreeView.Nodes[i].Nodes.Count) {
194            if (!typesTreeView.Nodes[i].Nodes[j].Text.ToLower().Contains(searchString)) {
195              if ((typesTreeView.Nodes[i].Nodes[j].Tag as Type).Equals(selectedType))
196                SelectedType = null;
197              typesTreeView.Nodes[i].Nodes[j].Remove();
198            } else
199              j++;
200          }
201          if (typesTreeView.Nodes[i].Nodes.Count == 0)
202            typesTreeView.Nodes[i].Remove();
203          else
204            i++;
205        }
206        typesTreeView.EndUpdate();
207        currentSearchString = searchString;
208
209        // if there is just one type node left, select by default
210        if (typesTreeView.Nodes.Count == 1) {
211          if (typesTreeView.Nodes[0].Nodes.Count == 1) {
212            typesTreeView.SelectedNode = typesTreeView.Nodes[0].Nodes[0];
213          }
214        }
215
216        if (typesTreeView.Nodes.Count == 0) {
217          SelectedType = null;
218          typesTreeView.Enabled = false;
219        } else {
220          SetTreeNodeVisibility();
221          typesTreeView.Enabled = true;
222        }
223        UpdateDescription();
224      }
225    }
226
227    public virtual object CreateInstanceOfSelectedType(params object[] args) {
228      if (SelectedType == null)
229        throw new InvalidOperationException("No type selected.");
230      else
231        return Activator.CreateInstance(SelectedType, args);
232    }
233
234    protected virtual void UpdateTypeParameters() {
235      typeParametersListView.Items.Clear();
236      if ((SelectedType == null) || !SelectedType.ContainsGenericParameters) {
237        typeParametersGroupBox.Enabled = false;
238        typeParametersSplitContainer.Panel2Collapsed = true;
239      } else {
240        typeParametersGroupBox.Enabled = true;
241        typeParametersSplitContainer.Panel2Collapsed = false;
242        setTypeParameterButton.Enabled = false;
243
244        foreach (Type param in SelectedType.GetGenericArguments()) {
245          if (param.IsGenericParameter) {
246            ListViewItem item = new ListViewItem();
247            item.Text = param.Name;
248
249            item.ToolTipText = "Constraints:";
250            Type[] constraints = param.GetGenericParameterConstraints();
251            if (constraints.Length == 0) {
252              item.ToolTipText += " none";
253            } else {
254              foreach (Type constraint in constraints)
255                item.ToolTipText += " " + constraint.GetPrettyName();
256            }
257
258            item.Tag = param;
259            typeParametersListView.Items.Add(item);
260          }
261        }
262        typeParametersListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
263      }
264    }
265
266    protected virtual void SetTypeParameter() {
267      if (typeSelectorDialog == null) {
268        typeSelectorDialog = new TypeSelectorDialog();
269        typeSelectorDialog.Caption = "Select Type of Generic Type Parameter";
270      }
271      Type param = typeParametersListView.SelectedItems[0].Tag as Type;
272      Type[] constraints = param.GetGenericParameterConstraints();
273      bool showNotInstantiableTypes = !param.GenericParameterAttributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint);
274      typeSelectorDialog.TypeSelector.Configure(constraints, showNotInstantiableTypes, true, true);
275
276      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
277        Type selected = typeSelectorDialog.TypeSelector.SelectedType;
278        Type[] parameters = SelectedType.GetGenericArguments();
279        parameters[param.GenericParameterPosition] = selected;
280        SelectedType = SelectedType.GetGenericTypeDefinition().MakeGenericType(parameters);
281
282        typeParametersListView.SelectedItems[0].Text = param.Name + ": " + selected.GetPrettyName();
283        typeParametersListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
284      }
285    }
286
287    protected virtual void UpdateDescription() {
288      descriptionTextBox.Text = string.Empty;
289
290      if (typesTreeView.SelectedNode != null) {
291        IPluginDescription plugin = typesTreeView.SelectedNode.Tag as IPluginDescription;
292        if (plugin != null) {
293          StringBuilder sb = new StringBuilder();
294          sb.Append("Plugin: ").Append(plugin.Name).Append(Environment.NewLine);
295          sb.Append("Version: ").Append(plugin.Version.ToString()).Append(Environment.NewLine);
296          descriptionTextBox.Text = sb.ToString();
297        }
298        Type type = typesTreeView.SelectedNode.Tag as Type;
299        if (type != null) {
300          string description = ItemAttribute.GetDescription(type);
301          if (description != null)
302            descriptionTextBox.Text = description;
303        }
304      } else if (typesTreeView.Nodes.Count == 0) {
305        descriptionTextBox.Text = "No types found";
306      }
307    }
308
309    #region Events
310    public event EventHandler SelectedTypeChanged;
311    protected virtual void OnSelectedTypeChanged() {
312      if (SelectedTypeChanged != null)
313        SelectedTypeChanged(this, EventArgs.Empty);
314    }
315    #endregion
316
317    #region Control Events
318    protected virtual void searchTextBox_TextChanged(object sender, System.EventArgs e) {
319      Filter(searchTextBox.Text);
320    }
321
322    protected virtual void typesTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
323      if (typesTreeView.SelectedNode == null) SelectedType = null;
324      else SelectedType = typesTreeView.SelectedNode.Tag as Type;
325      UpdateTypeParameters();
326      UpdateDescription();
327    }
328    protected virtual void typesTreeView_ItemDrag(object sender, ItemDragEventArgs e) {
329      TreeNode node = (TreeNode)e.Item;
330      Type type = node.Tag as Type;
331      if ((type != null) && (!type.IsInterface) && (!type.IsAbstract) && (!type.HasElementType) && (!type.ContainsGenericParameters)) {
332        object o = Activator.CreateInstance(type);
333        DataObject data = new DataObject();
334        data.SetData(HeuristicLab.Common.Constants.DragDropDataFormat, o);
335        DoDragDrop(data, DragDropEffects.Copy);
336      }
337    }
338    protected virtual void typesTreeView_VisibleChanged(object sender, EventArgs e) {
339      if (Visible) SetTreeNodeVisibility();
340    }
341
342    protected virtual void typeParametersListView_SelectedIndexChanged(object sender, EventArgs e) {
343      setTypeParameterButton.Enabled = typeParametersListView.SelectedItems.Count == 1;
344    }
345    protected virtual void typeParametersListView_DoubleClick(object sender, EventArgs e) {
346      if (typeParametersListView.SelectedItems.Count == 1)
347        SetTypeParameter();
348    }
349
350    protected virtual void setTypeParameterButton_Click(object sender, EventArgs e) {
351      SetTypeParameter();
352    }
353    #endregion
354
355    #region Helpers
356    private void RestoreSelectedNode(TreeNode selectedNode) {
357      if (selectedNode != null) {
358        foreach (TreeNode node in typesTreeView.Nodes) {
359          if (node.Text.Equals(selectedNode.Text)) typesTreeView.SelectedNode = node;
360          foreach (TreeNode child in node.Nodes) {
361            if ((child.Text.Equals(selectedNode.Text)) && (child.Tag == selectedNode.Tag))
362              typesTreeView.SelectedNode = child;
363          }
364        }
365        if (typesTreeView.SelectedNode == null) SelectedType = null;
366      }
367    }
368    private void SetTreeNodeVisibility() {
369      TreeNode selectedNode = typesTreeView.SelectedNode;
370      if (string.IsNullOrEmpty(currentSearchString) && (typesTreeView.Nodes.Count > 1)) {
371        typesTreeView.CollapseAll();
372        if (selectedNode != null) typesTreeView.SelectedNode = selectedNode;
373      } else {
374        typesTreeView.ExpandAll();
375      }
376      if (selectedNode != null) selectedNode.EnsureVisible();
377    }
378    #endregion
379  }
380}
Note: See TracBrowser for help on using the repository browser.