Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5188 was 5068, checked in by abeham, 14 years ago

#1324

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