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

Last change on this file since 6518 was 6518, checked in by gkronber, 10 years ago

#1536 enabled the plugin manager for every user again but removed the first tab which allowed to update all installed plugins as this is accomplished by the auto-updating mechanism now.

File size: 11.9 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      FileVersionInfo pluginInfrastructureVersion = FileVersionInfo.GetVersionInfo(GetType().Assembly.Location);
199      pluginManagerListViewItem = new ListViewItem(pluginManagerItemName, 0);
200      pluginManagerListViewItem.Group = applicationsListView.Groups["Plugin Management"];
201      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, pluginInfrastructureVersion.FileVersion));
202      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, "Install, upgrade or delete plugins"));
203      pluginManagerListViewItem.ToolTipText = "Install, upgrade or delete plugins";
204
205      applicationsListView.Items.Add(pluginManagerListViewItem);
206    }
207
208    private void AddUpdatePluginsItem() {
209      if (updatesAvailable) {
210        var updateListViewItem = new ListViewItem(updatePluginsItemName, 1);
211        updateListViewItem.Group = applicationsListView.Groups["Plugin Management"];
212        updateListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(updateListViewItem, ""));
213        updateListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(updateListViewItem, "Download and install updates"));
214        updateListViewItem.ToolTipText = "Download and install updates";
215
216        applicationsListView.Items.Add(updateListViewItem);
217      }
218    }
219
220    private void StartApplication(ApplicationDescription app) {
221      splashScreen.Show("Loading " + app.Name);
222      Thread t = new Thread(delegate() {
223        bool stopped = false;
224        do {
225          try {
226            if (!abortRequested) {
227              pluginManager.Run(app);
228            }
229            stopped = true;
230          }
231          catch (Exception ex) {
232            stopped = false;
233            ThreadPool.QueueUserWorkItem(delegate(object exception) { ErrorHandling.ShowErrorDialog(this, (Exception)exception); }, ex);
234            Thread.Sleep(5000); // sleep 5 seconds before autorestart
235          }
236        } while (!abortRequested && !stopped && app.AutoRestart);
237      });
238      t.SetApartmentState(ApartmentState.STA); // needed for the AdvancedOptimizationFrontent
239      t.Start();
240    }
241
242    private void applicationsListView_SelectedIndexChanged(object sender, EventArgs e) {
243      startButton.Enabled = applicationsListView.SelectedItems.Count > 0;
244    }
245
246    private void largeIconsButton_Click(object sender, EventArgs e) {
247      applicationsListView.View = View.LargeIcon;
248    }
249
250    private void detailsButton_Click(object sender, EventArgs e) {
251      applicationsListView.View = View.Details;
252      foreach (ColumnHeader column in applicationsListView.Columns) {
253        if (applicationsListView.Items.Count > 0)
254          column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
255        else column.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
256      }
257    }
258
259    private void MainForm_FormClosing(object sender, FormClosingEventArgs e) {
260      splashScreen.Close();
261      abortRequested = true;
262    }
263
264    private void aboutButton_Click(object sender, EventArgs e) {
265      List<IPluginDescription> plugins = new List<IPluginDescription>(pluginManager.Plugins.OfType<IPluginDescription>());
266      using (var dialog = new AboutDialog(plugins)) {
267        dialog.ShowDialog();
268      }
269    }
270  }
271}
Note: See TracBrowser for help on using the repository browser.