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
RevLine 
[2]1#region License Information
2/* HeuristicLab
[15583]3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[2]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;
[13586]24using System.Drawing;
[4068]25using System.IO;
26using System.Linq;
[2]27using System.Threading;
[8563]28using System.Threading.Tasks;
[4068]29using System.Windows.Forms;
30using HeuristicLab.PluginInfrastructure.Advanced;
[2481]31using HeuristicLab.PluginInfrastructure.Manager;
[13586]32using HeuristicLab.PluginInfrastructure.Properties;
[2]33
[2527]34namespace HeuristicLab.PluginInfrastructure.Starter {
[3092]35  /// <summary>
36  /// The starter form is responsible for initializing the plugin infrastructure
37  /// and shows a list of installed applications.
38  /// </summary>
[2507]39  public partial class StarterForm : Form {
[6413]40    private const string pluginManagerItemName = "Plugin Manager";
41    private const string updatePluginsItemName = "Updates Available";
[8818]42    private const string optimizerItemName = "Optimizer";
[2]43
[8748]44    private readonly ICommandLineArgument[] arguments;
[6413]45
[2]46    private ListViewItem pluginManagerListViewItem;
[1392]47    private bool abortRequested;
[2488]48    private PluginManager pluginManager;
[3113]49    private SplashScreen splashScreen;
[6413]50    private bool updatesAvailable = false;
[8563]51
[3092]52    /// <summary>
53    /// Initializes an instance of the starter form.
54    /// The starter form shows a splashscreen and initializes the plugin infrastructure.
55    /// </summary>
[2507]56    public StarterForm()
[2481]57      : base() {
58      InitializeComponent();
[3748]59      largeImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.HeuristicLab.ToBitmap());
[6413]60      largeImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.UpdateAvailable.ToBitmap());
[3748]61      smallImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.HeuristicLab.ToBitmap());
[6413]62      smallImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.UpdateAvailable.ToBitmap());
[11113]63      Text = "HeuristicLab " + AssemblyHelpers.GetFileVersion(GetType().Assembly);
[2481]64
[2748]65      string pluginPath = Path.GetFullPath(Application.StartupPath);
[2495]66      pluginManager = new PluginManager(pluginPath);
[3113]67      splashScreen = new SplashScreen(pluginManager, 1000);
[8748]68      splashScreen.VisibleChanged += new EventHandler(splashScreen_VisibleChanged);
[3736]69      splashScreen.Show(this, "Loading HeuristicLab...");
[2]70
[13586]71      if (CheckSavedStarterFormSettings()) {
72        Location = Settings.Default.StarterFormLocation;
73        Size = Settings.Default.StarterFormSize;
74        WindowState = Settings.Default.StarterFormWindowState;
75      }
76
[2497]77      pluginManager.DiscoverAndCheckPlugins();
[3474]78      UpdateApplicationsList();
[6413]79
[6554]80      CheckUpdatesAvailableAsync();
[2]81    }
82
[3092]83    /// <summary>
[8563]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() {
[8748]89      arguments = CommandLineArgumentHandling.GetArguments(args);
[16102]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();
[8563]115    }
116
[8748]117    protected override void SetVisibleCore(bool value) {
[8818]118      value &= !(arguments.OfType<HideStarterArgument>().Any() || arguments.OfType<OpenArgument>().Any());
[8748]119      if (!value) HandleArguments();
120      base.SetVisibleCore(value);
[8563]121    }
122
[8748]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;
[13586]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();
[8748]143    }
144
145    private void applicationsListView_SelectedIndexChanged(object sender, EventArgs e) {
146      startButton.Enabled = applicationsListView.SelectedItems.Count > 0;
147    }
148
[2]149    private void applicationsListView_ItemActivate(object sender, EventArgs e) {
[1394]150      if (applicationsListView.SelectedItems.Count > 0) {
[2]151        ListViewItem selected = applicationsListView.SelectedItems[0];
[6413]152        if (selected.Text == pluginManagerItemName) {
[2922]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 +
[3573]155              "Please stop all active HeuristicLab applications and try again.", "Plugin Manager",
156              MessageBoxButtons.OK, MessageBoxIcon.Information);
[2922]157          } else {
158            try {
159              Cursor = Cursors.AppStarting;
[4482]160              using (InstallationManagerForm form = new InstallationManagerForm(pluginManager)) {
161                form.ShowDialog(this);
162              }
[3474]163              UpdateApplicationsList();
[2922]164            }
165            finally {
166              Cursor = Cursors.Arrow;
167            }
[1394]168          }
[6413]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              }
[6554]180              updatesAvailable = false;
181              CheckUpdatesAvailableAsync();
[6413]182              UpdateApplicationsList();
183            }
184            finally {
185              Cursor = Cursors.Arrow;
186            }
187          }
[2]188        } else {
[2481]189          ApplicationDescription app = (ApplicationDescription)applicationsListView.SelectedItems[0].Tag;
[8818]190          StartApplication(app, arguments);
[2]191        }
192      }
193    }
194
[8748]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
[8818]217      if (!splashScreen.Visible && arguments != null &&
218           (arguments.OfType<HideStarterArgument>().Any() || arguments.OfType<OpenArgument>().Any()))
[8748]219        Close();
220    }
221    #endregion
222
223    #region Helpers
[13586]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
[3474]232    private void UpdateApplicationsList() {
[6413]233      if (InvokeRequired) Invoke((Action)UpdateApplicationsList);
234      else {
235        applicationsListView.Items.Clear();
236        AddPluginManagerItem();
237        AddUpdatePluginsItem();
[3474]238
[6413]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    }
[3474]255
[6413]256    private void AddPluginManagerItem() {
[6518]257      pluginManagerListViewItem = new ListViewItem(pluginManagerItemName, 0);
258      pluginManagerListViewItem.Group = applicationsListView.Groups["Plugin Management"];
[11113]259      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, AssemblyHelpers.GetFileVersion(GetType().Assembly)));
[6518]260      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, "Install, upgrade or delete plugins"));
261      pluginManagerListViewItem.ToolTipText = "Install, upgrade or delete plugins";
[6413]262
[6518]263      applicationsListView.Items.Add(pluginManagerListViewItem);
[6413]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);
[3600]275      }
[3474]276    }
277
[8748]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 {
[8818]317        if (arguments.OfType<OpenArgument>().Any() && !arguments.OfType<StartArgument>().Any()) {
318          InitiateApplicationStart(optimizerItemName);
319        }
[8748]320        foreach (var argument in arguments) {
321          if (argument is StartArgument) {
[8818]322            var arg = (StartArgument)argument;
323            InitiateApplicationStart(arg.Value);
[8748]324          }
325        }
326      }
327      catch (AggregateException ex) {
328        ErrorHandling.ShowErrorDialog(this, "One or more errors occurred while initializing the application.", ex);
329      }
330    }
331
[8818]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) {
[16102]347      if (args.All(x => !(x is HideStarterArgument)))
348        splashScreen.Show("Loading " + app.Name);
[2507]349      Thread t = new Thread(delegate() {
350        bool stopped = false;
351        do {
352          try {
[2922]353            if (!abortRequested) {
[8818]354              pluginManager.Run(app, args);
[2922]355            }
[2507]356            stopped = true;
357          }
358          catch (Exception ex) {
359            stopped = false;
[3758]360            ThreadPool.QueueUserWorkItem(delegate(object exception) { ErrorHandling.ShowErrorDialog(this, (Exception)exception); }, ex);
[2507]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    }
[8748]368    #endregion
[2]369  }
370}
Note: See TracBrowser for help on using the repository browser.