Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Breadcrumbs/HeuristicLab.MainForm.WindowsForms/3.3/MainForms/MainForm.cs @ 10089

Last change on this file since 10089 was 10089, checked in by jkarder, 11 years ago

#2116:

  • added hotlinking functionality
  • added methods for outermost view host detection and manipulation
File size: 22.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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    public virtual void UpdateTitle() { }
180
181    private void FormActivated(object sender, EventArgs e) {
182      this.ActiveView = GetView((Form)sender);
183    }
184
185    protected override void OnFormClosing(FormClosingEventArgs e) {
186      foreach (KeyValuePair<IView, Form> pair in this.views) {
187        DockForm dockForm = pair.Value as DockForm;
188        View view = pair.Key as View;
189        if (view != null && dockForm != null && dockForm.DockState != DockState.Document) {
190          view.CloseReason = CloseReason.ApplicationExitCall;
191          view.OnClosingHelper(dockForm, e);
192        }
193      }
194      base.OnFormClosing(e);
195    }
196
197    protected override void OnFormClosed(FormClosedEventArgs e) {
198      foreach (KeyValuePair<IView, Form> pair in this.views.ToList()) {
199        DockForm dockForm = pair.Value as DockForm;
200        View view = pair.Key as View;
201        if (view != null && dockForm != null && dockForm.DockState != DockState.Document) {
202          view.CloseReason = CloseReason.ApplicationExitCall;
203          view.OnClosedHelper(dockForm, e);
204          dockForm.Close();
205        }
206      }
207      base.OnFormClosed(e);
208    }
209    #endregion
210
211    #region create, get, show, hide, close views
212    protected virtual Form CreateForm(IView view) {
213      throw new NotImplementedException("CreateForm must be implemented in subclasses of MainForm.");
214    }
215
216    internal Form GetForm(IView view) {
217      if (views.ContainsKey(view))
218        return views[view];
219      return null;
220    }
221    protected IView GetView(Form form) {
222      return views.Where(x => x.Value == form).Single().Key;
223    }
224
225    public T GetOutermostViewOfType<T>(Control childControl) where T : class, IView {
226      T outermostView = null;
227      for (var control = childControl; control != null; control = control.Parent) {
228        var vh = control as T;
229        if (vh != null) outermostView = vh;
230      }
231      return outermostView;
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    public void ShowContentInSpecificViewHost(IContent content, ViewHost viewHost) {
276      if (viewHost == null) return;
277      viewHost.Content = null;
278      var viewType = MainFormManager.GetDefaultViewType(content.GetType());
279      viewHost.ViewType = viewType;
280      viewHost.Content = content;
281    }
282
283    internal void ShowView(IView view) {
284      if (InvokeRequired) Invoke((Action<IView>)ShowView, view);
285      else {
286        Form form = GetForm(view);
287        bool firstTimeShown = form == null;
288        if (firstTimeShown) {
289          form = CreateForm(view);
290          form.Activated += new EventHandler(FormActivated);
291          form.FormClosed += new FormClosedEventHandler(ChildFormClosed);
292          view.Changed += new EventHandler(View_Changed);
293          views[view] = form;
294        }
295        this.ShowView(view, firstTimeShown);
296        this.OnViewShown(view, firstTimeShown);
297      }
298    }
299
300    private void View_Changed(object sender, EventArgs e) {
301      IView view = (IView)sender;
302      if (view == this.ActiveView)
303        this.OnActiveViewChanged();
304      this.OnChanged();
305    }
306
307    protected virtual void ShowView(IView view, bool firstTimeShown) {
308    }
309
310    internal void HideView(IView view) {
311      if (InvokeRequired) Invoke((Action<IView>)HideView, view);
312      else {
313        this.Hide(view);
314        if (this.activeView == view)
315          this.ActiveView = null;
316        this.OnViewHidden(view);
317      }
318    }
319
320    protected virtual void Hide(IView view) {
321    }
322
323    private void ChildFormClosed(object sender, FormClosedEventArgs e) {
324      Form form = (Form)sender;
325      IView view = GetView(form);
326
327      view.Changed -= new EventHandler(View_Changed);
328      form.Activated -= new EventHandler(FormActivated);
329      form.FormClosed -= new FormClosedEventHandler(ChildFormClosed);
330
331      views.Remove(view);
332      this.OnViewClosed(view);
333      if (ActiveView == view)
334        ActiveView = null;
335    }
336
337    internal void CloseView(IView view) {
338      if (InvokeRequired) Invoke((Action<IView>)CloseView, view);
339      else if (views.ContainsKey(view)) {
340        this.views[view].Close();
341        this.OnViewClosed(view);
342      }
343    }
344
345    internal void CloseView(IView view, CloseReason closeReason) {
346      if (InvokeRequired) Invoke((Action<IView>)CloseView, view);
347      else if (views.ContainsKey(view)) {
348        ((View)view).CloseReason = closeReason;
349        this.CloseView(view);
350      }
351    }
352
353    public void CloseAllViews() {
354      foreach (IView view in views.Keys.ToArray())
355        CloseView(view);
356    }
357
358    public void CloseAllViews(CloseReason closeReason) {
359      foreach (IView view in views.Keys.ToArray())
360        CloseView(view, closeReason);
361    }
362    #endregion
363
364    #region progress views
365    private readonly Dictionary<IContent, IProgress> contentProgressLookup = new Dictionary<IContent, IProgress>();
366    private readonly Dictionary<Control, IProgress> viewProgressLookup = new Dictionary<Control, IProgress>();
367    private readonly List<ProgressView> progressViews = new List<ProgressView>();
368
369    /// <summary>
370    /// Adds a <see cref="ProgressView"/> to the <see cref="ContentView"/>s showing the specified content.
371    /// </summary>
372    public IProgress AddOperationProgressToContent(IContent content, string progressMessage, bool addToObjectGraphObjects = true) {
373      if (InvokeRequired) {
374        IProgress result = (IProgress)Invoke((Func<IContent, string, bool, IProgress>)AddOperationProgressToContent, content, progressMessage, addToObjectGraphObjects);
375        return result;
376      }
377      if (contentProgressLookup.ContainsKey(content))
378        throw new ArgumentException("A progress is already registered for the specified content.", "content");
379
380      var contentViews = views.Keys.OfType<ContentView>();
381      if (!contentViews.Any(v => v.Content == content))
382        throw new ArgumentException("The content is not displayed in a top-level view", "content");
383
384      if (addToObjectGraphObjects) {
385        var containedObjects = content.GetObjectGraphObjects();
386        contentViews = contentViews.Where(v => containedObjects.Contains(v.Content));
387      } else
388        contentViews = contentViews.Where(v => v.Content == content);
389
390      var progress = new Progress(progressMessage, ProgressState.Started);
391      foreach (var contentView in contentViews) {
392        progressViews.Add(new ProgressView(contentView, progress));
393      }
394
395      contentProgressLookup[content] = progress;
396      return progress;
397    }
398
399    /// <summary>
400    /// Adds a <see cref="ProgressView"/> to the specified view.
401    /// </summary>
402    public IProgress AddOperationProgressToView(Control control, string progressMessage) {
403      var progress = new Progress(progressMessage, ProgressState.Started);
404      AddOperationProgressToView(control, progress);
405      return progress;
406    }
407
408    public void AddOperationProgressToView(Control control, IProgress progress) {
409      if (InvokeRequired) {
410        Invoke((Action<Control, IProgress>)AddOperationProgressToView, control, progress);
411        return;
412      }
413      if (control == null) throw new ArgumentNullException("control", "The view must not be null.");
414      if (progress == null) throw new ArgumentNullException("progress", "The progress must not be null.");
415
416      IProgress oldProgress;
417      if (viewProgressLookup.TryGetValue(control, out oldProgress)) {
418        foreach (var progressView in progressViews.Where(v => v.Content == oldProgress).ToList()) {
419          progressView.Dispose();
420          progressViews.Remove(progressView);
421        }
422        viewProgressLookup.Remove(control);
423      }
424
425      progressViews.Add(new ProgressView(control, progress));
426      viewProgressLookup[control] = progress;
427    }
428
429    /// <summary>
430    /// Removes an existing <see cref="ProgressView"/> from the <see cref="ContentView"/>s showing the specified content.
431    /// </summary>
432    public void RemoveOperationProgressFromContent(IContent content, bool finishProgress = true) {
433      if (InvokeRequired) {
434        Invoke((Action<IContent, bool>)RemoveOperationProgressFromContent, content, finishProgress);
435        return;
436      }
437
438      IProgress progress;
439      if (!contentProgressLookup.TryGetValue(content, out progress))
440        throw new ArgumentException("No progress is registered for the specified content.", "content");
441
442      if (finishProgress) progress.Finish();
443      foreach (var progressView in progressViews.Where(v => v.Content == progress).ToList()) {
444        progressView.Dispose();
445        progressViews.Remove(progressView);
446      }
447      contentProgressLookup.Remove(content);
448
449    }
450
451    /// <summary>
452    /// Removes an existing <see cref="ProgressView"/> from the specified view.
453    /// </summary>
454    public void RemoveOperationProgressFromView(Control control, bool finishProgress = true) {
455      IProgress progress;
456      if (!viewProgressLookup.TryGetValue(control, out progress))
457        throw new ArgumentException("No progress is registered for the specified control.", "control");
458
459      if (finishProgress) progress.Finish();
460      foreach (var progressView in progressViews.Where(v => v.Content == progress).ToList()) {
461        progressView.Dispose();
462        progressViews.Remove(progressView);
463      }
464      viewProgressLookup.Remove(control);
465    }
466    #endregion
467
468    #region create menu and toolbar
469    private void CreateGUI() {
470      IEnumerable<object> allUserInterfaceItems = ApplicationManager.Manager.GetInstances(userInterfaceItemType);
471
472      IEnumerable<IPositionableUserInterfaceItem> toolStripMenuItems =
473        from mi in allUserInterfaceItems
474        where (mi is IPositionableUserInterfaceItem) &&
475              (mi is IMenuItem || mi is IMenuSeparatorItem)
476        orderby ((IPositionableUserInterfaceItem)mi).Position
477        select (IPositionableUserInterfaceItem)mi;
478
479      foreach (IPositionableUserInterfaceItem menuItem in toolStripMenuItems) {
480        if (menuItem is IMenuItem)
481          AddToolStripMenuItem((IMenuItem)menuItem);
482        else if (menuItem is IMenuSeparatorItem)
483          AddToolStripMenuItem((IMenuSeparatorItem)menuItem);
484      }
485
486      IEnumerable<IPositionableUserInterfaceItem> toolStripButtonItems =
487        from bi in allUserInterfaceItems
488        where (bi is IPositionableUserInterfaceItem) &&
489              (bi is IToolBarItem || bi is IToolBarSeparatorItem)
490        orderby ((IPositionableUserInterfaceItem)bi).Position
491        select (IPositionableUserInterfaceItem)bi;
492
493      foreach (IPositionableUserInterfaceItem toolStripButtonItem in toolStripButtonItems) {
494        if (toolStripButtonItem is IToolBarItem)
495          AddToolStripButtonItem((IToolBarItem)toolStripButtonItem);
496        else if (toolStripButtonItem is IToolBarSeparatorItem)
497          AddToolStripButtonItem((IToolBarSeparatorItem)toolStripButtonItem);
498      }
499
500      this.AdditionalCreationOfGuiElements();
501    }
502
503    protected virtual void AdditionalCreationOfGuiElements() {
504    }
505
506    private void AddToolStripMenuItem(IMenuItem menuItem) {
507      ToolStripMenuItem item = new ToolStripMenuItem();
508      this.SetToolStripItemProperties(item, menuItem);
509      this.InsertItem(menuItem.Structure, typeof(ToolStripMenuItem), item, menuStrip.Items);
510      if (menuItem is MenuItem) {
511        MenuItem menuItemBase = (MenuItem)menuItem;
512        menuItemBase.ToolStripItem = item;
513        item.ShortcutKeys = menuItemBase.ShortCutKeys;
514        item.DisplayStyle = menuItemBase.ToolStripItemDisplayStyle;
515      }
516    }
517
518    private void AddToolStripMenuItem(IMenuSeparatorItem menuItem) {
519      this.InsertItem(menuItem.Structure, typeof(ToolStripMenuItem), new ToolStripSeparator(), menuStrip.Items);
520    }
521
522    private void AddToolStripButtonItem(IToolBarItem buttonItem) {
523      ToolStripItem item = new ToolStripButton();
524      if (buttonItem is ToolBarItem) {
525        ToolBarItem buttonItemBase = (ToolBarItem)buttonItem;
526        if (buttonItemBase.IsDropDownButton)
527          item = new ToolStripDropDownButton();
528
529        item.DisplayStyle = buttonItemBase.ToolStripItemDisplayStyle;
530        buttonItemBase.ToolStripItem = item;
531      }
532
533      this.SetToolStripItemProperties(item, buttonItem);
534      this.InsertItem(buttonItem.Structure, typeof(ToolStripDropDownButton), item, toolStrip.Items);
535    }
536
537    private void AddToolStripButtonItem(IToolBarSeparatorItem buttonItem) {
538      this.InsertItem(buttonItem.Structure, typeof(ToolStripDropDownButton), new ToolStripSeparator(), toolStrip.Items);
539    }
540
541    private void InsertItem(IEnumerable<string> structure, Type t, ToolStripItem item, ToolStripItemCollection parentItems) {
542      ToolStripDropDownItem parent = null;
543      foreach (string s in structure) {
544        if (parentItems.ContainsKey(s))
545          parent = (ToolStripDropDownItem)parentItems[s];
546        else {
547          parent = (ToolStripDropDownItem)Activator.CreateInstance(t, s, null, null, s); ;
548          parentItems.Add(parent);
549        }
550        parentItems = parent.DropDownItems;
551      }
552      parentItems.Add(item);
553    }
554
555    private void SetToolStripItemProperties(ToolStripItem toolStripItem, IActionUserInterfaceItem userInterfaceItem) {
556      toolStripItem.Name = userInterfaceItem.Name;
557      toolStripItem.Text = userInterfaceItem.Name;
558      toolStripItem.ToolTipText = userInterfaceItem.ToolTipText;
559      toolStripItem.Tag = userInterfaceItem;
560      toolStripItem.Image = userInterfaceItem.Image;
561      toolStripItem.Click += new EventHandler(ToolStripItemClicked);
562      this.userInterfaceItems.Add(userInterfaceItem);
563    }
564
565    private void ToolStripItemClicked(object sender, EventArgs e) {
566      System.Windows.Forms.ToolStripItem item = (System.Windows.Forms.ToolStripItem)sender;
567      try {
568        ((IActionUserInterfaceItem)item.Tag).Execute();
569      } catch (Exception ex) {
570        ErrorHandling.ShowErrorDialog((Control)MainFormManager.MainForm, ex);
571      }
572    }
573    #endregion
574
575    #region Cursor Handling
576    public void SetAppStartingCursor() {
577      if (InvokeRequired)
578        Invoke(new Action(SetAppStartingCursor));
579      else {
580        appStartingCursors++;
581        SetCursor();
582      }
583    }
584    public void ResetAppStartingCursor() {
585      if (InvokeRequired)
586        Invoke(new Action(ResetAppStartingCursor));
587      else {
588        appStartingCursors--;
589        SetCursor();
590      }
591    }
592    public void SetWaitCursor() {
593      if (InvokeRequired)
594        Invoke(new Action(SetWaitCursor));
595      else {
596        waitingCursors++;
597        SetCursor();
598      }
599    }
600    public void ResetWaitCursor() {
601      if (InvokeRequired)
602        Invoke(new Action(ResetWaitCursor));
603      else {
604        waitingCursors--;
605        SetCursor();
606      }
607    }
608    private void SetCursor() {
609      if (waitingCursors > 0) Cursor = Cursors.WaitCursor;
610      else if (appStartingCursors > 0) Cursor = Cursors.AppStarting;
611      else Cursor = Cursors.Default;
612    }
613    #endregion
614  }
615}
Note: See TracBrowser for help on using the repository browser.