Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Breadcrumbs/HeuristicLab.Core.Views/3.3/ItemCollectionView.cs @ 10089

Last change on this file since 10089 was 10089, checked in by jkarder, 10 years ago

#2116:

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