Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1652

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