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