Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5057 was 5057, checked in by abeham, 13 years ago

#1324

  • Removed update of ImageIndex from RemoveListViewItem()
  • Added method RebuildImageList for synchronizing the SmallImageList after a removal
  • Added a dictionary to provide faster access to items in the collection
File size: 14.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Linq;
25using System.Windows.Forms;
26using HeuristicLab.Collections;
27using HeuristicLab.MainForm;
28using HeuristicLab.MainForm.WindowsForms;
29using HeuristicLab.PluginInfrastructure;
30
31namespace HeuristicLab.Core.Views {
32  [View("ItemCollection View")]
33  [Content(typeof(ItemCollection<>), true)]
34  [Content(typeof(IItemCollection<>), false)]
35  public partial class ItemCollectionView<T> : ItemView where T : class, IItem {
36    private Dictionary<T, List<ListViewItem>> listViewItemMapping;
37    protected TypeSelectorDialog typeSelectorDialog;
38
39    public new IItemCollection<T> Content {
40      get { return (IItemCollection<T>)base.Content; }
41      set { base.Content = value; }
42    }
43
44    public ListView ItemsListView {
45      get { return itemsListView; }
46    }
47
48    public ItemCollectionView() {
49      InitializeComponent();
50      listViewItemMapping = new Dictionary<T, List<ListViewItem>>();
51    }
52
53    protected override void DeregisterContentEvents() {
54      Content.ItemsAdded -= new CollectionItemsChangedEventHandler<T>(Content_ItemsAdded);
55      Content.ItemsRemoved -= new CollectionItemsChangedEventHandler<T>(Content_ItemsRemoved);
56      Content.CollectionReset -= new CollectionItemsChangedEventHandler<T>(Content_CollectionReset);
57      base.DeregisterContentEvents();
58    }
59    protected override void RegisterContentEvents() {
60      base.RegisterContentEvents();
61      Content.ItemsAdded += new CollectionItemsChangedEventHandler<T>(Content_ItemsAdded);
62      Content.ItemsRemoved += new CollectionItemsChangedEventHandler<T>(Content_ItemsRemoved);
63      Content.CollectionReset += new CollectionItemsChangedEventHandler<T>(Content_CollectionReset);
64    }
65
66    protected override void OnContentChanged() {
67      base.OnContentChanged();
68      while (itemsListView.Items.Count > 0) RemoveListViewItem(itemsListView.Items[0]);
69      RebuildImageList();
70      viewHost.Content = null;
71      if (Content != null) {
72        Caption += " (" + Content.GetType().Name + ")";
73        foreach (T item in Content)
74          AddListViewItem(CreateListViewItem(item));
75        AdjustListViewColumnSizes();
76        SortItemsListView(SortOrder.Ascending);
77      }
78    }
79
80    protected override void SetEnabledStateOfControls() {
81      base.SetEnabledStateOfControls();
82      if (Content == null) {
83        addButton.Enabled = false;
84        sortAscendingButton.Enabled = false;
85        sortDescendingButton.Enabled = false;
86        removeButton.Enabled = false;
87        itemsListView.Enabled = false;
88        detailsGroupBox.Enabled = false;
89      } else {
90        addButton.Enabled = !Content.IsReadOnly && !ReadOnly;
91        sortAscendingButton.Enabled = itemsListView.Items.Count > 1;
92        sortDescendingButton.Enabled = itemsListView.Items.Count > 1;
93        removeButton.Enabled = !Content.IsReadOnly && !ReadOnly && itemsListView.SelectedItems.Count > 0;
94        itemsListView.Enabled = true;
95        detailsGroupBox.Enabled = itemsListView.SelectedItems.Count == 1;
96      }
97    }
98
99    protected virtual T CreateItem() {
100      if (typeSelectorDialog == null) {
101        typeSelectorDialog = new TypeSelectorDialog();
102        typeSelectorDialog.Caption = "Select Item";
103        typeSelectorDialog.TypeSelector.Caption = "Available Items";
104        typeSelectorDialog.TypeSelector.Configure(typeof(T), false, true);
105      }
106
107      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
108        try {
109          return (T)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
110        } catch (Exception ex) {
111          ErrorHandling.ShowErrorDialog(this, ex);
112        }
113      }
114      return null;
115    }
116    protected virtual ListViewItem CreateListViewItem(T item) {
117      ListViewItem listViewItem = new ListViewItem();
118      listViewItem.Text = item.ToString();
119      listViewItem.ToolTipText = item.ItemName + ": " + item.ItemDescription;
120      listViewItem.Tag = item;
121      itemsListView.SmallImageList.Images.Add(item.ItemImage);
122      listViewItem.ImageIndex = itemsListView.SmallImageList.Images.Count - 1;
123      return listViewItem;
124    }
125    protected virtual void AddListViewItem(ListViewItem listViewItem) {
126      T item = (listViewItem.Tag as T);
127      itemsListView.Items.Add(listViewItem);
128      item.ItemImageChanged += new EventHandler(Item_ItemImageChanged);
129      item.ToStringChanged += new EventHandler(Item_ToStringChanged);
130      if (!listViewItemMapping.ContainsKey(item))
131        listViewItemMapping.Add(item, new List<ListViewItem>());
132      listViewItemMapping[item].Add(listViewItem);
133      sortAscendingButton.Enabled = itemsListView.Items.Count > 1;
134      sortDescendingButton.Enabled = itemsListView.Items.Count > 1;
135    }
136    protected virtual void RemoveListViewItem(ListViewItem listViewItem) {
137      T item = (listViewItem.Tag as T);
138      listViewItemMapping[item].Remove(listViewItem);
139      if (listViewItemMapping[item].Count == 0) {
140        listViewItemMapping.Remove(item);
141        item.ItemImageChanged -= new EventHandler(Item_ItemImageChanged);
142        item.ToStringChanged -= new EventHandler(Item_ToStringChanged);
143      }
144      listViewItem.Remove();
145      sortAscendingButton.Enabled = itemsListView.Items.Count > 1;
146      sortDescendingButton.Enabled = itemsListView.Items.Count > 1;
147    }
148    protected virtual void UpdateListViewItemImage(ListViewItem listViewItem) {
149      int i = listViewItem.ImageIndex;
150      listViewItem.ImageList.Images[i] = ((T)listViewItem.Tag).ItemImage;
151      listViewItem.ImageIndex = -1;
152      listViewItem.ImageIndex = i;
153    }
154    protected virtual void UpdateListViewItemText(ListViewItem listViewItem) {
155      if (!listViewItem.Text.Equals(listViewItem.Tag.ToString()))
156        listViewItem.Text = listViewItem.Tag.ToString();
157    }
158    protected virtual IEnumerable<ListViewItem> GetListViewItemsForItem(T item) {
159      return listViewItemMapping[item];
160    }
161
162    #region ListView Events
163    protected virtual void itemsListView_SelectedIndexChanged(object sender, EventArgs e) {
164      removeButton.Enabled = (Content != null) && !Content.IsReadOnly && !ReadOnly && itemsListView.SelectedItems.Count > 0;
165      AdjustListViewColumnSizes();
166      if (showDetailsCheckBox.Checked) {
167        if (itemsListView.SelectedItems.Count == 1) {
168          T item = (T)itemsListView.SelectedItems[0].Tag;
169          detailsGroupBox.Enabled = true;
170          viewHost.Content = item;
171        } else {
172          viewHost.Content = null;
173          detailsGroupBox.Enabled = false;
174        }
175      }
176    }
177    protected virtual void itemsListView_KeyDown(object sender, KeyEventArgs e) {
178      if (e.KeyCode == Keys.Delete) {
179        if ((itemsListView.SelectedItems.Count > 0) && !Content.IsReadOnly && !ReadOnly) {
180          foreach (ListViewItem item in itemsListView.SelectedItems)
181            Content.Remove((T)item.Tag);
182        }
183      }
184    }
185    protected virtual void itemsListView_DoubleClick(object sender, EventArgs e) {
186      if (itemsListView.SelectedItems.Count == 1) {
187        T item = (T)itemsListView.SelectedItems[0].Tag;
188        IContentView view = MainFormManager.MainForm.ShowContent(item);
189        if (view != null) {
190          view.ReadOnly = ReadOnly;
191          view.Locked = Locked;
192        }
193      }
194    }
195    protected virtual void itemsListView_ItemDrag(object sender, ItemDragEventArgs e) {
196      if (!Locked) {
197        ListViewItem listViewItem = (ListViewItem)e.Item;
198        T item = (T)listViewItem.Tag;
199        DataObject data = new DataObject();
200        data.SetData("Type", item.GetType());
201        data.SetData("Value", item);
202        if (Content.IsReadOnly || ReadOnly) {
203          DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link);
204        } else {
205          DragDropEffects result = DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link | DragDropEffects.Move);
206          if ((result & DragDropEffects.Move) == DragDropEffects.Move)
207            Content.Remove(item);
208        }
209      }
210    }
211    protected virtual void itemsListView_DragEnterOver(object sender, DragEventArgs e) {
212      e.Effect = DragDropEffects.None;
213      Type type = e.Data.GetData("Type") as Type;
214      if (!Content.IsReadOnly && !ReadOnly && (type != null) && (typeof(T).IsAssignableFrom(type))) {
215        if ((e.KeyState & 32) == 32) e.Effect = DragDropEffects.Link;  // ALT key
216        else if ((e.KeyState & 4) == 4) e.Effect = DragDropEffects.Move;  // SHIFT key
217        else if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy) e.Effect = DragDropEffects.Copy;
218        else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move) e.Effect = DragDropEffects.Move;
219        else if ((e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link) e.Effect = DragDropEffects.Link;
220      }
221    }
222    protected virtual void itemsListView_DragDrop(object sender, DragEventArgs e) {
223      if (e.Effect != DragDropEffects.None) {
224        T item = e.Data.GetData("Value") as T;
225        if ((e.Effect & DragDropEffects.Copy) == DragDropEffects.Copy) item = (T)item.Clone();
226        Content.Add(item);
227      }
228    }
229    #endregion
230
231    #region Button Events
232    protected virtual void addButton_Click(object sender, EventArgs e) {
233      T item = CreateItem();
234      if (item != null)
235        Content.Add(item);
236    }
237    protected virtual void sortAscendingButton_Click(object sender, EventArgs e) {
238      SortItemsListView(SortOrder.Ascending);
239    }
240    protected virtual void sortDescendingButton_Click(object sender, EventArgs e) {
241      SortItemsListView(SortOrder.Descending);
242    }
243    protected virtual void removeButton_Click(object sender, EventArgs e) {
244      if (itemsListView.SelectedItems.Count > 0) {
245        foreach (ListViewItem item in itemsListView.SelectedItems)
246          Content.Remove((T)item.Tag);
247        itemsListView.SelectedItems.Clear();
248      }
249    }
250    #endregion
251
252    #region CheckBox Events
253    protected virtual void showDetailsCheckBox_CheckedChanged(object sender, EventArgs e) {
254      if (showDetailsCheckBox.Checked) {
255        splitContainer.Panel2Collapsed = false;
256        detailsGroupBox.Enabled = itemsListView.SelectedItems.Count == 1;
257        viewHost.Content = itemsListView.SelectedItems.Count == 1 ? (T)itemsListView.SelectedItems[0].Tag : null;
258      } else {
259        splitContainer.Panel2Collapsed = true;
260        viewHost.Content = null;
261      }
262    }
263    #endregion
264
265    #region Content Events
266    protected virtual void Content_ItemsAdded(object sender, CollectionItemsChangedEventArgs<T> e) {
267      if (InvokeRequired)
268        Invoke(new CollectionItemsChangedEventHandler<T>(Content_ItemsAdded), sender, e);
269      else {
270        foreach (T item in e.Items)
271          AddListViewItem(CreateListViewItem(item));
272        AdjustListViewColumnSizes();
273      }
274
275    }
276    protected virtual void Content_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<T> e) {
277      if (InvokeRequired)
278        Invoke(new CollectionItemsChangedEventHandler<T>(Content_ItemsRemoved), sender, e);
279      else {
280        foreach (T item in e.Items) {
281          //remove only the first matching ListViewItem, because the IItem could be contained multiple times in the ItemCollection
282          ListViewItem listviewItem = GetListViewItemsForItem(item).FirstOrDefault();
283          if (listviewItem != null) RemoveListViewItem(listviewItem);
284        }
285        RebuildImageList();
286      }
287    }
288    protected virtual void Content_CollectionReset(object sender, CollectionItemsChangedEventArgs<T> e) {
289      if (InvokeRequired)
290        Invoke(new CollectionItemsChangedEventHandler<T>(Content_CollectionReset), sender, e);
291      else {
292        foreach (T item in e.OldItems) {
293          //remove only the first matching ListViewItem, because the IItem could be contained multiple times in the ItemCollection
294          ListViewItem listviewItem = GetListViewItemsForItem(item).FirstOrDefault();
295          if (listviewItem != null) RemoveListViewItem(listviewItem);
296        }
297        RebuildImageList();
298        foreach (T item in e.Items)
299          AddListViewItem(CreateListViewItem(item));
300      }
301    }
302    #endregion
303
304    #region Item Events
305    protected virtual void Item_ItemImageChanged(object sender, EventArgs e) {
306      if (InvokeRequired)
307        Invoke(new EventHandler(Item_ItemImageChanged), sender, e);
308      else {
309        T item = (T)sender;
310        foreach (ListViewItem listViewItem in GetListViewItemsForItem(item))
311          UpdateListViewItemImage(listViewItem);
312      }
313    }
314    protected virtual void Item_ToStringChanged(object sender, EventArgs e) {
315      if (InvokeRequired)
316        Invoke(new EventHandler(Item_ToStringChanged), sender, e);
317      else {
318        T item = (T)sender;
319        foreach (ListViewItem listViewItem in GetListViewItemsForItem(item))
320          UpdateListViewItemText(listViewItem);
321      }
322    }
323    #endregion
324
325    #region Helpers
326    protected virtual void SortItemsListView(SortOrder sortOrder) {
327      itemsListView.Sorting = SortOrder.None;
328      itemsListView.Sorting = sortOrder;
329      itemsListView.Sorting = SortOrder.None;
330    }
331    protected virtual void AdjustListViewColumnSizes() {
332      if (itemsListView.Items.Count > 0) {
333        for (int i = 0; i < itemsListView.Columns.Count; i++)
334          itemsListView.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
335      }
336    }
337    private void RebuildImageList() {
338      itemsListView.SmallImageList.Images.Clear();
339      foreach (ListViewItem item in itemsListView.Items) {
340        itemsListView.SmallImageList.Images.Add(((T)item.Tag).ItemImage);
341        item.ImageIndex = itemsListView.SmallImageList.Images.Count - 1;
342      }
343    }
344    #endregion
345  }
346}
Note: See TracBrowser for help on using the repository browser.