Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Core.Views/3.3/ItemListView.cs @ 3531

Last change on this file since 3531 was 3526, checked in by swagner, 15 years ago

Implemented reviewers' comments (#893)

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