Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Optimization.Views/3.3/AlgorithmView.cs @ 4049

Last change on this file since 4049 was 4011, checked in by mkommend, 14 years ago
  • refactored ViewHost and various views to use fewer nested controls
  • added UnitTests for ContentViews to ensure proper using of the ContentAttribute
  • fixed some views which could not handle null as Content

(ticket #972)

File size: 10.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.Windows.Forms;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Core.Views;
28using HeuristicLab.MainForm;
29using HeuristicLab.Persistence.Default.Xml;
30using HeuristicLab.PluginInfrastructure;
31
32namespace HeuristicLab.Optimization.Views {
33  /// <summary>
34  /// The base class for visual representations of items.
35  /// </summary>
36  [View("Algorithm View")]
37  [Content(typeof(Algorithm), true)]
38  [Content(typeof(IAlgorithm), false)]
39  public partial class AlgorithmView : NamedItemView {
40    private TypeSelectorDialog problemTypeSelectorDialog;
41
42    public new IAlgorithm Content {
43      get { return (IAlgorithm)base.Content; }
44      set { base.Content = value; }
45    }
46
47    /// <summary>
48    /// Initializes a new instance of <see cref="ItemBaseView"/>.
49    /// </summary>
50    public AlgorithmView() {
51      InitializeComponent();
52    }
53
54    protected override void OnInitialized(EventArgs e) {
55      // Set order of tab pages according to z order.
56      // NOTE: This is required due to a bug in the VS designer.
57      List<Control> tabPages = new List<Control>();
58      for (int i = 0; i < tabControl.Controls.Count; i++) {
59        tabPages.Add(tabControl.Controls[i]);
60      }
61      tabControl.Controls.Clear();
62      foreach (Control control in tabPages)
63        tabControl.Controls.Add(control);
64
65      base.OnInitialized(e);
66    }
67
68    protected override void DeregisterContentEvents() {
69      Content.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(Content_ExceptionOccurred);
70      Content.ExecutionStateChanged -= new EventHandler(Content_ExecutionStateChanged);
71      Content.ExecutionTimeChanged -= new EventHandler(Content_ExecutionTimeChanged);
72      Content.Prepared -= new EventHandler(Content_Prepared);
73      Content.ProblemChanged -= new EventHandler(Content_ProblemChanged);
74      base.DeregisterContentEvents();
75    }
76    protected override void RegisterContentEvents() {
77      base.RegisterContentEvents();
78      Content.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(Content_ExceptionOccurred);
79      Content.ExecutionStateChanged += new EventHandler(Content_ExecutionStateChanged);
80      Content.ExecutionTimeChanged += new EventHandler(Content_ExecutionTimeChanged);
81      Content.Prepared += new EventHandler(Content_Prepared);
82      Content.ProblemChanged += new EventHandler(Content_ProblemChanged);
83    }
84
85    protected override void OnContentChanged() {
86      base.OnContentChanged();
87      if (Content == null) {
88        parameterCollectionView.Content = null;
89        problemViewHost.Content = null;
90        resultsView.Content = null;
91        runsView.Content = null;
92        executionTimeTextBox.Text = "-";
93      } else {
94        parameterCollectionView.Content = Content.Parameters;
95        problemViewHost.ViewType = null;
96        problemViewHost.Content = Content.Problem;
97        resultsView.Content = Content.Results.AsReadOnly();
98        runsView.Content = Content.Runs;
99        executionTimeTextBox.Text = Content.ExecutionTime.ToString();
100      }
101    }
102
103    protected override void SetEnabledStateOfControls() {
104      base.SetEnabledStateOfControls();
105      parameterCollectionView.Enabled = Content != null;
106      newProblemButton.Enabled = Content != null && !ReadOnly;
107      openProblemButton.Enabled = Content != null && !ReadOnly;
108      problemViewHost.Enabled = Content != null;
109      resultsView.Enabled = Content != null;
110      runsView.Enabled = Content != null;
111      executionTimeTextBox.Enabled = Content != null;
112      SetEnabledStateOfExecutableButtons();
113    }
114
115    protected override void OnClosed(FormClosedEventArgs e) {
116      if ((Content != null) && (Content.ExecutionState == ExecutionState.Started)) Content.Stop();
117      base.OnClosed(e);
118    }
119
120    #region Content Events
121    protected virtual void Content_ProblemChanged(object sender, EventArgs e) {
122      if (InvokeRequired)
123        Invoke(new EventHandler(Content_ProblemChanged), sender, e);
124      else {
125        problemViewHost.ViewType = null;
126        problemViewHost.Content = Content.Problem;
127      }
128    }
129    protected virtual void Content_Prepared(object sender, EventArgs e) {
130      if (InvokeRequired)
131        Invoke(new EventHandler(Content_Prepared), sender, e);
132      else
133        resultsView.Content = Content.Results.AsReadOnly();
134    }
135    protected virtual void Content_ExecutionStateChanged(object sender, EventArgs e) {
136      if (InvokeRequired)
137        Invoke(new EventHandler(Content_ExecutionStateChanged), sender, e);
138      else {
139        ReadOnly = Content.ExecutionState == ExecutionState.Started;
140        Locked = Content.ExecutionState == ExecutionState.Started;
141        SetEnabledStateOfExecutableButtons();
142      }
143    }
144    protected virtual void Content_ExecutionTimeChanged(object sender, EventArgs e) {
145      if (InvokeRequired)
146        Invoke(new EventHandler(Content_ExecutionTimeChanged), sender, e);
147      else
148        executionTimeTextBox.Text = Content.ExecutionTime.ToString();
149    }
150    protected virtual void Content_ExceptionOccurred(object sender, EventArgs<Exception> e) {
151      if (InvokeRequired)
152        Invoke(new EventHandler<EventArgs<Exception>>(Content_ExceptionOccurred), sender, e);
153      else
154        ErrorHandling.ShowErrorDialog(this, e.Value);
155    }
156    #endregion
157
158    #region Control Events
159    protected virtual void newProblemButton_Click(object sender, EventArgs e) {
160      if (problemTypeSelectorDialog == null) {
161        problemTypeSelectorDialog = new TypeSelectorDialog();
162        problemTypeSelectorDialog.Caption = "Select Problem";
163        problemTypeSelectorDialog.TypeSelector.Caption = "Available Problems";
164        problemTypeSelectorDialog.TypeSelector.Configure(Content.ProblemType, false, true);
165      }
166      if (problemTypeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
167        try {
168          Content.Problem = (IProblem)problemTypeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
169        }
170        catch (Exception ex) {
171          ErrorHandling.ShowErrorDialog(this, ex);
172        }
173      }
174    }
175    protected virtual void openProblemButton_Click(object sender, EventArgs e) {
176      openFileDialog.Title = "Open Problem";
177      if (openFileDialog.ShowDialog(this) == DialogResult.OK) {
178        newProblemButton.Enabled = openProblemButton.Enabled = false;
179        problemViewHost.Enabled = false;
180
181        ContentManager.LoadAsync(openFileDialog.FileName, delegate(IStorableContent content, Exception error) {
182          try {
183            if (error != null) throw error;
184            IProblem problem = content as IProblem;
185            if (problem == null)
186              Invoke(new Action(() =>
187                MessageBox.Show(this, "The selected file does not contain a problem.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error)));
188            else if (!Content.ProblemType.IsInstanceOfType(problem))
189              Invoke(new Action(() =>
190                MessageBox.Show(this, "The selected file contains a problem type which is not supported by this algorithm.", "Invalid Problem Type", MessageBoxButtons.OK, MessageBoxIcon.Error)));
191            else
192              Content.Problem = problem;
193          }
194          catch (Exception ex) {
195            Invoke(new Action(() => ErrorHandling.ShowErrorDialog(this, ex)));
196          }
197          finally {
198            Invoke(new Action(delegate() {
199              problemViewHost.Enabled = true;
200              newProblemButton.Enabled = openProblemButton.Enabled = true;
201            }));
202          }
203        });
204      }
205    }
206    protected virtual void startButton_Click(object sender, EventArgs e) {
207      Content.Start();
208    }
209    protected virtual void pauseButton_Click(object sender, EventArgs e) {
210      Content.Pause();
211    }
212    protected virtual void stopButton_Click(object sender, EventArgs e) {
213      Content.Stop();
214    }
215    protected virtual void resetButton_Click(object sender, EventArgs e) {
216      Content.Prepare(false);
217    }
218    protected virtual void problemViewHost_DragEnterOver(object sender, DragEventArgs e) {
219      e.Effect = DragDropEffects.None;
220      Type type = e.Data.GetData("Type") as Type;
221      if ((type != null) && (Content.ProblemType.IsAssignableFrom(type))) {
222        if ((e.KeyState & 32) == 32) e.Effect = DragDropEffects.Link;  // ALT key
223        else if ((e.KeyState & 4) == 4) e.Effect = DragDropEffects.Move;  // SHIFT key
224        else if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy) e.Effect = DragDropEffects.Copy;
225        else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move) e.Effect = DragDropEffects.Move;
226        else if ((e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link) e.Effect = DragDropEffects.Link;
227      }
228    }
229    protected virtual void problemViewHost_DragDrop(object sender, DragEventArgs e) {
230      if (e.Effect != DragDropEffects.None) {
231        IProblem problem = e.Data.GetData("Value") as IProblem;
232        if ((e.Effect & DragDropEffects.Copy) == DragDropEffects.Copy) problem = (IProblem)problem.Clone();
233        Content.Problem = problem;
234      }
235    }
236    #endregion
237
238    #region Helpers
239    private void SetEnabledStateOfExecutableButtons() {
240      if (Content == null) {
241        startButton.Enabled = pauseButton.Enabled = stopButton.Enabled = resetButton.Enabled = false;
242      } else {
243        startButton.Enabled = (Content.ExecutionState == ExecutionState.Prepared) || (Content.ExecutionState == ExecutionState.Paused);
244        pauseButton.Enabled = Content.ExecutionState == ExecutionState.Started;
245        stopButton.Enabled = (Content.ExecutionState == ExecutionState.Started) || (Content.ExecutionState == ExecutionState.Paused);
246        resetButton.Enabled = Content.ExecutionState != ExecutionState.Started;
247      }
248    }
249    #endregion
250  }
251}
Note: See TracBrowser for help on using the repository browser.