Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.PluginInfrastructure/3.3/Starter/StarterForm.cs @ 9456

Last change on this file since 9456 was 9456, checked in by swagner, 11 years ago

Updated copyright year and added some missing license headers (#1889)

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