Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Optimization.Views/3.3/RunCollectionView.cs @ 6284

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

Fixed NullReferenceException in collection views when updating the item image of a hidden item (#1377)

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