Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Breadcrumbs/HeuristicLab.Scripting.Views/3.3/VariableStoreView.cs @ 12694

Last change on this file since 12694 was 11594, checked in by jkarder, 10 years ago

#2116: merged r10041-r11593 from trunk into branch

File size: 19.7 KB
RevLine 
[10332]1#region License Information
2/* HeuristicLab
[10506]3 * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[10332]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;
[10506]25using System.Text.RegularExpressions;
[10332]26using System.Windows.Forms;
27using HeuristicLab.Collections;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Core.Views;
31using HeuristicLab.MainForm;
32using HeuristicLab.MainForm.WindowsForms;
[10358]33using HeuristicLab.Persistence.Core;
34using HeuristicLab.Persistence.Default.Xml;
[10332]35using HeuristicLab.PluginInfrastructure;
36
[10506]37namespace HeuristicLab.Scripting.Views {
[10332]38  [View("ItemCollection View")]
39  [Content(typeof(VariableStore), true)]
40  public partial class VariableStoreView : AsynchronousContentView {
[11594]41    #region Image Names
42    private const string ErrorImageName = "Error";
43    private const string WarningImageName = "Warning";
44    private const string HeuristicLabObjectImageName = "HeuristicLabObject";
45    private const string ObjectImageName = "Object";
46    private const string NothingImageName = "Nothing";
47    #endregion
48
49    protected readonly Dictionary<string, ListViewItem> itemListViewItemMapping;
50    protected readonly Dictionary<Type, bool> serializableLookup;
[10332]51    protected TypeSelectorDialog typeSelectorDialog;
52    protected bool validDragOperation;
53
54    public new VariableStore Content {
55      get { return (VariableStore)base.Content; }
56      set { base.Content = value; }
57    }
58
59    public ListView ItemsListView {
60      get { return variableListView; }
61    }
62
63    public VariableStoreView() {
64      InitializeComponent();
65      itemListViewItemMapping = new Dictionary<string, ListViewItem>();
[11594]66      serializableLookup = new Dictionary<Type, bool>();
67
68      var images = variableListView.SmallImageList.Images;
69      images.Add(ErrorImageName, Common.Resources.VSImageLibrary.Error);
70      images.Add(WarningImageName, Common.Resources.VSImageLibrary.Warning);
71      images.Add(HeuristicLabObjectImageName, Common.Resources.HeuristicLab.Icon.ToBitmap());
72      images.Add(ObjectImageName, Common.Resources.VSImageLibrary.Object);
73      images.Add(NothingImageName, Common.Resources.VSImageLibrary.Nothing);
[10332]74    }
75
76    protected override void Dispose(bool disposing) {
77      if (disposing) {
78        if (typeSelectorDialog != null) typeSelectorDialog.Dispose();
79        if (components != null) components.Dispose();
80      }
81      base.Dispose(disposing);
82    }
83
84    protected override void DeregisterContentEvents() {
85      Content.ItemsAdded -= Content_ItemsAdded;
86      Content.ItemsReplaced -= Content_ItemsReplaced;
87      Content.ItemsRemoved -= Content_ItemsRemoved;
88      Content.CollectionReset -= Content_CollectionReset;
89      base.DeregisterContentEvents();
90    }
91    protected override void RegisterContentEvents() {
92      base.RegisterContentEvents();
93      Content.ItemsAdded += Content_ItemsAdded;
94      Content.ItemsReplaced += Content_ItemsReplaced;
95      Content.ItemsRemoved += Content_ItemsRemoved;
96      Content.CollectionReset += Content_CollectionReset;
97    }
98
99    protected override void OnContentChanged() {
100      base.OnContentChanged();
101      variableListView.Items.Clear();
102      itemListViewItemMapping.Clear();
103      if (Content != null) {
104        Caption += " (" + Content.GetType().Name + ")";
105        foreach (var item in Content)
106          AddVariable(item);
107        AdjustListViewColumnSizes();
108        SortItemsListView(SortOrder.Ascending);
109      }
110    }
111
112    protected override void SetEnabledStateOfControls() {
113      base.SetEnabledStateOfControls();
114      if (Content == null) {
115        addButton.Enabled = false;
116        sortAscendingButton.Enabled = false;
117        sortDescendingButton.Enabled = false;
118        removeButton.Enabled = false;
119        variableListView.Enabled = false;
120      } else {
[11594]121        bool enabled = !Locked && !ReadOnly;
122        addButton.Enabled = enabled;
[10332]123        sortAscendingButton.Enabled = variableListView.Items.Count > 1;
124        sortDescendingButton.Enabled = variableListView.Items.Count > 1;
[11594]125        removeButton.Enabled = enabled && variableListView.SelectedItems.Count > 0;
126        variableListView.Enabled = enabled;
127        variableListView.LabelEdit = enabled;
[10332]128      }
129    }
130
131    protected virtual object CreateItem() {
132      if (typeSelectorDialog == null) {
133        typeSelectorDialog = new TypeSelectorDialog { Caption = "Select Item" };
134        typeSelectorDialog.TypeSelector.Caption = "Available Items";
135        typeSelectorDialog.TypeSelector.Configure(typeof(IItem), false, true);
136      }
137
138      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
139        try {
140          return (object)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
141        } catch (Exception ex) {
142          ErrorHandling.ShowErrorDialog(this, ex);
143        }
144      }
145      return null;
146    }
147
148    protected virtual void AddVariable(KeyValuePair<string, object> variable) {
149      if (string.IsNullOrEmpty(variable.Key)) throw new ArgumentException("The variable must have a name.", "variable");
[10358]150      bool serializable = IsSerializable(variable);
[11594]151
152      var listViewItem = new ListViewItem();
153      AssignVariableToListViewItem(listViewItem, variable);
154      SetImageKey(listViewItem, serializable);
155      SetToolTipText(listViewItem, serializable);
[10332]156      variableListView.Items.Add(listViewItem);
[11594]157
[10332]158      itemListViewItemMapping[variable.Key] = listViewItem;
159      sortAscendingButton.Enabled = variableListView.Items.Count > 1;
160      sortDescendingButton.Enabled = variableListView.Items.Count > 1;
161      var item = variable.Value as IItem;
162      if (item != null) item.ToStringChanged += item_ToStringChanged;
163    }
164
165    protected virtual void RemoveVariable(KeyValuePair<string, object> variable) {
166      if (string.IsNullOrEmpty(variable.Key)) throw new ArgumentException("The variable must have a name.", "variable");
[11594]167
[10332]168      ListViewItem listViewItem;
[11594]169      if (!itemListViewItemMapping.TryGetValue(variable.Key, out listViewItem)) return;
170
171      itemListViewItemMapping.Remove(variable.Key);
172      variableListView.Items.Remove(listViewItem);
173      sortAscendingButton.Enabled = variableListView.Items.Count > 1;
174      sortDescendingButton.Enabled = variableListView.Items.Count > 1;
175      var item = variable.Value as IItem;
176      if (item != null) item.ToStringChanged -= item_ToStringChanged;
[10332]177    }
178
179    protected virtual void UpdateVariable(KeyValuePair<string, object> variable) {
180      if (string.IsNullOrEmpty(variable.Key)) throw new ArgumentException("The variable must have a name.", "variable");
[11594]181
[10332]182      ListViewItem listViewItem;
[11594]183      if (!itemListViewItemMapping.TryGetValue(variable.Key, out listViewItem))
184        throw new ArgumentException("A variable with the specified name does not exist.", "variable");
185
186      bool serializable = IsSerializable(variable);
187      AssignVariableToListViewItem(listViewItem, variable);
188      SetImageKey(listViewItem, serializable);
189      SetToolTipText(listViewItem, serializable);
190
[10332]191    }
192
193    #region ListView Events
194    protected virtual void variableListView_SelectedIndexChanged(object sender, EventArgs e) {
[10358]195      removeButton.Enabled = (Content != null) && !Locked && !ReadOnly && variableListView.SelectedItems.Count > 0;
[10332]196      AdjustListViewColumnSizes();
197    }
198    protected virtual void variableListView_KeyDown(object sender, KeyEventArgs e) {
[11594]199      switch (e.KeyCode) {
200        case Keys.Delete:
201          if ((variableListView.SelectedItems.Count > 0) && !Locked && !ReadOnly) {
202            foreach (ListViewItem item in variableListView.SelectedItems)
203              Content.Remove(item.Text);
204          }
205          break;
206        case Keys.F2:
207          if (variableListView.SelectedItems.Count != 1) return;
208          var selectedItem = variableListView.SelectedItems[0];
209          if (variableListView.LabelEdit)
210            selectedItem.BeginEdit();
211          break;
212        case Keys.A:
213          if (e.Modifiers.HasFlag(Keys.Control)) {
214            foreach (ListViewItem item in variableListView.Items)
215              item.Selected = true;
216          }
217          break;
[10332]218      }
219    }
220    protected virtual void variableListView_DoubleClick(object sender, EventArgs e) {
[11594]221      if (variableListView.SelectedItems.Count != 1) return;
222      var item = variableListView.SelectedItems[0].Tag as KeyValuePair<string, object>?;
223      if (item == null) return;
224
225      var value = item.Value.Value as IContent;
226      if (value == null) return;
227
228      IContentView view = MainFormManager.MainForm.ShowContent(value);
229      if (view == null) return;
230
231      view.ReadOnly = ReadOnly;
232      view.Locked = Locked;
[10332]233    }
234    protected virtual void variableListView_ItemDrag(object sender, ItemDragEventArgs e) {
[11594]235      if (Locked || variableListView.SelectedItems.Count != 1) return;
[10332]236
[11594]237      var listViewItem = variableListView.SelectedItems[0];
238      var item = (KeyValuePair<string, object>)listViewItem.Tag;
239      if (!(item.Value is IDeepCloneable)) return;
240      var data = new DataObject(HeuristicLab.Common.Constants.DragDropDataFormat, item);
241      DoDragDrop(data, DragDropEffects.Copy);
[10332]242    }
243    protected virtual void variableListView_DragEnter(object sender, DragEventArgs e) {
[10577]244      validDragOperation = !Locked && !ReadOnly && e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) != null;
[10332]245    }
246    protected virtual void variableListView_DragOver(object sender, DragEventArgs e) {
247      e.Effect = DragDropEffects.None;
248      if (validDragOperation) {
[11594]249        if (e.AllowedEffect.HasFlag(DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy;
[10332]250      }
251    }
252    protected virtual void variableListView_DragDrop(object sender, DragEventArgs e) {
[11594]253      if (e.Effect != DragDropEffects.Copy) return;
254      object item = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
255
256      string variableName;
257      bool editLabel;
258
259      if (item is KeyValuePair<string, object>) {
260        var variable = (KeyValuePair<string, object>)item;
261        variableName = GenerateNewVariableName(out editLabel, variable.Key, false);
262        item = variable.Value;
263      } else {
264        var namedItem = item as INamedItem;
265        if (namedItem != null)
266          variableName = GenerateNewVariableName(out editLabel, namedItem.Name, false);
267        else
268          variableName = GenerateNewVariableName(out editLabel);
[10332]269      }
[11594]270
271      var cloneable = item as IDeepCloneable;
272      if (cloneable != null) item = cloneable.Clone();
273
274      Content.Add(variableName, item);
275
276      var listViewItem = variableListView.FindItemWithText(variableName);
277      variableListView.SelectedItems.Clear();
278      if (editLabel) listViewItem.BeginEdit();
[10332]279    }
280
[10506]281    private readonly Regex SafeVariableNameRegex = new Regex("^[@]?[_a-zA-Z][_a-zA-Z0-9]*$");
[11594]282    private const string DefaultVariableName = "enter_name";
283
[10332]284    private void variableListView_AfterLabelEdit(object sender, LabelEditEventArgs e) {
[10506]285      string name = e.Label;
[11594]286      if (!string.IsNullOrEmpty(name)) {
[10332]287        var variable = (KeyValuePair<string, object>)variableListView.Items[e.Item].Tag;
[10506]288        if (!Content.ContainsKey(name)) {
[10332]289          Content.Remove(variable.Key);
[10506]290          Content.Add(name, variable.Value);
[10332]291        }
292      }
293      e.CancelEdit = true;
294    }
295    #endregion
296
297    #region Button Events
298    protected virtual void addButton_Click(object sender, EventArgs e) {
[11594]299      object variableValue = CreateItem();
300      if (variableValue == null) return;
301
302      string variableName;
303      var namedItem = variableValue as INamedItem;
304      if (namedItem != null)
305        variableName = GenerateNewVariableName(namedItem.Name, false);
306      else
307        variableName = GenerateNewVariableName();
308
309      Content.Add(variableName, variableValue);
310
311      var item = variableListView.FindItemWithText(variableName);
312      variableListView.SelectedItems.Clear();
313      item.BeginEdit();
[10332]314    }
315    protected virtual void sortAscendingButton_Click(object sender, EventArgs e) {
316      SortItemsListView(SortOrder.Ascending);
317    }
318    protected virtual void sortDescendingButton_Click(object sender, EventArgs e) {
319      SortItemsListView(SortOrder.Descending);
320    }
321    protected virtual void removeButton_Click(object sender, EventArgs e) {
322      if (variableListView.SelectedItems.Count > 0) {
323        foreach (ListViewItem item in variableListView.SelectedItems)
324          Content.Remove(item.Text);
325        variableListView.SelectedItems.Clear();
326      }
327    }
328    #endregion
329
330    #region Content Events
331    protected virtual void Content_ItemsAdded(object sender, CollectionItemsChangedEventArgs<KeyValuePair<string, object>> e) {
332      if (InvokeRequired)
333        Invoke(new CollectionItemsChangedEventHandler<KeyValuePair<string, object>>(Content_ItemsAdded), sender, e);
334      else {
335        foreach (var item in e.Items)
336          AddVariable(item);
337        AdjustListViewColumnSizes();
338      }
339    }
340
341    protected virtual void Content_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<KeyValuePair<string, object>> e) {
342      if (InvokeRequired)
343        Invoke(new CollectionItemsChangedEventHandler<KeyValuePair<string, object>>(Content_ItemsReplaced), sender, e);
344      else {
345        foreach (var item in e.Items)
346          UpdateVariable(item);
347        AdjustListViewColumnSizes();
348      }
349    }
350
351    protected virtual void Content_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<KeyValuePair<string, object>> e) {
352      if (InvokeRequired)
353        Invoke(new CollectionItemsChangedEventHandler<KeyValuePair<string, object>>(Content_ItemsRemoved), sender, e);
354      else {
355        foreach (var item in e.Items)
356          RemoveVariable(item);
357        AdjustListViewColumnSizes();
358      }
359    }
360    protected virtual void Content_CollectionReset(object sender, CollectionItemsChangedEventArgs<KeyValuePair<string, object>> e) {
361      if (InvokeRequired)
362        Invoke(new CollectionItemsChangedEventHandler<KeyValuePair<string, object>>(Content_CollectionReset), sender, e);
363      else {
364        foreach (var item in e.OldItems)
365          RemoveVariable(item);
366        foreach (var item in e.Items)
367          AddVariable(item);
368        AdjustListViewColumnSizes();
369      }
370    }
371
372    private void item_ToStringChanged(object sender, EventArgs e) {
373      foreach (ListViewItem item in variableListView.Items) {
374        var variable = item.Tag as KeyValuePair<string, object>?;
[11594]375        if (variable == null || variable.Value.Value != sender) continue;
376
377        string value = (variable.Value.Value ?? "null").ToString();
378        item.SubItems[1].Text = value;
379        item.SubItems[2].Text = variable.Value.Value.GetType().ToString();
380        SetToolTipText(item, item.ImageIndex != 0);
[10332]381      }
382    }
383    #endregion
384
385    #region Helpers
386    protected virtual void SortItemsListView(SortOrder sortOrder) {
387      variableListView.Sorting = SortOrder.None;
388      variableListView.Sorting = sortOrder;
389      variableListView.Sorting = SortOrder.None;
390    }
391    protected virtual void AdjustListViewColumnSizes() {
[10506]392      foreach (ColumnHeader ch in variableListView.Columns)
393        ch.Width = -2;
[10332]394    }
[11594]395
396    protected virtual void AssignVariableToListViewItem(ListViewItem listViewItem, KeyValuePair<string, object> variable) {
397      string value = (variable.Value ?? "null").ToString();
398      string type = variable.Value == null ? "null" : variable.Value.GetType().ToString();
399
400      listViewItem.Tag = variable;
401
402      var subItems = listViewItem.SubItems;
403      subItems[0].Text = variable.Key;
404      if (subItems.Count == 1) { // variable information is added; subitems do not exist yet
405        subItems.AddRange(new[] { value, type });
406      } else { // variable information is updated; subitems are changed
407        subItems[1].Text = value;
408        subItems[2].Text = type;
[10332]409      }
410    }
411
[11594]412    protected virtual void SetImageKey(ListViewItem listViewItem, bool serializable) {
413      var variable = (KeyValuePair<string, object>)listViewItem.Tag;
414      if (!serializable) listViewItem.ImageKey = ErrorImageName;
415      else if (!SafeVariableNameRegex.IsMatch(variable.Key)) listViewItem.ImageKey = WarningImageName;
416      else if (variable.Value is IItem) listViewItem.ImageKey = HeuristicLabObjectImageName;
417      else if (variable.Value != null) listViewItem.ImageKey = ObjectImageName;
418      else listViewItem.ImageKey = NothingImageName;
419    }
420
421    protected virtual void SetToolTipText(ListViewItem listViewItem, bool serializable) {
422      var variable = (KeyValuePair<string, object>)listViewItem.Tag;
[10332]423      if (string.IsNullOrEmpty(variable.Key)) throw new ArgumentException("The variable must have a name.", "variable");
[11594]424      string value = listViewItem.SubItems[1].Text;
425      string type = listViewItem.SubItems[2].Text;
426
[10332]427      string[] lines = {
428        "Name: " + variable.Key,
429        "Value: " + value,
[10358]430        "Type: " + type
[10332]431      };
[11594]432
[10358]433      string toolTipText = string.Join(Environment.NewLine, lines);
[11594]434      if (!SafeVariableNameRegex.IsMatch(variable.Key))
435        toolTipText = "Caution: Identifier is no valid C# identifier!" + Environment.NewLine + toolTipText;
[10358]436      if (!serializable)
[10727]437        toolTipText = "Caution: Type is not serializable!" + Environment.NewLine + toolTipText;
[11594]438      listViewItem.ToolTipText = toolTipText;
[10332]439    }
440
[11594]441    private string GenerateNewVariableName(string defaultName = DefaultVariableName, bool generateValidIdentifier = true) {
442      bool editLabel;
443      return GenerateNewVariableName(out editLabel, defaultName, generateValidIdentifier);
444    }
445
446    private string GenerateNewVariableName(out bool defaultNameExists, string defaultName = DefaultVariableName, bool generateValidIdentifier = true) {
447      if (string.IsNullOrEmpty(defaultName) || generateValidIdentifier && !SafeVariableNameRegex.IsMatch(defaultName))
448        defaultName = DefaultVariableName;
[10332]449      if (Content.ContainsKey(defaultName)) {
450        int i = 1;
[11594]451        string formatString = generateValidIdentifier ? "{0}{1}" : "{0} ({1})";
[10332]452        string newName;
453        do {
[11594]454          newName = string.Format(formatString, defaultName, i++);
[10332]455        } while (Content.ContainsKey(newName));
[11594]456        defaultNameExists = true;
[10332]457        return newName;
458      }
[11594]459      defaultNameExists = false;
[10332]460      return defaultName;
461    }
[10358]462
463    private bool IsSerializable(KeyValuePair<string, object> variable) {
[11594]464      Type type = null;
465      bool serializable;
466
467      if (variable.Value != null) {
468        type = variable.Value.GetType();
469        if (serializableLookup.TryGetValue(type, out serializable))
470          return serializable;
471      }
472
[10358]473      var ser = new Serializer(variable, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()), "ROOT", true);
474      try {
[11594]475        serializable = ser.Count() > 0; // try to create all serialization tokens
[10358]476      } catch (PersistenceException) {
[11594]477        serializable = false;
[10358]478      }
[11594]479
480      if (type != null)
481        serializableLookup[type] = serializable;
482      return serializable;
[10358]483    }
[10332]484    #endregion
485  }
486}
Note: See TracBrowser for help on using the repository browser.