Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 13334 was 13334, checked in by gkronber, 8 years ago

#2522: removed unused files

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