Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Core.Views/3.3/ItemCollectionView.cs @ 6522

Last change on this file since 6522 was 6472, checked in by mkommend, 13 years ago

#1564: Corrected cloning bug in drop method of collection views.

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