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
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    private readonly ICommandLineArgument[] arguments;
43
44    private ListViewItem pluginManagerListViewItem;
45    private bool abortRequested;
46    private PluginManager pluginManager;
47    private SplashScreen splashScreen;
48    private bool updatesAvailable = false;
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.VisibleChanged += new EventHandler(splashScreen_VisibleChanged);
68      splashScreen.Show(this, "Loading HeuristicLab...");
69
70      pluginManager.DiscoverAndCheckPlugins();
71      UpdateApplicationsList();
72
73      CheckUpdatesAvailableAsync();
74    }
75
76    /// <summary>
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() {
82      arguments = CommandLineArgumentHandling.GetArguments(args);
83    }
84
85    protected override void SetVisibleCore(bool value) {
86      value &= !arguments.OfType<HideStarterArgument>().Any();
87      if (!value) HandleArguments();
88      base.SetVisibleCore(value);
89    }
90
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
105    private void applicationsListView_ItemActivate(object sender, EventArgs e) {
106      if (applicationsListView.SelectedItems.Count > 0) {
107        ListViewItem selected = applicationsListView.SelectedItems[0];
108        if (selected.Text == pluginManagerItemName) {
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 +
111              "Please stop all active HeuristicLab applications and try again.", "Plugin Manager",
112              MessageBoxButtons.OK, MessageBoxIcon.Information);
113          } else {
114            try {
115              Cursor = Cursors.AppStarting;
116              using (InstallationManagerForm form = new InstallationManagerForm(pluginManager)) {
117                form.ShowDialog(this);
118              }
119              UpdateApplicationsList();
120            }
121            finally {
122              Cursor = Cursors.Arrow;
123            }
124          }
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              }
136              updatesAvailable = false;
137              CheckUpdatesAvailableAsync();
138              UpdateApplicationsList();
139            }
140            finally {
141              Cursor = Cursors.Arrow;
142            }
143          }
144        } else {
145          ApplicationDescription app = (ApplicationDescription)applicationsListView.SelectedItems[0].Tag;
146          StartApplication(app);
147        }
148      }
149    }
150
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
179    private void UpdateApplicationsList() {
180      if (InvokeRequired) Invoke((Action)UpdateApplicationsList);
181      else {
182        applicationsListView.Items.Clear();
183        AddPluginManagerItem();
184        AddUpdatePluginsItem();
185
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    }
202
203    private void AddPluginManagerItem() {
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";
210
211      applicationsListView.Items.Add(pluginManagerListViewItem);
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);
223      }
224    }
225
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
286    private void StartApplication(ApplicationDescription app) {
287      splashScreen.Show("Loading " + app.Name);
288      Thread t = new Thread(delegate() {
289        bool stopped = false;
290        do {
291          try {
292            if (!abortRequested) {
293              pluginManager.Run(app);
294            }
295            stopped = true;
296          }
297          catch (Exception ex) {
298            stopped = false;
299            ThreadPool.QueueUserWorkItem(delegate(object exception) { ErrorHandling.ShowErrorDialog(this, (Exception)exception); }, ex);
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    }
307    #endregion
308  }
309}
Note: See TracBrowser for help on using the repository browser.