Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.DatasetRefactor/sources/HeuristicLab.Core.Views/3.3/ItemArrayView.cs @ 12105

Last change on this file since 12105 was 12105, checked in by bburlacu, 9 years ago

#2276: Merged trunk changes.

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