Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5599 was 5445, checked in by swagner, 14 years ago

Updated year of copyrights (#1406)

File size: 13.6 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.Core;
28using HeuristicLab.Core.Views;
29using HeuristicLab.MainForm;
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 Dispose(bool disposing) {
55      if (disposing) {
56        if (problemTypeSelectorDialog != null) problemTypeSelectorDialog.Dispose();
57        if (components != null) components.Dispose();
58      }
59      base.Dispose(disposing);
60    }
61
62    protected override void OnInitialized(EventArgs e) {
63      // Set order of tab pages according to z order.
64      // NOTE: This is required due to a bug in the VS designer.
65      List<Control> tabPages = new List<Control>();
66      for (int i = 0; i < tabControl.Controls.Count; i++) {
67        tabPages.Add(tabControl.Controls[i]);
68      }
69      tabControl.Controls.Clear();
70      foreach (Control control in tabPages)
71        tabControl.Controls.Add(control);
72
73      base.OnInitialized(e);
74    }
75
76    protected override void DeregisterContentEvents() {
77      Content.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(Content_ExceptionOccurred);
78      Content.ExecutionStateChanged -= new EventHandler(Content_ExecutionStateChanged);
79      Content.ExecutionTimeChanged -= new EventHandler(Content_ExecutionTimeChanged);
80      Content.Prepared -= new EventHandler(Content_Prepared);
81      Content.Started -= new EventHandler(Content_Started);
82      Content.Paused -= new EventHandler(Content_Paused);
83      Content.Stopped -= new EventHandler(Content_Stopped);
84      Content.ProblemChanged -= new EventHandler(Content_ProblemChanged);
85      Content.StoreAlgorithmInEachRunChanged -= new EventHandler(Content_StoreAlgorithmInEachRunChanged);
86      base.DeregisterContentEvents();
87    }
88    protected override void RegisterContentEvents() {
89      base.RegisterContentEvents();
90      Content.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(Content_ExceptionOccurred);
91      Content.ExecutionStateChanged += new EventHandler(Content_ExecutionStateChanged);
92      Content.ExecutionTimeChanged += new EventHandler(Content_ExecutionTimeChanged);
93      Content.Prepared += new EventHandler(Content_Prepared);
94      Content.Started += new EventHandler(Content_Started);
95      Content.Paused += new EventHandler(Content_Paused);
96      Content.Stopped += new EventHandler(Content_Stopped);
97      Content.ProblemChanged += new EventHandler(Content_ProblemChanged);
98      Content.StoreAlgorithmInEachRunChanged += new EventHandler(Content_StoreAlgorithmInEachRunChanged);
99    }
100
101    protected override void OnContentChanged() {
102      base.OnContentChanged();
103      if (Content == null) {
104        parameterCollectionView.Content = null;
105        problemViewHost.Content = null;
106        resultsView.Content = null;
107        runsView.Content = null;
108        storeAlgorithmInEachRunCheckBox.Checked = true;
109        executionTimeTextBox.Text = "-";
110      } else {
111        Locked = ReadOnly = Content.ExecutionState == ExecutionState.Started;
112        parameterCollectionView.Content = Content.Parameters;
113        problemViewHost.ViewType = null;
114        problemViewHost.Content = Content.Problem;
115        resultsView.Content = Content.Results.AsReadOnly();
116        runsView.Content = Content.Runs;
117        storeAlgorithmInEachRunCheckBox.Checked = Content.StoreAlgorithmInEachRun;
118        executionTimeTextBox.Text = Content.ExecutionTime.ToString();
119      }
120    }
121
122    protected override void SetEnabledStateOfControls() {
123      base.SetEnabledStateOfControls();
124      parameterCollectionView.Enabled = Content != null;
125      newProblemButton.Enabled = Content != null && !ReadOnly;
126      openProblemButton.Enabled = Content != null && !ReadOnly;
127      problemViewHost.Enabled = Content != null;
128      resultsView.Enabled = Content != null;
129      runsView.Enabled = Content != null;
130      storeAlgorithmInEachRunCheckBox.Enabled = Content != null && !ReadOnly;
131      executionTimeTextBox.Enabled = Content != null;
132      SetEnabledStateOfExecutableButtons();
133    }
134
135    protected override void OnClosed(FormClosedEventArgs e) {
136      if ((Content != null) && (Content.ExecutionState == ExecutionState.Started)) {
137        //The content must be stopped if no other view showing the content is available
138        var optimizers = MainFormManager.MainForm.Views.OfType<IContentView>().Where(v => v != this).Select(v => v.Content).OfType<IOptimizer>();
139        if (!optimizers.Contains(Content)) {
140          var nestedOptimizers = optimizers.SelectMany(opt => opt.NestedOptimizers);
141          if (!nestedOptimizers.Contains(Content)) Content.Stop();
142        }
143      }
144      base.OnClosed(e);
145    }
146
147    #region Content Events
148    protected virtual void Content_ProblemChanged(object sender, EventArgs e) {
149      if (InvokeRequired)
150        Invoke(new EventHandler(Content_ProblemChanged), sender, e);
151      else {
152        problemViewHost.ViewType = null;
153        problemViewHost.Content = Content.Problem;
154      }
155    }
156    protected virtual void Content_ExecutionStateChanged(object sender, EventArgs e) {
157      if (InvokeRequired)
158        Invoke(new EventHandler(Content_ExecutionStateChanged), sender, e);
159      else
160        startButton.Enabled = pauseButton.Enabled = stopButton.Enabled = resetButton.Enabled = false;
161    }
162    protected virtual void Content_ExecutionTimeChanged(object sender, EventArgs e) {
163      if (InvokeRequired)
164        Invoke(new EventHandler(Content_ExecutionTimeChanged), sender, e);
165      else
166        executionTimeTextBox.Text = Content == null ? "-" : Content.ExecutionTime.ToString();
167    }
168    protected virtual void Content_StoreAlgorithmInEachRunChanged(object sender, EventArgs e) {
169      if (InvokeRequired)
170        Invoke(new EventHandler(Content_StoreAlgorithmInEachRunChanged), sender, e);
171      else
172        storeAlgorithmInEachRunCheckBox.Checked = Content.StoreAlgorithmInEachRun;
173    }
174    protected virtual void Content_Prepared(object sender, EventArgs e) {
175      if (InvokeRequired)
176        Invoke(new EventHandler(Content_Prepared), sender, e);
177      else {
178        resultsView.Content = Content.Results.AsReadOnly();
179        ReadOnly = Locked = false;
180        SetEnabledStateOfExecutableButtons();
181      }
182    }
183    protected virtual void Content_Started(object sender, EventArgs e) {
184      if (InvokeRequired)
185        Invoke(new EventHandler(Content_Started), sender, e);
186      else {
187        ReadOnly = Locked = true;
188        SetEnabledStateOfExecutableButtons();
189      }
190    }
191    protected virtual void Content_Paused(object sender, EventArgs e) {
192      if (InvokeRequired)
193        Invoke(new EventHandler(Content_Paused), sender, e);
194      else {
195        ReadOnly = Locked = false;
196        SetEnabledStateOfExecutableButtons();
197      }
198    }
199    protected virtual void Content_Stopped(object sender, EventArgs e) {
200      if (InvokeRequired)
201        Invoke(new EventHandler(Content_Stopped), sender, e);
202      else {
203        ReadOnly = Locked = false;
204        SetEnabledStateOfExecutableButtons();
205      }
206    }
207    protected virtual void Content_ExceptionOccurred(object sender, EventArgs<Exception> e) {
208      if (InvokeRequired)
209        Invoke(new EventHandler<EventArgs<Exception>>(Content_ExceptionOccurred), sender, e);
210      else
211        ErrorHandling.ShowErrorDialog(this, e.Value);
212    }
213    #endregion
214
215    #region Control Events
216    protected virtual void newProblemButton_Click(object sender, EventArgs e) {
217      if (problemTypeSelectorDialog == null) {
218        problemTypeSelectorDialog = new TypeSelectorDialog();
219        problemTypeSelectorDialog.Caption = "Select Problem";
220        problemTypeSelectorDialog.TypeSelector.Caption = "Available Problems";
221        problemTypeSelectorDialog.TypeSelector.Configure(Content.ProblemType, false, true);
222      }
223      if (problemTypeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
224        try {
225          Content.Problem = (IProblem)problemTypeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
226        }
227        catch (Exception ex) {
228          ErrorHandling.ShowErrorDialog(this, ex);
229        }
230      }
231    }
232    protected virtual void openProblemButton_Click(object sender, EventArgs e) {
233      openFileDialog.Title = "Open Problem";
234      if (openFileDialog.ShowDialog(this) == DialogResult.OK) {
235        newProblemButton.Enabled = openProblemButton.Enabled = false;
236        problemViewHost.Enabled = false;
237
238        ContentManager.LoadAsync(openFileDialog.FileName, delegate(IStorableContent content, Exception error) {
239          try {
240            if (error != null) throw error;
241            IProblem problem = content as IProblem;
242            if (problem == null)
243              Invoke(new Action(() =>
244                MessageBox.Show(this, "The selected file does not contain a problem.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error)));
245            else if (!Content.ProblemType.IsInstanceOfType(problem))
246              Invoke(new Action(() =>
247                MessageBox.Show(this, "The selected file contains a problem type which is not supported by this algorithm.", "Invalid Problem Type", MessageBoxButtons.OK, MessageBoxIcon.Error)));
248            else
249              Content.Problem = problem;
250          }
251          catch (Exception ex) {
252            Invoke(new Action(() => ErrorHandling.ShowErrorDialog(this, ex)));
253          }
254          finally {
255            Invoke(new Action(delegate() {
256              problemViewHost.Enabled = true;
257              newProblemButton.Enabled = openProblemButton.Enabled = true;
258            }));
259          }
260        });
261      }
262    }
263    protected virtual void storeAlgorithmInEachRunCheckBox_CheckedChanged(object sender, EventArgs e) {
264      if (Content != null) Content.StoreAlgorithmInEachRun = storeAlgorithmInEachRunCheckBox.Checked;
265    }
266    protected virtual void startButton_Click(object sender, EventArgs e) {
267      Content.Start();
268    }
269    protected virtual void pauseButton_Click(object sender, EventArgs e) {
270      Content.Pause();
271    }
272    protected virtual void stopButton_Click(object sender, EventArgs e) {
273      Content.Stop();
274    }
275    protected virtual void resetButton_Click(object sender, EventArgs e) {
276      Content.Prepare(false);
277    }
278    protected virtual void problemTabPage_DragEnterOver(object sender, DragEventArgs e) {
279      e.Effect = DragDropEffects.None;
280      Type type = e.Data.GetData("Type") as Type;
281      if ((type != null) && (Content.ProblemType.IsAssignableFrom(type))) {
282        if ((e.KeyState & 32) == 32) e.Effect = DragDropEffects.Link;  // ALT key
283        else if ((e.KeyState & 4) == 4) e.Effect = DragDropEffects.Move;  // SHIFT key
284        else if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy) e.Effect = DragDropEffects.Copy;
285        else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move) e.Effect = DragDropEffects.Move;
286        else if ((e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link) e.Effect = DragDropEffects.Link;
287      }
288    }
289    protected virtual void problemTabPage_DragDrop(object sender, DragEventArgs e) {
290      if (e.Effect != DragDropEffects.None) {
291        IProblem problem = e.Data.GetData("Value") as IProblem;
292        if ((e.Effect & DragDropEffects.Copy) == DragDropEffects.Copy) problem = (IProblem)problem.Clone();
293        Content.Problem = problem;
294      }
295    }
296    #endregion
297
298    #region Helpers
299    private void SetEnabledStateOfExecutableButtons() {
300      if (Content == null) {
301        startButton.Enabled = pauseButton.Enabled = stopButton.Enabled = resetButton.Enabled = false;
302      } else {
303        startButton.Enabled = (Content.ExecutionState == ExecutionState.Prepared) || (Content.ExecutionState == ExecutionState.Paused);
304        pauseButton.Enabled = Content.ExecutionState == ExecutionState.Started;
305        stopButton.Enabled = (Content.ExecutionState == ExecutionState.Started) || (Content.ExecutionState == ExecutionState.Paused);
306        resetButton.Enabled = Content.ExecutionState != ExecutionState.Started;
307      }
308    }
309    #endregion
310  }
311}
Note: See TracBrowser for help on using the repository browser.