source: branches/RefactorPluginInfrastructure-2522/HeuristicLab.PluginInfrastructure/3.3/Starter/StarterForm.cs @ 13333

Last change on this file since 13333 was 13333, checked in by gkronber, 7 years ago

#2522: removed classes for plugin uploading and updating

File size: 10.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.IO;
25using System.Linq;
26using System.Threading;
27using System.Threading.Tasks;
28using System.Windows.Forms;
29using HeuristicLab.PluginInfrastructure.Advanced;
30using HeuristicLab.PluginInfrastructure.Manager;
31
32namespace HeuristicLab.PluginInfrastructure.Starter {
33  /// <summary>
34  /// The starter form is responsible for initializing the plugin infrastructure
35  /// and shows a list of installed applications.
36  /// </summary>
37  public partial class StarterForm : Form {
38    private const string pluginManagerItemName = "Plugin Manager";
39    // private const string updatePluginsItemName = "Updates Available";
40    private const string optimizerItemName = "Optimizer"; // TODO: encoding a specific name of an application here is problematic (applications are discovered dynamically)
41
42    private readonly ICommandLineArgument[] arguments;
43
44    private ListViewItem pluginManagerListViewItem;
45    private bool abortRequested; // TODO: necessary
46    private PluginManager pluginManager;
47    private SplashScreen splashScreen;
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      Text = "HeuristicLab " + AssemblyHelpers.GetFileVersion(GetType().Assembly);
61
62      string pluginPath = Path.GetFullPath(Application.StartupPath);
63      pluginManager = new PluginManager(pluginPath);
64      splashScreen = new SplashScreen(pluginManager, 1000);
65      splashScreen.VisibleChanged += new EventHandler(splashScreen_VisibleChanged);
66      splashScreen.Show(this, "Loading HeuristicLab...");
67
68      pluginManager.DiscoverAndCheckPlugins();
69      UpdateApplicationsList();
70    }
71
72    /// <summary>
73    /// Creates a new StarterForm and passes the arguments in <paramref name="args"/>.
74    /// </summary>
75    /// <param name="args">The arguments that should be processed</param>
76    public StarterForm(string[] args)
77      : this() {
78      arguments = CommandLineArgumentHandling.GetArguments(args);
79    }
80
81    protected override void SetVisibleCore(bool value) {
82      value &= !(arguments.OfType<HideStarterArgument>().Any() || arguments.OfType<OpenArgument>().Any());
83      if (!value) HandleArguments();
84      base.SetVisibleCore(value);
85    }
86
87    #region Events
88    private void StarterForm_Load(object sender, EventArgs e) {
89      HandleArguments();
90    }
91
92    private void StarterForm_FormClosing(object sender, FormClosingEventArgs e) {
93      splashScreen.Close();
94      abortRequested = true;
95    }
96
97    private void applicationsListView_SelectedIndexChanged(object sender, EventArgs e) {
98      startButton.Enabled = applicationsListView.SelectedItems.Count > 0;
99    }
100
101    private void applicationsListView_ItemActivate(object sender, EventArgs e) {
102      if (applicationsListView.SelectedItems.Count > 0) {
103        ListViewItem selected = applicationsListView.SelectedItems[0];
104        if (selected.Text == pluginManagerItemName) {
105          if (pluginManager.Plugins.Any(x => x.PluginState == PluginState.Loaded)) {
106            MessageBox.Show("Installation Manager cannot be started while another HeuristicLab application is active." + Environment.NewLine +
107              "Please stop all active HeuristicLab applications and try again.", "Plugin Manager",
108              MessageBoxButtons.OK, MessageBoxIcon.Information);
109          } else {
110            try {
111              Cursor = Cursors.AppStarting;
112              using (InstallationManagerForm form = new InstallationManagerForm(pluginManager)) {
113                form.ShowDialog(this);
114              }
115              UpdateApplicationsList();
116            }
117            finally {
118              Cursor = Cursors.Arrow;
119            }
120          }
121        } else {
122          ApplicationDescription app = (ApplicationDescription)applicationsListView.SelectedItems[0].Tag;
123          StartApplication(app, arguments);
124        }
125      }
126    }
127
128    private void largeIconsButton_Click(object sender, EventArgs e) {
129      applicationsListView.View = View.LargeIcon;
130    }
131
132    private void detailsButton_Click(object sender, EventArgs e) {
133      applicationsListView.View = View.Details;
134      foreach (ColumnHeader column in applicationsListView.Columns) {
135        if (applicationsListView.Items.Count > 0)
136          column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
137        else column.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
138      }
139    }
140
141    private void aboutButton_Click(object sender, EventArgs e) {
142      List<IPluginDescription> plugins = new List<IPluginDescription>(pluginManager.Plugins.OfType<IPluginDescription>());
143      using (var dialog = new AboutDialog(plugins)) {
144        dialog.ShowDialog();
145      }
146    }
147
148    private void splashScreen_VisibleChanged(object sender, EventArgs e) {
149      // close hidden starter form
150      if (!splashScreen.Visible && arguments != null &&
151           (arguments.OfType<HideStarterArgument>().Any() || arguments.OfType<OpenArgument>().Any()))
152        Close();
153    }
154    #endregion
155
156    #region Helpers
157    private void UpdateApplicationsList() {
158      if (InvokeRequired) Invoke((Action)UpdateApplicationsList);
159      else {
160        applicationsListView.Items.Clear();
161        AddPluginManagerItem();
162
163        foreach (ApplicationDescription info in pluginManager.Applications) {
164          ListViewItem item = new ListViewItem(info.Name, 0);
165          item.Tag = info;
166          item.Group = applicationsListView.Groups["Applications"];
167          item.SubItems.Add(new ListViewItem.ListViewSubItem(item, info.Version.ToString()));
168          item.SubItems.Add(new ListViewItem.ListViewSubItem(item, info.Description));
169          item.ToolTipText = info.Description;
170          applicationsListView.Items.Add(item);
171        }
172        foreach (ColumnHeader column in applicationsListView.Columns) {
173          if (applicationsListView.Items.Count > 0)
174            column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
175          else column.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
176        }
177      }
178    }
179
180    private void AddPluginManagerItem() {
181      pluginManagerListViewItem = new ListViewItem(pluginManagerItemName, 0);
182      pluginManagerListViewItem.Group = applicationsListView.Groups["Plugin Management"];
183      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, AssemblyHelpers.GetFileVersion(GetType().Assembly)));
184      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, "Install, upgrade or delete plugins"));
185      pluginManagerListViewItem.ToolTipText = "Install, upgrade or delete plugins";
186
187      applicationsListView.Items.Add(pluginManagerListViewItem);
188    }
189
190    private void HandleArguments() {
191      try {
192        if (arguments.OfType<OpenArgument>().Any() && !arguments.OfType<StartArgument>().Any()) {
193          InitiateApplicationStart(optimizerItemName);
194        }
195        foreach (var argument in arguments) {
196          if (argument is StartArgument) {
197            var arg = (StartArgument)argument;
198            InitiateApplicationStart(arg.Value);
199          }
200        }
201      }
202      catch (AggregateException ex) {
203        ErrorHandling.ShowErrorDialog(this, "One or more errors occurred while initializing the application.", ex);
204      }
205    }
206
207    private void InitiateApplicationStart(string appName) {
208      var appDesc = (from desc in pluginManager.Applications
209                     where desc.Name.Equals(appName)
210                     select desc).SingleOrDefault();
211      if (appDesc != null) {
212        StartApplication(appDesc, arguments);
213      } else {
214        MessageBox.Show("Cannot start application " + appName + ".",
215                        "HeuristicLab",
216                        MessageBoxButtons.OK,
217                        MessageBoxIcon.Warning);
218      }
219    }
220
221    private void StartApplication(ApplicationDescription app, ICommandLineArgument[] args) {
222      splashScreen.Show("Loading " + app.Name);
223      Thread t = new Thread(delegate() {
224        bool stopped = false;
225        do {
226          try {
227            if (!abortRequested) {
228              pluginManager.Run(app, args);
229            }
230            stopped = true;
231          }
232          catch (Exception ex) {
233            stopped = false;
234            ThreadPool.QueueUserWorkItem(delegate(object exception) { ErrorHandling.ShowErrorDialog(this, (Exception)exception); }, ex);
235            Thread.Sleep(5000); // sleep 5 seconds before autorestart
236          }
237        } while (!abortRequested && !stopped && app.AutoRestart);
238      });
239      t.SetApartmentState(ApartmentState.STA); // needed for the AdvancedOptimizationFrontent
240      t.Start();
241    }
242    #endregion
243  }
244}
Note: See TracBrowser for help on using the repository browser.