Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataPreprocessing/HeuristicLab.Core.Views/3.3/ItemCollectionView.cs @ 10902

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