Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3633 was 3588, checked in by swagner, 15 years ago

Worked on UI support for choosing generic type parameters (#42)

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