Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Optimizer/3.3/StartPage.cs @ 11067

Last change on this file since 11067 was 11067, checked in by jkarder, 10 years ago

#2195: set cursor to 'waiting' while loading samples

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