Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Core.Views/3.3/ItemCollectionView.cs @ 17563

Last change on this file since 17563 was 17181, checked in by swagner, 5 years ago

#2875: Merged r17180 from trunk to stable

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