Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5444 was 5270, checked in by mkommend, 14 years ago

Implemented ShowContent method in MainForm which reuses existing views and adapted the ClipBoard (ticket #1372).

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