Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2213_irace/HeuristicLab.PluginInfrastructure/3.3/Starter/StarterForm.cs @ 17514

Last change on this file since 17514 was 16102, checked in by abeham, 6 years ago

#2213: some pending changes exploring the topic

File size: 16.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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.Drawing;
25using System.IO;
26using System.Linq;
27using System.Threading;
28using System.Threading.Tasks;
29using System.Windows.Forms;
30using HeuristicLab.PluginInfrastructure.Advanced;
31using HeuristicLab.PluginInfrastructure.Manager;
32using HeuristicLab.PluginInfrastructure.Properties;
33
34namespace HeuristicLab.PluginInfrastructure.Starter {
35  /// <summary>
36  /// The starter form is responsible for initializing the plugin infrastructure
37  /// and shows a list of installed applications.
38  /// </summary>
39  public partial class StarterForm : Form {
40    private const string pluginManagerItemName = "Plugin Manager";
41    private const string updatePluginsItemName = "Updates Available";
42    private const string optimizerItemName = "Optimizer";
43
44    private readonly ICommandLineArgument[] arguments;
45
46    private ListViewItem pluginManagerListViewItem;
47    private bool abortRequested;
48    private PluginManager pluginManager;
49    private SplashScreen splashScreen;
50    private bool updatesAvailable = false;
51
52    /// <summary>
53    /// Initializes an instance of the starter form.
54    /// The starter form shows a splashscreen and initializes the plugin infrastructure.
55    /// </summary>
56    public StarterForm()
57      : base() {
58      InitializeComponent();
59      largeImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.HeuristicLab.ToBitmap());
60      largeImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.UpdateAvailable.ToBitmap());
61      smallImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.HeuristicLab.ToBitmap());
62      smallImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.UpdateAvailable.ToBitmap());
63      Text = "HeuristicLab " + AssemblyHelpers.GetFileVersion(GetType().Assembly);
64
65      string pluginPath = Path.GetFullPath(Application.StartupPath);
66      pluginManager = new PluginManager(pluginPath);
67      splashScreen = new SplashScreen(pluginManager, 1000);
68      splashScreen.VisibleChanged += new EventHandler(splashScreen_VisibleChanged);
69      splashScreen.Show(this, "Loading HeuristicLab...");
70
71      if (CheckSavedStarterFormSettings()) {
72        Location = Settings.Default.StarterFormLocation;
73        Size = Settings.Default.StarterFormSize;
74        WindowState = Settings.Default.StarterFormWindowState;
75      }
76
77      pluginManager.DiscoverAndCheckPlugins();
78      UpdateApplicationsList();
79
80      CheckUpdatesAvailableAsync();
81    }
82
83    /// <summary>
84    /// Creates a new StarterForm and passes the arguments in <paramref name="args"/>.
85    /// </summary>
86    /// <param name="args">The arguments that should be processed</param>
87    public StarterForm(string[] args)
88      : this() {
89      arguments = CommandLineArgumentHandling.GetArguments(args);
90
91      InitializeComponent();
92      largeImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.HeuristicLab.ToBitmap());
93      largeImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.UpdateAvailable.ToBitmap());
94      smallImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.HeuristicLab.ToBitmap());
95      smallImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.UpdateAvailable.ToBitmap());
96      Text = "HeuristicLab " + AssemblyHelpers.GetFileVersion(GetType().Assembly);
97
98      string pluginPath = Path.GetFullPath(Application.StartupPath);
99      pluginManager = new PluginManager(pluginPath);
100      splashScreen = new SplashScreen(pluginManager, 1000);
101      splashScreen.VisibleChanged += new EventHandler(splashScreen_VisibleChanged);
102      if (arguments.All(x => !(x is HideStarterArgument)))
103        splashScreen.Show(this, "Loading HeuristicLab...");
104
105      if (CheckSavedStarterFormSettings()) {
106        Location = Settings.Default.StarterFormLocation;
107        Size = Settings.Default.StarterFormSize;
108        WindowState = Settings.Default.StarterFormWindowState;
109      }
110
111      pluginManager.DiscoverAndCheckPlugins();
112      UpdateApplicationsList();
113
114      CheckUpdatesAvailableAsync();
115    }
116
117    protected override void SetVisibleCore(bool value) {
118      value &= !(arguments.OfType<HideStarterArgument>().Any() || arguments.OfType<OpenArgument>().Any());
119      if (!value) HandleArguments();
120      base.SetVisibleCore(value);
121    }
122
123    #region Events
124    private void StarterForm_Load(object sender, EventArgs e) {
125      HandleArguments();
126    }
127
128    private void StarterForm_FormClosing(object sender, FormClosingEventArgs e) {
129      splashScreen.Close();
130      abortRequested = true;
131
132      if (WindowState != FormWindowState.Minimized)
133        Settings.Default.StarterFormWindowState = WindowState;
134      if (WindowState != FormWindowState.Normal) {
135        Settings.Default.StarterFormLocation = RestoreBounds.Location;
136        Settings.Default.StarterFormSize = RestoreBounds.Size;
137      } else if (WindowState == FormWindowState.Normal) {
138        Settings.Default.StarterFormLocation = Location;
139        Settings.Default.StarterFormSize = Size;
140      }
141
142      Settings.Default.Save();
143    }
144
145    private void applicationsListView_SelectedIndexChanged(object sender, EventArgs e) {
146      startButton.Enabled = applicationsListView.SelectedItems.Count > 0;
147    }
148
149    private void applicationsListView_ItemActivate(object sender, EventArgs e) {
150      if (applicationsListView.SelectedItems.Count > 0) {
151        ListViewItem selected = applicationsListView.SelectedItems[0];
152        if (selected.Text == pluginManagerItemName) {
153          if (pluginManager.Plugins.Any(x => x.PluginState == PluginState.Loaded)) {
154            MessageBox.Show("Installation Manager cannot be started while another HeuristicLab application is active." + Environment.NewLine +
155              "Please stop all active HeuristicLab applications and try again.", "Plugin Manager",
156              MessageBoxButtons.OK, MessageBoxIcon.Information);
157          } else {
158            try {
159              Cursor = Cursors.AppStarting;
160              using (InstallationManagerForm form = new InstallationManagerForm(pluginManager)) {
161                form.ShowDialog(this);
162              }
163              UpdateApplicationsList();
164            }
165            finally {
166              Cursor = Cursors.Arrow;
167            }
168          }
169        } else if (selected.Text == updatePluginsItemName) {
170          if (pluginManager.Plugins.Any(x => x.PluginState == PluginState.Loaded)) {
171            MessageBox.Show("Updating is not possible while another HeuristicLab application is active." + Environment.NewLine +
172              "Please stop all active HeuristicLab applications and try again.", "Update plugins",
173              MessageBoxButtons.OK, MessageBoxIcon.Information);
174          } else {
175            try {
176              Cursor = Cursors.AppStarting;
177              using (PluginUpdaterForm form = new PluginUpdaterForm(pluginManager)) {
178                form.ShowDialog(this);
179              }
180              updatesAvailable = false;
181              CheckUpdatesAvailableAsync();
182              UpdateApplicationsList();
183            }
184            finally {
185              Cursor = Cursors.Arrow;
186            }
187          }
188        } else {
189          ApplicationDescription app = (ApplicationDescription)applicationsListView.SelectedItems[0].Tag;
190          StartApplication(app, arguments);
191        }
192      }
193    }
194
195    private void largeIconsButton_Click(object sender, EventArgs e) {
196      applicationsListView.View = View.LargeIcon;
197    }
198
199    private void detailsButton_Click(object sender, EventArgs e) {
200      applicationsListView.View = View.Details;
201      foreach (ColumnHeader column in applicationsListView.Columns) {
202        if (applicationsListView.Items.Count > 0)
203          column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
204        else column.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
205      }
206    }
207
208    private void aboutButton_Click(object sender, EventArgs e) {
209      List<IPluginDescription> plugins = new List<IPluginDescription>(pluginManager.Plugins.OfType<IPluginDescription>());
210      using (var dialog = new AboutDialog(plugins)) {
211        dialog.ShowDialog();
212      }
213    }
214
215    private void splashScreen_VisibleChanged(object sender, EventArgs e) {
216      // close hidden starter form
217      if (!splashScreen.Visible && arguments != null &&
218           (arguments.OfType<HideStarterArgument>().Any() || arguments.OfType<OpenArgument>().Any()))
219        Close();
220    }
221    #endregion
222
223    #region Helpers
224    private bool CheckSavedStarterFormSettings() {
225      var formArea = new Rectangle(Settings.Default.StarterFormLocation, Settings.Default.StarterFormSize);
226      var screenArea = Screen.FromRectangle(formArea).WorkingArea;
227      var overlappingArea = Rectangle.Intersect(formArea, screenArea);
228      bool offLimits = overlappingArea.IsEmpty || overlappingArea.Width * overlappingArea.Height < formArea.Width * formArea.Height * 0.25;
229      return !formArea.IsEmpty && !offLimits;
230    }
231
232    private void UpdateApplicationsList() {
233      if (InvokeRequired) Invoke((Action)UpdateApplicationsList);
234      else {
235        applicationsListView.Items.Clear();
236        AddPluginManagerItem();
237        AddUpdatePluginsItem();
238
239        foreach (ApplicationDescription info in pluginManager.Applications) {
240          ListViewItem item = new ListViewItem(info.Name, 0);
241          item.Tag = info;
242          item.Group = applicationsListView.Groups["Applications"];
243          item.SubItems.Add(new ListViewItem.ListViewSubItem(item, info.Version.ToString()));
244          item.SubItems.Add(new ListViewItem.ListViewSubItem(item, info.Description));
245          item.ToolTipText = info.Description;
246          applicationsListView.Items.Add(item);
247        }
248        foreach (ColumnHeader column in applicationsListView.Columns) {
249          if (applicationsListView.Items.Count > 0)
250            column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
251          else column.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
252        }
253      }
254    }
255
256    private void AddPluginManagerItem() {
257      pluginManagerListViewItem = new ListViewItem(pluginManagerItemName, 0);
258      pluginManagerListViewItem.Group = applicationsListView.Groups["Plugin Management"];
259      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, AssemblyHelpers.GetFileVersion(GetType().Assembly)));
260      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, "Install, upgrade or delete plugins"));
261      pluginManagerListViewItem.ToolTipText = "Install, upgrade or delete plugins";
262
263      applicationsListView.Items.Add(pluginManagerListViewItem);
264    }
265
266    private void AddUpdatePluginsItem() {
267      if (updatesAvailable) {
268        var updateListViewItem = new ListViewItem(updatePluginsItemName, 1);
269        updateListViewItem.Group = applicationsListView.Groups["Plugin Management"];
270        updateListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(updateListViewItem, ""));
271        updateListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(updateListViewItem, "Download and install updates"));
272        updateListViewItem.ToolTipText = "Download and install updates";
273
274        applicationsListView.Items.Add(updateListViewItem);
275      }
276    }
277
278    private void CheckUpdatesAvailableAsync() {
279      string pluginPath = Path.GetFullPath(Application.StartupPath);
280      var task = Task.Factory.StartNew<bool>(() => {
281        var installationManager = new InstallationManager(pluginPath);
282        IEnumerable<IPluginDescription> installedPlugins = pluginManager.Plugins.OfType<IPluginDescription>();
283        var remotePlugins = installationManager.GetRemotePluginList();
284        // if there is a local plugin with same name and same major and minor version then it's an update
285        var pluginsToUpdate = from remotePlugin in remotePlugins
286                              let matchingLocalPlugins = from installedPlugin in installedPlugins
287                                                         where installedPlugin.Name == remotePlugin.Name
288                                                         where installedPlugin.Version.Major == remotePlugin.Version.Major
289                                                         where installedPlugin.Version.Minor == remotePlugin.Version.Minor
290                                                         where Util.IsNewerThan(remotePlugin, installedPlugin)
291                                                         select installedPlugin
292                              where matchingLocalPlugins.Count() > 0
293                              select remotePlugin;
294        return pluginsToUpdate.Count() > 0;
295      });
296      task.ContinueWith(t => {
297        try {
298          t.Wait();
299          updatesAvailable = t.Result;
300          UpdateApplicationsList();
301        }
302        catch (AggregateException ae) {
303          ae.Handle(ex => {
304            if (ex is InstallationManagerException) {
305              // this is expected when no internet connection is available => do nothing
306              return true;
307            } else {
308              return false;
309            }
310          });
311        }
312      });
313    }
314
315    private void HandleArguments() {
316      try {
317        if (arguments.OfType<OpenArgument>().Any() && !arguments.OfType<StartArgument>().Any()) {
318          InitiateApplicationStart(optimizerItemName);
319        }
320        foreach (var argument in arguments) {
321          if (argument is StartArgument) {
322            var arg = (StartArgument)argument;
323            InitiateApplicationStart(arg.Value);
324          }
325        }
326      }
327      catch (AggregateException ex) {
328        ErrorHandling.ShowErrorDialog(this, "One or more errors occurred while initializing the application.", ex);
329      }
330    }
331
332    private void InitiateApplicationStart(string appName) {
333      var appDesc = (from desc in pluginManager.Applications
334                     where desc.Name.Equals(appName)
335                     select desc).SingleOrDefault();
336      if (appDesc != null) {
337        StartApplication(appDesc, arguments);
338      } else {
339        MessageBox.Show("Cannot start application " + appName + ".",
340                        "HeuristicLab",
341                        MessageBoxButtons.OK,
342                        MessageBoxIcon.Warning);
343      }
344    }
345
346    private void StartApplication(ApplicationDescription app, ICommandLineArgument[] args) {
347      if (args.All(x => !(x is HideStarterArgument)))
348        splashScreen.Show("Loading " + app.Name);
349      Thread t = new Thread(delegate() {
350        bool stopped = false;
351        do {
352          try {
353            if (!abortRequested) {
354              pluginManager.Run(app, args);
355            }
356            stopped = true;
357          }
358          catch (Exception ex) {
359            stopped = false;
360            ThreadPool.QueueUserWorkItem(delegate(object exception) { ErrorHandling.ShowErrorDialog(this, (Exception)exception); }, ex);
361            Thread.Sleep(5000); // sleep 5 seconds before autorestart
362          }
363        } while (!abortRequested && !stopped && app.AutoRestart);
364      });
365      t.SetApartmentState(ApartmentState.STA); // needed for the AdvancedOptimizationFrontent
366      t.Start();
367    }
368    #endregion
369  }
370}
Note: See TracBrowser for help on using the repository browser.