Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Core.Views/3.3/Clipboard.cs @ 6527

Last change on this file since 6527 was 6527, checked in by swagner, 12 years ago

Corrected cloning of multiple dropped items (#1564)

File size: 16.9 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.IO;
26using System.Linq;
27using System.Threading;
28using System.Windows.Forms;
29using HeuristicLab.Common;
30using HeuristicLab.MainForm;
31using HeuristicLab.Persistence.Default.Xml;
32using HeuristicLab.PluginInfrastructure;
33
34namespace HeuristicLab.Core.Views {
35  [View("Clipboard")]
36  public sealed partial class Clipboard<T> : HeuristicLab.MainForm.WindowsForms.Sidebar where T : class, IItem {
37    private TypeSelectorDialog typeSelectorDialog;
38    private Dictionary<T, ListViewItem> itemListViewItemMapping;
39    private bool validDragOperation;
40    private bool draggedItemsAlreadyContained;
41
42    private string itemsPath;
43    public string ItemsPath {
44      get { return itemsPath; }
45      private set {
46        if (string.IsNullOrEmpty(value)) throw new ArgumentException(string.Format("Invalid items path \"{0}\".", value));
47        itemsPath = value;
48        try {
49          if (!Directory.Exists(itemsPath)) {
50            Directory.CreateDirectory(itemsPath);
51            // directory creation might take some time -> wait until it is definitively created
52            while (!Directory.Exists(itemsPath)) {
53              Thread.Sleep(100);
54              Directory.CreateDirectory(itemsPath);
55            }
56          }
57        }
58        catch (Exception ex) {
59          throw new ArgumentException(string.Format("Invalid items path \"{0}\".", itemsPath), ex);
60        }
61      }
62    }
63
64    public Clipboard() {
65      InitializeComponent();
66      ItemsPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
67                  Path.DirectorySeparatorChar + "HeuristicLab" + Path.DirectorySeparatorChar + "Clipboard";
68      itemListViewItemMapping = new Dictionary<T, ListViewItem>();
69    }
70    public Clipboard(string itemsPath) {
71      InitializeComponent();
72      ItemsPath = itemsPath;
73      itemListViewItemMapping = new Dictionary<T, ListViewItem>();
74    }
75
76    protected override void Dispose(bool disposing) {
77      if (disposing) {
78        if (typeSelectorDialog != null) typeSelectorDialog.Dispose();
79        foreach (T item in itemListViewItemMapping.Keys) {
80          item.ItemImageChanged -= new EventHandler(Item_ItemImageChanged);
81          item.ToStringChanged -= new EventHandler(Item_ToStringChanged);
82        }
83        if (components != null) components.Dispose();
84      }
85      base.Dispose(disposing);
86    }
87
88    protected override void OnInitialized(EventArgs e) {
89      base.OnInitialized(e);
90      SetEnabledStateOfControls();
91      Enabled = false;
92      infoLabel.Text = "Loading ...";
93      progressBar.Value = 0;
94      infoPanel.Visible = true;
95      ThreadPool.QueueUserWorkItem(new WaitCallback(LoadItems));
96    }
97
98    protected override void SetEnabledStateOfControls() {
99      base.SetEnabledStateOfControls();
100      addButton.Enabled = !ReadOnly;
101      removeButton.Enabled = !ReadOnly && listView.SelectedItems.Count > 0;
102      saveButton.Enabled = !ReadOnly;
103    }
104
105    public void AddItem(T item) {
106      if (InvokeRequired)
107        Invoke(new Action<T>(AddItem), item);
108      else {
109        if (item == null) throw new ArgumentNullException("item", "Cannot add null item to clipboard.");
110        if (!itemListViewItemMapping.ContainsKey(item)) {
111          ListViewItem listViewItem = new ListViewItem(item.ToString());
112          listViewItem.ToolTipText = item.ItemName + ": " + item.ItemDescription;
113          listView.SmallImageList.Images.Add(item.ItemImage);
114          listViewItem.ImageIndex = listView.SmallImageList.Images.Count - 1;
115          listViewItem.Tag = item;
116          listView.Items.Add(listViewItem);
117          itemListViewItemMapping.Add(item, listViewItem);
118          item.ItemImageChanged += new EventHandler(Item_ItemImageChanged);
119          item.ToStringChanged += new EventHandler(Item_ToStringChanged);
120          sortAscendingButton.Enabled = sortDescendingButton.Enabled = listView.Items.Count > 1;
121          AdjustListViewColumnSizes();
122        }
123      }
124    }
125
126    private void RemoveItem(T item) {
127      if (InvokeRequired)
128        Invoke(new Action<T>(RemoveItem), item);
129      else {
130        if (itemListViewItemMapping.ContainsKey(item)) {
131          item.ItemImageChanged -= new EventHandler(Item_ItemImageChanged);
132          item.ToStringChanged -= new EventHandler(Item_ToStringChanged);
133          ListViewItem listViewItem = itemListViewItemMapping[item];
134          listViewItem.Remove();
135          itemListViewItemMapping.Remove(item);
136          sortAscendingButton.Enabled = sortDescendingButton.Enabled = listView.Items.Count > 1;
137        }
138      }
139    }
140    private void Save() {
141      if (InvokeRequired)
142        Invoke(new Action(Save));
143      else {
144        Enabled = false;
145        infoLabel.Text = "Saving ...";
146        progressBar.Value = 0;
147        infoPanel.Visible = true;
148        ThreadPool.QueueUserWorkItem(new WaitCallback(SaveItems));
149      }
150    }
151
152    #region Loading/Saving Items
153    private void LoadItems(object state) {
154      string[] items = Directory.GetFiles(ItemsPath);
155      foreach (string filename in items) {
156        try {
157          T item = XmlParser.Deserialize<T>(filename);
158          OnItemLoaded(item, progressBar.Maximum / items.Length);
159        }
160        catch (Exception) { }
161      }
162      OnAllItemsLoaded();
163    }
164    private void OnItemLoaded(T item, int progress) {
165      if (InvokeRequired)
166        Invoke(new Action<T, int>(OnItemLoaded), item, progress);
167      else {
168        AddItem(item);
169        progressBar.Value += progress;
170      }
171    }
172    private void OnAllItemsLoaded() {
173      if (InvokeRequired)
174        Invoke(new Action(OnAllItemsLoaded));
175      else {
176        Enabled = true;
177        if (listView.Items.Count > 0) {
178          for (int i = 0; i < listView.Columns.Count; i++)
179            listView.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
180        }
181        infoPanel.Visible = false;
182      }
183    }
184    private void SaveItems(object param) {
185      Directory.Delete(ItemsPath, true);
186      Directory.CreateDirectory(ItemsPath);
187      // directory creation might take some time -> wait until it is definitively created
188      while (!Directory.Exists(ItemsPath)) {
189        Thread.Sleep(100);
190        Directory.CreateDirectory(ItemsPath);
191      }
192
193      int i = 0;
194      T[] items = GetStorableItems(itemListViewItemMapping.Keys);
195
196      foreach (T item in items) {
197        try {
198          i++;
199          SetEnabledStateOfContentViews(item, false);
200          XmlGenerator.Serialize(item, ItemsPath + Path.DirectorySeparatorChar + i.ToString("00000000") + ".hl", 9);
201          OnItemSaved(item, progressBar.Maximum / listView.Items.Count);
202        }
203        catch (Exception) { }
204        finally {
205          SetEnabledStateOfContentViews(item, true);
206        }
207      }
208      OnAllItemsSaved();
209    }
210
211    private void OnItemSaved(T item, int progress) {
212      if (item != null) {
213        if (InvokeRequired)
214          Invoke(new Action<T, int>(OnItemSaved), item, progress);
215        else {
216          progressBar.Value += progress;
217        }
218      }
219    }
220    private void OnAllItemsSaved() {
221      if (InvokeRequired)
222        Invoke(new Action(OnAllItemsLoaded));
223      else {
224        Enabled = true;
225        infoPanel.Visible = false;
226      }
227    }
228
229    private void SetEnabledStateOfContentViews(IItem item, bool enabled) {
230      if (InvokeRequired)
231        Invoke((Action<IItem, bool>)SetEnabledStateOfContentViews, item, enabled);
232      else {
233        var views = MainFormManager.MainForm.Views.OfType<IContentView>().Where(v => v.Content == item).ToList();
234        views.ForEach(v => v.Enabled = enabled);
235      }
236    }
237
238    private static T[] GetStorableItems(IEnumerable<T> items) {
239      var query = from item in items
240                  let executeable = item as IExecutable
241                  let views = MainFormManager.MainForm.Views.OfType<IContentView>().Where(v => v.Content == item)
242                  where executeable == null || executeable.ExecutionState != ExecutionState.Started
243                  where !views.Any(v => v.Locked)
244                  select item;
245      T[] itemArray = query.ToArray();
246      return itemArray;
247    }
248    #endregion
249
250    #region ListView Events
251    private void listView_SelectedIndexChanged(object sender, EventArgs e) {
252      removeButton.Enabled = !ReadOnly && listView.SelectedItems.Count > 0;
253    }
254    private void listView_KeyDown(object sender, KeyEventArgs e) {
255      if (e.KeyCode == Keys.Delete) {
256        if (!ReadOnly && (listView.SelectedItems.Count > 0)) {
257          foreach (ListViewItem item in listView.SelectedItems)
258            RemoveItem((T)item.Tag);
259          RebuildImageList();
260        }
261      }
262    }
263    private void listView_DoubleClick(object sender, EventArgs e) {
264      if (listView.SelectedItems.Count == 1) {
265        T item = (T)listView.SelectedItems[0].Tag;
266        IContentView view = MainFormManager.MainForm.ShowContent(item, true);
267      }
268    }
269    private void listView_ItemDrag(object sender, ItemDragEventArgs e) {
270      List<T> items = new List<T>();
271      foreach (ListViewItem listViewItem in listView.SelectedItems) {
272        T item = listViewItem.Tag as T;
273        if (item != null) items.Add(item);
274      }
275
276      if (items.Count > 0) {
277        DataObject data = new DataObject();
278        if (items.Count == 1) data.SetData(HeuristicLab.Common.Constants.DragDropDataFormat, items[0]);
279        else data.SetData(HeuristicLab.Common.Constants.DragDropDataFormat, items);
280        if (ReadOnly) {
281          DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link);
282        } else {
283          DragDropEffects result = DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link | DragDropEffects.Move);
284          if ((result & DragDropEffects.Move) == DragDropEffects.Move) {
285            foreach (T item in items) RemoveItem(item);
286            RebuildImageList();
287          }
288        }
289      }
290    }
291    private void listView_DragEnter(object sender, DragEventArgs e) {
292      validDragOperation = false;
293      draggedItemsAlreadyContained = false;
294      if (!ReadOnly && (e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) is T)) {
295        validDragOperation = true;
296        draggedItemsAlreadyContained = itemListViewItemMapping.ContainsKey((T)e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat));
297      } else if (!ReadOnly && (e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) is IEnumerable)) {
298        validDragOperation = true;
299        IEnumerable items = (IEnumerable)e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
300        foreach (object item in items) {
301          validDragOperation = validDragOperation && (item is T);
302          draggedItemsAlreadyContained = draggedItemsAlreadyContained || itemListViewItemMapping.ContainsKey((T)item);
303        }
304      }
305    }
306    private void listView_DragOver(object sender, DragEventArgs e) {
307      e.Effect = DragDropEffects.None;
308      if (validDragOperation) {
309        if (((e.KeyState & 32) == 32) && !draggedItemsAlreadyContained) e.Effect = DragDropEffects.Link;  // ALT key
310        else if (((e.KeyState & 4) == 4) && !draggedItemsAlreadyContained) e.Effect = DragDropEffects.Move;  // SHIFT key
311        else if (e.AllowedEffect.HasFlag(DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy;
312        else if (e.AllowedEffect.HasFlag(DragDropEffects.Move) && !draggedItemsAlreadyContained) e.Effect = DragDropEffects.Move;
313        else if (e.AllowedEffect.HasFlag(DragDropEffects.Link) && !draggedItemsAlreadyContained) e.Effect = DragDropEffects.Link;
314      }
315    }
316    private void listView_DragDrop(object sender, DragEventArgs e) {
317      if (e.Effect != DragDropEffects.None) {
318        try {
319          if (e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) is T) {
320            T item = (T)e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
321            AddItem(e.Effect.HasFlag(DragDropEffects.Copy) ? (T)item.Clone() : item);
322          } else if (e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) is IEnumerable) {
323            IEnumerable<T> items = ((IEnumerable)e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat)).Cast<T>();
324            if (e.Effect.HasFlag(DragDropEffects.Copy)) {
325              Cloner cloner = new Cloner();
326              items = items.Select(x => cloner.Clone(x));
327            }
328            foreach (T item in items)
329              AddItem(item);
330          }
331        }
332        catch (Exception ex) {
333          ErrorHandling.ShowErrorDialog(this, ex);
334        }
335      }
336    }
337    #endregion
338
339    #region Button Events
340    private void addButton_Click(object sender, EventArgs e) {
341      if (typeSelectorDialog == null) {
342        typeSelectorDialog = new TypeSelectorDialog();
343        typeSelectorDialog.Caption = "Select Item";
344        typeSelectorDialog.TypeSelector.Caption = "Available Items";
345        typeSelectorDialog.TypeSelector.Configure(typeof(T), false, true);
346      }
347
348      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
349        try {
350          AddItem((T)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType());
351        }
352        catch (Exception ex) {
353          ErrorHandling.ShowErrorDialog(this, ex);
354        }
355      }
356    }
357    private void sortAscendingButton_Click(object sender, EventArgs e) {
358      listView.Sorting = SortOrder.None;
359      listView.Sorting = SortOrder.Ascending;
360    }
361    private void sortDescendingButton_Click(object sender, EventArgs e) {
362      listView.Sorting = SortOrder.None;
363      listView.Sorting = SortOrder.Descending;
364    }
365    private void removeButton_Click(object sender, EventArgs e) {
366      if (listView.SelectedItems.Count > 0) {
367        foreach (ListViewItem item in listView.SelectedItems)
368          RemoveItem((T)item.Tag);
369        RebuildImageList();
370      }
371    }
372    private void saveButton_Click(object sender, EventArgs e) {
373      IEnumerable<T> items = itemListViewItemMapping.Keys.Except(GetStorableItems(itemListViewItemMapping.Keys));
374      if (items.Any()) {
375        string itemNames = string.Join(Environment.NewLine, items.Select(item => item.ToString()).ToArray());
376        MessageBox.Show("The following items are not saved, because they are locked (e.g. used in a running algorithm):" + Environment.NewLine + Environment.NewLine +
377          itemNames + Environment.NewLine + Environment.NewLine + "All other items will be saved.", "Cannot save all items", MessageBoxButtons.OK, MessageBoxIcon.Warning);
378      }
379      Save();
380    }
381    #endregion
382
383    #region Item Events
384    private void Item_ItemImageChanged(object sender, EventArgs e) {
385      if (InvokeRequired)
386        Invoke(new EventHandler(Item_ItemImageChanged), sender, e);
387      else {
388        T item = (T)sender;
389        ListViewItem listViewItem = itemListViewItemMapping[item];
390        int i = listViewItem.ImageIndex;
391        listView.SmallImageList.Images[i] = item.ItemImage;
392        listViewItem.ImageIndex = -1;
393        listViewItem.ImageIndex = i;
394      }
395    }
396    private void Item_ToStringChanged(object sender, EventArgs e) {
397      if (InvokeRequired)
398        Invoke(new EventHandler(Item_ToStringChanged), sender, e);
399      else {
400        T item = (T)sender;
401        itemListViewItemMapping[item].Text = item.ToString();
402        listView.Sort();
403        AdjustListViewColumnSizes();
404      }
405    }
406    #endregion
407
408    #region Helpers
409    private void AdjustListViewColumnSizes() {
410      if (listView.Items.Count > 0) {
411        for (int i = 0; i < listView.Columns.Count; i++)
412          listView.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
413      }
414    }
415    private void RebuildImageList() {
416      listView.SmallImageList.Images.Clear();
417      foreach (ListViewItem item in listView.Items) {
418        listView.SmallImageList.Images.Add(((T)item.Tag).ItemImage);
419        item.ImageIndex = listView.SmallImageList.Images.Count - 1;
420      }
421    }
422    #endregion
423  }
424}
Note: See TracBrowser for help on using the repository browser.