Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3548 was 3548, checked in by gkronber, 14 years ago

Fixed cross-thread exception potential in AlgorithmView. #990

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