Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Optimizer/3.3/StartPage.cs @ 17000

Last change on this file since 17000 was 17000, checked in by gkronber, 5 years ago

#2925: merged r16992:16997 from trunk to branch

File size: 9.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 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.IO;
25using System.Linq;
26using System.Reflection;
27using System.Threading;
28using System.Windows.Forms;
29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.MainForm;
32
33namespace HeuristicLab.Optimizer {
34  [View("Start Page")]
35  public partial class StartPage : HeuristicLab.MainForm.WindowsForms.View {
36    private const string StandardProblemsGroupName = "Standard Problems";
37    private const string DataAnalysisGroupName = "Data Analysis";
38    private const string ScriptsGroupName = "Scripts";
39    private const string UncategorizedGroupName = "Uncategorized";
40    private const string SampleNamePrefix = "HeuristicLab.Optimizer.Documents.";
41    private const string SampleNameSuffix = ".hl";
42
43    private readonly Dictionary<ListViewGroup, List<string>> groupLookup = new Dictionary<ListViewGroup, List<string>>();
44    private readonly ListViewGroup standardProblemsGroup = new ListViewGroup(StandardProblemsGroupName);
45    private readonly ListViewGroup dataAnalysisGroup = new ListViewGroup(DataAnalysisGroupName);
46    private readonly ListViewGroup scriptsGroup = new ListViewGroup(ScriptsGroupName);
47    private readonly ListViewGroup uncategorizedGroup = new ListViewGroup(UncategorizedGroupName);
48
49    private IProgress progress;
50
51    public StartPage() {
52      InitializeComponent();
53    }
54
55    protected override void OnInitialized(EventArgs e) {
56      base.OnInitialized(e);
57      Assembly assembly = Assembly.GetExecutingAssembly();
58      AssemblyFileVersionAttribute version = assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true).
59                                             Cast<AssemblyFileVersionAttribute>().FirstOrDefault();
60      titleLabel.Text = "HeuristicLab Optimizer";
61      if (version != null) titleLabel.Text += " " + version.Version;
62
63      try {
64        using (Stream stream = assembly.GetManifestResourceStream(typeof(StartPage), "Documents.FirstSteps.rtf"))
65          firstStepsRichTextBox.LoadFile(stream, RichTextBoxStreamType.RichText);
66      } catch (Exception) { }
67
68      samplesListView.Enabled = false;
69      samplesListView.Groups.Add(standardProblemsGroup);
70      samplesListView.Groups.Add(dataAnalysisGroup);
71      samplesListView.Groups.Add(scriptsGroup);
72      samplesListView.Groups.Add(uncategorizedGroup);
73      FillGroupLookup();
74
75      showStartPageCheckBox.Checked = Properties.Settings.Default.ShowStartPage;
76
77      ThreadPool.QueueUserWorkItem(new WaitCallback(LoadSamples));
78    }
79
80    protected override void OnClosing(FormClosingEventArgs e) {
81      base.OnClosing(e);
82      if (e.CloseReason == CloseReason.UserClosing) {
83        e.Cancel = true;
84        this.Hide();
85      }
86    }
87
88    private void LoadSamples(object state) {
89      progress = Progress.ShowOnControl(samplesListView, "Loading...");
90      try {
91        var assembly = Assembly.GetExecutingAssembly();
92        var samples = assembly.GetManifestResourceNames().Where(x => x.EndsWith(SampleNameSuffix));
93        int count = samples.Count();
94
95        foreach (var entry in groupLookup) {
96          var group = entry.Key;
97          var sampleList = entry.Value;
98          foreach (var sampleName in sampleList) {
99            string resourceName = SampleNamePrefix + sampleName + SampleNameSuffix;
100            LoadSample(resourceName, assembly, group, count);
101          }
102        }
103
104        var categorizedSamples = groupLookup.Select(x => x.Value).SelectMany(x => x).Select(x => SampleNamePrefix + x + SampleNameSuffix);
105        var uncategorizedSamples = samples.Except(categorizedSamples);
106
107        foreach (var resourceName in uncategorizedSamples) {
108          LoadSample(resourceName, assembly, uncategorizedGroup, count);
109        }
110
111        OnAllSamplesLoaded();
112      } finally {
113        Progress.HideFromControl(samplesListView);
114      }
115    }
116
117    private void LoadSample(string name, Assembly assembly, ListViewGroup group, int count) {
118      string path = Path.GetTempFileName();
119      try {
120        using (var stream = assembly.GetManifestResourceStream(name)) {
121          WriteStreamToTempFile(stream, path); // create a file in a temporary folder (persistence cannot load these files directly from the stream)
122          var item = (INamedItem)ContentManager.Load(path);
123          OnSampleLoaded(item, group, 1.0 / count);
124        }
125      } catch (Exception) {
126      } finally {
127        if (File.Exists(path)) {
128          File.Delete(path); // make sure we remove the temporary file
129        }
130      }
131    }
132
133    private void FillGroupLookup() {
134      var standardProblems = new List<string> { "ALPSGA_TSP", "ES_Griewank", "OSES_Griewank", "GA_Grouping", "GA_TSP", "GA_VRP", "GE_ArtificialAnt",
135                "IslandGA_TSP", "LS_Knapsack", "PSO_Rastrigin", "RAPGA_JSSP",
136                "SA_Rastrigin", "SGP_SantaFe", "GP_Multiplexer", "SGP_Robocode", "SS_VRP", "TS_TSP", "TS_VRP", "VNS_OP", "VNS_TSP", "GA_BPP"
137        };
138      groupLookup[standardProblemsGroup] = standardProblems;
139      var dataAnalysisProblems = new List<string> { "ALPSGP_SymReg", "SGP_SymbClass", "SGP_SymbReg", "OSGP_SymReg", "OSGP_TimeSeries", "GE_SymbReg", "GPR" };
140      groupLookup[dataAnalysisGroup] = dataAnalysisProblems;
141      var scripts = new List<string> { "GA_QAP_Script", "GUI_Automation_Script", "OSGA_Rastrigin_Script",
142                                       "GridSearch_RF_Classification_Script", "GridSearch_RF_Regression_Script",
143                                       "GridSearch_SVM_Classification_Script", "GridSearch_SVM_Regression_Script" };
144      groupLookup[scriptsGroup] = scripts;
145    }
146
147    private void OnSampleLoaded(INamedItem sample, ListViewGroup group, double progress) {
148      if (InvokeRequired)
149        Invoke(new Action<INamedItem, ListViewGroup, double>(OnSampleLoaded), sample, group, progress);
150      else {
151        ListViewItem item = new ListViewItem(new string[] { sample.Name, sample.Description }, group);
152        item.ToolTipText = sample.ItemName + ": " + sample.ItemDescription;
153        samplesListView.SmallImageList.Images.Add(sample.ItemImage);
154        item.ImageIndex = samplesListView.SmallImageList.Images.Count - 1;
155        item.Tag = sample;
156        samplesListView.Items.Add(item);
157        this.progress.ProgressValue += progress;
158      }
159    }
160    private void OnAllSamplesLoaded() {
161      if (InvokeRequired)
162        Invoke(new Action(OnAllSamplesLoaded));
163      else {
164        samplesListView.Enabled = samplesListView.Items.Count > 0;
165        if (samplesListView.Items.Count > 0) {
166          for (int i = 0; i < samplesListView.Columns.Count; i++)
167            samplesListView.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
168        }
169      }
170    }
171
172    private void firstStepsRichTextBox_LinkClicked(object sender, LinkClickedEventArgs e) {
173      System.Diagnostics.Process.Start(e.LinkText);
174    }
175
176    private void samplesListView_DoubleClick(object sender, EventArgs e) {
177      if (samplesListView.SelectedItems.Count == 1) {
178        var mainForm = MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>();
179        try {
180          mainForm.SetWaitCursor();
181          mainForm.ShowContent((IContent)((IItem)samplesListView.SelectedItems[0].Tag).Clone());
182        } finally {
183          mainForm.ResetWaitCursor();
184        }
185
186      }
187    }
188    private void samplesListView_ItemDrag(object sender, ItemDragEventArgs e) {
189      ListViewItem listViewItem = (ListViewItem)e.Item;
190      IItem item = (IItem)listViewItem.Tag;
191      DataObject data = new DataObject();
192      data.SetData(HeuristicLab.Common.Constants.DragDropDataFormat, item);
193      DragDropEffects result = DoDragDrop(data, DragDropEffects.Copy);
194    }
195
196    private void showStartPageCheckBox_CheckedChanged(object sender, EventArgs e) {
197      Properties.Settings.Default.ShowStartPage = showStartPageCheckBox.Checked;
198      Properties.Settings.Default.Save();
199    }
200
201    #region Helpers
202    private void WriteStreamToTempFile(Stream stream, string path) {
203      using (FileStream output = new FileStream(path, FileMode.Create, FileAccess.Write)) {
204        stream.CopyTo(output);
205      }
206    }
207    #endregion
208  }
209}
Note: See TracBrowser for help on using the repository browser.