Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4435 was 4435, checked in by mkommend, 13 years ago

Adjusted the SetEnabledStateOfControls method in all views, added the Enabled property into the IView interface and adapted the ViewHost, View and ContentView class (ticket #1155).

File size: 13.4 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          SetEnabledStateOfContentViews(item, false);
185          XmlGenerator.Serialize(item, ItemsPath + Path.DirectorySeparatorChar + i.ToString("00000000") + ".hl", 9);
186          OnItemSaved(item, progressBar.Maximum / listView.Items.Count);
187        }
188        catch (Exception) { }
189      }
190      OnAllItemsSaved();
191    }
192    private void OnItemSaved(T item, int progress) {
193      if (item != null) {
194        if (InvokeRequired)
195          Invoke(new Action<T, int>(OnItemSaved), item, progress);
196        else {
197          progressBar.Value += progress;
198          SetEnabledStateOfContentViews(item, true);
199        }
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
211    private void SetEnabledStateOfContentViews(IItem item, bool enabled) {
212      if (InvokeRequired)
213        Invoke((Action<IItem, bool>)SetEnabledStateOfContentViews, item, enabled);
214      else {
215        var views = MainFormManager.MainForm.Views.OfType<IContentView>().Where(v => v.Content == item).ToList();
216        views.ForEach(v => v.Enabled = enabled);
217      }
218    }
219    #endregion
220
221    #region ListView Events
222    private void listView_SelectedIndexChanged(object sender, EventArgs e) {
223      removeButton.Enabled = !ReadOnly && listView.SelectedItems.Count > 0;
224    }
225    private void listView_KeyDown(object sender, KeyEventArgs e) {
226      if (e.KeyCode == Keys.Delete) {
227        if (!ReadOnly && (listView.SelectedItems.Count > 0)) {
228          foreach (ListViewItem item in listView.SelectedItems)
229            RemoveItem((T)item.Tag);
230        }
231      }
232    }
233    private void listView_DoubleClick(object sender, EventArgs e) {
234      if (listView.SelectedItems.Count == 1) {
235        T item = (T)listView.SelectedItems[0].Tag;
236        IContentView view;
237        view = MainFormManager.MainForm.Views.OfType<IContentView>().Where(x => (x.Content != null) && (x.Content == item)).FirstOrDefault();
238        if (view != null) {
239          view.Show();
240        } else {
241          view = MainFormManager.MainForm.ShowContent(item);
242          if (view != null) {
243            view.ReadOnly = this.ReadOnly;
244          }
245        }
246      }
247    }
248    private void listView_ItemDrag(object sender, ItemDragEventArgs e) {
249      ListViewItem listViewItem = (ListViewItem)e.Item;
250      T item = (T)listViewItem.Tag;
251      DataObject data = new DataObject();
252      data.SetData("Type", item.GetType());
253      data.SetData("Value", item);
254      if (ReadOnly) {
255        DragDropEffects result = DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link);
256      } else {
257        DragDropEffects result = DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Link | DragDropEffects.Move);
258        if ((result & DragDropEffects.Move) == DragDropEffects.Move)
259          RemoveItem(item);
260      }
261    }
262    private void listView_DragEnterOver(object sender, DragEventArgs e) {
263      e.Effect = DragDropEffects.None;
264      Type type = e.Data.GetData("Type") as Type;
265      T item = e.Data.GetData("Value") as T;
266      if (!ReadOnly && (type != null) && (item != null)) {
267        if ((e.KeyState & 32) == 32) e.Effect = DragDropEffects.Link;  // ALT key
268        else if (((e.KeyState & 4) == 4) && !itemListViewItemTable.ContainsKey(item)) e.Effect = DragDropEffects.Move;  // SHIFT key
269        else if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy) e.Effect = DragDropEffects.Copy;
270        else if (((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move) && !itemListViewItemTable.ContainsKey(item)) e.Effect = DragDropEffects.Move;
271        else if (((e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link) && !itemListViewItemTable.ContainsKey(item)) e.Effect = DragDropEffects.Link;
272      }
273    }
274    private void listView_DragDrop(object sender, DragEventArgs e) {
275      if (e.Effect != DragDropEffects.None) {
276        T item = e.Data.GetData("Value") as T;
277        if ((e.Effect & DragDropEffects.Copy) == DragDropEffects.Copy) item = (T)item.Clone();
278        AddItem(item);
279      }
280    }
281    #endregion
282
283    #region Button Events
284    private void addButton_Click(object sender, EventArgs e) {
285      if (typeSelectorDialog == null) {
286        typeSelectorDialog = new TypeSelectorDialog();
287        typeSelectorDialog.Caption = "Select Item";
288        typeSelectorDialog.TypeSelector.Caption = "Available Items";
289        typeSelectorDialog.TypeSelector.Configure(typeof(T), false, true);
290      }
291
292      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
293        try {
294          AddItem((T)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType());
295        }
296        catch (Exception ex) {
297          ErrorHandling.ShowErrorDialog(this, ex);
298        }
299      }
300    }
301    private void sortAscendingButton_Click(object sender, EventArgs e) {
302      listView.Sorting = SortOrder.None;
303      listView.Sorting = SortOrder.Ascending;
304    }
305    private void sortDescendingButton_Click(object sender, EventArgs e) {
306      listView.Sorting = SortOrder.None;
307      listView.Sorting = SortOrder.Descending;
308    }
309    private void removeButton_Click(object sender, EventArgs e) {
310      if (listView.SelectedItems.Count > 0) {
311        foreach (ListViewItem item in listView.SelectedItems)
312          RemoveItem((T)item.Tag);
313      }
314    }
315    private void saveButton_Click(object sender, EventArgs e) {
316      Save();
317    }
318    #endregion
319
320    #region Item Events
321    private void Item_ItemImageChanged(object sender, EventArgs e) {
322      if (InvokeRequired)
323        Invoke(new EventHandler(Item_ItemImageChanged), sender, e);
324      else {
325        T item = (T)sender;
326        ListViewItem listViewItem = itemListViewItemTable[item];
327        int i = listViewItem.ImageIndex;
328        listViewItem.ImageList.Images[i] = item.ItemImage;
329        listViewItem.ImageIndex = -1;
330        listViewItem.ImageIndex = i;
331      }
332    }
333    private void Item_ToStringChanged(object sender, EventArgs e) {
334      if (InvokeRequired)
335        Invoke(new EventHandler(Item_ToStringChanged), sender, e);
336      else {
337        T item = (T)sender;
338        itemListViewItemTable[item].Text = item.ToString();
339        listView.Sort();
340        AdjustListViewColumnSizes();
341      }
342    }
343    #endregion
344
345    #region Helpers
346    private void AdjustListViewColumnSizes() {
347      if (listView.Items.Count > 0) {
348        for (int i = 0; i < listView.Columns.Count; i++)
349          listView.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
350      }
351    }
352    #endregion
353  }
354}
Note: See TracBrowser for help on using the repository browser.