Free cookie consent management tool by TermsFeed Policy Generator

source: tags/3.3.0/HeuristicLab.Core.Views/3.3/Clipboard.cs @ 15524

Last change on this file since 15524 was 3819, checked in by swagner, 14 years ago

Implemented reviewers' comments (#893)

File size: 13.0 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.IO;
25using System.Linq;
26using System.Threading;
27using System.Windows.Forms;
28using HeuristicLab.MainForm;
29using HeuristicLab.Persistence.Default.Xml;
30using HeuristicLab.PluginInfrastructure;
31
32namespace HeuristicLab.Core.Views {
33  [View("Clipboard")]
34  public sealed partial class Clipboard<T> : HeuristicLab.MainForm.WindowsForms.Sidebar where T : class, IItem {
35    private TypeSelectorDialog typeSelectorDialog;
36    private Dictionary<T, ListViewItem> itemListViewItemTable;
37
38    private string itemsPath;
39    public string ItemsPath {
40      get { return itemsPath; }
41      private set {
42        if (string.IsNullOrEmpty(value)) throw new ArgumentException(string.Format("Invalid items path \"{0}\".", value));
43        itemsPath = value;
44        try {
45          if (!Directory.Exists(itemsPath)) {
46            Directory.CreateDirectory(itemsPath);
47            // directory creation might take some time -> wait until it is definitively created
48            while (!Directory.Exists(itemsPath)) {
49              Thread.Sleep(100);
50              Directory.CreateDirectory(itemsPath);
51            }
52          }
53        }
54        catch (Exception ex) {
55          throw new ArgumentException(string.Format("Invalid items path \"{0}\".", itemsPath), ex);
56        }
57      }
58    }
59
60    public Clipboard() {
61      InitializeComponent();
62      ItemsPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
63                  Path.DirectorySeparatorChar + "HeuristicLab" + Path.DirectorySeparatorChar + "Clipboard";
64      itemListViewItemTable = new Dictionary<T, ListViewItem>();
65    }
66    public Clipboard(string itemsPath) {
67      InitializeComponent();
68      ItemsPath = itemsPath;
69      itemListViewItemTable = new Dictionary<T, ListViewItem>();
70    }
71
72    protected override void OnInitialized(EventArgs e) {
73      base.OnInitialized(e);
74      SetEnabledStateOfControls();
75      Enabled = false;
76      infoLabel.Text = "Loading ...";
77      progressBar.Value = 0;
78      infoPanel.Visible = true;
79      ThreadPool.QueueUserWorkItem(new WaitCallback(LoadItems));
80    }
81    protected override void OnReadOnlyChanged() {
82      base.OnReadOnlyChanged();
83      SetEnabledStateOfControls();
84    }
85
86    private void SetEnabledStateOfControls() {
87      addButton.Enabled = !ReadOnly;
88      removeButton.Enabled = !ReadOnly && listView.SelectedItems.Count > 0;
89      saveButton.Enabled = !ReadOnly;
90    }
91
92    public void AddItem(T item) {
93      if (InvokeRequired)
94        Invoke(new Action<T>(AddItem), item);
95      else {
96        if (!itemListViewItemTable.ContainsKey(item)) {
97          ListViewItem listViewItem = new ListViewItem(item.ToString());
98          listViewItem.ToolTipText = item.ItemName + ": " + item.ItemDescription;
99          listView.SmallImageList.Images.Add(item.ItemImage);
100          listViewItem.ImageIndex = listView.SmallImageList.Images.Count - 1;
101          listViewItem.Tag = item;
102          listView.Items.Add(listViewItem);
103          itemListViewItemTable.Add(item, listViewItem);
104          item.ItemImageChanged += new EventHandler(Item_ItemImageChanged);
105          item.ToStringChanged += new EventHandler(Item_ToStringChanged);
106          sortAscendingButton.Enabled = sortDescendingButton.Enabled = listView.Items.Count > 1;
107          AdjustListViewColumnSizes();
108        }
109      }
110    }
111
112    private void RemoveItem(T item) {
113      if (InvokeRequired)
114        Invoke(new Action<T>(RemoveItem), item);
115      else {
116        if (itemListViewItemTable.ContainsKey(item)) {
117          item.ItemImageChanged -= new EventHandler(Item_ItemImageChanged);
118          item.ToStringChanged -= new EventHandler(Item_ToStringChanged);
119          ListViewItem listViewItem = itemListViewItemTable[item];
120          listViewItem.Remove();
121          foreach (ListViewItem other in listView.Items)
122            if (other.ImageIndex > listViewItem.ImageIndex) other.ImageIndex--;
123          listView.SmallImageList.Images.RemoveAt(listViewItem.ImageIndex);
124          itemListViewItemTable.Remove(item);
125          sortAscendingButton.Enabled = sortDescendingButton.Enabled = listView.Items.Count > 1;
126        }
127      }
128    }
129    private void Save() {
130      if (InvokeRequired)
131        Invoke(new Action(Save));
132      else {
133        Enabled = false;
134        infoLabel.Text = "Saving ...";
135        progressBar.Value = 0;
136        infoPanel.Visible = true;
137        ThreadPool.QueueUserWorkItem(new WaitCallback(SaveItems));
138      }
139    }
140
141    #region Loading/Saving Items
142    private void LoadItems(object state) {
143      string[] items = Directory.GetFiles(ItemsPath);
144      foreach (string filename in items) {
145        try {
146          T item = XmlParser.Deserialize<T>(filename);
147          OnItemLoaded(item, progressBar.Maximum / items.Length);
148        }
149        catch (Exception) { }
150      }
151      OnAllItemsLoaded();
152    }
153    private void OnItemLoaded(T item, int progress) {
154      if (InvokeRequired)
155        Invoke(new Action<T, int>(OnItemLoaded), item, progress);
156      else {
157        AddItem(item);
158        progressBar.Value += progress;
159      }
160    }
161    private void OnAllItemsLoaded() {
162      if (InvokeRequired)
163        Invoke(new Action(OnAllItemsLoaded));
164      else {
165        Enabled = true;
166        if (listView.Items.Count > 0) {
167          for (int i = 0; i < listView.Columns.Count; i++)
168            listView.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
169        }
170        infoPanel.Visible = false;
171      }
172    }
173    private void SaveItems(object param) {
174      Directory.Delete(ItemsPath, true);
175      Directory.CreateDirectory(ItemsPath);
176      // directory creation might take some time -> wait until it is definitively created
177      while (!Directory.Exists(ItemsPath)) {
178        Thread.Sleep(100);
179        Directory.CreateDirectory(ItemsPath);
180      }
181
182      int i = 0;
183      T[] items = itemListViewItemTable.Keys.ToArray();
184      foreach (T item in items) {
185        try {
186          i++;
187          XmlGenerator.Serialize(item, ItemsPath + Path.DirectorySeparatorChar + i.ToString("00000000") + ".hl", 9);
188          OnItemSaved(item, progressBar.Maximum / listView.Items.Count);
189        }
190        catch (Exception) { }
191      }
192      OnAllItemsSaved();
193    }
194    private void OnItemSaved(T item, int progress) {
195      if (item != null) {
196        if (InvokeRequired)
197          Invoke(new Action<T, int>(OnItemLoaded), item, progress);
198        else
199          progressBar.Value += progress;
200      }
201    }
202    private void OnAllItemsSaved() {
203      if (InvokeRequired)
204        Invoke(new Action(OnAllItemsLoaded));
205      else {
206        Enabled = true;
207        infoPanel.Visible = false;
208      }
209    }
210    #endregion
211
212    #region ListView Events
213    private void listView_SelectedIndexChanged(object sender, EventArgs e) {
214      removeButton.Enabled = !ReadOnly && listView.SelectedItems.Count > 0;
215    }
216    private void listView_KeyDown(object sender, KeyEventArgs e) {
217      if (e.KeyCode == Keys.Delete) {
218        if (!ReadOnly && (listView.SelectedItems.Count > 0)) {
219          foreach (ListViewItem item in listView.SelectedItems)
220            RemoveItem((T)item.Tag);
221        }
222      }
223    }
224    private void listView_DoubleClick(object sender, EventArgs e) {
225      if (listView.SelectedItems.Count == 1) {
226        T item = (T)listView.SelectedItems[0].Tag;
227        IContentView view;
228        view = MainFormManager.MainForm.Views.OfType<IContentView>().Where(x => (x.Content != null) && (x.Content == item)).FirstOrDefault();
229        if (view != null) {
230          view.Show();
231        } else {
232          view = MainFormManager.MainForm.ShowContent(item);
233          if (view != null) {
234            view.ReadOnly = this.ReadOnly;
235          }
236        }
237      }
238    }
239    private void listView_ItemDrag(object sender, ItemDragEventArgs e) {
240      ListViewItem listViewItem = (ListViewItem)e.Item;
241      T item = (T)listViewItem.Tag;
242      DataObject data = new DataObject();
243      data.SetData("Type", item.GetType());
244      data.SetData("Value", item);
245      if (ReadOnly) {
246        DragDropEffects result = DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link);
247      } else {
248        DragDropEffects result = DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link | DragDropEffects.Move);
249        if ((result & DragDropEffects.Move) == DragDropEffects.Move)
250          RemoveItem(item);
251      }
252    }
253    private void listView_DragEnterOver(object sender, DragEventArgs e) {
254      e.Effect = DragDropEffects.None;
255      Type type = e.Data.GetData("Type") as Type;
256      T item = e.Data.GetData("Value") as T;
257      if (!ReadOnly && (type != null) && (item != null)) {
258        if ((e.KeyState & 32) == 32) e.Effect = DragDropEffects.Link;  // ALT key
259        else if (((e.KeyState & 4) == 4) && !itemListViewItemTable.ContainsKey(item)) e.Effect = DragDropEffects.Move;  // SHIFT key
260        else if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy) e.Effect = DragDropEffects.Copy;
261        else if (((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move) && !itemListViewItemTable.ContainsKey(item)) e.Effect = DragDropEffects.Move;
262        else if (((e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link) && !itemListViewItemTable.ContainsKey(item)) e.Effect = DragDropEffects.Link;
263      }
264    }
265    private void listView_DragDrop(object sender, DragEventArgs e) {
266      if (e.Effect != DragDropEffects.None) {
267        T item = e.Data.GetData("Value") as T;
268        if ((e.Effect & DragDropEffects.Copy) == DragDropEffects.Copy) item = (T)item.Clone();
269        AddItem(item);
270      }
271    }
272    #endregion
273
274    #region Button Events
275    private void addButton_Click(object sender, EventArgs e) {
276      if (typeSelectorDialog == null) {
277        typeSelectorDialog = new TypeSelectorDialog();
278        typeSelectorDialog.Caption = "Select Item";
279        typeSelectorDialog.TypeSelector.Caption = "Available Items";
280        typeSelectorDialog.TypeSelector.Configure(typeof(T), false, true);
281      }
282
283      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
284        try {
285          AddItem((T)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType());
286        }
287        catch (Exception ex) {
288          ErrorHandling.ShowErrorDialog(this, ex);
289        }
290      }
291    }
292    private void sortAscendingButton_Click(object sender, EventArgs e) {
293      listView.Sorting = SortOrder.None;
294      listView.Sorting = SortOrder.Ascending;
295    }
296    private void sortDescendingButton_Click(object sender, EventArgs e) {
297      listView.Sorting = SortOrder.None;
298      listView.Sorting = SortOrder.Descending;
299    }
300    private void removeButton_Click(object sender, EventArgs e) {
301      if (listView.SelectedItems.Count > 0) {
302        foreach (ListViewItem item in listView.SelectedItems)
303          RemoveItem((T)item.Tag);
304      }
305    }
306    private void saveButton_Click(object sender, EventArgs e) {
307      Save();
308    }
309    #endregion
310
311    #region Item Events
312    private void Item_ItemImageChanged(object sender, EventArgs e) {
313      if (InvokeRequired)
314        Invoke(new EventHandler(Item_ItemImageChanged), sender, e);
315      else {
316        T item = (T)sender;
317        ListViewItem listViewItem = itemListViewItemTable[item];
318        int i = listViewItem.ImageIndex;
319        listViewItem.ImageList.Images[i] = item.ItemImage;
320        listViewItem.ImageIndex = -1;
321        listViewItem.ImageIndex = i;
322      }
323    }
324    private void Item_ToStringChanged(object sender, EventArgs e) {
325      if (InvokeRequired)
326        Invoke(new EventHandler(Item_ToStringChanged), sender, e);
327      else {
328        T item = (T)sender;
329        itemListViewItemTable[item].Text = item.ToString();
330        listView.Sort();
331        AdjustListViewColumnSizes();
332      }
333    }
334    #endregion
335
336    #region Helpers
337    private void AdjustListViewColumnSizes() {
338      if (listView.Items.Count > 0) {
339        for (int i = 0; i < listView.Columns.Count; i++)
340          listView.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
341      }
342    }
343    #endregion
344  }
345}
Note: See TracBrowser for help on using the repository browser.