Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1926:

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