Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3454 was 3435, checked in by swagner, 15 years ago

Reverted r3433 and corrected read-only handling in RunCollectionView (#973)

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> : AsynchronousContentView 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        viewHost.ReadOnly = ReadOnly;
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, false);
137      }
138
139      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
140        try {
141          return (T)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
142        }
143        catch (Exception ex) {
144          Auxiliary.ShowErrorMessageBox(ex);
145        }
146      }
147      return null;
148    }
149    protected virtual ListViewItem CreateListViewItem(T item) {
150      ListViewItem listViewItem = new ListViewItem();
151      listViewItem.Text = item == null ? "null" : item.ToString();
152      listViewItem.ToolTipText = item == null ? string.Empty : item.ItemName + ": " + item.ItemDescription;
153      itemsListView.SmallImageList.Images.Add(item == null ? HeuristicLab.Common.Resources.VS2008ImageLibrary.Nothing : item.ItemImage);
154      listViewItem.ImageIndex = itemsListView.SmallImageList.Images.Count - 1;
155      listViewItem.Tag = item;
156      return listViewItem;
157    }
158    protected virtual void AddListViewItem(ListViewItem listViewItem) {
159      itemsListView.Items.Add(listViewItem);
160      if (listViewItem.Tag != null) {
161        ((T)listViewItem.Tag).ItemImageChanged += new EventHandler(Item_ItemImageChanged);
162        ((T)listViewItem.Tag).ToStringChanged += new EventHandler(Item_ToStringChanged);
163      }
164      AdjustListViewColumnSizes();
165    }
166    protected virtual void InsertListViewItem(int index, ListViewItem listViewItem) {
167      itemsListView.Items.Insert(index, listViewItem);
168      if (listViewItem.Tag != null) {
169        ((T)listViewItem.Tag).ItemImageChanged += new EventHandler(Item_ItemImageChanged);
170        ((T)listViewItem.Tag).ToStringChanged += new EventHandler(Item_ToStringChanged);
171      }
172      AdjustListViewColumnSizes();
173    }
174    protected virtual void RemoveListViewItem(ListViewItem listViewItem) {
175      if (listViewItem.Tag != null) {
176        ((T)listViewItem.Tag).ItemImageChanged -= new EventHandler(Item_ItemImageChanged);
177        ((T)listViewItem.Tag).ToStringChanged -= new EventHandler(Item_ToStringChanged);
178      }
179      listViewItem.Remove();
180      foreach (ListViewItem other in itemsListView.Items)
181        if (other.ImageIndex > listViewItem.ImageIndex) other.ImageIndex--;
182      itemsListView.SmallImageList.Images.RemoveAt(listViewItem.ImageIndex);
183    }
184    protected virtual void UpdateListViewItemImage(ListViewItem listViewItem) {
185      T item = listViewItem.Tag as T;
186      int i = listViewItem.ImageIndex;
187      listViewItem.ImageList.Images[i] = item == null ? HeuristicLab.Common.Resources.VS2008ImageLibrary.Nothing : item.ItemImage;
188      listViewItem.ImageIndex = -1;
189      listViewItem.ImageIndex = i;
190    }
191    protected virtual void UpdateListViewItemText(ListViewItem listViewItem) {
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;
195    }
196
197    #region ListView Events
198    protected virtual void itemsListView_SelectedIndexChanged(object sender, EventArgs e) {
199      addButton.Enabled = itemsListView.SelectedItems.Count > 0 && !Content.IsReadOnly && !ReadOnly;
200      moveUpButton.Enabled = itemsListView.SelectedItems.Count == 1 &&
201                             itemsListView.SelectedIndices[0] != 0 &&
202                             !Content.IsReadOnly && !ReadOnly;
203      moveDownButton.Enabled = itemsListView.SelectedItems.Count == 1 &&
204                               itemsListView.SelectedIndices[0] != itemsListView.Items.Count - 1 &&
205                               !Content.IsReadOnly && !ReadOnly;
206      removeButton.Enabled = itemsListView.SelectedItems.Count > 0 && !Content.IsReadOnly && !ReadOnly;
207
208      if (itemsListView.SelectedItems.Count == 1) {
209        T item = itemsListView.SelectedItems[0].Tag as T;
210        detailsGroupBox.Enabled = true;
211        viewHost.ViewType = null;
212        viewHost.Content = item;
213      } else {
214        viewHost.Content = null;
215        detailsGroupBox.Enabled = false;
216      }
217    }
218
219    protected virtual void itemsListView_KeyDown(object sender, KeyEventArgs e) {
220      if (e.KeyCode == Keys.Delete) {
221        if ((itemsListView.SelectedItems.Count > 0) && !Content.IsReadOnly && !ReadOnly) {
222          foreach (ListViewItem item in itemsListView.SelectedItems)
223            Content[item.Index] = null;
224        }
225      }
226    }
227
228    protected virtual void itemsListView_DoubleClick(object sender, EventArgs e) {
229      if (itemsListView.SelectedItems.Count == 1) {
230        T item = itemsListView.SelectedItems[0].Tag as T;
231        if (item != null) {
232          IContentView view = MainFormManager.CreateDefaultView(item);
233          if (view != null) {
234            view.ReadOnly = ReadOnly;
235            view.Locked = Locked;
236            view.Show();
237          }
238        }
239      }
240    }
241
242    protected virtual void itemsListView_ItemDrag(object sender, ItemDragEventArgs e) {
243      if (!Locked) {
244        ListViewItem listViewItem = (ListViewItem)e.Item;
245        T item = listViewItem.Tag as T;
246        if (item != null) {
247          DataObject data = new DataObject();
248          data.SetData("Type", item.GetType());
249          data.SetData("Value", item);
250          if (Content.IsReadOnly || ReadOnly) {
251            DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link);
252          } else {
253            DragDropEffects result = DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link | DragDropEffects.Move);
254            if ((result & DragDropEffects.Move) == DragDropEffects.Move)
255              Content[listViewItem.Index] = null;
256          }
257        }
258      }
259    }
260    protected virtual void itemsListView_DragEnterOver(object sender, DragEventArgs e) {
261      e.Effect = DragDropEffects.None;
262      Type type = e.Data.GetData("Type") as Type;
263      if (!Content.IsReadOnly && !ReadOnly && (type != null) && (typeof(T).IsAssignableFrom(type))) {
264        Point p = itemsListView.PointToClient(new Point(e.X, e.Y));
265        ListViewItem listViewItem = itemsListView.GetItemAt(p.X, p.Y);
266        if (listViewItem != null) {
267          if ((e.KeyState & 8) == 8) e.Effect = DragDropEffects.Copy;  // CTRL key
268          else if ((e.KeyState & 4) == 4) e.Effect = DragDropEffects.Move;  // SHIFT key
269          else if ((e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link) e.Effect = DragDropEffects.Link;
270          else if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy) e.Effect = DragDropEffects.Copy;
271          else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move) e.Effect = DragDropEffects.Move;
272        }
273      }
274    }
275    protected virtual void itemsListView_DragDrop(object sender, DragEventArgs e) {
276      if (e.Effect != DragDropEffects.None) {
277        T item = e.Data.GetData("Value") as T;
278        if ((e.Effect & DragDropEffects.Copy) == DragDropEffects.Copy) item = (T)item.Clone();
279
280        Point p = itemsListView.PointToClient(new Point(e.X, e.Y));
281        ListViewItem listViewItem = itemsListView.GetItemAt(p.X, p.Y);
282        Content[listViewItem.Index] = item;
283      }
284    }
285    #endregion
286
287    #region Button Events
288    protected virtual void addButton_Click(object sender, EventArgs e) {
289      if (itemsListView.SelectedItems.Count > 0) {
290        T item = CreateItem();
291        if (item != null) {
292          foreach (ListViewItem listViewItem in itemsListView.SelectedItems)
293            Content[listViewItem.Index] = item;
294        }
295      }
296    }
297    protected virtual void moveUpButton_Click(object sender, EventArgs e) {
298      if (itemsListView.SelectedItems.Count == 1) {
299        int index = itemsListView.SelectedIndices[0];
300        T item = Content[index - 1];
301        Content[index - 1] = Content[index];
302        itemsListView.Items[index].Selected = false;
303        itemsListView.Items[index - 1].Selected = true;
304        Content[index] = item;
305      }
306    }
307    protected virtual void moveDownButton_Click(object sender, EventArgs e) {
308      if (itemsListView.SelectedItems.Count == 1) {
309        int index = itemsListView.SelectedIndices[0];
310        T item = Content[index + 1];
311        Content[index + 1] = Content[index];
312        itemsListView.Items[index].Selected = false;
313        itemsListView.Items[index + 1].Selected = true;
314        Content[index] = item;
315      }
316    }
317    protected virtual void removeButton_Click(object sender, EventArgs e) {
318      if (itemsListView.SelectedItems.Count > 0) {
319        foreach (ListViewItem item in itemsListView.SelectedItems)
320          Content[item.Index] = null;
321      }
322    }
323    #endregion
324
325    #region Content Events
326    protected virtual void Content_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<T>> e) {
327      if (InvokeRequired)
328        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsReplaced), sender, e);
329      else {
330        int[] selected = new int[itemsListView.SelectedIndices.Count];
331        itemsListView.SelectedIndices.CopyTo(selected, 0);
332
333        List<ListViewItem> listViewItems = new List<ListViewItem>();
334        foreach (IndexedItem<T> item in e.OldItems)
335          listViewItems.Add(itemsListView.Items[item.Index]);
336        foreach (ListViewItem listViewItem in listViewItems)
337          RemoveListViewItem(listViewItem);
338
339        foreach (IndexedItem<T> item in e.Items)
340          InsertListViewItem(item.Index, CreateListViewItem(item.Value));
341
342        for (int i = 0; i < selected.Length; i++)
343          itemsListView.Items[selected[i]].Selected = true;
344      }
345    }
346    protected virtual void Content_ItemsMoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<T>> e) {
347      if (InvokeRequired)
348        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsMoved), sender, e);
349      else {
350        foreach (IndexedItem<T> item in e.Items) {
351          ListViewItem listViewItem = itemsListView.Items[item.Index];
352          listViewItem.Tag = item.Value;
353          UpdateListViewItemImage(listViewItem);
354          UpdateListViewItemText(listViewItem);
355        }
356      }
357    }
358    protected virtual void Content_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<T>> e) {
359      if (InvokeRequired)
360        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_CollectionReset), sender, e);
361      else {
362        List<ListViewItem> listViewItems = new List<ListViewItem>();
363        foreach (IndexedItem<T> item in e.OldItems)
364          listViewItems.Add(itemsListView.Items[item.Index]);
365        foreach (ListViewItem listViewItem in listViewItems)
366          RemoveListViewItem(listViewItem);
367
368        foreach (IndexedItem<T> item in e.Items)
369          InsertListViewItem(item.Index, CreateListViewItem(item.Value));
370      }
371    }
372    #endregion
373
374    #region Item Events
375    protected virtual void Item_ItemImageChanged(object sender, EventArgs e) {
376      if (InvokeRequired)
377        Invoke(new EventHandler(Item_ItemImageChanged), sender, e);
378      else {
379        T item = (T)sender;
380        foreach (ListViewItem listViewItem in itemsListView.Items) {
381          if (((T)listViewItem.Tag) == item)
382            UpdateListViewItemImage(listViewItem);
383        }
384      }
385    }
386    protected virtual void Item_ToStringChanged(object sender, EventArgs e) {
387      if (InvokeRequired)
388        Invoke(new EventHandler(Item_ToStringChanged), sender, e);
389      else {
390        T item = (T)sender;
391        foreach (ListViewItem listViewItem in itemsListView.Items) {
392          if (((T)listViewItem.Tag) == item)
393            UpdateListViewItemText(listViewItem);
394        }
395        AdjustListViewColumnSizes();
396      }
397    }
398    #endregion
399
400    #region Helpers
401    protected virtual void AdjustListViewColumnSizes() {
402      if (itemsListView.Items.Count > 0) {
403        for (int i = 0; i < itemsListView.Columns.Count; i++)
404          itemsListView.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
405      }
406    }
407    #endregion
408  }
409}
Note: See TracBrowser for help on using the repository browser.