Free cookie consent management tool by TermsFeed Policy Generator

source: branches/RefactorPluginInfrastructure-2522/HeuristicLab.PluginInfrastructure.UI/StarterForm.cs @ 13348

Last change on this file since 13348 was 13338, checked in by gkronber, 9 years ago

#2522:

  • moved UI components out of HeuristicLab.PluginInfrastructure -> HeuristicLab.PluginInfrastructure.UI
  • moved ErrorDialog to HeuristicLab.MainForm.WindowsForms
  • moved ErrorHandling (for building an error message string) to HeuristicLab.Common
  • Changed exception handlers in Views to use MainForm.ShowError()
  • Changed usages for ErrorDialog in non-UI components to throw exceptions instead.
File size: 9.4 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.Manager;
30
31namespace HeuristicLab.PluginInfrastructure.UI {
32  /// <summary>
33  /// The starter form is responsible for initializing the plugin infrastructure
34  /// and shows a list of installed applications.
35  /// </summary>
36  public partial class StarterForm : Form {
37    private const string pluginManagerItemName = "Plugin Manager";
38    // private const string updatePluginsItemName = "Updates Available";
39    private const string optimizerItemName = "Optimizer"; // TODO: encoding a specific name of an application here is problematic (applications are discovered dynamically)
40
41    private readonly ICommandLineArgument[] arguments;
42
43    private ListViewItem pluginManagerListViewItem;
44    private bool abortRequested; // TODO: necessary?
45    private PluginManager pluginManager;
46    private SplashScreen splashScreen;
47
48    /// <summary>
49    /// Initializes an instance of the starter form.
50    /// The starter form shows a splashscreen and initializes the plugin infrastructure.
51    /// </summary>
52    public StarterForm()
53      : base() {
54      InitializeComponent();
55      largeImageList.Images.Add(Resources.HeuristicLab.ToBitmap());
56      smallImageList.Images.Add(Resources.HeuristicLab.ToBitmap());
57      Text = "HeuristicLab " + AssemblyExtensions.GetFileVersion(GetType().Assembly);
58
59      string pluginPath = Path.GetFullPath(Application.StartupPath);
60      pluginManager = new PluginManager(pluginPath);
61      splashScreen = new SplashScreen(pluginManager, 1000);
62      splashScreen.VisibleChanged += new EventHandler(splashScreen_VisibleChanged);
63      splashScreen.Show(this, "Loading HeuristicLab...");
64
65      pluginManager.DiscoverAndCheckPlugins();
66      UpdateApplicationsList();
67    }
68
69    /// <summary>
70    /// Creates a new StarterForm and passes the arguments in <paramref name="args"/>.
71    /// </summary>
72    /// <param name="args">The arguments that should be processed</param>
73    public StarterForm(string[] args)
74      : this() {
75      arguments = CommandLineArgumentHandling.GetArguments(args);
76    }
77
78    protected override void SetVisibleCore(bool value) {
79      value &= !(arguments.OfType<HideStarterArgument>().Any() || arguments.OfType<OpenArgument>().Any());
80      if (!value) HandleArguments();
81      base.SetVisibleCore(value);
82    }
83
84    #region Events
85    private void StarterForm_Load(object sender, EventArgs e) {
86      HandleArguments();
87    }
88
89    private void StarterForm_FormClosing(object sender, FormClosingEventArgs e) {
90      splashScreen.Close();
91      abortRequested = true;
92    }
93
94    private void applicationsListView_SelectedIndexChanged(object sender, EventArgs e) {
95      startButton.Enabled = applicationsListView.SelectedItems.Count > 0;
96    }
97
98    private void applicationsListView_ItemActivate(object sender, EventArgs e) {
99      if (applicationsListView.SelectedItems.Count > 0) {
100        ListViewItem selected = applicationsListView.SelectedItems[0];
101        if (selected.Text == pluginManagerItemName) {
102          if (pluginManager.Plugins.Any(x => x.PluginState == PluginState.Loaded)) {
103            MessageBox.Show("Installation Manager cannot be started while another HeuristicLab application is active." + Environment.NewLine +
104              "Please stop all active HeuristicLab applications and try again.", "Plugin Manager",
105              MessageBoxButtons.OK, MessageBoxIcon.Information);
106          } else {
107            try {
108              Cursor = Cursors.AppStarting;
109              using (InstallationManagerForm form = new InstallationManagerForm(pluginManager)) {
110                form.ShowDialog(this);
111              }
112              UpdateApplicationsList();
113            } finally {
114              Cursor = Cursors.Arrow;
115            }
116          }
117        } else {
118          ApplicationDescription app = (ApplicationDescription)applicationsListView.SelectedItems[0].Tag;
119          StartApplication(app, arguments);
120        }
121      }
122    }
123
124    private void largeIconsButton_Click(object sender, EventArgs e) {
125      applicationsListView.View = View.LargeIcon;
126    }
127
128    private void detailsButton_Click(object sender, EventArgs e) {
129      applicationsListView.View = View.Details;
130      foreach (ColumnHeader column in applicationsListView.Columns) {
131        if (applicationsListView.Items.Count > 0)
132          column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
133        else column.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
134      }
135    }
136
137    private void aboutButton_Click(object sender, EventArgs e) {
138      List<IPluginDescription> plugins = new List<IPluginDescription>(pluginManager.Plugins.OfType<IPluginDescription>());
139      using (var dialog = new AboutDialog(plugins)) {
140        dialog.ShowDialog();
141      }
142    }
143
144    private void splashScreen_VisibleChanged(object sender, EventArgs e) {
145      // close hidden starter form
146      if (!splashScreen.Visible && arguments != null &&
147           (arguments.OfType<HideStarterArgument>().Any() || arguments.OfType<OpenArgument>().Any()))
148        Close();
149    }
150    #endregion
151
152    #region Helpers
153    private void UpdateApplicationsList() {
154      if (InvokeRequired) Invoke((Action)UpdateApplicationsList);
155      else {
156        applicationsListView.Items.Clear();
157        AddPluginManagerItem();
158
159        foreach (ApplicationDescription info in pluginManager.Applications) {
160          ListViewItem item = new ListViewItem(info.Name, 0);
161          item.Tag = info;
162          item.Group = applicationsListView.Groups["Applications"];
163          item.SubItems.Add(new ListViewItem.ListViewSubItem(item, info.Version.ToString()));
164          item.SubItems.Add(new ListViewItem.ListViewSubItem(item, info.Description));
165          item.ToolTipText = info.Description;
166          applicationsListView.Items.Add(item);
167        }
168        foreach (ColumnHeader column in applicationsListView.Columns) {
169          if (applicationsListView.Items.Count > 0)
170            column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
171          else column.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
172        }
173      }
174    }
175
176    private void AddPluginManagerItem() {
177      pluginManagerListViewItem = new ListViewItem(pluginManagerItemName, 0);
178      pluginManagerListViewItem.Group = applicationsListView.Groups["Plugin Management"];
179      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, AssemblyExtensions.GetFileVersion(GetType().Assembly)));
180      pluginManagerListViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(pluginManagerListViewItem, "Install, upgrade or delete plugins"));
181      pluginManagerListViewItem.ToolTipText = "Install, upgrade or delete plugins";
182
183      applicationsListView.Items.Add(pluginManagerListViewItem);
184    }
185
186    private void HandleArguments() {
187      try {
188        if (arguments.OfType<OpenArgument>().Any() && !arguments.OfType<StartArgument>().Any()) {
189          InitiateApplicationStart(optimizerItemName);
190        }
191        foreach (var argument in arguments) {
192          if (argument is StartArgument) {
193            var arg = (StartArgument)argument;
194            InitiateApplicationStart(arg.Value);
195          }
196        }
197      } catch (AggregateException ex) {
198        ShowErrorDialog(ex);
199      }
200    }
201
202    private void InitiateApplicationStart(string appName) {
203      var appDesc = (from desc in pluginManager.Applications
204                     where desc.Name.Equals(appName)
205                     select desc).SingleOrDefault();
206      if (appDesc != null) {
207        StartApplication(appDesc, arguments);
208      } else {
209        MessageBox.Show("Cannot start application " + appName + ".",
210                        "HeuristicLab",
211                        MessageBoxButtons.OK,
212                        MessageBoxIcon.Warning);
213      }
214    }
215
216    private void StartApplication(ApplicationDescription app, ICommandLineArgument[] args) {
217      splashScreen.Show("Loading " + app.Name);
218      // STAThread is necessary for a UI component we are using in the application
219      var t = new Thread(() => pluginManager.Run(app, args));
220      t.SetApartmentState(ApartmentState.STA);
221      t.Start();
222    }
223    #endregion
224
225    private void ShowErrorDialog(Exception exception) {
226      MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
227    }
228  }
229}
Note: See TracBrowser for help on using the repository browser.