Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.AdvancedOptimizationFrontend/3.3/MainForm.cs @ 1844

Last change on this file since 1844 was 1844, checked in by epitzer, 15 years ago

Don't crash application if exceptions occur during load/save (#603)

File size: 11.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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.ComponentModel;
25using System.Data;
26using System.Drawing;
27using System.Text;
28using System.Threading;
29using System.Windows.Forms;
30using WeifenLuo.WinFormsUI.Docking;
31using HeuristicLab.PluginInfrastructure;
32using HeuristicLab.Core;
33using System.IO;
34
35namespace HeuristicLab.AdvancedOptimizationFrontend {
36  /// <summary>
37  /// The main form of the application.
38  /// </summary>
39  public partial class MainForm : Form, IControlManager {
40    #region Inner Types
41    private class Task {
42      public string filename;
43      public IStorable storable;
44      public IEditor editor;
45
46      private Task() { }
47      public Task(string filename, IStorable storable, IEditor editor) {
48        this.filename = filename;
49        this.storable = storable;
50        this.editor = editor;
51      }
52    }
53    #endregion
54
55    private object locker;
56    private int runningTasks;
57
58    /// <summary>
59    /// Initializes a new instance of <see cref="MainForm"/>.
60    /// </summary>
61    public MainForm() {
62      InitializeComponent();
63
64      locker = new object();
65      runningTasks = 0;
66
67      AvailableOperatorsForm form = new AvailableOperatorsForm();
68      form.Show(dockPanel);
69
70      DiscoveryService discoveryService = new DiscoveryService();
71
72      // discover creatable items
73      Type[] creatables = discoveryService.GetTypes(typeof(IEditable));
74      string[] names = new string[creatables.Length];
75      for (int i = 0; i < creatables.Length; i++)
76        names[i] = creatables[i].Name;
77      Array.Sort(names, creatables);
78      foreach (Type type in creatables) {
79        if (!type.IsAbstract) {
80          ToolStripMenuItem item = new ToolStripMenuItem();
81          item.Tag = type;
82          item.Text = "&" + type.Name + "...";
83          item.Click += new EventHandler(newToolStripMenuItem_Click);
84          newToolStripMenuItem.DropDownItems.Add(item);
85
86          item = new ToolStripMenuItem();
87          item.Tag = type;
88          item.Text = "&" + type.Name + "...";
89          item.Click += new EventHandler(newToolStripMenuItem_Click);
90          newToolStripDropDownButton.DropDownItems.Add(item);
91        }
92      }
93    }
94
95    #region IControlManager Members
96    /// <summary>
97    /// Displays the given <paramref name="control"/>.
98    /// </summary>
99    /// <exception cref="InvalidOperationException">Thrown when the given <paramref name="control"/>
100    /// is neither a view nor an editor.</exception>
101    /// <param name="control">The control to display.</param>
102    public void ShowControl(IControl control) {
103      DockContent content;
104      if (control is IEditor)
105        content = new EditorForm((IEditor)control);
106      else if (control is IView)
107        content = new ViewForm((IView)control);
108      else
109        throw new InvalidOperationException("Control is neither a view nor an editor.");
110
111      content.TabText = content.Text;
112      content.Show(dockPanel);
113    }
114    #endregion
115
116    private void EnableDisableItems() {
117      closeToolStripMenuItem.Enabled = false;
118      closeAllToolStripMenuItem.Enabled = false;
119      saveToolStripMenuItem.Enabled = false;
120      saveToolStripButton.Enabled = false;
121      saveAsToolStripMenuItem.Enabled = false;
122      saveAllToolStripMenuItem.Enabled = false;
123      saveAllToolStripButton.Enabled = false;
124
125      if (ActiveMdiChild != null) {
126        closeToolStripMenuItem.Enabled = true;
127        closeAllToolStripMenuItem.Enabled = true;
128        saveAllToolStripMenuItem.Enabled = true;
129        saveAllToolStripButton.Enabled = true;
130        EditorForm form = ActiveMdiChild as EditorForm;
131        if (form != null){
132          if (((Control)form.Editor).Enabled) {
133            saveToolStripMenuItem.Enabled = true;
134            saveToolStripButton.Enabled = true;
135            saveAsToolStripMenuItem.Enabled = true;
136          } else {
137            closeToolStripMenuItem.Enabled = false;
138            closeAllToolStripMenuItem.Enabled = false;
139          }
140        }
141      }
142    }
143
144    #region Open and Save Methods
145    private void Open() {
146      if (openFileDialog.ShowDialog(this) == DialogResult.OK) {
147        lock (locker) runningTasks++;
148        Cursor = Cursors.AppStarting;
149        Task task = new Task(openFileDialog.FileName, null, null);
150        ThreadPool.QueueUserWorkItem(new WaitCallback(AsynchronousLoad), task);
151      }
152    }
153    private void AsynchronousLoad(object state) {
154      Task task = (Task)state;
155      try {
156        task.storable = PersistenceManager.Load(task.filename);
157      } catch (FileNotFoundException fileNotFoundEx) {
158        MessageBox.Show("Sorry couldn't open file \"" + task.filename + "\".\nThe file or plugin \"" + fileNotFoundEx.FileName + "\" is not available.\nPlease make sure you have all necessary plugins installed.",
159          "Reader Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
160      } catch (TypeLoadException typeLoadEx) {
161        MessageBox.Show("Sorry couldn't open file \"" + task.filename + "\".\nThe type \"" + typeLoadEx.TypeName + "\" is not available.\nPlease make sure that you have the correct version the plugin installed.",
162          "Reader Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
163      } catch (Exception e) {
164        MessageBox.Show(String.Format(
165          "Sorry couldn't open file \"{0}\".\n The following exception occurred: {1}",
166          task.filename, e.ToString()),
167          "Reader Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
168      }
169      LoadFinished(task);
170    }
171    private delegate void TaskFinishedDelegate(Task task);
172    private void LoadFinished(Task task) {
173      if (InvokeRequired)
174        Invoke(new TaskFinishedDelegate(LoadFinished), task);
175      else {
176        IEditor editor = null;
177        if (task.storable != null) {
178          IEditable editable = task.storable as IEditable;
179          if (editable != null)
180            editor = editable.CreateEditor();
181        }
182        if (editor == null)
183          MessageBox.Show("Could not open item. The selected item doesn't provide an editor.", "Editor Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
184        else {
185          editor.Filename = task.filename;
186          PluginManager.ControlManager.ShowControl(editor);
187        }
188        lock (locker) {
189          runningTasks--;
190          if (runningTasks == 0)
191            Cursor = Cursors.Default;
192        }
193      }
194    }
195    private void Save(EditorForm form) {
196      if (form.Editor.Filename == null)
197        SaveAs(form);
198      else {
199        lock (locker) runningTasks++;
200        Cursor = Cursors.AppStarting;
201        ((Control)form.Editor).Enabled = false;
202        EnableDisableItems();
203        Task task = new Task(form.Editor.Filename, form.Editor.Item, form.Editor);
204        ThreadPool.QueueUserWorkItem(new WaitCallback(AsynchronousSave), task);
205      }
206    }
207    private void SaveAs(EditorForm form) {
208      if (saveFileDialog.ShowDialog(this) == DialogResult.OK) {
209        form.Editor.Filename = saveFileDialog.FileName;
210        Save(form);
211      }
212
213    }
214    private void AsynchronousSave(object state) {
215      Task task = (Task)state;
216      try {
217        PersistenceManager.Save(task.storable, task.filename);
218      } catch (Exception e) {
219        MessageBox.Show(String.Format(
220          "Sorry couldn't open file \"{0}\".\n The following exception occurred: {1}",
221          task.filename, e.ToString()),
222          "Reader Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
223      }
224      SaveFinished(task);
225    }
226    private void SaveFinished(Task task) {
227      if (InvokeRequired)
228        Invoke(new TaskFinishedDelegate(SaveFinished), task);
229      else {
230        ((Control)task.editor).Enabled = true;
231        EnableDisableItems();
232        lock (locker) {
233          runningTasks--;
234          if (runningTasks == 0)
235            Cursor = Cursors.Default;
236        }
237      }
238    }
239    #endregion
240
241    private void MainForm_MdiChildActivate(object sender, EventArgs e) {
242      EnableDisableItems();
243    }
244
245    #region Menu Events
246    private void newToolStripMenuItem_Click(object sender, EventArgs e) {
247      ToolStripItem item = (ToolStripItem)sender;
248      Type type = (Type)item.Tag;
249      IEditable editable = (IEditable)Activator.CreateInstance(type);
250      if (editable == null) {
251        MessageBox.Show("The selected item is not editable.", "Editable Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
252      } else {
253        IEditor editor = editable.CreateEditor();
254        if (editor == null) {
255          MessageBox.Show("The selected item doesn't provide an editor.", "Editor Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
256        } else {
257          PluginManager.ControlManager.ShowControl(editor);
258          EnableDisableItems();
259        }
260      }
261    }
262    private void openToolStripMenuItem_Click(object sender, EventArgs e) {
263      Open();
264    }
265    private void saveToolStripMenuItem_Click(object sender, EventArgs e) {
266      EditorForm form = ActiveMdiChild as EditorForm;
267      Save(form);
268    }
269    private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) {
270      EditorForm form = ActiveMdiChild as EditorForm;
271      SaveAs(form);
272    }
273    private void saveAllToolStripMenuItem_Click(object sender, EventArgs e) {
274      for (int i = 0; i < MdiChildren.Length; i++) {
275        EditorForm form = MdiChildren[i] as EditorForm;
276        if (((Control)form.Editor).Enabled) Save(form);
277      }
278    }
279    private void closeToolStripMenuItem_Click(object sender, EventArgs e) {
280      ActiveMdiChild.Close();
281      EnableDisableItems();
282    }
283    private void closeAllToolStripMenuItem_Click(object sender, EventArgs e) {
284      while (MdiChildren.Length > 0)
285        MdiChildren[0].Close();
286      EnableDisableItems();
287    }
288    private void exitToolStripMenuItem_Click(object sender, EventArgs e) {
289      Application.Exit();
290    }
291    private void availableOperatorsToolStripMenuItem_Click(object sender, EventArgs e) {
292      AvailableOperatorsForm form = new AvailableOperatorsForm();
293      form.Show(dockPanel);
294    }
295    private void collectGarbageToolStripMenuItem_Click(object sender, EventArgs e) {
296      GC.Collect();
297    }
298    private void aboutToolStripMenuItem_Click(object sender, EventArgs e) {
299      AboutDialog dialog = new AboutDialog();
300      dialog.ShowDialog(this);
301      dialog.Dispose();
302    }
303    #endregion
304
305    #region ToolStrip Events
306    private void openToolStripButton_Click(object sender, EventArgs e) {
307      Open();
308    }
309    private void saveToolStripButton_Click(object sender, EventArgs e) {
310      EditorForm form = ActiveMdiChild as EditorForm;
311      Save(form);
312    }
313    private void saveAllToolStripButton_Click(object sender, EventArgs e) {
314      for (int i = 0; i < MdiChildren.Length; i++) {
315        EditorForm form = MdiChildren[i] as EditorForm;
316        if (form!=null && ((Control)form.Editor).Enabled) Save(form);
317      }
318    }
319    #endregion
320  }
321}
Note: See TracBrowser for help on using the repository browser.