Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1926: refactored argument handling infrastructure based on the changes suggested by ascheibe in comment:7:ticket:1926

File size: 12.6 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 passes the arguments in <paramref name="args"/>.
114    /// </summary>
115    /// <param name="args">The arguments that should be processed</param>
116    public StarterForm(string[] args)
117      : this() {
118      this.arguments = args;
119    }
120
121    private void StarterForm_Shown(object sender, EventArgs e) {
122      try {
123        foreach (var argument in ArgumentHandling.GetArguments(arguments)) {
124          if (argument.Token == Argument.START) {
125            var appDesc = (from desc in pluginManager.Applications
126                           where desc.Name == argument.Value
127                           select desc).SingleOrDefault();
128            if (appDesc != null) {
129              StartApplication(appDesc);
130            } else {
131              MessageBox.Show("Cannot start application " + argument.Value + ".",
132                              "HeuristicLab",
133                              MessageBoxButtons.OK,
134                              MessageBoxIcon.Warning);
135            }
136          }
137        }
138      }
139      catch (AggregateException ex) {
140        ErrorHandling.ShowErrorDialog(this, "One or more errors occurred while initializing the application.", ex);
141      }
142    }
143
144    private void applicationsListView_ItemActivate(object sender, EventArgs e) {
145      if (applicationsListView.SelectedItems.Count > 0) {
146        ListViewItem selected = applicationsListView.SelectedItems[0];
147        if (selected.Text == pluginManagerItemName) {
148          if (pluginManager.Plugins.Any(x => x.PluginState == PluginState.Loaded)) {
149            MessageBox.Show("Installation Manager cannot be started while another HeuristicLab application is active." + Environment.NewLine +
150              "Please stop all active HeuristicLab applications and try again.", "Plugin Manager",
151              MessageBoxButtons.OK, MessageBoxIcon.Information);
152          } else {
153            try {
154              Cursor = Cursors.AppStarting;
155              using (InstallationManagerForm form = new InstallationManagerForm(pluginManager)) {
156                form.ShowDialog(this);
157              }
158              UpdateApplicationsList();
159            }
160            finally {
161              Cursor = Cursors.Arrow;
162            }
163          }
164        } else if (selected.Text == updatePluginsItemName) {
165          if (pluginManager.Plugins.Any(x => x.PluginState == PluginState.Loaded)) {
166            MessageBox.Show("Updating is not possible while another HeuristicLab application is active." + Environment.NewLine +
167              "Please stop all active HeuristicLab applications and try again.", "Update plugins",
168              MessageBoxButtons.OK, MessageBoxIcon.Information);
169          } else {
170            try {
171              Cursor = Cursors.AppStarting;
172              using (PluginUpdaterForm form = new PluginUpdaterForm(pluginManager)) {
173                form.ShowDialog(this);
174              }
175              updatesAvailable = false;
176              CheckUpdatesAvailableAsync();
177              UpdateApplicationsList();
178            }
179            finally {
180              Cursor = Cursors.Arrow;
181            }
182          }
183        } else {
184          ApplicationDescription app = (ApplicationDescription)applicationsListView.SelectedItems[0].Tag;
185          StartApplication(app);
186        }
187      }
188    }
189
190    private void UpdateApplicationsList() {
191      if (InvokeRequired) Invoke((Action)UpdateApplicationsList);
192      else {
193        applicationsListView.Items.Clear();
194        AddPluginManagerItem();
195        AddUpdatePluginsItem();
196
197        foreach (ApplicationDescription info in pluginManager.Applications) {
198          ListViewItem item = new ListViewItem(info.Name, 0);
199          item.Tag = info;
200          item.Group = applicationsListView.Groups["Applications"];
201          item.SubItems.Add(new ListViewItem.ListViewSubItem(item, info.Version.ToString()));
202          item.SubItems.Add(new ListViewItem.ListViewSubItem(item, info.Description));
203          item.ToolTipText = info.Description;
204          applicationsListView.Items.Add(item);
205        }
206        foreach (ColumnHeader column in applicationsListView.Columns) {
207          if (applicationsListView.Items.Count > 0)
208            column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
209          else column.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
210        }
211      }
212    }
213
214    private void AddPluginManagerItem() {
215      FileVersionInfo pluginInfrastructureVersion = FileVersionInfo.GetVersionInfo(GetType().Assembly.Location);
216      pluginManagerListViewItem = new ListViewItem(pluginManagerItemName, 0);
217      pluginManagerListViewItem.Group = applicationsListView.Groups["Plugin Management"];
218      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, pluginInfrastructureVersion.FileVersion));
219      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, "Install, upgrade or delete plugins"));
220      pluginManagerListViewItem.ToolTipText = "Install, upgrade or delete plugins";
221
222      applicationsListView.Items.Add(pluginManagerListViewItem);
223    }
224
225    private void AddUpdatePluginsItem() {
226      if (updatesAvailable) {
227        var updateListViewItem = new ListViewItem(updatePluginsItemName, 1);
228        updateListViewItem.Group = applicationsListView.Groups["Plugin Management"];
229        updateListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(updateListViewItem, ""));
230        updateListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(updateListViewItem, "Download and install updates"));
231        updateListViewItem.ToolTipText = "Download and install updates";
232
233        applicationsListView.Items.Add(updateListViewItem);
234      }
235    }
236
237    private void StartApplication(ApplicationDescription app) {
238      splashScreen.Show("Loading " + app.Name);
239      Thread t = new Thread(delegate() {
240        bool stopped = false;
241        do {
242          try {
243            if (!abortRequested) {
244              pluginManager.Run(app);
245            }
246            stopped = true;
247          }
248          catch (Exception ex) {
249            stopped = false;
250            ThreadPool.QueueUserWorkItem(delegate(object exception) { ErrorHandling.ShowErrorDialog(this, (Exception)exception); }, ex);
251            Thread.Sleep(5000); // sleep 5 seconds before autorestart
252          }
253        } while (!abortRequested && !stopped && app.AutoRestart);
254      });
255      t.SetApartmentState(ApartmentState.STA); // needed for the AdvancedOptimizationFrontent
256      t.Start();
257    }
258
259    private void applicationsListView_SelectedIndexChanged(object sender, EventArgs e) {
260      startButton.Enabled = applicationsListView.SelectedItems.Count > 0;
261    }
262
263    private void largeIconsButton_Click(object sender, EventArgs e) {
264      applicationsListView.View = View.LargeIcon;
265    }
266
267    private void detailsButton_Click(object sender, EventArgs e) {
268      applicationsListView.View = View.Details;
269      foreach (ColumnHeader column in applicationsListView.Columns) {
270        if (applicationsListView.Items.Count > 0)
271          column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
272        else column.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
273      }
274    }
275
276    private void StarterForm_FormClosing(object sender, FormClosingEventArgs e) {
277      splashScreen.Close();
278      abortRequested = true;
279    }
280
281    private void aboutButton_Click(object sender, EventArgs e) {
282      List<IPluginDescription> plugins = new List<IPluginDescription>(pluginManager.Plugins.OfType<IPluginDescription>());
283      using (var dialog = new AboutDialog(plugins)) {
284        dialog.ShowDialog();
285      }
286    }
287  }
288}
Note: See TracBrowser for help on using the repository browser.