Free cookie consent management tool by TermsFeed Policy Generator

source: branches/RuntimeOptimizer/HeuristicLab.Optimization.Views/3.3/TimeLimitRunView.cs @ 8955

Last change on this file since 8955 was 8955, checked in by abeham, 11 years ago

#1985: Added optimizer and view

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