Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Core.Views/3.3/ItemArrayView.cs @ 3483

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

Worked on the refactoring of saving and loading items (#990)

File size: 17.5 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.Drawing;
25using System.Windows.Forms;
26using HeuristicLab.Collections;
27using HeuristicLab.MainForm;
28using HeuristicLab.MainForm.WindowsForms;
29
30namespace HeuristicLab.Core.Views {
31  /// <summary>
32  /// The visual representation of all variables in a specified scope.
33  /// </summary>
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 TypeSelectorDialog typeSelectorDialog;
39
40    /// <summary>
41    /// Gets or sets the scope whose variables to represent visually.
42    /// </summary>
43    /// <remarks>Uses property <see cref="ViewBase.Item"/> of base class <see cref="ViewBase"/>.
44    /// No won data storage present.</remarks>
45    public new IItemArray<T> Content {
46      get { return (IItemArray<T>)base.Content; }
47      set { base.Content = value; }
48    }
49
50    public ListView ItemsListView {
51      get { return itemsListView; }
52    }
53
54    /// <summary>
55    /// Initializes a new instance of <see cref="VariablesScopeView"/> with caption "Variables Scope View".
56    /// </summary>
57    public ItemArrayView() {
58      InitializeComponent();
59      Caption = "Item Array";
60    }
61    public ItemArrayView(IItemArray<T> content)
62      : this() {
63      Content = content;
64    }
65
66    /// <summary>
67    /// Removes the eventhandlers from the underlying <see cref="IScope"/>.
68    /// </summary>
69    /// <remarks>Calls <see cref="ViewBase.RemoveItemEvents"/> of base class <see cref="ViewBase"/>.</remarks>
70    protected override void DeregisterContentEvents() {
71      Content.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsReplaced);
72      Content.ItemsMoved -= new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsMoved);
73      Content.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_CollectionReset);
74      base.DeregisterContentEvents();
75    }
76
77    /// <summary>
78    /// Adds eventhandlers to the underlying <see cref="IScope"/>.
79    /// </summary>
80    /// <remarks>Calls <see cref="ViewBase.AddItemEvents"/> of base class <see cref="ViewBase"/>.</remarks>
81    protected override void RegisterContentEvents() {
82      base.RegisterContentEvents();
83      Content.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsReplaced);
84      Content.ItemsMoved += new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsMoved);
85      Content.CollectionReset += new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_CollectionReset);
86    }
87
88    protected override void OnContentChanged() {
89      base.OnContentChanged();
90      Caption = "Item Array";
91      while (itemsListView.Items.Count > 0) RemoveListViewItem(itemsListView.Items[0]);
92      viewHost.Content = null;
93      if (Content != null) {
94        Caption += " (" + Content.GetType().Name + ")";
95        foreach (T item in Content)
96          AddListViewItem(CreateListViewItem(item));
97      }
98      SetEnabledStateOfControls();
99    }
100
101    protected override void OnReadOnlyChanged() {
102      base.OnReadOnlyChanged();
103      SetEnabledStateOfControls();
104    }
105
106    private void SetEnabledStateOfControls() {
107      if (Content == null) {
108        addButton.Enabled = false;
109        moveUpButton.Enabled = false;
110        moveDownButton.Enabled = false;
111        removeButton.Enabled = false;
112        itemsListView.Enabled = false;
113        detailsGroupBox.Enabled = false;
114      } else {
115        addButton.Enabled = itemsListView.SelectedItems.Count > 0 &&
116                            !Content.IsReadOnly && !ReadOnly;
117        moveUpButton.Enabled = itemsListView.SelectedItems.Count == 1 &&
118                               itemsListView.SelectedIndices[0] != 0 &&
119                               !Content.IsReadOnly && !ReadOnly;
120        moveDownButton.Enabled = itemsListView.SelectedItems.Count == 1 &&
121                                 itemsListView.SelectedIndices[0] != itemsListView.Items.Count - 1 &&
122                                 !Content.IsReadOnly && !ReadOnly;
123        removeButton.Enabled = itemsListView.SelectedItems.Count > 0 &&
124                               !Content.IsReadOnly && !ReadOnly;
125        itemsListView.Enabled = true;
126        detailsGroupBox.Enabled = true;
127      }
128    }
129
130    protected virtual T CreateItem() {
131      if (typeSelectorDialog == null) {
132        typeSelectorDialog = new TypeSelectorDialog();
133        typeSelectorDialog.Caption = "Select Item";
134        typeSelectorDialog.TypeSelector.Caption = "Available Items";
135        typeSelectorDialog.TypeSelector.Configure(typeof(T), false, false);
136      }
137
138      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
139        try {
140          return (T)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
141        }
142        catch (Exception ex) {
143          Auxiliary.ShowErrorMessageBox(ex);
144        }
145      }
146      return null;
147    }
148    protected virtual ListViewItem CreateListViewItem(T item) {
149      ListViewItem listViewItem = new ListViewItem();
150      listViewItem.Text = item == null ? "null" : item.ToString();
151      listViewItem.ToolTipText = item == null ? string.Empty : item.ItemName + ": " + item.ItemDescription;
152      itemsListView.SmallImageList.Images.Add(item == null ? HeuristicLab.Common.Resources.VS2008ImageLibrary.Nothing : item.ItemImage);
153      listViewItem.ImageIndex = itemsListView.SmallImageList.Images.Count - 1;
154      listViewItem.Tag = item;
155      return listViewItem;
156    }
157    protected virtual void AddListViewItem(ListViewItem listViewItem) {
158      itemsListView.Items.Add(listViewItem);
159      if (listViewItem.Tag != null) {
160        ((T)listViewItem.Tag).ItemImageChanged += new EventHandler(Item_ItemImageChanged);
161        ((T)listViewItem.Tag).ToStringChanged += new EventHandler(Item_ToStringChanged);
162      }
163      AdjustListViewColumnSizes();
164    }
165    protected virtual void InsertListViewItem(int index, ListViewItem listViewItem) {
166      itemsListView.Items.Insert(index, listViewItem);
167      if (listViewItem.Tag != null) {
168        ((T)listViewItem.Tag).ItemImageChanged += new EventHandler(Item_ItemImageChanged);
169        ((T)listViewItem.Tag).ToStringChanged += new EventHandler(Item_ToStringChanged);
170      }
171      AdjustListViewColumnSizes();
172    }
173    protected virtual void RemoveListViewItem(ListViewItem listViewItem) {
174      if (listViewItem.Tag != null) {
175        ((T)listViewItem.Tag).ItemImageChanged -= new EventHandler(Item_ItemImageChanged);
176        ((T)listViewItem.Tag).ToStringChanged -= new EventHandler(Item_ToStringChanged);
177      }
178      listViewItem.Remove();
179      foreach (ListViewItem other in itemsListView.Items)
180        if (other.ImageIndex > listViewItem.ImageIndex) other.ImageIndex--;
181      itemsListView.SmallImageList.Images.RemoveAt(listViewItem.ImageIndex);
182    }
183    protected virtual void UpdateListViewItemImage(ListViewItem listViewItem) {
184      T item = listViewItem.Tag as T;
185      int i = listViewItem.ImageIndex;
186      listViewItem.ImageList.Images[i] = item == null ? HeuristicLab.Common.Resources.VS2008ImageLibrary.Nothing : item.ItemImage;
187      listViewItem.ImageIndex = -1;
188      listViewItem.ImageIndex = i;
189    }
190    protected virtual void UpdateListViewItemText(ListViewItem listViewItem) {
191      T item = listViewItem.Tag as T;
192      listViewItem.Text = item == null ? "null" : item.ToString();
193      listViewItem.ToolTipText = item == null ? string.Empty : item.ItemName + ": " + item.ItemDescription;
194    }
195
196    #region ListView Events
197    protected virtual void itemsListView_SelectedIndexChanged(object sender, EventArgs e) {
198      addButton.Enabled = itemsListView.SelectedItems.Count > 0 && (Content != null) && !Content.IsReadOnly && !ReadOnly;
199      moveUpButton.Enabled = itemsListView.SelectedItems.Count == 1 &&
200                             itemsListView.SelectedIndices[0] != 0 &&
201                             (Content != null) && !Content.IsReadOnly && !ReadOnly;
202      moveDownButton.Enabled = itemsListView.SelectedItems.Count == 1 &&
203                               itemsListView.SelectedIndices[0] != itemsListView.Items.Count - 1 &&
204                               (Content != null) && !Content.IsReadOnly && !ReadOnly;
205      removeButton.Enabled = itemsListView.SelectedItems.Count > 0 && (Content != null) && !Content.IsReadOnly && !ReadOnly;
206
207      if (itemsListView.SelectedItems.Count == 1) {
208        T item = itemsListView.SelectedItems[0].Tag as T;
209        detailsGroupBox.Enabled = true;
210        viewHost.ViewType = null;
211        viewHost.Content = item;
212      } else {
213        viewHost.Content = null;
214        detailsGroupBox.Enabled = false;
215      }
216    }
217
218    protected virtual void itemsListView_KeyDown(object sender, KeyEventArgs e) {
219      if (e.KeyCode == Keys.Delete) {
220        if ((itemsListView.SelectedItems.Count > 0) && !Content.IsReadOnly && !ReadOnly) {
221          foreach (ListViewItem item in itemsListView.SelectedItems)
222            Content[item.Index] = null;
223        }
224      }
225    }
226
227    protected virtual void itemsListView_DoubleClick(object sender, EventArgs e) {
228      if (itemsListView.SelectedItems.Count == 1) {
229        T item = itemsListView.SelectedItems[0].Tag as T;
230        if (item != null) {
231          IContentView view = MainFormManager.CreateDefaultView(item);
232          if (view != null) {
233            view.ReadOnly = ReadOnly;
234            view.Locked = Locked;
235            view.Show();
236          }
237        }
238      }
239    }
240
241    protected virtual void itemsListView_ItemDrag(object sender, ItemDragEventArgs e) {
242      if (!Locked) {
243        ListViewItem listViewItem = (ListViewItem)e.Item;
244        T item = listViewItem.Tag as T;
245        if (item != null) {
246          DataObject data = new DataObject();
247          data.SetData("Type", item.GetType());
248          data.SetData("Value", item);
249          if (Content.IsReadOnly || ReadOnly) {
250            DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link);
251          } else {
252            DragDropEffects result = DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link | DragDropEffects.Move);
253            if ((result & DragDropEffects.Move) == DragDropEffects.Move)
254              Content[listViewItem.Index] = null;
255          }
256        }
257      }
258    }
259    protected virtual void itemsListView_DragEnterOver(object sender, DragEventArgs e) {
260      e.Effect = DragDropEffects.None;
261      Type type = e.Data.GetData("Type") as Type;
262      if (!Content.IsReadOnly && !ReadOnly && (type != null) && (typeof(T).IsAssignableFrom(type))) {
263        Point p = itemsListView.PointToClient(new Point(e.X, e.Y));
264        ListViewItem listViewItem = itemsListView.GetItemAt(p.X, p.Y);
265        if (listViewItem != null) {
266          if ((e.KeyState & 8) == 8) e.Effect = DragDropEffects.Copy;  // CTRL key
267          else if ((e.KeyState & 4) == 4) e.Effect = DragDropEffects.Move;  // SHIFT key
268          else if ((e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link) e.Effect = DragDropEffects.Link;
269          else if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy) e.Effect = DragDropEffects.Copy;
270          else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move) e.Effect = DragDropEffects.Move;
271        }
272      }
273    }
274    protected virtual void itemsListView_DragDrop(object sender, DragEventArgs e) {
275      if (e.Effect != DragDropEffects.None) {
276        T item = e.Data.GetData("Value") as T;
277        if ((e.Effect & DragDropEffects.Copy) == DragDropEffects.Copy) item = (T)item.Clone();
278
279        Point p = itemsListView.PointToClient(new Point(e.X, e.Y));
280        ListViewItem listViewItem = itemsListView.GetItemAt(p.X, p.Y);
281        Content[listViewItem.Index] = item;
282      }
283    }
284    #endregion
285
286    #region Button Events
287    protected virtual void addButton_Click(object sender, EventArgs e) {
288      if (itemsListView.SelectedItems.Count > 0) {
289        T item = CreateItem();
290        if (item != null) {
291          foreach (ListViewItem listViewItem in itemsListView.SelectedItems)
292            Content[listViewItem.Index] = item;
293        }
294      }
295    }
296    protected virtual void moveUpButton_Click(object sender, EventArgs e) {
297      if (itemsListView.SelectedItems.Count == 1) {
298        int index = itemsListView.SelectedIndices[0];
299        T item = Content[index - 1];
300        Content[index - 1] = Content[index];
301        itemsListView.Items[index].Selected = false;
302        itemsListView.Items[index - 1].Selected = true;
303        Content[index] = item;
304      }
305    }
306    protected virtual void moveDownButton_Click(object sender, EventArgs e) {
307      if (itemsListView.SelectedItems.Count == 1) {
308        int index = itemsListView.SelectedIndices[0];
309        T item = Content[index + 1];
310        Content[index + 1] = Content[index];
311        itemsListView.Items[index].Selected = false;
312        itemsListView.Items[index + 1].Selected = true;
313        Content[index] = item;
314      }
315    }
316    protected virtual void removeButton_Click(object sender, EventArgs e) {
317      if (itemsListView.SelectedItems.Count > 0) {
318        foreach (ListViewItem item in itemsListView.SelectedItems)
319          Content[item.Index] = null;
320      }
321    }
322    #endregion
323
324    #region Content Events
325    protected virtual void Content_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<T>> e) {
326      if (InvokeRequired)
327        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsReplaced), sender, e);
328      else {
329        int[] selected = new int[itemsListView.SelectedIndices.Count];
330        itemsListView.SelectedIndices.CopyTo(selected, 0);
331
332        List<ListViewItem> listViewItems = new List<ListViewItem>();
333        foreach (IndexedItem<T> item in e.OldItems)
334          listViewItems.Add(itemsListView.Items[item.Index]);
335        foreach (ListViewItem listViewItem in listViewItems)
336          RemoveListViewItem(listViewItem);
337
338        foreach (IndexedItem<T> item in e.Items)
339          InsertListViewItem(item.Index, CreateListViewItem(item.Value));
340
341        for (int i = 0; i < selected.Length; i++)
342          itemsListView.Items[selected[i]].Selected = true;
343      }
344    }
345    protected virtual void Content_ItemsMoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<T>> e) {
346      if (InvokeRequired)
347        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsMoved), sender, e);
348      else {
349        foreach (IndexedItem<T> item in e.Items) {
350          ListViewItem listViewItem = itemsListView.Items[item.Index];
351          listViewItem.Tag = item.Value;
352          UpdateListViewItemImage(listViewItem);
353          UpdateListViewItemText(listViewItem);
354        }
355      }
356    }
357    protected virtual void Content_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<T>> e) {
358      if (InvokeRequired)
359        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_CollectionReset), sender, e);
360      else {
361        List<ListViewItem> listViewItems = new List<ListViewItem>();
362        foreach (IndexedItem<T> item in e.OldItems)
363          listViewItems.Add(itemsListView.Items[item.Index]);
364        foreach (ListViewItem listViewItem in listViewItems)
365          RemoveListViewItem(listViewItem);
366
367        foreach (IndexedItem<T> item in e.Items)
368          InsertListViewItem(item.Index, CreateListViewItem(item.Value));
369      }
370    }
371    #endregion
372
373    #region Item Events
374    protected virtual void Item_ItemImageChanged(object sender, EventArgs e) {
375      if (InvokeRequired)
376        Invoke(new EventHandler(Item_ItemImageChanged), sender, e);
377      else {
378        T item = (T)sender;
379        foreach (ListViewItem listViewItem in itemsListView.Items) {
380          if (((T)listViewItem.Tag) == item)
381            UpdateListViewItemImage(listViewItem);
382        }
383      }
384    }
385    protected virtual void Item_ToStringChanged(object sender, EventArgs e) {
386      if (InvokeRequired)
387        Invoke(new EventHandler(Item_ToStringChanged), sender, e);
388      else {
389        T item = (T)sender;
390        foreach (ListViewItem listViewItem in itemsListView.Items) {
391          if (((T)listViewItem.Tag) == item)
392            UpdateListViewItemText(listViewItem);
393        }
394        AdjustListViewColumnSizes();
395      }
396    }
397    #endregion
398
399    #region Helpers
400    protected virtual void AdjustListViewColumnSizes() {
401      if (itemsListView.Items.Count > 0) {
402        for (int i = 0; i < itemsListView.Columns.Count; i++)
403          itemsListView.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
404      }
405    }
406    #endregion
407  }
408}
Note: See TracBrowser for help on using the repository browser.