Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.PluginInfrastructure/3.3/Starter/StarterForm.cs @ 17698

Last change on this file since 17698 was 17181, checked in by swagner, 5 years ago

#2875: Merged r17180 from trunk to stable

File size: 14.8 KB
RevLine 
[2]1#region License Information
2/* HeuristicLab
[17181]3 * Copyright (C) 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;
[13884]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;
[13884]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());
[11121]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
[13884]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);
[8563]90    }
91
[8748]92    protected override void SetVisibleCore(bool value) {
[8818]93      value &= !(arguments.OfType<HideStarterArgument>().Any() || arguments.OfType<OpenArgument>().Any());
[8748]94      if (!value) HandleArguments();
95      base.SetVisibleCore(value);
[8563]96    }
97
[8748]98    #region Events
99    private void StarterForm_Load(object sender, EventArgs e) {
100      HandleArguments();
101    }
102
103    private void StarterForm_FormClosing(object sender, FormClosingEventArgs e) {
104      splashScreen.Close();
105      abortRequested = true;
[13884]106
107      if (WindowState != FormWindowState.Minimized)
108        Settings.Default.StarterFormWindowState = WindowState;
109      if (WindowState != FormWindowState.Normal) {
110        Settings.Default.StarterFormLocation = RestoreBounds.Location;
111        Settings.Default.StarterFormSize = RestoreBounds.Size;
112      } else if (WindowState == FormWindowState.Normal) {
113        Settings.Default.StarterFormLocation = Location;
114        Settings.Default.StarterFormSize = Size;
115      }
116
117      Settings.Default.Save();
[8748]118    }
119
120    private void applicationsListView_SelectedIndexChanged(object sender, EventArgs e) {
121      startButton.Enabled = applicationsListView.SelectedItems.Count > 0;
122    }
123
[2]124    private void applicationsListView_ItemActivate(object sender, EventArgs e) {
[1394]125      if (applicationsListView.SelectedItems.Count > 0) {
[2]126        ListViewItem selected = applicationsListView.SelectedItems[0];
[6413]127        if (selected.Text == pluginManagerItemName) {
[2922]128          if (pluginManager.Plugins.Any(x => x.PluginState == PluginState.Loaded)) {
129            MessageBox.Show("Installation Manager cannot be started while another HeuristicLab application is active." + Environment.NewLine +
[3573]130              "Please stop all active HeuristicLab applications and try again.", "Plugin Manager",
131              MessageBoxButtons.OK, MessageBoxIcon.Information);
[2922]132          } else {
133            try {
134              Cursor = Cursors.AppStarting;
[4482]135              using (InstallationManagerForm form = new InstallationManagerForm(pluginManager)) {
136                form.ShowDialog(this);
137              }
[3474]138              UpdateApplicationsList();
[2922]139            }
140            finally {
141              Cursor = Cursors.Arrow;
142            }
[1394]143          }
[6413]144        } else if (selected.Text == updatePluginsItemName) {
145          if (pluginManager.Plugins.Any(x => x.PluginState == PluginState.Loaded)) {
146            MessageBox.Show("Updating is not possible while another HeuristicLab application is active." + Environment.NewLine +
147              "Please stop all active HeuristicLab applications and try again.", "Update plugins",
148              MessageBoxButtons.OK, MessageBoxIcon.Information);
149          } else {
150            try {
151              Cursor = Cursors.AppStarting;
152              using (PluginUpdaterForm form = new PluginUpdaterForm(pluginManager)) {
153                form.ShowDialog(this);
154              }
[6554]155              updatesAvailable = false;
156              CheckUpdatesAvailableAsync();
[6413]157              UpdateApplicationsList();
158            }
159            finally {
160              Cursor = Cursors.Arrow;
161            }
162          }
[2]163        } else {
[2481]164          ApplicationDescription app = (ApplicationDescription)applicationsListView.SelectedItems[0].Tag;
[8818]165          StartApplication(app, arguments);
[2]166        }
167      }
168    }
169
[8748]170    private void largeIconsButton_Click(object sender, EventArgs e) {
171      applicationsListView.View = View.LargeIcon;
172    }
173
174    private void detailsButton_Click(object sender, EventArgs e) {
175      applicationsListView.View = View.Details;
176      foreach (ColumnHeader column in applicationsListView.Columns) {
177        if (applicationsListView.Items.Count > 0)
178          column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
179        else column.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
180      }
181    }
182
183    private void aboutButton_Click(object sender, EventArgs e) {
184      List<IPluginDescription> plugins = new List<IPluginDescription>(pluginManager.Plugins.OfType<IPluginDescription>());
185      using (var dialog = new AboutDialog(plugins)) {
186        dialog.ShowDialog();
187      }
188    }
189
190    private void splashScreen_VisibleChanged(object sender, EventArgs e) {
191      // close hidden starter form
[8818]192      if (!splashScreen.Visible && arguments != null &&
193           (arguments.OfType<HideStarterArgument>().Any() || arguments.OfType<OpenArgument>().Any()))
[8748]194        Close();
195    }
196    #endregion
197
198    #region Helpers
[13884]199    private bool CheckSavedStarterFormSettings() {
200      var formArea = new Rectangle(Settings.Default.StarterFormLocation, Settings.Default.StarterFormSize);
201      var screenArea = Screen.FromRectangle(formArea).WorkingArea;
202      var overlappingArea = Rectangle.Intersect(formArea, screenArea);
203      bool offLimits = overlappingArea.IsEmpty || overlappingArea.Width * overlappingArea.Height < formArea.Width * formArea.Height * 0.25;
204      return !formArea.IsEmpty && !offLimits;
205    }
206
[3474]207    private void UpdateApplicationsList() {
[6413]208      if (InvokeRequired) Invoke((Action)UpdateApplicationsList);
209      else {
210        applicationsListView.Items.Clear();
211        AddPluginManagerItem();
212        AddUpdatePluginsItem();
[3474]213
[6413]214        foreach (ApplicationDescription info in pluginManager.Applications) {
215          ListViewItem item = new ListViewItem(info.Name, 0);
216          item.Tag = info;
217          item.Group = applicationsListView.Groups["Applications"];
218          item.SubItems.Add(new ListViewItem.ListViewSubItem(item, info.Version.ToString()));
219          item.SubItems.Add(new ListViewItem.ListViewSubItem(item, info.Description));
220          item.ToolTipText = info.Description;
221          applicationsListView.Items.Add(item);
222        }
223        foreach (ColumnHeader column in applicationsListView.Columns) {
224          if (applicationsListView.Items.Count > 0)
225            column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
226          else column.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
227        }
228      }
229    }
[3474]230
[6413]231    private void AddPluginManagerItem() {
[6518]232      pluginManagerListViewItem = new ListViewItem(pluginManagerItemName, 0);
233      pluginManagerListViewItem.Group = applicationsListView.Groups["Plugin Management"];
[11121]234      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, AssemblyHelpers.GetFileVersion(GetType().Assembly)));
[6518]235      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, "Install, upgrade or delete plugins"));
236      pluginManagerListViewItem.ToolTipText = "Install, upgrade or delete plugins";
[6413]237
[6518]238      applicationsListView.Items.Add(pluginManagerListViewItem);
[6413]239    }
240
241    private void AddUpdatePluginsItem() {
242      if (updatesAvailable) {
243        var updateListViewItem = new ListViewItem(updatePluginsItemName, 1);
244        updateListViewItem.Group = applicationsListView.Groups["Plugin Management"];
245        updateListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(updateListViewItem, ""));
246        updateListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(updateListViewItem, "Download and install updates"));
247        updateListViewItem.ToolTipText = "Download and install updates";
248
249        applicationsListView.Items.Add(updateListViewItem);
[3600]250      }
[3474]251    }
252
[8748]253    private void CheckUpdatesAvailableAsync() {
254      string pluginPath = Path.GetFullPath(Application.StartupPath);
255      var task = Task.Factory.StartNew<bool>(() => {
256        var installationManager = new InstallationManager(pluginPath);
257        IEnumerable<IPluginDescription> installedPlugins = pluginManager.Plugins.OfType<IPluginDescription>();
258        var remotePlugins = installationManager.GetRemotePluginList();
259        // if there is a local plugin with same name and same major and minor version then it's an update
260        var pluginsToUpdate = from remotePlugin in remotePlugins
261                              let matchingLocalPlugins = from installedPlugin in installedPlugins
262                                                         where installedPlugin.Name == remotePlugin.Name
263                                                         where installedPlugin.Version.Major == remotePlugin.Version.Major
264                                                         where installedPlugin.Version.Minor == remotePlugin.Version.Minor
265                                                         where Util.IsNewerThan(remotePlugin, installedPlugin)
266                                                         select installedPlugin
267                              where matchingLocalPlugins.Count() > 0
268                              select remotePlugin;
269        return pluginsToUpdate.Count() > 0;
270      });
271      task.ContinueWith(t => {
272        try {
273          t.Wait();
274          updatesAvailable = t.Result;
275          UpdateApplicationsList();
276        }
277        catch (AggregateException ae) {
278          ae.Handle(ex => {
279            if (ex is InstallationManagerException) {
280              // this is expected when no internet connection is available => do nothing
281              return true;
282            } else {
283              return false;
284            }
285          });
286        }
287      });
288    }
289
290    private void HandleArguments() {
291      try {
[8818]292        if (arguments.OfType<OpenArgument>().Any() && !arguments.OfType<StartArgument>().Any()) {
293          InitiateApplicationStart(optimizerItemName);
294        }
[8748]295        foreach (var argument in arguments) {
296          if (argument is StartArgument) {
[8818]297            var arg = (StartArgument)argument;
298            InitiateApplicationStart(arg.Value);
[8748]299          }
300        }
301      }
302      catch (AggregateException ex) {
303        ErrorHandling.ShowErrorDialog(this, "One or more errors occurred while initializing the application.", ex);
304      }
305    }
306
[8818]307    private void InitiateApplicationStart(string appName) {
308      var appDesc = (from desc in pluginManager.Applications
309                     where desc.Name.Equals(appName)
310                     select desc).SingleOrDefault();
311      if (appDesc != null) {
312        StartApplication(appDesc, arguments);
313      } else {
314        MessageBox.Show("Cannot start application " + appName + ".",
315                        "HeuristicLab",
316                        MessageBoxButtons.OK,
317                        MessageBoxIcon.Warning);
318      }
319    }
320
321    private void StartApplication(ApplicationDescription app, ICommandLineArgument[] args) {
[3113]322      splashScreen.Show("Loading " + app.Name);
[2507]323      Thread t = new Thread(delegate() {
324        bool stopped = false;
325        do {
326          try {
[2922]327            if (!abortRequested) {
[8818]328              pluginManager.Run(app, args);
[2922]329            }
[2507]330            stopped = true;
331          }
332          catch (Exception ex) {
333            stopped = false;
[3758]334            ThreadPool.QueueUserWorkItem(delegate(object exception) { ErrorHandling.ShowErrorDialog(this, (Exception)exception); }, ex);
[2507]335            Thread.Sleep(5000); // sleep 5 seconds before autorestart
336          }
337        } while (!abortRequested && !stopped && app.AutoRestart);
338      });
339      t.SetApartmentState(ApartmentState.STA); // needed for the AdvancedOptimizationFrontent
340      t.Start();
341    }
[8748]342    #endregion
[2]343  }
344}
Note: See TracBrowser for help on using the repository browser.