Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3932 was 3904, checked in by mkommend, 15 years ago

Added SetEnabledStateOfControls as protected virtual method in !View. Therefore the overloading of OnReadOnlyChanged and OnLockedChanged got obsolete in most views, because the method got called in the !View respectively ContentView. (ticket #1021)

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