Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GP-MoveOperators/HeuristicLab.PluginInfrastructure/3.3/Starter/StarterForm.cs @ 8660

Last change on this file since 8660 was 8660, checked in by gkronber, 12 years ago

#1847 merged r8205:8635 from trunk into branch

File size: 13.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Threading.Tasks;
29using System.Windows.Forms;
30using HeuristicLab.PluginInfrastructure.Advanced;
31using HeuristicLab.PluginInfrastructure.Manager;
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    private string[] arguments;
49
50    /// <summary>
51    /// Initializes an instance of the starter form.
52    /// The starter form shows a splashscreen and initializes the plugin infrastructure.
53    /// </summary>
54    public StarterForm()
55      : base() {
56      InitializeComponent();
57      largeImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.HeuristicLab.ToBitmap());
58      largeImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.UpdateAvailable.ToBitmap());
59      smallImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.HeuristicLab.ToBitmap());
60      smallImageList.Images.Add(HeuristicLab.PluginInfrastructure.Resources.UpdateAvailable.ToBitmap());
61      FileVersionInfo pluginInfrastructureVersion = FileVersionInfo.GetVersionInfo(GetType().Assembly.Location);
62      Text = "HeuristicLab " + pluginInfrastructureVersion.FileVersion;
63
64      string pluginPath = Path.GetFullPath(Application.StartupPath);
65      pluginManager = new PluginManager(pluginPath);
66      splashScreen = new SplashScreen(pluginManager, 1000);
67      splashScreen.Show(this, "Loading HeuristicLab...");
68
69      pluginManager.DiscoverAndCheckPlugins();
70      UpdateApplicationsList();
71
72      CheckUpdatesAvailableAsync();
73    }
74
75    private void CheckUpdatesAvailableAsync() {
76      string pluginPath = Path.GetFullPath(Application.StartupPath);
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 => {
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;
104            } else {
105              return false;
106            }
107          });
108        }
109      });
110    }
111
112    /// <summary>
113    /// Creates a new StarterForm and tries to start application with <paramref name="appName"/> immediately.
114    /// </summary>
115    /// <param name="appName">Name of the application</param>
116    public StarterForm(string appName)
117      : this() {
118      var appDesc = (from desc in pluginManager.Applications
119                     where desc.Name == appName
120                     select desc).SingleOrDefault();
121      if (appDesc != null) {
122        StartApplication(appDesc);
123      } else {
124        MessageBox.Show("Cannot start application " + appName + ".",
125                        "HeuristicLab",
126                        MessageBoxButtons.OK,
127                        MessageBoxIcon.Warning);
128      }
129    }
130
131    /// <summary>
132    /// Creates a new StarterForm and passes the arguments in <paramref name="args"/>.
133    /// </summary>
134    /// <param name="args">The arguments that should be processed</param>
135    public StarterForm(string[] args)
136      : this() {
137      this.arguments = args;
138    }
139
140    private void StarterForm_Shown(object sender, EventArgs e) {
141      foreach (var argument in ArgumentHandling.GetArguments(arguments)) {
142        if (argument is StartArgument) {
143          var appDesc = (from desc in pluginManager.Applications
144                         where desc.Name == argument.Value
145                         select desc).SingleOrDefault();
146          if (appDesc != null) {
147            StartApplication(appDesc);
148          } else {
149            MessageBox.Show("Cannot start application " + argument.Value + ".",
150                            "HeuristicLab",
151                            MessageBoxButtons.OK,
152                            MessageBoxIcon.Warning);
153          }
154        }
155      }
156    }
157
158    private void applicationsListView_ItemActivate(object sender, EventArgs e) {
159      if (applicationsListView.SelectedItems.Count > 0) {
160        ListViewItem selected = applicationsListView.SelectedItems[0];
161        if (selected.Text == pluginManagerItemName) {
162          if (pluginManager.Plugins.Any(x => x.PluginState == PluginState.Loaded)) {
163            MessageBox.Show("Installation Manager cannot be started while another HeuristicLab application is active." + Environment.NewLine +
164              "Please stop all active HeuristicLab applications and try again.", "Plugin Manager",
165              MessageBoxButtons.OK, MessageBoxIcon.Information);
166          } else {
167            try {
168              Cursor = Cursors.AppStarting;
169              using (InstallationManagerForm form = new InstallationManagerForm(pluginManager)) {
170                form.ShowDialog(this);
171              }
172              UpdateApplicationsList();
173            }
174            finally {
175              Cursor = Cursors.Arrow;
176            }
177          }
178        } else if (selected.Text == updatePluginsItemName) {
179          if (pluginManager.Plugins.Any(x => x.PluginState == PluginState.Loaded)) {
180            MessageBox.Show("Updating is not possible while another HeuristicLab application is active." + Environment.NewLine +
181              "Please stop all active HeuristicLab applications and try again.", "Update plugins",
182              MessageBoxButtons.OK, MessageBoxIcon.Information);
183          } else {
184            try {
185              Cursor = Cursors.AppStarting;
186              using (PluginUpdaterForm form = new PluginUpdaterForm(pluginManager)) {
187                form.ShowDialog(this);
188              }
189              updatesAvailable = false;
190              CheckUpdatesAvailableAsync();
191              UpdateApplicationsList();
192            }
193            finally {
194              Cursor = Cursors.Arrow;
195            }
196          }
197        } else {
198          ApplicationDescription app = (ApplicationDescription)applicationsListView.SelectedItems[0].Tag;
199          StartApplication(app);
200        }
201      }
202    }
203
204    private void UpdateApplicationsList() {
205      if (InvokeRequired) Invoke((Action)UpdateApplicationsList);
206      else {
207        applicationsListView.Items.Clear();
208        AddPluginManagerItem();
209        AddUpdatePluginsItem();
210
211        foreach (ApplicationDescription info in pluginManager.Applications) {
212          ListViewItem item = new ListViewItem(info.Name, 0);
213          item.Tag = info;
214          item.Group = applicationsListView.Groups["Applications"];
215          item.SubItems.Add(new ListViewItem.ListViewSubItem(item, info.Version.ToString()));
216          item.SubItems.Add(new ListViewItem.ListViewSubItem(item, info.Description));
217          item.ToolTipText = info.Description;
218          applicationsListView.Items.Add(item);
219        }
220        foreach (ColumnHeader column in applicationsListView.Columns) {
221          if (applicationsListView.Items.Count > 0)
222            column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
223          else column.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
224        }
225      }
226    }
227
228    private void AddPluginManagerItem() {
229      FileVersionInfo pluginInfrastructureVersion = FileVersionInfo.GetVersionInfo(GetType().Assembly.Location);
230      pluginManagerListViewItem = new ListViewItem(pluginManagerItemName, 0);
231      pluginManagerListViewItem.Group = applicationsListView.Groups["Plugin Management"];
232      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, pluginInfrastructureVersion.FileVersion));
233      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, "Install, upgrade or delete plugins"));
234      pluginManagerListViewItem.ToolTipText = "Install, upgrade or delete plugins";
235
236      applicationsListView.Items.Add(pluginManagerListViewItem);
237    }
238
239    private void AddUpdatePluginsItem() {
240      if (updatesAvailable) {
241        var updateListViewItem = new ListViewItem(updatePluginsItemName, 1);
242        updateListViewItem.Group = applicationsListView.Groups["Plugin Management"];
243        updateListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(updateListViewItem, ""));
244        updateListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(updateListViewItem, "Download and install updates"));
245        updateListViewItem.ToolTipText = "Download and install updates";
246
247        applicationsListView.Items.Add(updateListViewItem);
248      }
249    }
250
251    private void StartApplication(ApplicationDescription app) {
252      splashScreen.Show("Loading " + app.Name);
253      Thread t = new Thread(delegate() {
254        bool stopped = false;
255        do {
256          try {
257            if (!abortRequested) {
258              pluginManager.Run(app);
259            }
260            stopped = true;
261          }
262          catch (Exception ex) {
263            stopped = false;
264            ThreadPool.QueueUserWorkItem(delegate(object exception) { ErrorHandling.ShowErrorDialog(this, (Exception)exception); }, ex);
265            Thread.Sleep(5000); // sleep 5 seconds before autorestart
266          }
267        } while (!abortRequested && !stopped && app.AutoRestart);
268      });
269      t.SetApartmentState(ApartmentState.STA); // needed for the AdvancedOptimizationFrontent
270      t.Start();
271    }
272
273    private void applicationsListView_SelectedIndexChanged(object sender, EventArgs e) {
274      startButton.Enabled = applicationsListView.SelectedItems.Count > 0;
275    }
276
277    private void largeIconsButton_Click(object sender, EventArgs e) {
278      applicationsListView.View = View.LargeIcon;
279    }
280
281    private void detailsButton_Click(object sender, EventArgs e) {
282      applicationsListView.View = View.Details;
283      foreach (ColumnHeader column in applicationsListView.Columns) {
284        if (applicationsListView.Items.Count > 0)
285          column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
286        else column.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
287      }
288    }
289
290    private void StarterForm_FormClosing(object sender, FormClosingEventArgs e) {
291      splashScreen.Close();
292      abortRequested = true;
293    }
294
295    private void aboutButton_Click(object sender, EventArgs e) {
296      List<IPluginDescription> plugins = new List<IPluginDescription>(pluginManager.Plugins.OfType<IPluginDescription>());
297      using (var dialog = new AboutDialog(plugins)) {
298        dialog.ShowDialog();
299      }
300    }
301  }
302}
Note: See TracBrowser for help on using the repository browser.