Free cookie consent management tool by TermsFeed Policy Generator

source: branches/RefactorPluginInfrastructure-2522/HeuristicLab.Core.Views/3.3/ItemArrayView.cs @ 13365

Last change on this file since 13365 was 13338, checked in by gkronber, 9 years ago

#2522:

  • moved UI components out of HeuristicLab.PluginInfrastructure -> HeuristicLab.PluginInfrastructure.UI
  • moved ErrorDialog to HeuristicLab.MainForm.WindowsForms
  • moved ErrorHandling (for building an error message string) to HeuristicLab.Common
  • Changed exception handlers in Views to use MainForm.ShowError()
  • Changed usages for ErrorDialog in non-UI components to throw exceptions instead.
File size: 20.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.Drawing;
25using System.Linq;
26using System.Text;
27using System.Windows.Forms;
28using HeuristicLab.Collections;
29using HeuristicLab.MainForm;
30
31namespace HeuristicLab.Core.Views {
32  [View("ItemArray View")]
33  [Content(typeof(ItemArray<>), true)]
34  [Content(typeof(IItemArray<>), false)]
35  [Content(typeof(ReadOnlyItemArray<>), true)]
36  public partial class ItemArrayView<T> : ItemView where T : class, IItem {
37    protected Dictionary<T, List<ListViewItem>> itemListViewItemMapping;
38    protected TypeSelectorDialog typeSelectorDialog;
39    protected bool validDragOperation;
40
41    public new IItemArray<T> Content {
42      get { return (IItemArray<T>)base.Content; }
43      set { base.Content = value; }
44    }
45
46    public ListView ItemsListView {
47      get { return itemsListView; }
48    }
49
50    public ItemArrayView() {
51      InitializeComponent();
52      itemListViewItemMapping = new Dictionary<T, List<ListViewItem>>();
53    }
54
55    protected override void Dispose(bool disposing) {
56      if (disposing) {
57        if (typeSelectorDialog != null) typeSelectorDialog.Dispose();
58        if (components != null) components.Dispose();
59      }
60      base.Dispose(disposing);
61    }
62
63    protected override void DeregisterContentEvents() {
64      Content.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsReplaced);
65      Content.ItemsMoved -= new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsMoved);
66      Content.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_CollectionReset);
67      foreach (T item in itemListViewItemMapping.Keys) {
68        DeregisterItemEvents(item);
69      }
70      base.DeregisterContentEvents();
71    }
72    protected override void RegisterContentEvents() {
73      base.RegisterContentEvents();
74      Content.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsReplaced);
75      Content.ItemsMoved += new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsMoved);
76      Content.CollectionReset += new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_CollectionReset);
77    }
78    protected virtual void DeregisterItemEvents(T item) {
79      item.ItemImageChanged -= new EventHandler(Item_ItemImageChanged);
80      item.ToStringChanged -= new EventHandler(Item_ToStringChanged);
81    }
82    protected virtual void RegisterItemEvents(T item) {
83      item.ItemImageChanged += new EventHandler(Item_ItemImageChanged);
84      item.ToStringChanged += new EventHandler(Item_ToStringChanged);
85    }
86
87    protected override void OnContentChanged() {
88      base.OnContentChanged();
89
90      int selectedIndex = -1;
91      if (itemsListView.SelectedItems.Count == 1) selectedIndex = itemsListView.SelectedIndices[0];
92
93      itemsListView.Items.Clear();
94      itemListViewItemMapping.Clear();
95      RebuildImageList();
96      viewHost.Content = null;
97      if (Content != null) {
98        Caption += " (" + Content.GetType().Name + ")";
99        foreach (T item in Content)
100          AddListViewItem(CreateListViewItem(item));
101        AdjustListViewColumnSizes();
102        if ((selectedIndex != -1) && (selectedIndex < itemsListView.Items.Count))
103          itemsListView.Items[selectedIndex].Selected = true;
104      }
105    }
106
107    protected override void SetEnabledStateOfControls() {
108      base.SetEnabledStateOfControls();
109      if (Content == null) {
110        addButton.Enabled = false;
111        moveUpButton.Enabled = false;
112        moveDownButton.Enabled = false;
113        removeButton.Enabled = false;
114        itemsListView.Enabled = false;
115        detailsGroupBox.Enabled = false;
116      } else {
117        addButton.Enabled = itemsListView.SelectedItems.Count > 0 &&
118                            !Content.IsReadOnly && !ReadOnly;
119        moveUpButton.Enabled = itemsListView.SelectedItems.Count == 1 &&
120                               itemsListView.SelectedIndices[0] != 0 &&
121                               !Content.IsReadOnly && !ReadOnly;
122        moveDownButton.Enabled = itemsListView.SelectedItems.Count == 1 &&
123                                 itemsListView.SelectedIndices[0] != itemsListView.Items.Count - 1 &&
124                                 !Content.IsReadOnly && !ReadOnly;
125        removeButton.Enabled = itemsListView.SelectedItems.Count > 0 &&
126                               !Content.IsReadOnly && !ReadOnly;
127        itemsListView.Enabled = true;
128        detailsGroupBox.Enabled = itemsListView.SelectedItems.Count == 1;
129      }
130    }
131
132    protected virtual T CreateItem() {
133      if (typeSelectorDialog == null) {
134        typeSelectorDialog = new TypeSelectorDialog();
135        typeSelectorDialog.Caption = "Select Item";
136        typeSelectorDialog.TypeSelector.Caption = "Available Items";
137        typeSelectorDialog.TypeSelector.Configure(typeof(T), false, true);
138      }
139
140      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
141        try {
142          return (T)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
143        } catch (Exception ex) {
144          MainFormManager.MainForm.ShowError(ex.Message, ex);
145        }
146      }
147      return null;
148    }
149    protected virtual ListViewItem CreateListViewItem(T item) {
150      ListViewItem listViewItem = new ListViewItem();
151      if (item == null) {
152        listViewItem.Text = "null";
153        itemsListView.SmallImageList.Images.Add(HeuristicLab.Common.Resources.VSImageLibrary.Nothing);
154        listViewItem.ImageIndex = itemsListView.SmallImageList.Images.Count - 1;
155      } else {
156        listViewItem.Text = item.ToString();
157        listViewItem.ToolTipText = item.ItemName + ": " + item.ItemDescription;
158        itemsListView.SmallImageList.Images.Add(item.ItemImage);
159        listViewItem.ImageIndex = itemsListView.SmallImageList.Images.Count - 1;
160        listViewItem.Tag = item;
161      }
162      return listViewItem;
163    }
164    protected virtual void AddListViewItem(ListViewItem listViewItem) {
165      if (listViewItem == null) throw new ArgumentNullException();
166      T item = (listViewItem.Tag as T);
167      itemsListView.Items.Add(listViewItem);
168      if (item != null) {
169        if (!itemListViewItemMapping.ContainsKey(item)) {
170          RegisterItemEvents(item);
171          itemListViewItemMapping.Add(item, new List<ListViewItem>());
172        }
173        itemListViewItemMapping[item].Add(listViewItem);
174      }
175    }
176    protected virtual void InsertListViewItem(int index, ListViewItem listViewItem) {
177      if (listViewItem == null) throw new ArgumentNullException();
178      T item = (listViewItem.Tag as T);
179      itemsListView.Items.Insert(index, listViewItem);
180      if (item != null) {
181        if (!itemListViewItemMapping.ContainsKey(item)) {
182          RegisterItemEvents(item);
183          itemListViewItemMapping.Add(item, new List<ListViewItem>());
184        }
185        itemListViewItemMapping[item].Add(listViewItem);
186      }
187    }
188    protected virtual void RemoveListViewItem(ListViewItem listViewItem) {
189      if (listViewItem == null) throw new ArgumentNullException();
190      T item = (listViewItem.Tag as T);
191      if (item != null) {
192        itemListViewItemMapping[item].Remove(listViewItem);
193        if (itemListViewItemMapping[item].Count == 0) {
194          itemListViewItemMapping.Remove(item);
195          DeregisterItemEvents(item);
196        }
197      }
198      listViewItem.Remove();
199    }
200    protected virtual void UpdateListViewItemImage(ListViewItem listViewItem) {
201      if (listViewItem == null) throw new ArgumentNullException();
202      T item = listViewItem.Tag as T;
203      int i = listViewItem.ImageIndex;
204      itemsListView.SmallImageList.Images[i] = item == null ? HeuristicLab.Common.Resources.VSImageLibrary.Nothing : item.ItemImage;
205      listViewItem.ImageIndex = -1;
206      listViewItem.ImageIndex = i;
207    }
208    protected virtual void UpdateListViewItemText(ListViewItem listViewItem) {
209      if (listViewItem == null) throw new ArgumentNullException();
210      T item = listViewItem.Tag as T;
211      listViewItem.Text = item == null ? "null" : item.ToString();
212      listViewItem.ToolTipText = item == null ? string.Empty : item.ItemName + ": " + item.ItemDescription;
213    }
214    protected virtual IEnumerable<ListViewItem> GetListViewItemsForItem(T item) {
215      if (item == null) {
216        List<ListViewItem> listViewItems = new List<ListViewItem>();
217        foreach (ListViewItem listViewItem in itemsListView.Items) {
218          if (listViewItem.Tag == null) listViewItems.Add(listViewItem);
219        }
220        return listViewItems;
221      } else {
222        List<ListViewItem> listViewItems = null;
223        itemListViewItemMapping.TryGetValue(item, out listViewItems);
224        return listViewItems == null ? Enumerable.Empty<ListViewItem>() : listViewItems;
225      }
226    }
227
228    #region ListView Events
229    protected virtual void itemsListView_SelectedIndexChanged(object sender, EventArgs e) {
230      addButton.Enabled = itemsListView.SelectedItems.Count > 0 && (Content != null) && !Content.IsReadOnly && !ReadOnly;
231      moveUpButton.Enabled = itemsListView.SelectedItems.Count == 1 &&
232                             itemsListView.SelectedIndices[0] != 0 &&
233                             (Content != null) && !Content.IsReadOnly && !ReadOnly;
234      moveDownButton.Enabled = itemsListView.SelectedItems.Count == 1 &&
235                               itemsListView.SelectedIndices[0] != itemsListView.Items.Count - 1 &&
236                               (Content != null) && !Content.IsReadOnly && !ReadOnly;
237      removeButton.Enabled = itemsListView.SelectedItems.Count > 0 && (Content != null) && !Content.IsReadOnly && !ReadOnly;
238      AdjustListViewColumnSizes();
239
240      if (showDetailsCheckBox.Checked) {
241        if (itemsListView.SelectedItems.Count == 1) {
242          T item = itemsListView.SelectedItems[0].Tag as T;
243          detailsGroupBox.Enabled = true;
244          viewHost.Content = item;
245        } else {
246          viewHost.Content = null;
247          detailsGroupBox.Enabled = false;
248        }
249      }
250    }
251
252    protected virtual void itemsListView_KeyDown(object sender, KeyEventArgs e) {
253      if (e.KeyCode == Keys.Delete) {
254        if ((itemsListView.SelectedItems.Count > 0) && !Content.IsReadOnly && !ReadOnly) {
255          foreach (ListViewItem item in itemsListView.SelectedItems)
256            Content[item.Index] = null;
257        }
258      } else if (e.KeyData == (Keys.Control | Keys.C)) {
259        if (itemsListView.SelectedItems.Count > 0) {
260          var builder = new StringBuilder();
261          foreach (ListViewItem selected in itemsListView.SelectedItems) {
262            builder.AppendLine(selected.Text);
263          }
264          Clipboard.SetText(builder.ToString());
265        }
266      }
267    }
268
269    protected virtual void itemsListView_DoubleClick(object sender, EventArgs e) {
270      if (itemsListView.SelectedItems.Count == 1) {
271        T item = itemsListView.SelectedItems[0].Tag as T;
272        if (item != null) {
273          IContentView view = MainFormManager.MainForm.ShowContent(item);
274          if (view != null) {
275            view.ReadOnly = ReadOnly;
276            view.Locked = Locked;
277          }
278        }
279      }
280    }
281
282    protected virtual void itemsListView_ItemDrag(object sender, ItemDragEventArgs e) {
283      if (!Locked) {
284        List<T> items = new List<T>();
285        foreach (ListViewItem listViewItem in itemsListView.SelectedItems) {
286          T item = listViewItem.Tag as T;
287          if (item != null) items.Add(item);
288        }
289
290        if (items.Count > 0) {
291          DataObject data = new DataObject();
292          if (items.Count == 1) data.SetData(HeuristicLab.Common.Constants.DragDropDataFormat, items[0]);
293          else data.SetData(HeuristicLab.Common.Constants.DragDropDataFormat, items);
294          if (Content.IsReadOnly || ReadOnly) {
295            DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link);
296          } else {
297            DragDropEffects result = DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link | DragDropEffects.Move);
298            if ((result & DragDropEffects.Move) == DragDropEffects.Move) {
299              foreach (ListViewItem listViewItem in itemsListView.SelectedItems.Cast<ListViewItem>().ToArray())
300                Content[listViewItem.Index] = null;
301            }
302          }
303        }
304      }
305    }
306    protected virtual void itemsListView_DragEnter(object sender, DragEventArgs e) {
307      validDragOperation = !Content.IsReadOnly && !ReadOnly && e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) is T;
308    }
309    protected virtual void itemsListView_DragOver(object sender, DragEventArgs e) {
310      e.Effect = DragDropEffects.None;
311      if (validDragOperation) {
312        Point p = itemsListView.PointToClient(new Point(e.X, e.Y));
313        ListViewItem listViewItem = itemsListView.GetItemAt(p.X, p.Y);
314        if (listViewItem != null) {
315          if ((e.KeyState & 32) == 32) e.Effect = DragDropEffects.Link;  // ALT key
316          else if ((e.KeyState & 4) == 4) e.Effect = DragDropEffects.Move;  // SHIFT key
317          else if (e.AllowedEffect.HasFlag(DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy;
318          else if (e.AllowedEffect.HasFlag(DragDropEffects.Move)) e.Effect = DragDropEffects.Move;
319          else if (e.AllowedEffect.HasFlag(DragDropEffects.Link)) e.Effect = DragDropEffects.Link;
320        }
321      }
322    }
323    protected virtual void itemsListView_DragDrop(object sender, DragEventArgs e) {
324      if (e.Effect != DragDropEffects.None) {
325        Point p = itemsListView.PointToClient(new Point(e.X, e.Y));
326        ListViewItem listViewItem = itemsListView.GetItemAt(p.X, p.Y);
327        T item = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) as T;
328        Content[listViewItem.Index] = e.Effect.HasFlag(DragDropEffects.Copy) ? (T)item.Clone() : item;
329      }
330    }
331    #endregion
332
333    #region Button Events
334    protected virtual void addButton_Click(object sender, EventArgs e) {
335      if (itemsListView.SelectedItems.Count > 0) {
336        T item = CreateItem();
337        if (item != null) {
338          foreach (ListViewItem listViewItem in itemsListView.SelectedItems)
339            Content[listViewItem.Index] = item;
340        }
341      }
342    }
343    protected virtual void moveUpButton_Click(object sender, EventArgs e) {
344      if (itemsListView.SelectedItems.Count == 1) {
345        int index = itemsListView.SelectedIndices[0];
346        Content.Reverse(index - 1, 2);
347        itemsListView.Items[index].Selected = false;
348        itemsListView.Items[index - 1].Selected = true;
349      }
350    }
351    protected virtual void moveDownButton_Click(object sender, EventArgs e) {
352      if (itemsListView.SelectedItems.Count == 1) {
353        int index = itemsListView.SelectedIndices[0];
354        Content.Reverse(index, 2);
355        itemsListView.Items[index].Selected = false;
356        itemsListView.Items[index + 1].Selected = true;
357      }
358    }
359    protected virtual void removeButton_Click(object sender, EventArgs e) {
360      if (itemsListView.SelectedItems.Count > 0) {
361        foreach (ListViewItem item in itemsListView.SelectedItems)
362          Content[item.Index] = null;
363      }
364    }
365    #endregion
366
367    #region CheckBox Events
368    protected virtual void showDetailsCheckBox_CheckedChanged(object sender, EventArgs e) {
369      if (showDetailsCheckBox.Checked) {
370        splitContainer.Panel2Collapsed = false;
371        detailsGroupBox.Enabled = itemsListView.SelectedItems.Count == 1;
372        viewHost.Content = itemsListView.SelectedItems.Count == 1 ? (T)itemsListView.SelectedItems[0].Tag : null;
373      } else {
374        splitContainer.Panel2Collapsed = true;
375        viewHost.Content = null;
376      }
377    }
378    #endregion
379
380    #region Content Events
381    protected virtual void Content_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<T>> e) {
382      if (InvokeRequired)
383        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsReplaced), sender, e);
384      else {
385        int[] selected = new int[itemsListView.SelectedIndices.Count];
386        itemsListView.SelectedIndices.CopyTo(selected, 0);
387
388        List<ListViewItem> listViewItems = new List<ListViewItem>();
389        foreach (IndexedItem<T> item in e.OldItems)
390          listViewItems.Add(itemsListView.Items[item.Index]);
391        foreach (ListViewItem listViewItem in listViewItems)
392          RemoveListViewItem(listViewItem);
393        RebuildImageList();
394
395        foreach (IndexedItem<T> item in e.Items)
396          InsertListViewItem(item.Index, CreateListViewItem(item.Value));
397        AdjustListViewColumnSizes();
398
399        for (int i = 0; i < selected.Length; i++)
400          itemsListView.Items[selected[i]].Selected = true;
401      }
402    }
403    protected virtual void Content_ItemsMoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<T>> e) {
404      if (InvokeRequired)
405        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsMoved), sender, e);
406      else {
407        foreach (IndexedItem<T> item in e.Items) {
408          ListViewItem listViewItem = itemsListView.Items[item.Index];
409          if (listViewItem.Tag != null)
410            itemListViewItemMapping[(T)listViewItem.Tag].Remove(listViewItem);
411          listViewItem.Tag = item.Value;
412          if (listViewItem.Tag != null)
413            itemListViewItemMapping[item.Value].Add(listViewItem);
414          UpdateListViewItemImage(listViewItem);
415          UpdateListViewItemText(listViewItem);
416        }
417      }
418    }
419    protected virtual void Content_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<T>> e) {
420      if (InvokeRequired)
421        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_CollectionReset), sender, e);
422      else {
423        List<ListViewItem> listViewItems = new List<ListViewItem>();
424        foreach (IndexedItem<T> item in e.OldItems)
425          listViewItems.Add(itemsListView.Items[item.Index]);
426        foreach (ListViewItem listViewItem in listViewItems)
427          RemoveListViewItem(listViewItem);
428        RebuildImageList();
429
430        foreach (IndexedItem<T> item in e.Items)
431          InsertListViewItem(item.Index, CreateListViewItem(item.Value));
432        AdjustListViewColumnSizes();
433      }
434    }
435    #endregion
436
437    #region Item Events
438    protected virtual void Item_ItemImageChanged(object sender, EventArgs e) {
439      if (InvokeRequired)
440        Invoke(new EventHandler(Item_ItemImageChanged), sender, e);
441      else {
442        T item = (T)sender;
443        foreach (ListViewItem listViewItem in GetListViewItemsForItem(item))
444          UpdateListViewItemImage(listViewItem);
445      }
446    }
447    protected virtual void Item_ToStringChanged(object sender, EventArgs e) {
448      if (InvokeRequired)
449        Invoke(new EventHandler(Item_ToStringChanged), sender, e);
450      else {
451        T item = (T)sender;
452        foreach (ListViewItem listViewItem in GetListViewItemsForItem(item))
453          UpdateListViewItemText(listViewItem);
454        AdjustListViewColumnSizes();
455      }
456    }
457    #endregion
458
459    #region Helpers
460    protected virtual void AdjustListViewColumnSizes() {
461      if (itemsListView.Items.Count > 0) {
462        for (int i = 0; i < itemsListView.Columns.Count; i++)
463          itemsListView.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
464      }
465    }
466    protected virtual void RebuildImageList() {
467      itemsListView.SmallImageList.Images.Clear();
468      foreach (ListViewItem listViewItem in itemsListView.Items) {
469        T item = listViewItem.Tag as T;
470        itemsListView.SmallImageList.Images.Add(item == null ? HeuristicLab.Common.Resources.VSImageLibrary.Nothing : item.ItemImage);
471        listViewItem.ImageIndex = itemsListView.SmallImageList.Images.Count - 1;
472      }
473    }
474    #endregion
475  }
476}
Note: See TracBrowser for help on using the repository browser.