Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5239 was 5239, checked in by swagner, 13 years ago

Adapted method RebuildImageList to work with null items (#1324)

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