Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Optimization.Views/3.3/TimeLimitRunView.cs @ 14161

Last change on this file since 14161 was 13317, checked in by ascheibe, 9 years ago

#2428 updated copyright year where it was missing

File size: 13.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.ComponentModel;
24using System.Linq;
25using System.Text.RegularExpressions;
26using System.Windows.Forms;
27using HeuristicLab.Collections;
28using HeuristicLab.Common;
29using HeuristicLab.Common.Resources;
30using HeuristicLab.Core;
31using HeuristicLab.Core.Views;
32using HeuristicLab.MainForm;
33using HeuristicLab.MainForm.WindowsForms;
34using HeuristicLab.PluginInfrastructure;
35
36namespace HeuristicLab.Optimization.Views {
37  [View("TimeLimit Run View")]
38  [Content(typeof(TimeLimitRun), IsDefaultView = true)]
39  public partial class TimeLimitRunView : IOptimizerView {
40    protected TypeSelectorDialog algorithmTypeSelectorDialog;
41    protected virtual bool SuppressEvents { get; set; }
42
43    public new TimeLimitRun Content {
44      get { return (TimeLimitRun)base.Content; }
45      set { base.Content = value; }
46    }
47
48    public TimeLimitRunView() {
49      InitializeComponent();
50      snapshotButton.Text = String.Empty;
51      snapshotButton.Image = VSImageLibrary.Camera;
52    }
53
54    protected override void Dispose(bool disposing) {
55      if (disposing) {
56        if (algorithmTypeSelectorDialog != null) algorithmTypeSelectorDialog.Dispose();
57        if (components != null) components.Dispose();
58      }
59      base.Dispose(disposing);
60    }
61
62    protected override void DeregisterContentEvents() {
63      Content.PropertyChanged -= Content_PropertyChanged;
64      Content.SnapshotTimes.ItemsAdded -= Content_SnapshotTimes_Changed;
65      Content.SnapshotTimes.ItemsMoved -= Content_SnapshotTimes_Changed;
66      Content.SnapshotTimes.ItemsRemoved -= Content_SnapshotTimes_Changed;
67      Content.SnapshotTimes.ItemsReplaced -= Content_SnapshotTimes_Changed;
68      Content.SnapshotTimes.CollectionReset -= Content_SnapshotTimes_Changed;
69      base.DeregisterContentEvents();
70    }
71    protected override void RegisterContentEvents() {
72      base.RegisterContentEvents();
73      Content.PropertyChanged += Content_PropertyChanged;
74      Content.SnapshotTimes.ItemsAdded += Content_SnapshotTimes_Changed;
75      Content.SnapshotTimes.ItemsMoved += Content_SnapshotTimes_Changed;
76      Content.SnapshotTimes.ItemsRemoved += Content_SnapshotTimes_Changed;
77      Content.SnapshotTimes.ItemsReplaced += Content_SnapshotTimes_Changed;
78      Content.SnapshotTimes.CollectionReset += Content_SnapshotTimes_Changed;
79    }
80
81    protected override void OnContentChanged() {
82      base.OnContentChanged();
83      SuppressEvents = true;
84      try {
85        if (Content == null) {
86          timeLimitTextBox.Text = TimeSpanHelper.FormatNatural(TimeSpan.FromSeconds(60));
87          snapshotsTextBox.Text = String.Empty;
88          storeAlgorithmInEachSnapshotCheckBox.Checked = false;
89          algorithmViewHost.Content = null;
90          snapshotsView.Content = null;
91          runsView.Content = null;
92        } else {
93          timeLimitTextBox.Text = TimeSpanHelper.FormatNatural(Content.MaximumExecutionTime);
94          snapshotsTextBox.Text = String.Join(" ; ", Content.SnapshotTimes.Select(x => TimeSpanHelper.FormatNatural(x, true)));
95          storeAlgorithmInEachSnapshotCheckBox.Checked = Content.StoreAlgorithmInEachSnapshot;
96          algorithmViewHost.Content = Content.Algorithm;
97          snapshotsView.Content = Content.Snapshots;
98          runsView.Content = Content.Runs;
99        }
100      } finally { SuppressEvents = false; }
101    }
102
103    protected override void SetEnabledStateOfControls() {
104      base.SetEnabledStateOfControls();
105      timeLimitTextBox.Enabled = Content != null && !ReadOnly;
106      snapshotsTextBox.Enabled = Content != null && !ReadOnly;
107      storeAlgorithmInEachSnapshotCheckBox.Enabled = Content != null && !ReadOnly;
108      newAlgorithmButton.Enabled = Content != null && !ReadOnly;
109      openAlgorithmButton.Enabled = Content != null && !ReadOnly;
110      algorithmViewHost.Enabled = Content != null;
111      snapshotsView.Enabled = Content != null;
112      runsView.Enabled = Content != null;
113    }
114
115    protected override void SetEnabledStateOfExecutableButtons() {
116      base.SetEnabledStateOfExecutableButtons();
117      snapshotButton.Enabled = Content != null && Content.Algorithm != null && Content.ExecutionState == ExecutionState.Paused;
118    }
119
120    protected override void OnClosed(FormClosedEventArgs e) {
121      if ((Content != null) && (Content.ExecutionState == ExecutionState.Started)) {
122        //The content must be stopped if no other view showing the content is available
123        var optimizers = MainFormManager.MainForm.Views.OfType<IContentView>().Where(v => v != this).Select(v => v.Content).OfType<IAlgorithm>();
124        if (!optimizers.Contains(Content.Algorithm)) {
125          var nestedOptimizers = optimizers.SelectMany(opt => opt.NestedOptimizers);
126          if (!nestedOptimizers.Contains(Content)) Content.Stop();
127        }
128      }
129      base.OnClosed(e);
130    }
131
132    #region Event Handlers
133    #region Content events
134    private void Content_PropertyChanged(object sender, PropertyChangedEventArgs e) {
135      switch (e.PropertyName) {
136        case "MaximumExecutionTime":
137          SuppressEvents = true;
138          try {
139            timeLimitTextBox.Text = TimeSpanHelper.FormatNatural(Content.MaximumExecutionTime);
140          } finally { SuppressEvents = false; }
141          break;
142        case "SnapshotTimes":
143          SuppressEvents = true;
144          try {
145            if (Content.SnapshotTimes.Any())
146              snapshotsTextBox.Text = String.Join(" ; ", Content.SnapshotTimes.Select(x => TimeSpanHelper.FormatNatural(x, true)));
147            else snapshotsTextBox.Text = String.Empty;
148            Content.SnapshotTimes.ItemsAdded += Content_SnapshotTimes_Changed;
149            Content.SnapshotTimes.ItemsMoved += Content_SnapshotTimes_Changed;
150            Content.SnapshotTimes.ItemsRemoved += Content_SnapshotTimes_Changed;
151            Content.SnapshotTimes.ItemsReplaced += Content_SnapshotTimes_Changed;
152            Content.SnapshotTimes.CollectionReset += Content_SnapshotTimes_Changed;
153          } finally { SuppressEvents = false; }
154          break;
155        case "StoreAlgorithmInEachSnapshot":
156          SuppressEvents = true;
157          try {
158            storeAlgorithmInEachSnapshotCheckBox.Checked = Content.StoreAlgorithmInEachSnapshot;
159          } finally { SuppressEvents = false; }
160          break;
161        case "Algorithm":
162          SuppressEvents = true;
163          try {
164            algorithmViewHost.Content = Content.Algorithm;
165          } finally { SuppressEvents = false; }
166          break;
167        case "Snapshots":
168          SuppressEvents = true;
169          try {
170            snapshotsView.Content = Content.Snapshots;
171          } finally { SuppressEvents = false; }
172          break;
173        case "Runs":
174          SuppressEvents = true;
175          try {
176            runsView.Content = Content.Runs;
177          } finally { SuppressEvents = false; }
178          break;
179      }
180    }
181
182    private void Content_SnapshotTimes_Changed(object sender, EventArgs e) {
183      SuppressEvents = true;
184      try {
185        if (Content.SnapshotTimes.Any())
186          snapshotsTextBox.Text = string.Join(" ; ", Content.SnapshotTimes.Select(x => TimeSpanHelper.FormatNatural(x, true)));
187        else snapshotsTextBox.Text = String.Empty;
188      } finally { SuppressEvents = false; }
189    }
190    #endregion
191
192    #region Control events
193    private void timeLimitTextBox_Validating(object sender, CancelEventArgs e) {
194      if (SuppressEvents) return;
195      TimeSpan ts;
196      if (!TimeSpanHelper.TryGetFromNaturalFormat(timeLimitTextBox.Text, out ts)) {
197        e.Cancel = !timeLimitTextBox.ReadOnly && timeLimitTextBox.Enabled;
198        errorProvider.SetError(timeLimitTextBox, "Please enter a valid time span, e.g. 20 seconds ; 45s ; 4min ; 1h ; 3 hours ; 2 days ; 4d");
199      } else {
200        Content.MaximumExecutionTime = ts;
201        e.Cancel = false;
202        errorProvider.SetError(timeLimitTextBox, null);
203      }
204    }
205
206    private void snapshotsTextBox_Validating(object sender, CancelEventArgs e) {
207      if (SuppressEvents) return;
208      e.Cancel = false;
209      errorProvider.SetError(snapshotsTextBox, null);
210
211      var snapshotTimes = new ObservableList<TimeSpan>();
212      var matches = Regex.Matches(snapshotsTextBox.Text, @"(\d+[ ;,\t]*\w+)");
213      foreach (Match m in matches) {
214        TimeSpan value;
215        if (!TimeSpanHelper.TryGetFromNaturalFormat(m.Value, out value)) {
216          e.Cancel = !snapshotsTextBox.ReadOnly && snapshotsTextBox.Enabled; // don't cancel an operation that cannot be edited
217          errorProvider.SetError(snapshotsTextBox, "Error parsing " + m.Value + ", please provide a valid time span, e.g. 20 seconds ; 45s ; 4min ; 1h ; 3 hours ; 2 days ; 4d");
218          return;
219        } else {
220          snapshotTimes.Add(value);
221        }
222      }
223      Content.SnapshotTimes = snapshotTimes;
224    }
225
226    private void storeAlgorithmInEachSnapshotCheckBox_CheckedChanged(object sender, EventArgs e) {
227      if (SuppressEvents) return;
228      SuppressEvents = true;
229      try {
230        Content.StoreAlgorithmInEachSnapshot = storeAlgorithmInEachSnapshotCheckBox.Checked;
231      } finally { SuppressEvents = false; }
232    }
233
234    private void newAlgorithmButton_Click(object sender, EventArgs e) {
235      if (algorithmTypeSelectorDialog == null) {
236        algorithmTypeSelectorDialog = new TypeSelectorDialog { Caption = "Select Algorithm" };
237        algorithmTypeSelectorDialog.TypeSelector.Caption = "Available Algorithms";
238        algorithmTypeSelectorDialog.TypeSelector.Configure(typeof(IAlgorithm), false, true);
239      }
240      if (algorithmTypeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
241        try {
242          Content.Algorithm = (IAlgorithm)algorithmTypeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
243        } catch (Exception ex) {
244          ErrorHandling.ShowErrorDialog(this, ex);
245        }
246      }
247    }
248
249    private void openAlgorithmButton_Click(object sender, EventArgs e) {
250      openFileDialog.Title = "Open Algorithm";
251      if (openFileDialog.ShowDialog(this) == DialogResult.OK) {
252        newAlgorithmButton.Enabled = openAlgorithmButton.Enabled = false;
253        algorithmViewHost.Enabled = false;
254
255        ContentManager.LoadAsync(openFileDialog.FileName, delegate(IStorableContent content, Exception error) {
256          try {
257            if (error != null) throw error;
258            var algorithm = content as IAlgorithm;
259            if (algorithm == null)
260              MessageBox.Show(this, "The selected file does not contain an algorithm.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error);
261            else
262              Content.Algorithm = algorithm;
263          } catch (Exception ex) {
264            ErrorHandling.ShowErrorDialog(this, ex);
265          } finally {
266            Invoke(new Action(delegate() {
267              algorithmViewHost.Enabled = true;
268              newAlgorithmButton.Enabled = openAlgorithmButton.Enabled = true;
269            }));
270          }
271        });
272      }
273    }
274
275    private void algorithmTabPage_DragEnterOver(object sender, DragEventArgs e) {
276      e.Effect = DragDropEffects.None;
277      if (!ReadOnly && (e.Data.GetData(Constants.DragDropDataFormat) is IAlgorithm)) {
278        if ((e.KeyState & 32) == 32) e.Effect = DragDropEffects.Link;  // ALT key
279        else if ((e.KeyState & 4) == 4) e.Effect = DragDropEffects.Move;  // SHIFT key
280        else if (e.AllowedEffect.HasFlag(DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy;
281        else if (e.AllowedEffect.HasFlag(DragDropEffects.Move)) e.Effect = DragDropEffects.Move;
282        else if (e.AllowedEffect.HasFlag(DragDropEffects.Link)) e.Effect = DragDropEffects.Link;
283      }
284    }
285
286    private void algorithmTabPage_DragDrop(object sender, DragEventArgs e) {
287      if (e.Effect != DragDropEffects.None) {
288        var algorithm = e.Data.GetData(Constants.DragDropDataFormat) as IAlgorithm;
289        if (e.Effect.HasFlag(DragDropEffects.Copy)) algorithm = (IAlgorithm)algorithm.Clone();
290        Content.Algorithm = algorithm;
291      }
292    }
293
294    private void snapshotButton_Click(object sender, EventArgs e) {
295      Content.Snapshot();
296    }
297
298    private void sequenceButton_Click(object sender, EventArgs e) {
299      using (var dialog = new DefineArithmeticTimeSpanProgressionDialog(TimeSpan.FromSeconds(1), Content.MaximumExecutionTime, TimeSpan.FromSeconds(1))) {
300        if (dialog.ShowDialog() == DialogResult.OK) {
301          if (dialog.Values.Any())
302            Content.SnapshotTimes = new ObservableList<TimeSpan>(dialog.Values);
303          else Content.SnapshotTimes = new ObservableList<TimeSpan>();
304        }
305      }
306    }
307    #endregion
308    #endregion
309  }
310}
Note: See TracBrowser for help on using the repository browser.