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

Last change on this file since 3416 was 3416, checked in by mkommend, 12 years ago

implemented ContentViews and propagation of view state changes (ticket #982)

File size: 12.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        tabControl.Enabled = false;
100        startButton.Enabled = pauseButton.Enabled = stopButton.Enabled = resetButton.Enabled = false;
101        executionTimeTextBox.Text = "-";
102        executionTimeTextBox.Enabled = false;
103      } else {
104        parameterCollectionView.Content = Content.Parameters;
105        saveProblemButton.Enabled = Content.Problem != null;
106        problemViewHost.ViewType = null;
107        problemViewHost.Content = Content.Problem;
108        resultsView.Content = Content.Results.AsReadOnly();
109        runsView.Content = Content.Runs;
110        tabControl.Enabled = true;
111        EnableDisableButtons();
112        executionTimeTextBox.Text = Content.ExecutionTime.ToString();
113        executionTimeTextBox.Enabled = true;
114      }
115      SetEnableStateOfControls();
116    }
117
118    protected override void OnReadOnlyChanged() {
119      base.OnReadOnlyChanged();
120      SetEnableStateOfControls();
121    }
122    private void SetEnableStateOfControls() {
123      parameterCollectionView.ReadOnly = ReadOnly;
124      problemViewHost.ReadOnly = ReadOnly;
125      resultsView.ReadOnly = ReadOnly;
126      runsView.ReadOnly = ReadOnly;
127    }
128
129    protected override void OnClosed(FormClosedEventArgs e) {
130      if ((Content != null) && (Content.ExecutionState == ExecutionState.Started)) Content.Stop();
131      base.OnClosed(e);
132    }
133
134    #region Content Events
135    protected virtual void Content_ProblemChanged(object sender, EventArgs e) {
136      if (InvokeRequired)
137        Invoke(new EventHandler(Content_ProblemChanged), sender, e);
138      else {
139        problemViewHost.ViewType = null;
140        problemViewHost.Content = Content.Problem;
141        saveProblemButton.Enabled = Content.Problem != null;
142      }
143    }
144    protected virtual void Content_Prepared(object sender, EventArgs e) {
145      if (InvokeRequired)
146        Invoke(new EventHandler(Content_Prepared), sender, e);
147      else
148        resultsView.Content = Content.Results.AsReadOnly();
149    }
150    protected virtual void Content_ExecutionStateChanged(object sender, EventArgs e) {
151      if (InvokeRequired)
152        Invoke(new EventHandler(Content_ExecutionStateChanged), sender, e);
153      else {
154        this.ReadOnly = Content.ExecutionState == ExecutionState.Started;
155        Locked = Content.ExecutionState == ExecutionState.Started;
156        EnableDisableButtons();
157      }
158    }
159    protected virtual void Content_ExecutionTimeChanged(object sender, EventArgs e) {
160      if (InvokeRequired)
161        Invoke(new EventHandler(Content_ExecutionTimeChanged), sender, e);
162      else
163        executionTimeTextBox.Text = Content.ExecutionTime.ToString();
164    }
165    protected virtual void Content_ExceptionOccurred(object sender, EventArgs<Exception> e) {
166      if (InvokeRequired)
167        Invoke(new EventHandler<EventArgs<Exception>>(Content_ExceptionOccurred), sender, e);
168      else
169        Auxiliary.ShowErrorMessageBox(e.Value);
170    }
171    #endregion
172
173    #region Control Events
174    protected virtual void newProblemButton_Click(object sender, EventArgs e) {
175      if (problemTypeSelectorDialog == null) {
176        problemTypeSelectorDialog = new TypeSelectorDialog();
177        problemTypeSelectorDialog.Caption = "Select Problem";
178        problemTypeSelectorDialog.TypeSelector.Caption = "Available Problems";
179        problemTypeSelectorDialog.TypeSelector.Configure(Content.ProblemType, false, false);
180      }
181      if (problemTypeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
182        try {
183          Content.Problem = (IProblem)problemTypeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
184        }
185        catch (Exception ex) {
186          Auxiliary.ShowErrorMessageBox(ex);
187        }
188      }
189    }
190    protected virtual void openProblemButton_Click(object sender, EventArgs e) {
191      openFileDialog.Title = "Open Problem";
192      if (openFileDialog.ShowDialog(this) == DialogResult.OK) {
193        this.Cursor = Cursors.AppStarting;
194        newProblemButton.Enabled = openProblemButton.Enabled = saveProblemButton.Enabled = false;
195        problemViewHost.Enabled = false;
196
197        var call = new Func<string, object>(XmlParser.Deserialize);
198        call.BeginInvoke(openFileDialog.FileName, delegate(IAsyncResult a) {
199          IProblem problem = null;
200          try {
201            problem = call.EndInvoke(a) as IProblem;
202          } catch (Exception ex) {
203            Auxiliary.ShowErrorMessageBox(ex);
204          }
205          Invoke(new Action(delegate() {
206            if (problem == null)
207              MessageBox.Show(this, "The selected file does not contain a problem.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error);
208            else if (!Content.ProblemType.IsInstanceOfType(problem))
209              MessageBox.Show(this, "The selected file contains a problem type which is not supported by this algorithm.", "Invalid Problem Type", MessageBoxButtons.OK, MessageBoxIcon.Error);
210            else
211              Content.Problem = problem;
212            problemViewHost.Enabled = true;
213            newProblemButton.Enabled = openProblemButton.Enabled = saveProblemButton.Enabled = true;
214            this.Cursor = Cursors.Default;
215          }));
216        }, null);
217      }
218    }
219    protected virtual void saveProblemButton_Click(object sender, EventArgs e) {
220      saveFileDialog.Title = "Save Problem";
221      if (saveFileDialog.ShowDialog(this) == DialogResult.OK) {
222        this.Cursor = Cursors.AppStarting;
223        newProblemButton.Enabled = openProblemButton.Enabled = saveProblemButton.Enabled = false;
224        problemViewHost.Enabled = false;
225
226        var call = new Action<IProblem, string, int>(XmlGenerator.Serialize);
227        int compression = 9;
228        if (saveFileDialog.FilterIndex == 1) compression = 0;
229        call.BeginInvoke(Content.Problem, saveFileDialog.FileName, compression, delegate(IAsyncResult a) {
230          try {
231            call.EndInvoke(a);
232          }
233          catch (Exception ex) {
234            Auxiliary.ShowErrorMessageBox(ex);
235          }
236          Invoke(new Action(delegate() {
237            problemViewHost.Enabled = true;
238            newProblemButton.Enabled = openProblemButton.Enabled = saveProblemButton.Enabled = true;
239            this.Cursor = Cursors.Default;
240          }));
241        }, null);
242      }
243    }
244    protected virtual void startButton_Click(object sender, EventArgs e) {
245      Content.Start();
246    }
247    protected virtual void pauseButton_Click(object sender, EventArgs e) {
248      Content.Pause();
249    }
250    protected virtual void stopButton_Click(object sender, EventArgs e) {
251      Content.Stop();
252    }
253    protected virtual void resetButton_Click(object sender, EventArgs e) {
254      if (Content.Runs.Count > 0) {
255        if (MessageBox.Show(this, "Clear all runs executed so far?", "Clear All Runs?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
256          Content.Prepare(true);
257        else
258          Content.Prepare(false);
259      } else {
260        Content.Prepare();
261      }
262    }
263    protected virtual void problemPanel_DragEnterOver(object sender, DragEventArgs e) {
264      e.Effect = DragDropEffects.None;
265      Type type = e.Data.GetData("Type") as Type;
266      if ((type != null) && (Content.ProblemType.IsAssignableFrom(type))) {
267        if ((e.KeyState & 8) == 8) e.Effect = DragDropEffects.Copy;  // CTRL key
268        else if ((e.KeyState & 4) == 4) e.Effect = DragDropEffects.Move;  // SHIFT key
269        else if ((e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link) e.Effect = DragDropEffects.Link;
270        else if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy) e.Effect = DragDropEffects.Copy;
271        else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move) e.Effect = DragDropEffects.Move;
272      }
273    }
274    protected virtual void problemPanel_DragDrop(object sender, DragEventArgs e) {
275      if (e.Effect != DragDropEffects.None) {
276        IProblem problem = e.Data.GetData("Value") as IProblem;
277        if ((e.Effect & DragDropEffects.Copy) == DragDropEffects.Copy) problem = (IProblem)problem.Clone();
278        Content.Problem = problem;
279      }
280    }
281    #endregion
282
283    #region Helpers
284    private void EnableDisableButtons() {
285      startButton.Enabled = (Content.ExecutionState == ExecutionState.Prepared) || (Content.ExecutionState == ExecutionState.Paused);
286      pauseButton.Enabled = Content.ExecutionState == ExecutionState.Started;
287      stopButton.Enabled = (Content.ExecutionState == ExecutionState.Started) || (Content.ExecutionState == ExecutionState.Paused);
288      resetButton.Enabled = Content.ExecutionState != ExecutionState.Started;
289    }
290    #endregion
291  }
292}
Note: See TracBrowser for help on using the repository browser.