Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Core.Views/3.3/ItemCollectionView.cs @ 9947

Last change on this file since 9947 was 6760, checked in by epitzer, 13 years ago

#1530 integrate changes from trunk

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