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

Last change on this file since 3423 was 3423, checked in by mkommend, 12 years ago

added setting of locked property after the creation of contentviews (ticket #982)

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> : 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 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        viewHost.ReadOnly = ReadOnly;
131      }
132    }
133
134    protected virtual T CreateItem() {
135      if (typeSelectorDialog == null) {
136        typeSelectorDialog = new TypeSelectorDialog();
137        typeSelectorDialog.Caption = "Select Item";
138        typeSelectorDialog.TypeSelector.Caption = "Available Items";
139        typeSelectorDialog.TypeSelector.Configure(typeof(T), false, false);
140      }
141
142      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
143        try {
144          return (T)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
145        }
146        catch (Exception ex) {
147          Auxiliary.ShowErrorMessageBox(ex);
148        }
149      }
150      return null;
151    }
152    protected virtual ListViewItem CreateListViewItem(T item) {
153      ListViewItem listViewItem = new ListViewItem();
154      listViewItem.Text = item.ToString();
155      listViewItem.ToolTipText = item.ItemName + ": " + item.ItemDescription;
156      listViewItem.Tag = item;
157      itemsListView.SmallImageList.Images.Add(item.ItemImage);
158      listViewItem.ImageIndex = itemsListView.SmallImageList.Images.Count - 1;
159      return listViewItem;
160    }
161    protected virtual void AddListViewItem(ListViewItem listViewItem) {
162      itemsListView.Items.Add(listViewItem);
163      ((T)listViewItem.Tag).ItemImageChanged += new EventHandler(Item_ItemImageChanged);
164      ((T)listViewItem.Tag).ToStringChanged += new EventHandler(Item_ToStringChanged);
165      AdjustListViewColumnSizes();
166    }
167    protected virtual void InsertListViewItem(int index, ListViewItem listViewItem) {
168      itemsListView.Items.Insert(index, listViewItem);
169      ((T)listViewItem.Tag).ItemImageChanged += new EventHandler(Item_ItemImageChanged);
170      ((T)listViewItem.Tag).ToStringChanged += new EventHandler(Item_ToStringChanged);
171      AdjustListViewColumnSizes();
172    }
173    protected virtual void RemoveListViewItem(ListViewItem listViewItem) {
174      ((T)listViewItem.Tag).ItemImageChanged -= new EventHandler(Item_ItemImageChanged);
175      ((T)listViewItem.Tag).ToStringChanged -= new EventHandler(Item_ToStringChanged);
176      listViewItem.Remove();
177      foreach (ListViewItem other in itemsListView.Items)
178        if (other.ImageIndex > listViewItem.ImageIndex) other.ImageIndex--;
179      itemsListView.SmallImageList.Images.RemoveAt(listViewItem.ImageIndex);
180    }
181    protected virtual void UpdateListViewItemImage(ListViewItem listViewItem) {
182      int i = listViewItem.ImageIndex;
183      listViewItem.ImageList.Images[i] = ((T)listViewItem.Tag).ItemImage;
184      listViewItem.ImageIndex = -1;
185      listViewItem.ImageIndex = i;
186    }
187    protected virtual void UpdateListViewItemText(ListViewItem listViewItem) {
188      if (!listViewItem.Text.Equals(listViewItem.Tag.ToString()))
189        listViewItem.Text = listViewItem.Tag.ToString();
190    }
191
192    #region ListView Events
193    protected virtual void itemsListView_SelectedIndexChanged(object sender, EventArgs e) {
194      moveUpButton.Enabled = itemsListView.SelectedItems.Count == 1 &&
195                             itemsListView.SelectedIndices[0] != 0 &&
196                             !Content.IsReadOnly && !ReadOnly;
197      moveDownButton.Enabled = itemsListView.SelectedItems.Count == 1 &&
198                               itemsListView.SelectedIndices[0] != itemsListView.Items.Count - 1 &&
199                               !Content.IsReadOnly && !ReadOnly;
200      removeButton.Enabled = itemsListView.SelectedItems.Count > 0 &&
201                             !Content.IsReadOnly && !ReadOnly;
202
203      if (itemsListView.SelectedItems.Count == 1) {
204        T item = (T)itemsListView.SelectedItems[0].Tag;
205        detailsGroupBox.Enabled = true;
206        viewHost.ViewType = null;
207        viewHost.Content = item;
208      } else {
209        viewHost.Content = null;
210        detailsGroupBox.Enabled = false;
211      }
212    }
213
214    protected virtual void itemsListView_KeyDown(object sender, KeyEventArgs e) {
215      if (e.KeyCode == Keys.Delete) {
216        if ((itemsListView.SelectedItems.Count > 0) && !Content.IsReadOnly && !ReadOnly) {
217          foreach (ListViewItem item in itemsListView.SelectedItems)
218            Content.RemoveAt(item.Index);
219        }
220      }
221    }
222
223    protected virtual void itemsListView_DoubleClick(object sender, EventArgs e) {
224      if (itemsListView.SelectedItems.Count == 1) {
225        T item = (T)itemsListView.SelectedItems[0].Tag;
226        IContentView view = MainFormManager.CreateDefaultView(item);
227        if (view != null) {
228          view.ReadOnly = ReadOnly;
229          view.Locked = Locked;
230          view.Show();
231        }
232      }
233    }
234
235    protected virtual void itemsListView_ItemDrag(object sender, ItemDragEventArgs e) {
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    protected virtual void itemsListView_DragEnterOver(object sender, DragEventArgs e) {
250      e.Effect = DragDropEffects.None;
251      Type type = e.Data.GetData("Type") as Type;
252      if (!Content.IsReadOnly && !ReadOnly && (type != null) && (typeof(T).IsAssignableFrom(type))) {
253        if ((e.KeyState & 8) == 8) e.Effect = DragDropEffects.Copy;  // CTRL key
254        else if ((e.KeyState & 4) == 4) e.Effect = DragDropEffects.Move;  // SHIFT key
255        else if ((e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link) e.Effect = DragDropEffects.Link;
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      }
259    }
260    protected virtual void itemsListView_DragDrop(object sender, DragEventArgs e) {
261      if (e.Effect != DragDropEffects.None) {
262        T item = e.Data.GetData("Value") as T;
263        if ((e.Effect & DragDropEffects.Copy) == DragDropEffects.Copy) item = (T)item.Clone();
264
265        Point p = itemsListView.PointToClient(new Point(e.X, e.Y));
266        ListViewItem listViewItem = itemsListView.GetItemAt(p.X, p.Y);
267        if (listViewItem != null) Content.Insert(listViewItem.Index, item);
268        else Content.Add(item);
269      }
270    }
271    #endregion
272
273    #region Button Events
274    protected virtual void addButton_Click(object sender, EventArgs e) {
275      T item = CreateItem();
276      if (item != null)
277        Content.Add(item);
278    }
279    protected virtual void moveUpButton_Click(object sender, EventArgs e) {
280      if (itemsListView.SelectedItems.Count == 1) {
281        int index = itemsListView.SelectedIndices[0];
282        T item = Content[index - 1];
283        Content[index - 1] = Content[index];
284        itemsListView.Items[index].Selected = false;
285        itemsListView.Items[index - 1].Selected = true;
286        Content[index] = item;
287      }
288    }
289    protected virtual void moveDownButton_Click(object sender, EventArgs e) {
290      if (itemsListView.SelectedItems.Count == 1) {
291        int index = itemsListView.SelectedIndices[0];
292        T item = Content[index + 1];
293        Content[index + 1] = Content[index];
294        itemsListView.Items[index].Selected = false;
295        itemsListView.Items[index + 1].Selected = true;
296        Content[index] = item;
297      }
298    }
299    protected virtual void removeButton_Click(object sender, EventArgs e) {
300      if (itemsListView.SelectedItems.Count > 0) {
301        foreach (ListViewItem item in itemsListView.SelectedItems)
302          Content.RemoveAt(item.Index);
303      }
304    }
305    #endregion
306
307    #region Content Events
308    protected virtual void Content_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<T>> e) {
309      if (InvokeRequired)
310        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsAdded), sender, e);
311      else
312        foreach (IndexedItem<T> item in e.Items)
313          InsertListViewItem(item.Index, CreateListViewItem(item.Value));
314    }
315    protected virtual void Content_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<T>> e) {
316      if (InvokeRequired)
317        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<T>>(Content_ItemsRemoved), sender, e);
318      else {
319        List<ListViewItem> listViewItems = new List<ListViewItem>();
320        foreach (IndexedItem<T> item in e.Items)
321          listViewItems.Add(itemsListView.Items[item.Index]);
322        foreach (ListViewItem listViewItem in listViewItems)
323          RemoveListViewItem(listViewItem);
324      }
325    }
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.