Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6004 was 5839, checked in by swagner, 14 years ago

Fixed NullReferenceException in collection views when updating the item image of a hidden item (#1377)

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