Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceReintegration/HeuristicLab.Core.Views/3.3/Clipboard.cs @ 14927

Last change on this file since 14927 was 14927, checked in by gkronber, 7 years ago

#2520: changed all usages of StorableClass to use StorableType with an auto-generated GUID (did not add StorableType to other type definitions yet)

File size: 16.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.IO.Compression;
27using System.Linq;
28using System.Threading;
29using System.Windows.Forms;
30using HeuristicLab.Common;
31using HeuristicLab.MainForm;
32using HeuristicLab.Persistence.Default.Xml;
33using HeuristicLab.PluginInfrastructure;
34
35namespace HeuristicLab.Core.Views {
36  [View("Clipboard")]
37  public sealed partial class Clipboard<T> : HeuristicLab.MainForm.WindowsForms.Sidebar where T : class, IItem {
38    private TypeSelectorDialog typeSelectorDialog;
39    private Dictionary<T, ListViewItem> itemListViewItemMapping;
40    private bool validDragOperation;
41    private bool draggedItemsAlreadyContained;
42
43    private string itemsPath;
44    public string ItemsPath {
45      get { return itemsPath; }
46      private set {
47        if (string.IsNullOrEmpty(value)) throw new ArgumentException(string.Format("Invalid items path \"{0}\".", value));
48        itemsPath = value;
49        try {
50          if (!Directory.Exists(itemsPath)) {
51            Directory.CreateDirectory(itemsPath);
52            // directory creation might take some time -> wait until it is definitively created
53            while (!Directory.Exists(itemsPath)) {
54              Thread.Sleep(100);
55              Directory.CreateDirectory(itemsPath);
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        } catch (Exception) { }
160      }
161      OnAllItemsLoaded();
162    }
163    private void OnItemLoaded(T item, int progress) {
164      if (InvokeRequired)
165        Invoke(new Action<T, int>(OnItemLoaded), item, progress);
166      else {
167        AddItem(item);
168        progressBar.Value += progress;
169      }
170    }
171    private void OnAllItemsLoaded() {
172      if (InvokeRequired)
173        Invoke(new Action(OnAllItemsLoaded));
174      else {
175        Enabled = true;
176        if (listView.Items.Count > 0) {
177          for (int i = 0; i < listView.Columns.Count; i++)
178            listView.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
179        }
180        infoPanel.Visible = false;
181      }
182    }
183    private void SaveItems(object param) {
184      Directory.Delete(ItemsPath, true);
185      Directory.CreateDirectory(ItemsPath);
186      // directory creation might take some time -> wait until it is definitively created
187      while (!Directory.Exists(ItemsPath)) {
188        Thread.Sleep(100);
189        Directory.CreateDirectory(ItemsPath);
190      }
191
192      int i = 0;
193      T[] items = GetStorableItems(itemListViewItemMapping.Keys);
194
195      foreach (T item in items) {
196        try {
197          i++;
198          SetEnabledStateOfContentViews(item, false);
199          XmlGenerator.Serialize(item, ItemsPath + Path.DirectorySeparatorChar + i.ToString("00000000") + ".hl", CompressionLevel.Optimal);
200          OnItemSaved(item, progressBar.Maximum / listView.Items.Count);
201        } catch (Exception) { } finally {
202          SetEnabledStateOfContentViews(item, true);
203        }
204      }
205      OnAllItemsSaved();
206    }
207
208    private void OnItemSaved(T item, int progress) {
209      if (item != null) {
210        if (InvokeRequired)
211          Invoke(new Action<T, int>(OnItemSaved), item, progress);
212        else {
213          progressBar.Value += progress;
214        }
215      }
216    }
217    private void OnAllItemsSaved() {
218      if (InvokeRequired)
219        Invoke(new Action(OnAllItemsLoaded));
220      else {
221        Enabled = true;
222        infoPanel.Visible = false;
223      }
224    }
225
226    private void SetEnabledStateOfContentViews(IItem item, bool enabled) {
227      if (InvokeRequired)
228        Invoke((Action<IItem, bool>)SetEnabledStateOfContentViews, item, enabled);
229      else {
230        var views = MainFormManager.MainForm.Views.OfType<IContentView>().Where(v => v.Content == item).ToList();
231        views.ForEach(v => v.Enabled = enabled);
232      }
233    }
234
235    private static T[] GetStorableItems(IEnumerable<T> items) {
236      var query = from item in items
237                  let executeable = item as IExecutable
238                  let views = MainFormManager.MainForm.Views.OfType<IContentView>().Where(v => v.Content == item)
239                  where executeable == null || executeable.ExecutionState != ExecutionState.Started
240                  where !views.Any(v => v.Locked)
241                  select item;
242      T[] itemArray = query.ToArray();
243      return itemArray;
244    }
245    #endregion
246
247    #region ListView Events
248    private void listView_SelectedIndexChanged(object sender, EventArgs e) {
249      removeButton.Enabled = !ReadOnly && listView.SelectedItems.Count > 0;
250    }
251    private void listView_KeyDown(object sender, KeyEventArgs e) {
252      if (e.KeyCode == Keys.Delete) {
253        if (!ReadOnly && (listView.SelectedItems.Count > 0)) {
254          foreach (ListViewItem item in listView.SelectedItems)
255            RemoveItem((T)item.Tag);
256          RebuildImageList();
257        }
258      }
259    }
260    private void listView_DoubleClick(object sender, EventArgs e) {
261      if (listView.SelectedItems.Count == 1) {
262        T item = (T)listView.SelectedItems[0].Tag;
263        IContentView view = MainFormManager.MainForm.ShowContent(item, true);
264      }
265    }
266    private void listView_ItemDrag(object sender, ItemDragEventArgs e) {
267      List<T> items = new List<T>();
268      foreach (ListViewItem listViewItem in listView.SelectedItems) {
269        T item = listViewItem.Tag as T;
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 (ReadOnly) {
278          DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link);
279        } else {
280          DragDropEffects result = DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link | DragDropEffects.Move);
281          if ((result & DragDropEffects.Move) == DragDropEffects.Move) {
282            foreach (T item in items) RemoveItem(item);
283            RebuildImageList();
284          }
285        }
286      }
287    }
288    private void listView_DragEnter(object sender, DragEventArgs e) {
289      validDragOperation = false;
290      draggedItemsAlreadyContained = false;
291      if (!ReadOnly && (e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) is T)) {
292        validDragOperation = true;
293        draggedItemsAlreadyContained = itemListViewItemMapping.ContainsKey((T)e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat));
294      } else if (!ReadOnly && (e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) is IEnumerable)) {
295        validDragOperation = true;
296        IEnumerable items = (IEnumerable)e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
297        foreach (object item in items) {
298          validDragOperation = validDragOperation && (item is T);
299          draggedItemsAlreadyContained = draggedItemsAlreadyContained || itemListViewItemMapping.ContainsKey((T)item);
300        }
301      }
302    }
303    private void listView_DragOver(object sender, DragEventArgs e) {
304      e.Effect = DragDropEffects.None;
305      if (validDragOperation) {
306        if (((e.KeyState & 32) == 32) && !draggedItemsAlreadyContained) e.Effect = DragDropEffects.Link;  // ALT key
307        else if (((e.KeyState & 4) == 4) && !draggedItemsAlreadyContained) e.Effect = DragDropEffects.Move;  // SHIFT key
308        else if (e.AllowedEffect.HasFlag(DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy;
309        else if (e.AllowedEffect.HasFlag(DragDropEffects.Move) && !draggedItemsAlreadyContained) e.Effect = DragDropEffects.Move;
310        else if (e.AllowedEffect.HasFlag(DragDropEffects.Link) && !draggedItemsAlreadyContained) e.Effect = DragDropEffects.Link;
311      }
312    }
313    private void listView_DragDrop(object sender, DragEventArgs e) {
314      if (e.Effect != DragDropEffects.None) {
315        try {
316          if (e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) is T) {
317            T item = (T)e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
318            AddItem(e.Effect.HasFlag(DragDropEffects.Copy) ? (T)item.Clone() : item);
319          } else if (e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) is IEnumerable) {
320            IEnumerable<T> items = ((IEnumerable)e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat)).Cast<T>();
321            if (e.Effect.HasFlag(DragDropEffects.Copy)) {
322              Cloner cloner = new Cloner();
323              items = items.Select(x => cloner.Clone(x));
324            }
325            foreach (T item in items)
326              AddItem(item);
327          }
328        } catch (Exception ex) {
329          ErrorHandling.ShowErrorDialog(this, ex);
330        }
331      }
332    }
333    #endregion
334
335    #region Button Events
336    private void addButton_Click(object sender, EventArgs e) {
337      if (typeSelectorDialog == null) {
338        typeSelectorDialog = new TypeSelectorDialog();
339        typeSelectorDialog.Caption = "Select Item";
340        typeSelectorDialog.TypeSelector.Caption = "Available Items";
341        typeSelectorDialog.TypeSelector.Configure(typeof(T), false, true);
342      }
343
344      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
345        try {
346          AddItem((T)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType());
347        } catch (Exception ex) {
348          ErrorHandling.ShowErrorDialog(this, ex);
349        }
350      }
351    }
352    private void sortAscendingButton_Click(object sender, EventArgs e) {
353      listView.Sorting = SortOrder.None;
354      listView.Sorting = SortOrder.Ascending;
355    }
356    private void sortDescendingButton_Click(object sender, EventArgs e) {
357      listView.Sorting = SortOrder.None;
358      listView.Sorting = SortOrder.Descending;
359    }
360    private void removeButton_Click(object sender, EventArgs e) {
361      if (listView.SelectedItems.Count > 0) {
362        foreach (ListViewItem item in listView.SelectedItems)
363          RemoveItem((T)item.Tag);
364        RebuildImageList();
365      }
366    }
367    private void saveButton_Click(object sender, EventArgs e) {
368      IEnumerable<T> items = itemListViewItemMapping.Keys.Except(GetStorableItems(itemListViewItemMapping.Keys));
369      if (items.Any()) {
370        string itemNames = string.Join(Environment.NewLine, items.Select(item => item.ToString()).ToArray());
371        MessageBox.Show("The following items are not saved, because they are locked (e.g. used in a running algorithm):" + Environment.NewLine + Environment.NewLine +
372          itemNames + Environment.NewLine + Environment.NewLine + "All other items will be saved.", "Cannot save all items", MessageBoxButtons.OK, MessageBoxIcon.Warning);
373      }
374      Save();
375    }
376    #endregion
377
378    #region Item Events
379    private void Item_ItemImageChanged(object sender, EventArgs e) {
380      if (InvokeRequired)
381        Invoke(new EventHandler(Item_ItemImageChanged), sender, e);
382      else {
383        T item = (T)sender;
384        ListViewItem listViewItem = itemListViewItemMapping[item];
385        int i = listViewItem.ImageIndex;
386        listView.SmallImageList.Images[i] = item.ItemImage;
387        listViewItem.ImageIndex = -1;
388        listViewItem.ImageIndex = i;
389      }
390    }
391    private void Item_ToStringChanged(object sender, EventArgs e) {
392      if (InvokeRequired)
393        Invoke(new EventHandler(Item_ToStringChanged), sender, e);
394      else {
395        T item = (T)sender;
396        itemListViewItemMapping[item].Text = item.ToString();
397        listView.Sort();
398        AdjustListViewColumnSizes();
399      }
400    }
401    #endregion
402
403    #region Helpers
404    private void AdjustListViewColumnSizes() {
405      if (listView.Items.Count > 0) {
406        for (int i = 0; i < listView.Columns.Count; i++)
407          listView.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
408      }
409    }
410    private void RebuildImageList() {
411      listView.SmallImageList.Images.Clear();
412      foreach (ListViewItem item in listView.Items) {
413        listView.SmallImageList.Images.Add(((T)item.Tag).ItemImage);
414        item.ImageIndex = listView.SmallImageList.Images.Count - 1;
415      }
416    }
417    #endregion
418  }
419}
Note: See TracBrowser for help on using the repository browser.