source: trunk/sources/HeuristicLab.MainForm.WindowsForms/3.3/MainForms/MainForm.cs @ 6935

Last change on this file since 6935 was 6935, checked in by ascheibe, 11 years ago

#1652 fixed a bug when saving a file in SD or MD mode

File size: 17.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.Linq;
25using System.Reflection;
26using System.Windows.Forms;
27using HeuristicLab.Common;
28using HeuristicLab.PluginInfrastructure;
29using WeifenLuo.WinFormsUI.Docking;
30
31namespace HeuristicLab.MainForm.WindowsForms {
32  public partial class MainForm : Form, IMainForm {
33    private bool initialized;
34    private int appStartingCursors;
35    private int waitingCursors;
36    private string title;
37
38    protected MainForm()
39      : base() {
40      InitializeComponent();
41      this.views = new Dictionary<IView, Form>();
42      this.userInterfaceItems = new List<IUserInterfaceItem>();
43      this.initialized = false;
44      this.showContentInViewHost = false;
45      appStartingCursors = 0;
46      waitingCursors = 0;
47    }
48
49    protected MainForm(Type userInterfaceItemType)
50      : this() {
51      this.userInterfaceItemType = userInterfaceItemType;
52    }
53
54    #region properties
55    private bool showContentInViewHost;
56    public bool ShowContentInViewHost {
57      get { return this.showContentInViewHost; }
58      set { this.showContentInViewHost = value; }
59    }
60
61    public string Title {
62      get { return this.Text; }
63      set {
64        if (InvokeRequired) {
65          Action<string> action = delegate(string s) { this.Title = s; };
66          Invoke(action, value);
67        } else
68          this.Text = value;
69      }
70    }
71
72    public override Cursor Cursor {
73      get { return base.Cursor; }
74      set {
75        if (InvokeRequired) {
76          Action<Cursor> action = delegate(Cursor c) { this.Cursor = c; };
77          Invoke(action, value);
78        } else
79          base.Cursor = value;
80      }
81    }
82
83    private Type userInterfaceItemType;
84    public Type UserInterfaceItemType {
85      get { return this.userInterfaceItemType; }
86    }
87
88    private Dictionary<IView, Form> views;
89    public IEnumerable<IView> Views {
90      get { return views.Keys; }
91    }
92
93    private IView activeView;
94    public IView ActiveView {
95      get { return this.activeView; }
96      protected set {
97        if (this.activeView != value) {
98          if (InvokeRequired) {
99            Action<IView> action = delegate(IView activeView) { this.ActiveView = activeView; };
100            Invoke(action, value);
101          } else {
102            this.activeView = value;
103            OnActiveViewChanged();
104          }
105        }
106      }
107    }
108
109    private List<IUserInterfaceItem> userInterfaceItems;
110    protected IEnumerable<IUserInterfaceItem> UserInterfaceItems {
111      get { return this.userInterfaceItems; }
112    }
113    #endregion
114
115    #region events
116    public event EventHandler ActiveViewChanged;
117    protected virtual void OnActiveViewChanged() {
118      if (InvokeRequired)
119        Invoke((MethodInvoker)OnActiveViewChanged);
120      else {
121        EventHandler handler = ActiveViewChanged;
122        if (handler != null)
123          handler(this, EventArgs.Empty);
124      }
125    }
126
127    public event EventHandler<ViewEventArgs> ViewClosed;
128    protected virtual void OnViewClosed(IView view) {
129      if (InvokeRequired) Invoke((Action<IView>)OnViewClosed, view);
130      else {
131        EventHandler<ViewEventArgs> handler = ViewClosed;
132        if (handler != null)
133          handler(this, new ViewEventArgs(view));
134      }
135    }
136
137    public event EventHandler<ViewShownEventArgs> ViewShown;
138    protected virtual void OnViewShown(IView view, bool firstTimeShown) {
139      if (InvokeRequired) Invoke((Action<IView, bool>)OnViewShown, view, firstTimeShown);
140      else {
141        EventHandler<ViewShownEventArgs> handler = ViewShown;
142        if (handler != null)
143          handler(this, new ViewShownEventArgs(view, firstTimeShown));
144      }
145    }
146
147    public event EventHandler<ViewEventArgs> ViewHidden;
148    protected virtual void OnViewHidden(IView view) {
149      if (InvokeRequired) Invoke((Action<IView>)OnViewHidden, view);
150      else {
151        EventHandler<ViewEventArgs> handler = ViewHidden;
152        if (handler != null)
153          handler(this, new ViewEventArgs(view));
154      }
155    }
156
157    public event EventHandler Changed;
158    protected void OnChanged() {
159      if (InvokeRequired)
160        Invoke((MethodInvoker)OnChanged);
161      else {
162        EventHandler handler = Changed;
163        if (handler != null)
164          Changed(this, EventArgs.Empty);
165      }
166    }
167
168    private void MainFormBase_Load(object sender, EventArgs e) {
169      if (!DesignMode) {
170        MainFormManager.RegisterMainForm(this);
171        this.CreateGUI();
172        if (!this.initialized) {
173          this.initialized = true;
174          this.OnInitialized(EventArgs.Empty);
175        }
176      }
177    }
178
179    protected virtual void OnInitialized(EventArgs e) {
180      AssemblyFileVersionAttribute version = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true).
181                                             Cast<AssemblyFileVersionAttribute>().FirstOrDefault();
182      title = "HeuristicLab Optimizer";
183      if (version != null) title += " " + version.Version;
184      Title = title;
185    }
186
187    private void FormActivated(object sender, EventArgs e) {
188      this.ActiveView = GetView((Form)sender);
189    }
190
191    protected override void OnFormClosing(FormClosingEventArgs e) {
192      foreach (KeyValuePair<IView, Form> pair in this.views) {
193        DockForm dockForm = pair.Value as DockForm;
194        View view = pair.Key as View;
195        if (view != null && dockForm != null && dockForm.DockState != DockState.Document) {
196          view.CloseReason = CloseReason.ApplicationExitCall;
197          view.OnClosingHelper(dockForm, e);
198        }
199      }
200      base.OnFormClosing(e);
201    }
202
203    protected override void OnFormClosed(FormClosedEventArgs e) {
204      foreach (KeyValuePair<IView, Form> pair in this.views.ToList()) {
205        DockForm dockForm = pair.Value as DockForm;
206        View view = pair.Key as View;
207        if (view != null && dockForm != null && dockForm.DockState != DockState.Document) {
208          view.CloseReason = CloseReason.ApplicationExitCall;
209          view.OnClosedHelper(dockForm, e);
210          dockForm.Close();
211        }
212      }
213      base.OnFormClosed(e);
214    }
215    #endregion
216
217    #region create, get, show, hide, close views
218    protected virtual Form CreateForm(IView view) {
219      throw new NotImplementedException("CreateForm must be implemented in subclasses of MainForm.");
220    }
221
222    internal Form GetForm(IView view) {
223      if (views.ContainsKey(view))
224        return views[view];
225      return null;
226    }
227    protected IView GetView(Form form) {
228      return views.Where(x => x.Value == form).Single().Key;
229    }
230
231    public IContentView ShowContent(IContent content) {
232      if (content == null) throw new ArgumentNullException("Content cannot be null.");
233      Type viewType = MainFormManager.GetDefaultViewType(content.GetType());
234      if (viewType != null) return ShowContent(content, viewType);
235      return null;
236    }
237
238    public IContentView ShowContent<T>(T content, bool reuseExistingView, IEqualityComparer<T> comparer = null) where T : class,IContent {
239      if (content == null) throw new ArgumentNullException("Content cannot be null.");
240      if (!reuseExistingView) return ShowContent(content);
241
242      IContentView view = null;
243      if (comparer == null) view = Views.OfType<IContentView>().Where(v => (v.Content as T) == content).FirstOrDefault();
244      else view = Views.OfType<IContentView>().Where(v => comparer.Equals((v.Content as T), content)).FirstOrDefault();
245
246      if (view == null) view = ShowContent(content);
247      else view.Show();
248
249      return view;
250    }
251
252    public IContentView ShowContent(IContent content, Type viewType) {
253      if (InvokeRequired) return (IContentView)Invoke((Func<IContent, Type, IContentView>)ShowContent, content, viewType);
254      else {
255        if (content == null) throw new ArgumentNullException("Content cannot be null.");
256        if (viewType == null) throw new ArgumentNullException("ViewType cannot be null.");
257
258        IContentView view = null;
259        if (ShowContentInViewHost) {
260          ViewHost viewHost = new ViewHost();
261          viewHost.ViewType = viewType;
262          view = viewHost;
263
264        } else view = MainFormManager.CreateView(viewType);
265
266        view.Content = content;
267        view.Show();
268        return view;
269      }
270    }
271
272    internal void ShowView(IView view) {
273      if (InvokeRequired) Invoke((Action<IView>)ShowView, view);
274      else {
275        Form form = GetForm(view);
276        bool firstTimeShown = form == null;
277        if (firstTimeShown) {
278          form = CreateForm(view);
279          form.Activated += new EventHandler(FormActivated);
280          form.FormClosed += new FormClosedEventHandler(ChildFormClosed);
281          view.Changed += new EventHandler(View_Changed);
282          views[view] = form;
283        }
284        this.ShowView(view, firstTimeShown);
285        this.OnViewShown(view, firstTimeShown);
286      }
287    }
288
289    private void View_Changed(object sender, EventArgs e) {
290      IView view = (IView)sender;
291      if (view == this.ActiveView)
292        this.OnActiveViewChanged();
293      this.OnChanged();
294    }
295
296    protected virtual void ShowView(IView view, bool firstTimeShown) {
297    }
298
299    internal void HideView(IView view) {
300      if (InvokeRequired) Invoke((Action<IView>)HideView, view);
301      else {
302        this.Hide(view);
303        if (this.activeView == view)
304          this.ActiveView = null;
305        this.OnViewHidden(view);
306      }
307    }
308
309    protected virtual void Hide(IView view) {
310    }
311
312    private void ChildFormClosed(object sender, FormClosedEventArgs e) {
313      Form form = (Form)sender;
314      IView view = GetView(form);
315
316      view.Changed -= new EventHandler(View_Changed);
317      form.Activated -= new EventHandler(FormActivated);
318      form.FormClosed -= new FormClosedEventHandler(ChildFormClosed);
319
320      views.Remove(view);
321      this.OnViewClosed(view);
322      if (ActiveView == view)
323        ActiveView = null;
324    }
325
326    internal void CloseView(IView view) {
327      if (InvokeRequired) Invoke((Action<IView>)CloseView, view);
328      else if (views.ContainsKey(view)) {
329        this.views[view].Close();
330        this.OnViewClosed(view);
331      }
332    }
333
334    internal void CloseView(IView view, CloseReason closeReason) {
335      if (InvokeRequired) Invoke((Action<IView>)CloseView, view);
336      else if (views.ContainsKey(view)) {
337        ((View)view).CloseReason = closeReason;
338        this.CloseView(view);
339      }
340    }
341
342    public void CloseAllViews() {
343      foreach (IView view in views.Keys.ToArray())
344        CloseView(view);
345    }
346
347    public void CloseAllViews(CloseReason closeReason) {
348      foreach (IView view in views.Keys.ToArray())
349        CloseView(view, closeReason);
350    }
351    #endregion
352
353    #region create menu and toolbar
354    private void CreateGUI() {
355      IEnumerable<object> allUserInterfaceItems = ApplicationManager.Manager.GetInstances(userInterfaceItemType);
356
357      IEnumerable<IPositionableUserInterfaceItem> toolStripMenuItems =
358        from mi in allUserInterfaceItems
359        where (mi is IPositionableUserInterfaceItem) &&
360              (mi is IMenuItem || mi is IMenuSeparatorItem)
361        orderby ((IPositionableUserInterfaceItem)mi).Position
362        select (IPositionableUserInterfaceItem)mi;
363
364      foreach (IPositionableUserInterfaceItem menuItem in toolStripMenuItems) {
365        if (menuItem is IMenuItem)
366          AddToolStripMenuItem((IMenuItem)menuItem);
367        else if (menuItem is IMenuSeparatorItem)
368          AddToolStripMenuItem((IMenuSeparatorItem)menuItem);
369      }
370
371      IEnumerable<IPositionableUserInterfaceItem> toolStripButtonItems =
372        from bi in allUserInterfaceItems
373        where (bi is IPositionableUserInterfaceItem) &&
374              (bi is IToolBarItem || bi is IToolBarSeparatorItem)
375        orderby ((IPositionableUserInterfaceItem)bi).Position
376        select (IPositionableUserInterfaceItem)bi;
377
378      foreach (IPositionableUserInterfaceItem toolStripButtonItem in toolStripButtonItems) {
379        if (toolStripButtonItem is IToolBarItem)
380          AddToolStripButtonItem((IToolBarItem)toolStripButtonItem);
381        else if (toolStripButtonItem is IToolBarSeparatorItem)
382          AddToolStripButtonItem((IToolBarSeparatorItem)toolStripButtonItem);
383      }
384
385      this.AdditionalCreationOfGuiElements();
386    }
387
388    protected virtual void AdditionalCreationOfGuiElements() {
389    }
390
391    private void AddToolStripMenuItem(IMenuItem menuItem) {
392      ToolStripMenuItem item = new ToolStripMenuItem();
393      this.SetToolStripItemProperties(item, menuItem);
394      if (menuItem is MenuItem) {
395        MenuItem menuItemBase = (MenuItem)menuItem;
396        menuItemBase.ToolStripItem = item;
397        item.ShortcutKeys = menuItemBase.ShortCutKeys;
398        item.DisplayStyle = menuItemBase.ToolStripItemDisplayStyle;
399      }
400      this.InsertItem(menuItem.Structure, typeof(ToolStripMenuItem), item, menuStrip.Items);
401    }
402
403    private void AddToolStripMenuItem(IMenuSeparatorItem menuItem) {
404      this.InsertItem(menuItem.Structure, typeof(ToolStripMenuItem), new ToolStripSeparator(), menuStrip.Items);
405    }
406
407    private void AddToolStripButtonItem(IToolBarItem buttonItem) {
408      ToolStripItem item = new ToolStripButton();
409      if (buttonItem is ToolBarItem) {
410        ToolBarItem buttonItemBase = (ToolBarItem)buttonItem;
411        if (buttonItemBase.IsDropDownButton)
412          item = new ToolStripDropDownButton();
413
414        item.DisplayStyle = buttonItemBase.ToolStripItemDisplayStyle;
415        buttonItemBase.ToolStripItem = item;
416      }
417
418      this.SetToolStripItemProperties(item, buttonItem);
419      this.InsertItem(buttonItem.Structure, typeof(ToolStripDropDownButton), item, toolStrip.Items);
420    }
421
422    private void AddToolStripButtonItem(IToolBarSeparatorItem buttonItem) {
423      this.InsertItem(buttonItem.Structure, typeof(ToolStripDropDownButton), new ToolStripSeparator(), toolStrip.Items);
424    }
425
426    private void InsertItem(IEnumerable<string> structure, Type t, ToolStripItem item, ToolStripItemCollection parentItems) {
427      ToolStripDropDownItem parent = null;
428      foreach (string s in structure) {
429        if (parentItems.ContainsKey(s))
430          parent = (ToolStripDropDownItem)parentItems[s];
431        else {
432          parent = (ToolStripDropDownItem)Activator.CreateInstance(t, s, null, null, s); ;
433          parentItems.Add(parent);
434        }
435        parentItems = parent.DropDownItems;
436      }
437      parentItems.Add(item);
438    }
439
440    private void SetToolStripItemProperties(ToolStripItem toolStripItem, IActionUserInterfaceItem userInterfaceItem) {
441      toolStripItem.Name = userInterfaceItem.Name;
442      toolStripItem.Text = userInterfaceItem.Name;
443      toolStripItem.ToolTipText = userInterfaceItem.ToolTipText;
444      toolStripItem.Tag = userInterfaceItem;
445      toolStripItem.Image = userInterfaceItem.Image;
446      toolStripItem.Click += new EventHandler(ToolStripItemClicked);
447      this.userInterfaceItems.Add(userInterfaceItem);
448    }
449
450    private void ToolStripItemClicked(object sender, EventArgs e) {
451      System.Windows.Forms.ToolStripItem item = (System.Windows.Forms.ToolStripItem)sender;
452      try {
453        ((IActionUserInterfaceItem)item.Tag).Execute();
454      }
455      catch (Exception ex) {
456        ErrorHandling.ShowErrorDialog((Control)MainFormManager.MainForm, ex);
457      }
458    }
459    #endregion
460
461    #region Cursor Handling
462    public void SetAppStartingCursor() {
463      if (InvokeRequired)
464        Invoke(new Action(SetAppStartingCursor));
465      else {
466        appStartingCursors++;
467        SetCursor();
468      }
469    }
470    public void ResetAppStartingCursor() {
471      if (InvokeRequired)
472        Invoke(new Action(ResetAppStartingCursor));
473      else {
474        appStartingCursors--;
475        SetCursor();
476      }
477    }
478    public void SetWaitCursor() {
479      if (InvokeRequired)
480        Invoke(new Action(SetWaitCursor));
481      else {
482        waitingCursors++;
483        SetCursor();
484      }
485    }
486    public void ResetWaitCursor() {
487      if (InvokeRequired)
488        Invoke(new Action(ResetWaitCursor));
489      else {
490        waitingCursors--;
491        SetCursor();
492      }
493    }
494    private void SetCursor() {
495      if (waitingCursors > 0) Cursor = Cursors.WaitCursor;
496      else if (appStartingCursors > 0) Cursor = Cursors.AppStarting;
497      else Cursor = Cursors.Default;
498    }
499    #endregion
500
501    public virtual void UpdateTitle() {
502      if (InvokeRequired)
503        Invoke(new Action(UpdateTitle));
504      else {
505        IContentView activeView = ActiveView as IContentView;
506        if ((activeView != null) && (activeView.Content != null) && (activeView.Content is IStorableContent)) {
507          IStorableContent content = (IStorableContent)activeView.Content;
508          Title = title + " [" + (string.IsNullOrEmpty(content.Filename) ? "Unsaved" : content.Filename) + "]";
509        } else {
510          Title = title;
511        }
512      }
513    }
514  }
515}
Note: See TracBrowser for help on using the repository browser.