Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2205_OptimizationNetworks/HeuristicLab.Scripting.Views/3.3/VariableStoreView.cs @ 16654

Last change on this file since 16654 was 11576, checked in by swagner, 10 years ago

#2205: Merged changes r11062:11557 from trunk/sources into branches/OptimizationNetworks

File size: 19.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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.RegularExpressions;
26using System.Windows.Forms;
27using HeuristicLab.Collections;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Core.Views;
31using HeuristicLab.MainForm;
32using HeuristicLab.MainForm.WindowsForms;
33using HeuristicLab.Persistence.Core;
34using HeuristicLab.Persistence.Default.Xml;
35using HeuristicLab.PluginInfrastructure;
36
37namespace HeuristicLab.Scripting.Views {
38  [View("ItemCollection View")]
39  [Content(typeof(VariableStore), true)]
40  public partial class VariableStoreView : AsynchronousContentView {
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;
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>();
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);
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 {
121        bool enabled = !Locked && !ReadOnly;
122        addButton.Enabled = enabled;
123        sortAscendingButton.Enabled = variableListView.Items.Count > 1;
124        sortDescendingButton.Enabled = variableListView.Items.Count > 1;
125        removeButton.Enabled = enabled && variableListView.SelectedItems.Count > 0;
126        variableListView.Enabled = enabled;
127        variableListView.LabelEdit = enabled;
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");
150      bool serializable = IsSerializable(variable);
151
152      var listViewItem = new ListViewItem();
153      AssignVariableToListViewItem(listViewItem, variable);
154      SetImageKey(listViewItem, serializable);
155      SetToolTipText(listViewItem, serializable);
156      variableListView.Items.Add(listViewItem);
157
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");
167
168      ListViewItem listViewItem;
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;
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");
181
182      ListViewItem listViewItem;
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
191    }
192
193    #region ListView Events
194    protected virtual void variableListView_SelectedIndexChanged(object sender, EventArgs e) {
195      removeButton.Enabled = (Content != null) && !Locked && !ReadOnly && variableListView.SelectedItems.Count > 0;
196      AdjustListViewColumnSizes();
197    }
198    protected virtual void variableListView_KeyDown(object sender, KeyEventArgs e) {
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;
218      }
219    }
220    protected virtual void variableListView_DoubleClick(object sender, EventArgs e) {
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;
233    }
234    protected virtual void variableListView_ItemDrag(object sender, ItemDragEventArgs e) {
235      if (Locked || variableListView.SelectedItems.Count != 1) return;
236
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);
242    }
243    protected virtual void variableListView_DragEnter(object sender, DragEventArgs e) {
244      validDragOperation = !Locked && !ReadOnly && e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) != null;
245    }
246    protected virtual void variableListView_DragOver(object sender, DragEventArgs e) {
247      e.Effect = DragDropEffects.None;
248      if (validDragOperation) {
249        if (e.AllowedEffect.HasFlag(DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy;
250      }
251    }
252    protected virtual void variableListView_DragDrop(object sender, DragEventArgs e) {
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);
269      }
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();
279    }
280
281    private readonly Regex SafeVariableNameRegex = new Regex("^[@]?[_a-zA-Z][_a-zA-Z0-9]*$");
282    private const string DefaultVariableName = "enter_name";
283
284    private void variableListView_AfterLabelEdit(object sender, LabelEditEventArgs e) {
285      string name = e.Label;
286      if (!string.IsNullOrEmpty(name)) {
287        var variable = (KeyValuePair<string, object>)variableListView.Items[e.Item].Tag;
288        if (!Content.ContainsKey(name)) {
289          Content.Remove(variable.Key);
290          Content.Add(name, variable.Value);
291        }
292      }
293      e.CancelEdit = true;
294    }
295    #endregion
296
297    #region Button Events
298    protected virtual void addButton_Click(object sender, EventArgs e) {
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();
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>?;
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);
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() {
392      foreach (ColumnHeader ch in variableListView.Columns)
393        ch.Width = -2;
394    }
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;
409      }
410    }
411
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;
423      if (string.IsNullOrEmpty(variable.Key)) throw new ArgumentException("The variable must have a name.", "variable");
424      string value = listViewItem.SubItems[1].Text;
425      string type = listViewItem.SubItems[2].Text;
426
427      string[] lines = {
428        "Name: " + variable.Key,
429        "Value: " + value,
430        "Type: " + type
431      };
432
433      string toolTipText = string.Join(Environment.NewLine, lines);
434      if (!SafeVariableNameRegex.IsMatch(variable.Key))
435        toolTipText = "Caution: Identifier is no valid C# identifier!" + Environment.NewLine + toolTipText;
436      if (!serializable)
437        toolTipText = "Caution: Type is not serializable!" + Environment.NewLine + toolTipText;
438      listViewItem.ToolTipText = toolTipText;
439    }
440
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;
449      if (Content.ContainsKey(defaultName)) {
450        int i = 1;
451        string formatString = generateValidIdentifier ? "{0}{1}" : "{0} ({1})";
452        string newName;
453        do {
454          newName = string.Format(formatString, defaultName, i++);
455        } while (Content.ContainsKey(newName));
456        defaultNameExists = true;
457        return newName;
458      }
459      defaultNameExists = false;
460      return defaultName;
461    }
462
463    private bool IsSerializable(KeyValuePair<string, object> variable) {
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
473      var ser = new Serializer(variable, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()), "ROOT", true);
474      try {
475        serializable = ser.Count() > 0; // try to create all serialization tokens
476      } catch (PersistenceException) {
477        serializable = false;
478      }
479
480      if (type != null)
481        serializableLookup[type] = serializable;
482      return serializable;
483    }
484    #endregion
485  }
486}
Note: See TracBrowser for help on using the repository browser.