Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 8818 was 8818, checked in by jkarder, 12 years ago

#1926:

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