3c8f4e2c7e76ed02230525f04147421db1776323
[debian/openrocket] / src / net / sf / openrocket / gui / main / BasicFrame.java
1 package net.sf.openrocket.gui.main;
2
3 import net.miginfocom.swing.MigLayout;
4 import net.sf.openrocket.aerodynamics.WarningSet;
5 import net.sf.openrocket.document.OpenRocketDocument;
6 import net.sf.openrocket.file.GeneralRocketLoader;
7 import net.sf.openrocket.file.RocketLoadException;
8 import net.sf.openrocket.file.RocketLoader;
9 import net.sf.openrocket.file.RocketSaver;
10 import net.sf.openrocket.file.openrocket.OpenRocketSaver;
11 import net.sf.openrocket.gui.StorageOptionChooser;
12 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
13 import net.sf.openrocket.gui.dialogs.AboutDialog;
14 import net.sf.openrocket.gui.dialogs.BugReportDialog;
15 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
16 import net.sf.openrocket.gui.dialogs.DebugLogDialog;
17 import net.sf.openrocket.gui.dialogs.DetailDialog;
18 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
19 import net.sf.openrocket.gui.dialogs.LicenseDialog;
20 import net.sf.openrocket.gui.dialogs.MotorDatabaseLoadingDialog;
21 import net.sf.openrocket.gui.dialogs.PrintDialog;
22 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
23 import net.sf.openrocket.gui.dialogs.WarningDialog;
24 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
25 import net.sf.openrocket.gui.main.componenttree.ComponentTree;
26 import net.sf.openrocket.gui.scalefigure.RocketPanel;
27 import net.sf.openrocket.logging.LogHelper;
28 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
29 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
30 import net.sf.openrocket.rocketcomponent.Rocket;
31 import net.sf.openrocket.rocketcomponent.RocketComponent;
32 import net.sf.openrocket.rocketcomponent.Stage;
33 import net.sf.openrocket.startup.Application;
34 import net.sf.openrocket.util.BugException;
35 import net.sf.openrocket.util.GUIUtil;
36 import net.sf.openrocket.util.Icons;
37 import net.sf.openrocket.util.MemoryManagement;
38 import net.sf.openrocket.util.MemoryManagement.MemoryData;
39 import net.sf.openrocket.util.OpenFileWorker;
40 import net.sf.openrocket.util.Prefs;
41 import net.sf.openrocket.util.Reflection;
42 import net.sf.openrocket.util.SaveFileWorker;
43 import net.sf.openrocket.util.TestRockets;
44
45 import javax.swing.Action;
46 import javax.swing.InputMap;
47 import javax.swing.JButton;
48 import javax.swing.JComponent;
49 import javax.swing.JFileChooser;
50 import javax.swing.JFrame;
51 import javax.swing.JMenu;
52 import javax.swing.JMenuBar;
53 import javax.swing.JMenuItem;
54 import javax.swing.JOptionPane;
55 import javax.swing.JPanel;
56 import javax.swing.JScrollPane;
57 import javax.swing.JSeparator;
58 import javax.swing.JSplitPane;
59 import javax.swing.JTabbedPane;
60 import javax.swing.JTextField;
61 import javax.swing.KeyStroke;
62 import javax.swing.ListSelectionModel;
63 import javax.swing.ScrollPaneConstants;
64 import javax.swing.SwingUtilities;
65 import javax.swing.border.TitledBorder;
66 import javax.swing.event.TreeSelectionEvent;
67 import javax.swing.event.TreeSelectionListener;
68 import javax.swing.filechooser.FileFilter;
69 import javax.swing.tree.DefaultTreeSelectionModel;
70 import javax.swing.tree.TreePath;
71 import javax.swing.tree.TreeSelectionModel;
72 import java.awt.Dimension;
73 import java.awt.Font;
74 import java.awt.Toolkit;
75 import java.awt.Window;
76 import java.awt.event.ActionEvent;
77 import java.awt.event.ActionListener;
78 import java.awt.event.ComponentAdapter;
79 import java.awt.event.ComponentEvent;
80 import java.awt.event.KeyEvent;
81 import java.awt.event.MouseAdapter;
82 import java.awt.event.MouseEvent;
83 import java.awt.event.MouseListener;
84 import java.awt.event.WindowAdapter;
85 import java.awt.event.WindowEvent;
86 import java.io.File;
87 import java.io.FileNotFoundException;
88 import java.io.IOException;
89 import java.io.InputStream;
90 import java.io.UnsupportedEncodingException;
91 import java.net.URI;
92 import java.net.URISyntaxException;
93 import java.net.URL;
94 import java.net.URLDecoder;
95 import java.util.ArrayList;
96 import java.util.Arrays;
97 import java.util.LinkedList;
98 import java.util.List;
99 import java.util.concurrent.ExecutionException;
100
101 public class BasicFrame extends JFrame {
102         private static final LogHelper log = Application.getLogger();
103         
104         /**
105          * The RocketLoader instance used for loading all rocket designs.
106          */
107         private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
108         
109         private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
110         
111
112         // FileFilters for different types of rocket design files
113         private static final FileFilter ALL_DESIGNS_FILTER =
114                         new SimpleFileFilter("All rocket designs (*.ork; *.rkt)",
115                                         ".ork", ".ork.gz", ".rkt", ".rkt.gz");
116         
117         private static final FileFilter OPENROCKET_DESIGN_FILTER =
118                         new SimpleFileFilter("OpenRocket designs (*.ork)", ".ork", ".ork.gz");
119         
120         private static final FileFilter ROCKSIM_DESIGN_FILTER =
121                         new SimpleFileFilter("RockSim designs (*.rkt)", ".rkt", ".rkt.gz");
122         
123
124
125
126         public static final int COMPONENT_TAB = 0;
127         public static final int SIMULATION_TAB = 1;
128         
129
130         /**
131          * List of currently open frames.  When the list goes empty
132          * it is time to exit the application.
133          */
134         private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
135         
136
137
138
139
140         /**
141          * Whether "New" and "Open" should replace this frame.
142          * Should be set to false on the first rocket modification.
143          */
144         private boolean replaceable = false;
145         
146
147
148         private final OpenRocketDocument document;
149         private final Rocket rocket;
150         
151         private JTabbedPane tabbedPane;
152         private RocketPanel rocketpanel;
153         private ComponentTree tree = null;
154         
155         private final DocumentSelectionModel selectionModel;
156         private final TreeSelectionModel componentSelectionModel;
157         private final ListSelectionModel simulationSelectionModel;
158         
159         /** Actions available for rocket modifications */
160         private final RocketActions actions;
161         
162         
163
164         /**
165          * Sole constructor.  Creates a new frame based on the supplied document
166          * and adds it to the current frames list.
167          * 
168          * @param document      the document to show.
169          */
170         public BasicFrame(OpenRocketDocument document) {
171                 log.debug("Instantiating new BasicFrame");
172                 
173                 this.document = document;
174                 this.rocket = document.getRocket();
175                 this.rocket.getDefaultConfiguration().setAllStages();
176                 
177
178                 // Set replaceable flag to false at first modification
179                 rocket.addComponentChangeListener(new ComponentChangeListener() {
180                         public void componentChanged(ComponentChangeEvent e) {
181                                 replaceable = false;
182                                 BasicFrame.this.rocket.removeComponentChangeListener(this);
183                         }
184                 });
185                 
186
187                 // Create the component tree selection model that will be used
188                 componentSelectionModel = new DefaultTreeSelectionModel();
189                 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
190                 
191                 // Obtain the simulation selection model that will be used
192                 SimulationPanel simulationPanel = new SimulationPanel(document);
193                 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
194                 
195                 // Combine into a DocumentSelectionModel
196                 selectionModel = new DocumentSelectionModel(document);
197                 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
198                 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
199                 
200
201                 actions = new RocketActions(document, selectionModel, this);
202                 
203
204                 log.debug("Constructing the BasicFrame UI");
205                 
206                 // The main vertical split pane         
207                 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
208                 vertical.setResizeWeight(0.5);
209                 this.add(vertical);
210                 
211
212                 // The top tabbed pane
213                 tabbedPane = new JTabbedPane();
214                 tabbedPane.addTab("Rocket design", null, designTab());
215                 tabbedPane.addTab("Flight simulations", null, simulationPanel);
216                 
217                 vertical.setTopComponent(tabbedPane);
218                 
219
220
221                 //  Bottom segment, rocket figure
222                 
223                 rocketpanel = new RocketPanel(document);
224                 vertical.setBottomComponent(rocketpanel);
225                 
226                 rocketpanel.setSelectionModel(tree.getSelectionModel());
227                 
228
229                 createMenu();
230                 
231
232                 rocket.addComponentChangeListener(new ComponentChangeListener() {
233                         public void componentChanged(ComponentChangeEvent e) {
234                                 setTitle();
235                         }
236                 });
237                 
238                 setTitle();
239                 this.pack();
240                 
241                 Dimension size = Prefs.getWindowSize(this.getClass());
242                 if (size == null) {
243                         size = Toolkit.getDefaultToolkit().getScreenSize();
244                         size.width = size.width * 9 / 10;
245                         size.height = size.height * 9 / 10;
246                 }
247                 this.setSize(size);
248                 this.addComponentListener(new ComponentAdapter() {
249                         @Override
250                         public void componentResized(ComponentEvent e) {
251                                 Prefs.setWindowSize(BasicFrame.this.getClass(), BasicFrame.this.getSize());
252                         }
253                 });
254                 this.setLocationByPlatform(true);
255                 
256                 GUIUtil.setWindowIcons(this);
257                 
258                 this.validate();
259                 vertical.setDividerLocation(0.4);
260                 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
261                 addWindowListener(new WindowAdapter() {
262                         @Override
263                         public void windowClosing(WindowEvent e) {
264                                 closeAction();
265                         }
266                 });
267                 frames.add(this);
268                 
269                 log.debug("BasicFrame instantiation complete");
270         }
271         
272         
273         /**
274          * Construct the "Rocket design" tab.  This contains a horizontal split pane
275          * with the left component the design tree and the right component buttons
276          * for adding components.
277          */
278         private JComponent designTab() {
279                 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
280                 horizontal.setResizeWeight(0.5);
281                 
282
283                 //  Upper-left segment, component tree
284                 
285                 JPanel panel = new JPanel(new MigLayout("fill, flowy", "", "[grow]"));
286                 
287                 tree = new ComponentTree(document);
288                 tree.setSelectionModel(componentSelectionModel);
289                 
290                 // Remove JTree key events that interfere with menu accelerators
291                 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
292                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
293                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
294                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
295                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
296                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
297                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
298                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
299                 
300
301
302                 // Double-click opens config dialog
303                 MouseListener ml = new MouseAdapter() {
304                         @Override
305                         public void mousePressed(MouseEvent e) {
306                                 int selRow = tree.getRowForLocation(e.getX(), e.getY());
307                                 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
308                                 if (selRow != -1) {
309                                         if ((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
310                                                 // Double-click
311                                                 RocketComponent c = (RocketComponent) selPath.getLastPathComponent();
312                                                 ComponentConfigDialog.showDialog(BasicFrame.this,
313                                                                 BasicFrame.this.document, c);
314                                         }
315                                 }
316                         }
317                 };
318                 tree.addMouseListener(ml);
319                 
320                 // Update dialog when selection is changed
321                 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
322                         public void valueChanged(TreeSelectionEvent e) {
323                                 // Scroll tree to the selected item
324                                 TreePath path = componentSelectionModel.getSelectionPath();
325                                 if (path == null)
326                                         return;
327                                 tree.scrollPathToVisible(path);
328                                 
329                                 if (!ComponentConfigDialog.isDialogVisible())
330                                         return;
331                                 RocketComponent c = (RocketComponent) path.getLastPathComponent();
332                                 ComponentConfigDialog.showDialog(BasicFrame.this,
333                                                 BasicFrame.this.document, c);
334                         }
335                 });
336                 
337                 // Place tree inside scroll pane
338                 JScrollPane scroll = new JScrollPane(tree);
339                 panel.add(scroll, "spany, grow, wrap");
340                 
341
342                 // Buttons
343                 JButton button = new JButton(actions.getMoveUpAction());
344                 panel.add(button, "sizegroup buttons, aligny 65%");
345                 
346                 button = new JButton(actions.getMoveDownAction());
347                 panel.add(button, "sizegroup buttons, aligny 0%");
348                 
349                 button = new JButton(actions.getEditAction());
350                 panel.add(button, "sizegroup buttons");
351                 
352                 button = new JButton(actions.getNewStageAction());
353                 panel.add(button, "sizegroup buttons");
354                 
355                 button = new JButton(actions.getDeleteAction());
356                 button.setIcon(null);
357                 button.setMnemonic(0);
358                 panel.add(button, "sizegroup buttons");
359                 
360                 horizontal.setLeftComponent(panel);
361                 
362
363                 //  Upper-right segment, component addition buttons
364                 
365                 panel = new JPanel(new MigLayout("fill, insets 0", "[0::]"));
366                 
367                 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
368                                 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
369                 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
370                                 scroll.getViewport()));
371                 scroll.setBorder(null);
372                 scroll.setViewportBorder(null);
373                 
374                 TitledBorder border = new TitledBorder("Add new component");
375                 border.setTitleFont(border.getTitleFont().deriveFont(Font.BOLD));
376                 scroll.setBorder(border);
377                 
378                 panel.add(scroll, "grow");
379                 
380                 horizontal.setRightComponent(panel);
381                 
382                 return horizontal;
383         }
384         
385         
386
387         /**
388          * Creates the menu for the window.
389          */
390         private void createMenu() {
391                 JMenuBar menubar = new JMenuBar();
392                 JMenu menu;
393                 JMenuItem item;
394                 
395                 ////  File
396                 menu = new JMenu("File");
397                 menu.setMnemonic(KeyEvent.VK_F);
398                 menu.getAccessibleContext().setAccessibleDescription("File-handling related tasks");
399                 menubar.add(menu);
400                 
401                 item = new JMenuItem("New", KeyEvent.VK_N);
402                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
403                 item.setMnemonic(KeyEvent.VK_N);
404                 item.getAccessibleContext().setAccessibleDescription("Create a new rocket design");
405                 item.setIcon(Icons.FILE_NEW);
406                 item.addActionListener(new ActionListener() {
407                         public void actionPerformed(ActionEvent e) {
408                                 log.user("New... selected");
409                                 newAction();
410                                 if (replaceable) {
411                                         log.info("Closing previous window");
412                                         closeAction();
413                                 }
414                         }
415                 });
416                 menu.add(item);
417                 
418                 item = new JMenuItem("Open...", KeyEvent.VK_O);
419                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
420                 item.getAccessibleContext().setAccessibleDescription("Open a rocket design");
421                 item.setIcon(Icons.FILE_OPEN);
422                 item.addActionListener(new ActionListener() {
423                         public void actionPerformed(ActionEvent e) {
424                                 log.user("Open... selected");
425                                 openAction();
426                         }
427                 });
428                 menu.add(item);
429                 
430                 item = new JMenuItem("Open example...");
431                 item.getAccessibleContext().setAccessibleDescription("Open an example rocket design");
432                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
433                                 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
434                 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
435                 item.addActionListener(new ActionListener() {
436                         public void actionPerformed(ActionEvent e) {
437                                 log.user("Open example... selected");
438                                 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
439                                 if (urls != null) {
440                                         for (URL u : urls) {
441                                                 log.user("Opening example " + u);
442                                                 open(u, BasicFrame.this);
443                                         }
444                                 }
445                         }
446                 });
447                 menu.add(item);
448                 
449                 menu.addSeparator();
450                 
451                 item = new JMenuItem("Save", KeyEvent.VK_S);
452                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
453                 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design");
454                 item.setIcon(Icons.FILE_SAVE);
455                 item.addActionListener(new ActionListener() {
456                         public void actionPerformed(ActionEvent e) {
457                                 log.user("Save selected");
458                                 saveAction();
459                         }
460                 });
461                 menu.add(item);
462                 
463                 item = new JMenuItem("Save as...", KeyEvent.VK_A);
464                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
465                                 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
466                 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design " +
467                                 "to a new file");
468                 item.setIcon(Icons.FILE_SAVE_AS);
469                 item.addActionListener(new ActionListener() {
470                         public void actionPerformed(ActionEvent e) {
471                                 log.user("Save as... selected");
472                                 saveAsAction();
473                         }
474                 });
475                 menu.add(item);
476                 
477                 //              menu.addSeparator();
478                 menu.add(new JSeparator());
479                 
480                 item = new JMenuItem("Close", KeyEvent.VK_C);
481                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
482                 item.getAccessibleContext().setAccessibleDescription("Close the current rocket design");
483                 item.setIcon(Icons.FILE_CLOSE);
484                 item.addActionListener(new ActionListener() {
485                         public void actionPerformed(ActionEvent e) {
486                                 log.user("Close selected");
487                                 closeAction();
488                         }
489                 });
490                 menu.add(item);
491                 
492                 menu.addSeparator();
493
494
495         item = new JMenuItem("Print...", KeyEvent.VK_P);
496         item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
497         item.getAccessibleContext().setAccessibleDescription("Print parts list and fin template");
498         item.addActionListener(new ActionListener() {
499             public void actionPerformed(ActionEvent e) {
500                 printAction();
501             }
502         });
503         menu.add(item);
504         
505                 item = new JMenuItem("Quit", KeyEvent.VK_Q);
506                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
507                 item.getAccessibleContext().setAccessibleDescription("Quit the program");
508                 item.setIcon(Icons.FILE_QUIT);
509                 item.addActionListener(new ActionListener() {
510                         public void actionPerformed(ActionEvent e) {
511                                 log.user("Quit selected");
512                                 quitAction();
513                         }
514                 });
515                 menu.add(item);
516                 
517
518
519                 ////  Edit
520                 menu = new JMenu("Edit");
521                 menu.setMnemonic(KeyEvent.VK_E);
522                 menu.getAccessibleContext().setAccessibleDescription("Rocket editing");
523                 menubar.add(menu);
524                 
525
526                 Action action = document.getUndoAction();
527                 item = new JMenuItem(action);
528                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
529                 item.setMnemonic(KeyEvent.VK_U);
530                 item.getAccessibleContext().setAccessibleDescription("Undo the previous operation");
531                 
532                 menu.add(item);
533                 
534                 action = document.getRedoAction();
535                 item = new JMenuItem(action);
536                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
537                 item.setMnemonic(KeyEvent.VK_R);
538                 item.getAccessibleContext().setAccessibleDescription("Redo the previously undone " +
539                                 "operation");
540                 menu.add(item);
541                 
542                 menu.addSeparator();
543                 
544
545                 item = new JMenuItem(actions.getCutAction());
546                 menu.add(item);
547                 
548                 item = new JMenuItem(actions.getCopyAction());
549                 menu.add(item);
550                 
551                 item = new JMenuItem(actions.getPasteAction());
552                 menu.add(item);
553                 
554                 item = new JMenuItem(actions.getDeleteAction());
555                 menu.add(item);
556                 
557                 menu.addSeparator();
558                 
559                 item = new JMenuItem("Preferences");
560                 item.setIcon(Icons.PREFERENCES);
561                 item.getAccessibleContext().setAccessibleDescription("Setup the application " +
562                                 "preferences");
563                 item.addActionListener(new ActionListener() {
564                         public void actionPerformed(ActionEvent e) {
565                                 log.user("Preferences selected");
566                                 PreferencesDialog.showPreferences();
567                         }
568                 });
569                 menu.add(item);
570                 
571
572
573
574                 ////  Analyze
575                 menu = new JMenu("Analyze");
576                 menu.setMnemonic(KeyEvent.VK_A);
577                 menu.getAccessibleContext().setAccessibleDescription("Analyzing the rocket");
578                 menubar.add(menu);
579                 
580                 item = new JMenuItem("Component analysis", KeyEvent.VK_C);
581                 item.getAccessibleContext().setAccessibleDescription("Analyze the rocket components " +
582                                 "separately");
583                 item.addActionListener(new ActionListener() {
584                         public void actionPerformed(ActionEvent e) {
585                                 log.user("Component analysis selected");
586                                 ComponentAnalysisDialog.showDialog(rocketpanel);
587                         }
588                 });
589                 menu.add(item);
590                 
591
592                 ////  Debug
593                 // (shown if openrocket.debug.menu is defined)
594                 if (System.getProperty("openrocket.debug.menu") != null) {
595                         menubar.add(makeDebugMenu());
596                 }
597                 
598
599
600                 ////  Help
601                 
602                 menu = new JMenu("Help");
603                 menu.setMnemonic(KeyEvent.VK_H);
604                 menu.getAccessibleContext().setAccessibleDescription("Information about OpenRocket");
605                 menubar.add(menu);
606                 
607
608
609                 item = new JMenuItem("License", KeyEvent.VK_L);
610                 item.getAccessibleContext().setAccessibleDescription("OpenRocket license information");
611                 item.addActionListener(new ActionListener() {
612                         public void actionPerformed(ActionEvent e) {
613                                 log.user("License selected");
614                                 new LicenseDialog(BasicFrame.this).setVisible(true);
615                         }
616                 });
617                 menu.add(item);
618                 
619                 menu.addSeparator();
620                 
621                 item = new JMenuItem("Bug report", KeyEvent.VK_B);
622                 item.getAccessibleContext().setAccessibleDescription("Information about reporting " +
623                                 "bugs in OpenRocket");
624                 item.addActionListener(new ActionListener() {
625                         public void actionPerformed(ActionEvent e) {
626                                 log.user("Bug report selected");
627                                 BugReportDialog.showBugReportDialog(BasicFrame.this);
628                         }
629                 });
630                 menu.add(item);
631                 
632                 item = new JMenuItem("Debug log");
633                 item.getAccessibleContext().setAccessibleDescription("View the OpenRocket debug log");
634                 item.addActionListener(new ActionListener() {
635                         public void actionPerformed(ActionEvent e) {
636                                 log.user("Debug log selected");
637                                 new DebugLogDialog(BasicFrame.this).setVisible(true);
638                         }
639                 });
640                 menu.add(item);
641                 
642                 menu.addSeparator();
643                 
644                 item = new JMenuItem("About", KeyEvent.VK_A);
645                 item.getAccessibleContext().setAccessibleDescription("About OpenRocket");
646                 item.addActionListener(new ActionListener() {
647                         public void actionPerformed(ActionEvent e) {
648                                 log.user("About selected");
649                                 new AboutDialog(BasicFrame.this).setVisible(true);
650                         }
651                 });
652                 menu.add(item);
653                 
654
655                 this.setJMenuBar(menubar);
656         }
657         
658         
659         private JMenu makeDebugMenu() {
660                 JMenu menu;
661                 JMenuItem item;
662                 
663                 ////  Debug menu
664                 menu = new JMenu("Debug");
665                 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
666                 
667                 item = new JMenuItem("What is this menu?");
668                 item.addActionListener(new ActionListener() {
669                         public void actionPerformed(ActionEvent e) {
670                                 log.user("What is this menu? selected");
671                                 JOptionPane.showMessageDialog(BasicFrame.this,
672                                                 new Object[] {
673                                                                 "The 'Debug' menu includes actions for testing and debugging " +
674                                                                                 "OpenRocket.", " ",
675                                                                 "The menu is made visible by defining the system property " +
676                                                                                 "'openrocket.debug.menu' when starting OpenRocket.",
677                                                                 "It should not be visible by default." },
678                                                 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
679                         }
680                 });
681                 menu.add(item);
682                 
683                 menu.addSeparator();
684                 
685                 item = new JMenuItem("Create test rocket");
686                 item.addActionListener(new ActionListener() {
687                         @Override
688                         public void actionPerformed(ActionEvent e) {
689                                 log.user("Create test rocket selected");
690                                 JTextField field = new JTextField();
691                                 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
692                                                 "Input text key to generate random rocket:",
693                                                 field
694                                         }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
695                                                 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
696                                                                 "Random", "OK"
697                                 }, "OK");
698                                 
699                                 Rocket r;
700                                 if (sel == 0) {
701                                         r = new TestRockets(null).makeTestRocket();
702                                 } else if (sel == 1) {
703                                         r = new TestRockets(field.getText()).makeTestRocket();
704                                 } else {
705                                         return;
706                                 }
707                                 
708                                 OpenRocketDocument doc = new OpenRocketDocument(r);
709                                 doc.setSaved(true);
710                                 BasicFrame frame = new BasicFrame(doc);
711                                 frame.setVisible(true);
712                         }
713                 });
714                 menu.add(item);
715                 
716
717
718                 item = new JMenuItem("Create 'Iso-Haisu'");
719                 item.addActionListener(new ActionListener() {
720                         @Override
721                         public void actionPerformed(ActionEvent e) {
722                                 log.user("Create Iso-Haisu selected");
723                                 Rocket r = TestRockets.makeIsoHaisu();
724                                 OpenRocketDocument doc = new OpenRocketDocument(r);
725                                 doc.setSaved(true);
726                                 BasicFrame frame = new BasicFrame(doc);
727                                 frame.setVisible(true);
728                         }
729                 });
730                 menu.add(item);
731                 
732
733                 item = new JMenuItem("Create 'Big Blue'");
734                 item.addActionListener(new ActionListener() {
735                         @Override
736                         public void actionPerformed(ActionEvent e) {
737                                 log.user("Create Big Blue selected");
738                                 Rocket r = TestRockets.makeBigBlue();
739                                 OpenRocketDocument doc = new OpenRocketDocument(r);
740                                 doc.setSaved(true);
741                                 BasicFrame frame = new BasicFrame(doc);
742                                 frame.setVisible(true);
743                         }
744                 });
745                 menu.add(item);
746                 
747                 menu.addSeparator();
748                 
749
750                 item = new JMenuItem("Memory statistics");
751                 item.addActionListener(new ActionListener() {
752                         @Override
753                         public void actionPerformed(ActionEvent e) {
754                                 log.user("Memory statistics selected");
755                                 
756                                 // Get discarded but remaining objects (this also runs System.gc multiple times)
757                                 List<MemoryData> objects = MemoryManagement.getRemainingObjects();
758                                 StringBuilder sb = new StringBuilder();
759                                 sb.append("Objects that should have been garbage-collected but have not been:\n");
760                                 int count = 0;
761                                 for (MemoryData data : objects) {
762                                         Object o = data.getReference().get();
763                                         if (o == null)
764                                                 continue;
765                                         sb.append("Age ").append(System.currentTimeMillis() - data.getRegistrationTime())
766                                                         .append(" ms:  ").append(o).append('\n');
767                                         count++;
768                                         // Explicitly null the strong reference to avoid possibility of invisible references
769                                         o = null;
770                                 }
771                                 sb.append("Total: " + count);
772                                 
773                                 // Get basic memory stats
774                                 System.gc();
775                                 long max = Runtime.getRuntime().maxMemory();
776                                 long free = Runtime.getRuntime().freeMemory();
777                                 long used = max - free;
778                                 String[] stats = new String[4];
779                                 stats[0] = "Memory usage:";
780                                 stats[1] = String.format("   Max memory:  %.1f MB", max / 1024.0 / 1024.0);
781                                 stats[2] = String.format("   Used memory: %.1f MB (%.0f%%)", used / 1024.0 / 1024.0, 100.0 * used / max);
782                                 stats[3] = String.format("   Free memory: %.1f MB (%.0f%%)", free / 1024.0 / 1024.0, 100.0 * free / max);
783                                 
784
785                                 DetailDialog.showDetailedMessageDialog(BasicFrame.this, stats, sb.toString(),
786                                                 "Memory statistics", JOptionPane.INFORMATION_MESSAGE);
787                         }
788                 });
789                 menu.add(item);
790                 
791
792                 item = new JMenuItem("Exhaust memory");
793                 item.addActionListener(new ActionListener() {
794                         @Override
795                         public void actionPerformed(ActionEvent e) {
796                                 log.user("Exhaust memory selected");
797                                 LinkedList<byte[]> data = new LinkedList<byte[]>();
798                                 int count = 0;
799                                 final int bytesPerArray = 10240;
800                                 try {
801                                         while (true) {
802                                                 byte[] array = new byte[bytesPerArray];
803                                                 for (int i = 0; i < bytesPerArray; i++) {
804                                                         array[i] = (byte) i;
805                                                 }
806                                                 data.add(array);
807                                                 count++;
808                                         }
809                                 } catch (OutOfMemoryError error) {
810                                         data = null;
811                                         long size = bytesPerArray * (long) count;
812                                         String s = String.format("OutOfMemory occurred after %d iterations (approx. %.1f MB consumed)",
813                                                         count, size / 1024.0 / 1024.0);
814                                         log.debug(s, error);
815                                         JOptionPane.showMessageDialog(BasicFrame.this, s);
816                                 }
817                         }
818                 });
819                 menu.add(item);
820                 
821
822                 menu.addSeparator();
823                 
824                 item = new JMenuItem("Exception here");
825                 item.addActionListener(new ActionListener() {
826                         @Override
827                         public void actionPerformed(ActionEvent e) {
828                                 log.user("Exception here selected");
829                                 throw new RuntimeException("Testing exception from menu action listener");
830                         }
831                 });
832                 menu.add(item);
833                 
834                 item = new JMenuItem("Exception from EDT");
835                 item.addActionListener(new ActionListener() {
836                         public void actionPerformed(ActionEvent e) {
837                                 log.user("Exception from EDT selected");
838                                 SwingUtilities.invokeLater(new Runnable() {
839                                         @Override
840                                         public void run() {
841                                                 throw new RuntimeException("Testing exception from " +
842                                                                 "later invoked EDT thread");
843                                         }
844                                 });
845                         }
846                 });
847                 menu.add(item);
848                 
849                 item = new JMenuItem("Exception from other thread");
850                 item.addActionListener(new ActionListener() {
851                         public void actionPerformed(ActionEvent e) {
852                                 log.user("Exception from other thread selected");
853                                 new Thread() {
854                                         @Override
855                                         public void run() {
856                                                 throw new RuntimeException("Testing exception from " +
857                                                                 "newly created thread");
858                                         }
859                                 }.start();
860                         }
861                 });
862                 menu.add(item);
863                 
864                 item = new JMenuItem("OutOfMemoryError here");
865                 item.addActionListener(new ActionListener() {
866                         @Override
867                         public void actionPerformed(ActionEvent e) {
868                                 log.user("OutOfMemoryError here selected");
869                                 throw new OutOfMemoryError("Testing OutOfMemoryError from menu action listener");
870                         }
871                 });
872                 menu.add(item);
873                 
874
875
876                 return menu;
877         }
878         
879         
880         /**
881          * Select the tab on the main pane.
882          * 
883          * @param tab   one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
884          */
885         public void selectTab(int tab) {
886                 tabbedPane.setSelectedIndex(tab);
887         }
888         
889         
890
891         private void openAction() {
892                 JFileChooser chooser = new JFileChooser();
893                 
894                 chooser.addChoosableFileFilter(ALL_DESIGNS_FILTER);
895                 chooser.addChoosableFileFilter(OPENROCKET_DESIGN_FILTER);
896                 chooser.addChoosableFileFilter(ROCKSIM_DESIGN_FILTER);
897                 chooser.setFileFilter(ALL_DESIGNS_FILTER);
898                 
899                 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
900                 chooser.setMultiSelectionEnabled(true);
901                 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
902                 int option = chooser.showOpenDialog(this);
903                 if (option != JFileChooser.APPROVE_OPTION) {
904                         log.user("Decided not to open files, option=" + option);
905                         return;
906                 }
907                 
908                 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
909                 
910                 File[] files = chooser.getSelectedFiles();
911                 log.user("Opening files " + Arrays.toString(files));
912                 
913                 for (File file : files) {
914                         log.info("Opening file: " + file);
915                         if (open(file, this)) {
916                                 
917                                 // Close previous window if replacing
918                                 if (replaceable && document.isSaved()) {
919                                         log.info("Closing window because it is replaceable");
920                                         closeAction();
921                                         replaceable = false;
922                                 }
923                         }
924                 }
925         }
926         
927         
928         /**
929          * Open a file based on a URL.
930          * @param url           the file to open.
931          * @param parent        the parent window for dialogs.
932          * @return                      <code>true</code> if opened successfully.
933          */
934         private static boolean open(URL url, BasicFrame parent) {
935                 String filename = null;
936                 
937                 // First figure out the file name from the URL
938                 
939                 // Try using URI.getPath();
940                 try {
941                         URI uri = url.toURI();
942                         filename = uri.getPath();
943                 } catch (URISyntaxException ignore) {
944                 }
945                 
946                 // Try URL-decoding the URL
947                 if (filename == null) {
948                         try {
949                                 filename = URLDecoder.decode(url.toString(), "UTF-8");
950                         } catch (UnsupportedEncodingException ignore) {
951                         }
952                 }
953                 
954                 // Last resort
955                 if (filename == null) {
956                         filename = "";
957                 }
958                 
959                 // Remove path from filename
960                 if (filename.lastIndexOf('/') >= 0) {
961                         filename = filename.substring(filename.lastIndexOf('/') + 1);
962                 }
963                 
964
965                 // Open the file
966                 log.info("Opening file from url=" + url + " filename=" + filename);
967                 try {
968                         InputStream is = url.openStream();
969                         if (open(is, filename, parent)) {
970                                 // Close previous window if replacing
971                                 if (parent.replaceable && parent.document.isSaved()) {
972                                         parent.closeAction();
973                                         parent.replaceable = false;
974                                 }
975                         }
976                 } catch (IOException e) {
977                         log.warn("Error opening file" + e);
978                         JOptionPane.showMessageDialog(parent,
979                                         "An error occurred while opening the file " + filename,
980                                         "Error loading file", JOptionPane.ERROR_MESSAGE);
981                 }
982                 
983                 return false;
984         }
985         
986         
987         /**
988          * Open the specified file from an InputStream in a new design frame.  If an error
989          * occurs, an error dialog is shown and <code>false</code> is returned.
990          * 
991          * @param stream        the stream to load from.
992          * @param filename      the file name to display in dialogs (not set to the document).
993          * @param parent        the parent component for which a progress dialog is opened.
994          * @return                      whether the file was successfully loaded and opened.
995          */
996         private static boolean open(InputStream stream, String filename, Window parent) {
997                 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
998                 return open(worker, filename, null, parent);
999         }
1000         
1001         
1002         /**
1003          * Open the specified file in a new design frame.  If an error occurs, an error
1004          * dialog is shown and <code>false</code> is returned.
1005          * 
1006          * @param file          the file to open.
1007          * @param parent        the parent component for which a progress dialog is opened.
1008          * @return                      whether the file was successfully loaded and opened.
1009          */
1010         public static boolean open(File file, Window parent) {
1011                 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
1012                 return open(worker, file.getName(), file, parent);
1013         }
1014         
1015         
1016         /**
1017          * Open the specified file using the provided worker.
1018          * 
1019          * @param worker        the OpenFileWorker that loads the file.
1020          * @param filename      the file name to display in dialogs.
1021          * @param file          the File to set the document to (may be null).
1022          * @param parent
1023          * @return
1024          */
1025         private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) {
1026                 
1027                 MotorDatabaseLoadingDialog.check(parent);
1028                 
1029                 // Open the file in a Swing worker thread
1030                 log.info("Starting OpenFileWorker");
1031                 if (!SwingWorkerDialog.runWorker(parent, "Opening file", "Reading " + filename + "...", worker)) {
1032                         // User cancelled the operation
1033                         log.info("User cancelled the OpenFileWorker");
1034                         return false;
1035                 }
1036                 
1037
1038                 // Handle the document
1039                 OpenRocketDocument doc = null;
1040                 try {
1041                         
1042                         doc = worker.get();
1043                         
1044                 } catch (ExecutionException e) {
1045                         
1046                         Throwable cause = e.getCause();
1047                         
1048                         if (cause instanceof FileNotFoundException) {
1049                                 
1050                                 log.warn("File not found", cause);
1051                                 JOptionPane.showMessageDialog(parent,
1052                                                 "File not found: " + filename,
1053                                                 "Error opening file", JOptionPane.ERROR_MESSAGE);
1054                                 return false;
1055                                 
1056                         } else if (cause instanceof RocketLoadException) {
1057                                 
1058                                 log.warn("Error loading the file", cause);
1059                                 JOptionPane.showMessageDialog(parent,
1060                                                 "Unable to open file '" + filename + "': "
1061                                                                 + cause.getMessage(),
1062                                                 "Error opening file", JOptionPane.ERROR_MESSAGE);
1063                                 return false;
1064                                 
1065                         } else {
1066                                 
1067                                 throw new BugException("Unknown error when opening file", e);
1068                                 
1069                         }
1070                         
1071                 } catch (InterruptedException e) {
1072                         throw new BugException("EDT was interrupted", e);
1073                 }
1074                 
1075                 if (doc == null) {
1076                         throw new BugException("Document loader returned null");
1077                 }
1078                 
1079
1080                 // Show warnings
1081                 WarningSet warnings = worker.getRocketLoader().getWarnings();
1082                 if (!warnings.isEmpty()) {
1083                         log.info("Warnings while reading file: " + warnings);
1084                         WarningDialog.showWarnings(parent,
1085                                         new Object[] {
1086                                                         "The following problems were encountered while opening " + filename + ".",
1087                                                         "Some design features may not have been loaded correctly."
1088                                         },
1089                                         "Warnings while opening file", warnings);
1090                 }
1091                 
1092
1093                 // Set document state
1094                 doc.setFile(file);
1095                 doc.setSaved(true);
1096                 
1097                 // Open the frame
1098                 log.debug("Opening new frame with the document");
1099                 BasicFrame frame = new BasicFrame(doc);
1100                 frame.setVisible(true);
1101                 
1102                 return true;
1103         }
1104         
1105         
1106
1107
1108
1109         private boolean saveAction() {
1110                 File file = document.getFile();
1111                 if (file == null) {
1112                         log.info("Document does not contain file, opening save as dialog instead");
1113                         return saveAsAction();
1114                 }
1115                 log.info("Saving document to " + file);
1116                 
1117                 // Saving RockSim designs is not supported
1118                 if (ROCKSIM_DESIGN_FILTER.accept(file)) {
1119                         file = new File(file.getAbsolutePath().replaceAll(".[rR][kK][tT](.[gG][zZ])?$",
1120                                         ".ork"));
1121                         
1122                         log.info("Attempting to save in RockSim format, renaming to " + file);
1123                         int option = JOptionPane.showConfirmDialog(this, new Object[] {
1124                                         "Saving designs in RockSim format is not supported.",
1125                                         "Save in OpenRocket format instead (" + file.getName() + ")?"
1126                                 }, "Save " + file.getName(), JOptionPane.YES_NO_OPTION,
1127                                         JOptionPane.QUESTION_MESSAGE, null);
1128                         if (option != JOptionPane.YES_OPTION) {
1129                                 log.user("User chose not to save");
1130                                 return false;
1131                         }
1132                         
1133                         document.setFile(file);
1134                 }
1135                 return saveAs(file);
1136         }
1137         
1138         
1139         private boolean saveAsAction() {
1140                 File file = null;
1141                 
1142                 // TODO: HIGH: what if *.rkt chosen?
1143                 StorageOptionChooser storageChooser =
1144                                 new StorageOptionChooser(document, document.getDefaultStorageOptions());
1145                 JFileChooser chooser = new JFileChooser();
1146                 chooser.setFileFilter(OPENROCKET_DESIGN_FILTER);
1147                 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
1148                 chooser.setAccessory(storageChooser);
1149                 if (document.getFile() != null)
1150                         chooser.setSelectedFile(document.getFile());
1151                 
1152                 int option = chooser.showSaveDialog(BasicFrame.this);
1153                 if (option != JFileChooser.APPROVE_OPTION) {
1154                         log.user("User decided not to save, option=" + option);
1155                         return false;
1156                 }
1157                 
1158                 file = chooser.getSelectedFile();
1159                 if (file == null) {
1160                         log.user("User did not select a file");
1161                         return false;
1162                 }
1163                 
1164                 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
1165                 storageChooser.storeOptions(document.getDefaultStorageOptions());
1166                 
1167                 if (file.getName().indexOf('.') < 0) {
1168                         log.debug("File name does not contain extension, adding .ork");
1169                         String name = file.getAbsolutePath();
1170                         name = name + ".ork";
1171                         file = new File(name);
1172                 }
1173                 
1174                 if (file.exists()) {
1175                         log.info("File " + file + " exists, confirming overwrite from user");
1176                         int result = JOptionPane.showConfirmDialog(this,
1177                                         "File '" + file.getName() + "' exists.  Do you want to overwrite it?",
1178                                         "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
1179                         if (result != JOptionPane.YES_OPTION) {
1180                                 log.user("User decided not to overwrite the file");
1181                                 return false;
1182                         }
1183                 }
1184                 
1185                 return saveAs(file);
1186         }
1187         
1188         private boolean saveAs(File file) {
1189                 log.info("Saving document as " + file);
1190                 boolean saved = false;
1191                 
1192                 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1193                         // User cancelled the dialog
1194                         log.user("User cancelled saving in storage options dialog");
1195                         return false;
1196                 }
1197                 
1198
1199                 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1200                 
1201                 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1202                                 "Writing " + file.getName() + "...", worker)) {
1203                         
1204                         // User cancelled the save
1205                         log.user("User cancelled the save, deleting the file");
1206                         file.delete();
1207                         return false;
1208                 }
1209                 
1210                 try {
1211                         worker.get();
1212                         document.setFile(file);
1213                         document.setSaved(true);
1214                         saved = true;
1215                         setTitle();
1216                 } catch (ExecutionException e) {
1217                         
1218                         Throwable cause = e.getCause();
1219                         
1220                         if (cause instanceof IOException) {
1221                                 log.warn("An I/O error occurred while saving " + file, cause);
1222                                 JOptionPane.showMessageDialog(this, new String[] {
1223                                                 "An I/O error occurred while saving:",
1224                                                 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1225                                 return false;
1226                         } else {
1227                                 Reflection.handleWrappedException(e);
1228                         }
1229                         
1230                 } catch (InterruptedException e) {
1231                         throw new BugException("EDT was interrupted", e);
1232                 }
1233                 
1234                 return saved;
1235         }
1236         
1237         
1238         private boolean closeAction() {
1239                 if (!document.isSaved()) {
1240                         log.info("Confirming whether to save the design");
1241                         ComponentConfigDialog.hideDialog();
1242                         int result = JOptionPane.showConfirmDialog(this,
1243                                         "Design '" + rocket.getName() + "' has not been saved.  " +
1244                                                         "Do you want to save it?",
1245                                         "Design not saved", JOptionPane.YES_NO_CANCEL_OPTION,
1246                                         JOptionPane.QUESTION_MESSAGE);
1247                         if (result == JOptionPane.YES_OPTION) {
1248                                 // Save
1249                                 log.user("User requested file save");
1250                                 if (!saveAction()) {
1251                                         log.info("File save was interrupted, not closing");
1252                                         return false;
1253                                 }
1254                         } else if (result == JOptionPane.NO_OPTION) {
1255                                 // Don't save: No-op
1256                                 log.user("User requested to discard design");
1257                         } else {
1258                                 // Cancel or close
1259                                 log.user("User cancelled closing, result=" + result);
1260                                 return false;
1261                         }
1262                 }
1263                 
1264                 // Rocket has been saved or discarded
1265                 log.debug("Disposing window");
1266                 this.dispose();
1267                 
1268                 ComponentConfigDialog.hideDialog();
1269                 ComponentAnalysisDialog.hideDialog();
1270                 
1271                 frames.remove(this);
1272                 if (frames.isEmpty()) {
1273                         log.info("Last frame closed, exiting");
1274                         System.exit(0);
1275                 }
1276                 return true;
1277         }
1278         
1279         
1280
1281     /**
1282      * 
1283      */
1284     public void printAction() {
1285         new PrintDialog(document);
1286     }
1287     
1288         /**
1289          * Open a new design window with a basic rocket+stage.
1290          */
1291         public static void newAction() {
1292                 log.info("New action initiated");
1293                 
1294                 Rocket rocket = new Rocket();
1295                 Stage stage = new Stage();
1296                 stage.setName("Sustainer");
1297                 rocket.addChild(stage);
1298                 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1299                 doc.setSaved(true);
1300                 
1301                 BasicFrame frame = new BasicFrame(doc);
1302                 frame.replaceable = true;
1303                 frame.setVisible(true);
1304                 ComponentConfigDialog.showDialog(frame, doc, rocket);
1305         }
1306         
1307         /**
1308          * Quit the application.  Confirms saving unsaved designs.  The action of File->Quit.
1309          */
1310         public static void quitAction() {
1311                 log.info("Quit action initiated");
1312                 for (int i = frames.size() - 1; i >= 0; i--) {
1313                         log.debug("Closing frame " + frames.get(i));
1314                         if (!frames.get(i).closeAction()) {
1315                                 // Close canceled
1316                                 log.info("Quit was cancelled");
1317                                 return;
1318                         }
1319                 }
1320                 // Should not be reached, but just in case
1321                 log.error("Should already have exited application");
1322                 System.exit(0);
1323         }
1324         
1325         
1326         /**
1327          * Set the title of the frame, taking into account the name of the rocket, file it 
1328          * has been saved to (if any) and saved status.
1329          */
1330         private void setTitle() {
1331                 File file = document.getFile();
1332                 boolean saved = document.isSaved();
1333                 String title;
1334                 
1335                 title = rocket.getName();
1336                 if (file != null) {
1337                         title = title + " (" + file.getName() + ")";
1338                 }
1339                 if (!saved)
1340                         title = "*" + title;
1341                 
1342                 setTitle(title);
1343         }
1344         
1345         
1346
1347         /**
1348          * Find a currently open BasicFrame containing the specified rocket.  This method
1349          * can be used to map a Rocket to a BasicFrame from GUI methods.
1350          * 
1351          * @param rocket the Rocket.
1352          * @return               the corresponding BasicFrame, or <code>null</code> if none found.
1353          */
1354         public static BasicFrame findFrame(Rocket rocket) {
1355                 for (BasicFrame f : frames) {
1356                         if (f.rocket == rocket) {
1357                                 log.debug("Found frame " + f + " for rocket " + rocket);
1358                                 return f;
1359                         }
1360                 }
1361                 log.debug("Could not find frame for rocket " + rocket);
1362                 return null;
1363         }
1364         
1365         /**
1366          * Find a currently open document by the rocket object.  This method can be used
1367          * to map a Rocket to OpenRocketDocument from GUI methods.
1368          * 
1369          * @param rocket the Rocket.
1370          * @return               the corresponding OpenRocketDocument, or <code>null</code> if not found.
1371          */
1372         public static OpenRocketDocument findDocument(Rocket rocket) {
1373                 BasicFrame frame = findFrame(rocket);
1374                 if (frame != null) {
1375                         return frame.document;
1376                 } else {
1377                         return null;
1378                 }
1379         }
1380 }