Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6515 was 6515, checked in by gkronber, 13 years ago

#1570: handled exception in auto-updating mechanism when no internet connection is available.

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