Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 8701 was 8677, checked in by jkarder, 12 years ago

#1926: refactored argument handling infrastructure based on the changes suggested by ascheibe in comment:7:ticket:1926

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