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.SwingWorkerDialog;
79 import net.sf.openrocket.gui.dialogs.WarningDialog;
80 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
81 import net.sf.openrocket.gui.main.componenttree.ComponentTree;
82 import net.sf.openrocket.gui.scalefigure.RocketPanel;
83 import net.sf.openrocket.logging.LogHelper;
84 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
85 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
86 import net.sf.openrocket.rocketcomponent.Rocket;
87 import net.sf.openrocket.rocketcomponent.RocketComponent;
88 import net.sf.openrocket.rocketcomponent.Stage;
89 import net.sf.openrocket.startup.Application;
90 import net.sf.openrocket.util.BugException;
91 import net.sf.openrocket.util.GUIUtil;
92 import net.sf.openrocket.util.Icons;
93 import net.sf.openrocket.util.MemoryManagement;
94 import net.sf.openrocket.util.MemoryManagement.MemoryData;
95 import net.sf.openrocket.util.OpenFileWorker;
96 import net.sf.openrocket.util.Prefs;
97 import net.sf.openrocket.util.Reflection;
98 import net.sf.openrocket.util.SaveFileWorker;
99 import net.sf.openrocket.util.TestRockets;
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                 item = new JMenuItem("Quit", KeyEvent.VK_Q);
495                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
496                 item.getAccessibleContext().setAccessibleDescription("Quit the program");
497                 item.setIcon(Icons.FILE_QUIT);
498                 item.addActionListener(new ActionListener() {
499                         public void actionPerformed(ActionEvent e) {
500                                 log.user("Quit selected");
501                                 quitAction();
502                         }
503                 });
504                 menu.add(item);
505                 
506
507
508                 ////  Edit
509                 menu = new JMenu("Edit");
510                 menu.setMnemonic(KeyEvent.VK_E);
511                 menu.getAccessibleContext().setAccessibleDescription("Rocket editing");
512                 menubar.add(menu);
513                 
514
515                 Action action = document.getUndoAction();
516                 item = new JMenuItem(action);
517                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
518                 item.setMnemonic(KeyEvent.VK_U);
519                 item.getAccessibleContext().setAccessibleDescription("Undo the previous operation");
520                 
521                 menu.add(item);
522                 
523                 action = document.getRedoAction();
524                 item = new JMenuItem(action);
525                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
526                 item.setMnemonic(KeyEvent.VK_R);
527                 item.getAccessibleContext().setAccessibleDescription("Redo the previously undone " +
528                                 "operation");
529                 menu.add(item);
530                 
531                 menu.addSeparator();
532                 
533
534                 item = new JMenuItem(actions.getCutAction());
535                 menu.add(item);
536                 
537                 item = new JMenuItem(actions.getCopyAction());
538                 menu.add(item);
539                 
540                 item = new JMenuItem(actions.getPasteAction());
541                 menu.add(item);
542                 
543                 item = new JMenuItem(actions.getDeleteAction());
544                 menu.add(item);
545                 
546                 menu.addSeparator();
547                 
548                 item = new JMenuItem("Preferences");
549                 item.setIcon(Icons.PREFERENCES);
550                 item.getAccessibleContext().setAccessibleDescription("Setup the application " +
551                                 "preferences");
552                 item.addActionListener(new ActionListener() {
553                         public void actionPerformed(ActionEvent e) {
554                                 log.user("Preferences selected");
555                                 PreferencesDialog.showPreferences();
556                         }
557                 });
558                 menu.add(item);
559                 
560
561
562
563                 ////  Analyze
564                 menu = new JMenu("Analyze");
565                 menu.setMnemonic(KeyEvent.VK_A);
566                 menu.getAccessibleContext().setAccessibleDescription("Analyzing the rocket");
567                 menubar.add(menu);
568                 
569                 item = new JMenuItem("Component analysis", KeyEvent.VK_C);
570                 item.getAccessibleContext().setAccessibleDescription("Analyze the rocket components " +
571                                 "separately");
572                 item.addActionListener(new ActionListener() {
573                         public void actionPerformed(ActionEvent e) {
574                                 log.user("Component analysis selected");
575                                 ComponentAnalysisDialog.showDialog(rocketpanel);
576                         }
577                 });
578                 menu.add(item);
579                 
580
581                 ////  Debug
582                 // (shown if openrocket.debug.menu is defined)
583                 if (System.getProperty("openrocket.debug.menu") != null) {
584                         menubar.add(makeDebugMenu());
585                 }
586                 
587
588
589                 ////  Help
590                 
591                 menu = new JMenu("Help");
592                 menu.setMnemonic(KeyEvent.VK_H);
593                 menu.getAccessibleContext().setAccessibleDescription("Information about OpenRocket");
594                 menubar.add(menu);
595                 
596
597
598                 item = new JMenuItem("License", KeyEvent.VK_L);
599                 item.getAccessibleContext().setAccessibleDescription("OpenRocket license information");
600                 item.addActionListener(new ActionListener() {
601                         public void actionPerformed(ActionEvent e) {
602                                 log.user("License selected");
603                                 new LicenseDialog(BasicFrame.this).setVisible(true);
604                         }
605                 });
606                 menu.add(item);
607                 
608                 menu.addSeparator();
609                 
610                 item = new JMenuItem("Bug report", KeyEvent.VK_B);
611                 item.getAccessibleContext().setAccessibleDescription("Information about reporting " +
612                                 "bugs in OpenRocket");
613                 item.addActionListener(new ActionListener() {
614                         public void actionPerformed(ActionEvent e) {
615                                 log.user("Bug report selected");
616                                 BugReportDialog.showBugReportDialog(BasicFrame.this);
617                         }
618                 });
619                 menu.add(item);
620                 
621                 item = new JMenuItem("Debug log");
622                 item.getAccessibleContext().setAccessibleDescription("View the OpenRocket debug log");
623                 item.addActionListener(new ActionListener() {
624                         public void actionPerformed(ActionEvent e) {
625                                 log.user("Debug log selected");
626                                 new DebugLogDialog(BasicFrame.this).setVisible(true);
627                         }
628                 });
629                 menu.add(item);
630                 
631                 menu.addSeparator();
632                 
633                 item = new JMenuItem("About", KeyEvent.VK_A);
634                 item.getAccessibleContext().setAccessibleDescription("About OpenRocket");
635                 item.addActionListener(new ActionListener() {
636                         public void actionPerformed(ActionEvent e) {
637                                 log.user("About selected");
638                                 new AboutDialog(BasicFrame.this).setVisible(true);
639                         }
640                 });
641                 menu.add(item);
642                 
643
644                 this.setJMenuBar(menubar);
645         }
646         
647         
648         private JMenu makeDebugMenu() {
649                 JMenu menu;
650                 JMenuItem item;
651                 
652                 ////  Debug menu
653                 menu = new JMenu("Debug");
654                 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
655                 
656                 item = new JMenuItem("What is this menu?");
657                 item.addActionListener(new ActionListener() {
658                         public void actionPerformed(ActionEvent e) {
659                                 log.user("What is this menu? selected");
660                                 JOptionPane.showMessageDialog(BasicFrame.this,
661                                                 new Object[] {
662                                                                 "The 'Debug' menu includes actions for testing and debugging " +
663                                                                                 "OpenRocket.", " ",
664                                                                 "The menu is made visible by defining the system property " +
665                                                                                 "'openrocket.debug.menu' when starting OpenRocket.",
666                                                                 "It should not be visible by default." },
667                                                 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
668                         }
669                 });
670                 menu.add(item);
671                 
672                 menu.addSeparator();
673                 
674                 item = new JMenuItem("Create test rocket");
675                 item.addActionListener(new ActionListener() {
676                         @Override
677                         public void actionPerformed(ActionEvent e) {
678                                 log.user("Create test rocket selected");
679                                 JTextField field = new JTextField();
680                                 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
681                                                 "Input text key to generate random rocket:",
682                                                 field
683                                         }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
684                                                 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
685                                                                 "Random", "OK"
686                                 }, "OK");
687                                 
688                                 Rocket r;
689                                 if (sel == 0) {
690                                         r = new TestRockets(null).makeTestRocket();
691                                 } else if (sel == 1) {
692                                         r = new TestRockets(field.getText()).makeTestRocket();
693                                 } else {
694                                         return;
695                                 }
696                                 
697                                 OpenRocketDocument doc = new OpenRocketDocument(r);
698                                 doc.setSaved(true);
699                                 BasicFrame frame = new BasicFrame(doc);
700                                 frame.setVisible(true);
701                         }
702                 });
703                 menu.add(item);
704                 
705
706
707                 item = new JMenuItem("Create 'Iso-Haisu'");
708                 item.addActionListener(new ActionListener() {
709                         @Override
710                         public void actionPerformed(ActionEvent e) {
711                                 log.user("Create Iso-Haisu selected");
712                                 Rocket r = TestRockets.makeIsoHaisu();
713                                 OpenRocketDocument doc = new OpenRocketDocument(r);
714                                 doc.setSaved(true);
715                                 BasicFrame frame = new BasicFrame(doc);
716                                 frame.setVisible(true);
717                         }
718                 });
719                 menu.add(item);
720                 
721
722                 item = new JMenuItem("Create 'Big Blue'");
723                 item.addActionListener(new ActionListener() {
724                         @Override
725                         public void actionPerformed(ActionEvent e) {
726                                 log.user("Create Big Blue selected");
727                                 Rocket r = TestRockets.makeBigBlue();
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                 menu.addSeparator();
737                 
738
739                 item = new JMenuItem("Memory statistics");
740                 item.addActionListener(new ActionListener() {
741                         @Override
742                         public void actionPerformed(ActionEvent e) {
743                                 log.user("Memory statistics selected");
744                                 
745                                 // Get discarded but remaining objects (this also runs System.gc multiple times)
746                                 List<MemoryData> objects = MemoryManagement.getRemainingObjects();
747                                 StringBuilder sb = new StringBuilder();
748                                 sb.append("Objects that should have been garbage-collected but have not been:\n");
749                                 int count = 0;
750                                 for (MemoryData data : objects) {
751                                         Object o = data.getReference().get();
752                                         if (o == null)
753                                                 continue;
754                                         sb.append("Age ").append(System.currentTimeMillis() - data.getRegistrationTime())
755                                                         .append(" ms:  ").append(o).append('\n');
756                                         count++;
757                                         // Explicitly null the strong reference to avoid possibility of invisible references
758                                         o = null;
759                                 }
760                                 sb.append("Total: " + count);
761                                 
762                                 // Get basic memory stats
763                                 System.gc();
764                                 long max = Runtime.getRuntime().maxMemory();
765                                 long free = Runtime.getRuntime().freeMemory();
766                                 long used = max - free;
767                                 String[] stats = new String[4];
768                                 stats[0] = "Memory usage:";
769                                 stats[1] = String.format("   Max memory:  %.1f MB", max / 1024.0 / 1024.0);
770                                 stats[2] = String.format("   Used memory: %.1f MB (%.0f%%)", used / 1024.0 / 1024.0, 100.0 * used / max);
771                                 stats[3] = String.format("   Free memory: %.1f MB (%.0f%%)", free / 1024.0 / 1024.0, 100.0 * free / max);
772                                 
773
774                                 DetailDialog.showDetailedMessageDialog(BasicFrame.this, stats, sb.toString(),
775                                                 "Memory statistics", JOptionPane.INFORMATION_MESSAGE);
776                         }
777                 });
778                 menu.add(item);
779                 
780
781                 item = new JMenuItem("Exhaust memory");
782                 item.addActionListener(new ActionListener() {
783                         @Override
784                         public void actionPerformed(ActionEvent e) {
785                                 log.user("Exhaust memory selected");
786                                 LinkedList<byte[]> data = new LinkedList<byte[]>();
787                                 int count = 0;
788                                 final int bytesPerArray = 10240;
789                                 try {
790                                         while (true) {
791                                                 byte[] array = new byte[bytesPerArray];
792                                                 for (int i = 0; i < bytesPerArray; i++) {
793                                                         array[i] = (byte) i;
794                                                 }
795                                                 data.add(array);
796                                                 count++;
797                                         }
798                                 } catch (OutOfMemoryError error) {
799                                         data = null;
800                                         long size = bytesPerArray * (long) count;
801                                         String s = String.format("OutOfMemory occurred after %d iterations (approx. %.1f MB consumed)",
802                                                         count, size / 1024.0 / 1024.0);
803                                         log.debug(s, error);
804                                         JOptionPane.showMessageDialog(BasicFrame.this, s);
805                                 }
806                         }
807                 });
808                 menu.add(item);
809                 
810
811                 menu.addSeparator();
812                 
813                 item = new JMenuItem("Exception here");
814                 item.addActionListener(new ActionListener() {
815                         @Override
816                         public void actionPerformed(ActionEvent e) {
817                                 log.user("Exception here selected");
818                                 throw new RuntimeException("Testing exception from menu action listener");
819                         }
820                 });
821                 menu.add(item);
822                 
823                 item = new JMenuItem("Exception from EDT");
824                 item.addActionListener(new ActionListener() {
825                         public void actionPerformed(ActionEvent e) {
826                                 log.user("Exception from EDT selected");
827                                 SwingUtilities.invokeLater(new Runnable() {
828                                         @Override
829                                         public void run() {
830                                                 throw new RuntimeException("Testing exception from " +
831                                                                 "later invoked EDT thread");
832                                         }
833                                 });
834                         }
835                 });
836                 menu.add(item);
837                 
838                 item = new JMenuItem("Exception from other thread");
839                 item.addActionListener(new ActionListener() {
840                         public void actionPerformed(ActionEvent e) {
841                                 log.user("Exception from other thread selected");
842                                 new Thread() {
843                                         @Override
844                                         public void run() {
845                                                 throw new RuntimeException("Testing exception from " +
846                                                                 "newly created thread");
847                                         }
848                                 }.start();
849                         }
850                 });
851                 menu.add(item);
852                 
853                 item = new JMenuItem("OutOfMemoryError here");
854                 item.addActionListener(new ActionListener() {
855                         @Override
856                         public void actionPerformed(ActionEvent e) {
857                                 log.user("OutOfMemoryError here selected");
858                                 throw new OutOfMemoryError("Testing OutOfMemoryError from menu action listener");
859                         }
860                 });
861                 menu.add(item);
862                 
863
864
865                 return menu;
866         }
867         
868         
869         /**
870          * Select the tab on the main pane.
871          * 
872          * @param tab   one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
873          */
874         public void selectTab(int tab) {
875                 tabbedPane.setSelectedIndex(tab);
876         }
877         
878         
879
880         private void openAction() {
881                 JFileChooser chooser = new JFileChooser();
882                 
883                 chooser.addChoosableFileFilter(ALL_DESIGNS_FILTER);
884                 chooser.addChoosableFileFilter(OPENROCKET_DESIGN_FILTER);
885                 chooser.addChoosableFileFilter(ROCKSIM_DESIGN_FILTER);
886                 chooser.setFileFilter(ALL_DESIGNS_FILTER);
887                 
888                 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
889                 chooser.setMultiSelectionEnabled(true);
890                 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
891                 int option = chooser.showOpenDialog(this);
892                 if (option != JFileChooser.APPROVE_OPTION) {
893                         log.user("Decided not to open files, option=" + option);
894                         return;
895                 }
896                 
897                 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
898                 
899                 File[] files = chooser.getSelectedFiles();
900                 log.user("Opening files " + Arrays.toString(files));
901                 
902                 for (File file : files) {
903                         log.info("Opening file: " + file);
904                         if (open(file, this)) {
905                                 
906                                 // Close previous window if replacing
907                                 if (replaceable && document.isSaved()) {
908                                         log.info("Closing window because it is replaceable");
909                                         closeAction();
910                                         replaceable = false;
911                                 }
912                         }
913                 }
914         }
915         
916         
917         /**
918          * Open a file based on a URL.
919          * @param url           the file to open.
920          * @param parent        the parent window for dialogs.
921          * @return                      <code>true</code> if opened successfully.
922          */
923         private static boolean open(URL url, BasicFrame parent) {
924                 String filename = null;
925                 
926                 // First figure out the file name from the URL
927                 
928                 // Try using URI.getPath();
929                 try {
930                         URI uri = url.toURI();
931                         filename = uri.getPath();
932                 } catch (URISyntaxException ignore) {
933                 }
934                 
935                 // Try URL-decoding the URL
936                 if (filename == null) {
937                         try {
938                                 filename = URLDecoder.decode(url.toString(), "UTF-8");
939                         } catch (UnsupportedEncodingException ignore) {
940                         }
941                 }
942                 
943                 // Last resort
944                 if (filename == null) {
945                         filename = "";
946                 }
947                 
948                 // Remove path from filename
949                 if (filename.lastIndexOf('/') >= 0) {
950                         filename = filename.substring(filename.lastIndexOf('/') + 1);
951                 }
952                 
953
954                 // Open the file
955                 log.info("Opening file from url=" + url + " filename=" + filename);
956                 try {
957                         InputStream is = url.openStream();
958                         if (open(is, filename, parent)) {
959                                 // Close previous window if replacing
960                                 if (parent.replaceable && parent.document.isSaved()) {
961                                         parent.closeAction();
962                                         parent.replaceable = false;
963                                 }
964                         }
965                 } catch (IOException e) {
966                         log.warn("Error opening file" + e);
967                         JOptionPane.showMessageDialog(parent,
968                                         "An error occurred while opening the file " + filename,
969                                         "Error loading file", JOptionPane.ERROR_MESSAGE);
970                 }
971                 
972                 return false;
973         }
974         
975         
976         /**
977          * Open the specified file from an InputStream in a new design frame.  If an error
978          * occurs, an error dialog is shown and <code>false</code> is returned.
979          * 
980          * @param stream        the stream to load from.
981          * @param filename      the file name to display in dialogs (not set to the document).
982          * @param parent        the parent component for which a progress dialog is opened.
983          * @return                      whether the file was successfully loaded and opened.
984          */
985         private static boolean open(InputStream stream, String filename, Window parent) {
986                 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
987                 return open(worker, filename, null, parent);
988         }
989         
990         
991         /**
992          * Open the specified file in a new design frame.  If an error occurs, an error
993          * dialog is shown and <code>false</code> is returned.
994          * 
995          * @param file          the file to open.
996          * @param parent        the parent component for which a progress dialog is opened.
997          * @return                      whether the file was successfully loaded and opened.
998          */
999         public static boolean open(File file, Window parent) {
1000                 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
1001                 return open(worker, file.getName(), file, parent);
1002         }
1003         
1004         
1005         /**
1006          * Open the specified file using the provided worker.
1007          * 
1008          * @param worker        the OpenFileWorker that loads the file.
1009          * @param filename      the file name to display in dialogs.
1010          * @param file          the File to set the document to (may be null).
1011          * @param parent
1012          * @return
1013          */
1014         private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) {
1015                 
1016                 MotorDatabaseLoadingDialog.check(parent);
1017                 
1018                 // Open the file in a Swing worker thread
1019                 log.info("Starting OpenFileWorker");
1020                 if (!SwingWorkerDialog.runWorker(parent, "Opening file", "Reading " + filename + "...", worker)) {
1021                         // User cancelled the operation
1022                         log.info("User cancelled the OpenFileWorker");
1023                         return false;
1024                 }
1025                 
1026
1027                 // Handle the document
1028                 OpenRocketDocument doc = null;
1029                 try {
1030                         
1031                         doc = worker.get();
1032                         
1033                 } catch (ExecutionException e) {
1034                         
1035                         Throwable cause = e.getCause();
1036                         
1037                         if (cause instanceof FileNotFoundException) {
1038                                 
1039                                 log.warn("File not found", cause);
1040                                 JOptionPane.showMessageDialog(parent,
1041                                                 "File not found: " + filename,
1042                                                 "Error opening file", JOptionPane.ERROR_MESSAGE);
1043                                 return false;
1044                                 
1045                         } else if (cause instanceof RocketLoadException) {
1046                                 
1047                                 log.warn("Error loading the file", cause);
1048                                 JOptionPane.showMessageDialog(parent,
1049                                                 "Unable to open file '" + filename + "': "
1050                                                                 + cause.getMessage(),
1051                                                 "Error opening file", JOptionPane.ERROR_MESSAGE);
1052                                 return false;
1053                                 
1054                         } else {
1055                                 
1056                                 throw new BugException("Unknown error when opening file", e);
1057                                 
1058                         }
1059                         
1060                 } catch (InterruptedException e) {
1061                         throw new BugException("EDT was interrupted", e);
1062                 }
1063                 
1064                 if (doc == null) {
1065                         throw new BugException("Document loader returned null");
1066                 }
1067                 
1068
1069                 // Show warnings
1070                 WarningSet warnings = worker.getRocketLoader().getWarnings();
1071                 if (!warnings.isEmpty()) {
1072                         log.info("Warnings while reading file: " + warnings);
1073                         WarningDialog.showWarnings(parent,
1074                                         new Object[] {
1075                                                         "The following problems were encountered while opening " + filename + ".",
1076                                                         "Some design features may not have been loaded correctly."
1077                                         },
1078                                         "Warnings while opening file", warnings);
1079                 }
1080                 
1081
1082                 // Set document state
1083                 doc.setFile(file);
1084                 doc.setSaved(true);
1085                 
1086                 // Open the frame
1087                 log.debug("Opening new frame with the document");
1088                 BasicFrame frame = new BasicFrame(doc);
1089                 frame.setVisible(true);
1090                 
1091                 return true;
1092         }
1093         
1094         
1095
1096
1097
1098         private boolean saveAction() {
1099                 File file = document.getFile();
1100                 if (file == null) {
1101                         log.info("Document does not contain file, opening save as dialog instead");
1102                         return saveAsAction();
1103                 }
1104                 log.info("Saving document to " + file);
1105                 
1106                 // Saving RockSim designs is not supported
1107                 if (ROCKSIM_DESIGN_FILTER.accept(file)) {
1108                         file = new File(file.getAbsolutePath().replaceAll(".[rR][kK][tT](.[gG][zZ])?$",
1109                                         ".ork"));
1110                         
1111                         log.info("Attempting to save in RockSim format, renaming to " + file);
1112                         int option = JOptionPane.showConfirmDialog(this, new Object[] {
1113                                         "Saving designs in RockSim format is not supported.",
1114                                         "Save in OpenRocket format instead (" + file.getName() + ")?"
1115                                 }, "Save " + file.getName(), JOptionPane.YES_NO_OPTION,
1116                                         JOptionPane.QUESTION_MESSAGE, null);
1117                         if (option != JOptionPane.YES_OPTION) {
1118                                 log.user("User chose not to save");
1119                                 return false;
1120                         }
1121                         
1122                         document.setFile(file);
1123                 }
1124                 return saveAs(file);
1125         }
1126         
1127         
1128         private boolean saveAsAction() {
1129                 File file = null;
1130                 
1131                 // TODO: HIGH: what if *.rkt chosen?
1132                 StorageOptionChooser storageChooser =
1133                                 new StorageOptionChooser(document, document.getDefaultStorageOptions());
1134                 JFileChooser chooser = new JFileChooser();
1135                 chooser.setFileFilter(OPENROCKET_DESIGN_FILTER);
1136                 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
1137                 chooser.setAccessory(storageChooser);
1138                 if (document.getFile() != null)
1139                         chooser.setSelectedFile(document.getFile());
1140                 
1141                 int option = chooser.showSaveDialog(BasicFrame.this);
1142                 if (option != JFileChooser.APPROVE_OPTION) {
1143                         log.user("User decided not to save, option=" + option);
1144                         return false;
1145                 }
1146                 
1147                 file = chooser.getSelectedFile();
1148                 if (file == null) {
1149                         log.user("User did not select a file");
1150                         return false;
1151                 }
1152                 
1153                 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
1154                 storageChooser.storeOptions(document.getDefaultStorageOptions());
1155                 
1156                 if (file.getName().indexOf('.') < 0) {
1157                         log.debug("File name does not contain extension, adding .ork");
1158                         String name = file.getAbsolutePath();
1159                         name = name + ".ork";
1160                         file = new File(name);
1161                 }
1162                 
1163                 if (file.exists()) {
1164                         log.info("File " + file + " exists, confirming overwrite from user");
1165                         int result = JOptionPane.showConfirmDialog(this,
1166                                         "File '" + file.getName() + "' exists.  Do you want to overwrite it?",
1167                                         "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
1168                         if (result != JOptionPane.YES_OPTION) {
1169                                 log.user("User decided not to overwrite the file");
1170                                 return false;
1171                         }
1172                 }
1173                 
1174                 return saveAs(file);
1175         }
1176         
1177         private boolean saveAs(File file) {
1178                 log.info("Saving document as " + file);
1179                 boolean saved = false;
1180                 
1181                 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1182                         // User cancelled the dialog
1183                         log.user("User cancelled saving in storage options dialog");
1184                         return false;
1185                 }
1186                 
1187
1188                 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1189                 
1190                 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1191                                 "Writing " + file.getName() + "...", worker)) {
1192                         
1193                         // User cancelled the save
1194                         log.user("User cancelled the save, deleting the file");
1195                         file.delete();
1196                         return false;
1197                 }
1198                 
1199                 try {
1200                         worker.get();
1201                         document.setFile(file);
1202                         document.setSaved(true);
1203                         saved = true;
1204                         setTitle();
1205                 } catch (ExecutionException e) {
1206                         
1207                         Throwable cause = e.getCause();
1208                         
1209                         if (cause instanceof IOException) {
1210                                 log.warn("An I/O error occurred while saving " + file, cause);
1211                                 JOptionPane.showMessageDialog(this, new String[] {
1212                                                 "An I/O error occurred while saving:",
1213                                                 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1214                                 return false;
1215                         } else {
1216                                 Reflection.handleWrappedException(e);
1217                         }
1218                         
1219                 } catch (InterruptedException e) {
1220                         throw new BugException("EDT was interrupted", e);
1221                 }
1222                 
1223                 return saved;
1224         }
1225         
1226         
1227         private boolean closeAction() {
1228                 if (!document.isSaved()) {
1229                         log.info("Confirming whether to save the design");
1230                         ComponentConfigDialog.hideDialog();
1231                         int result = JOptionPane.showConfirmDialog(this,
1232                                         "Design '" + rocket.getName() + "' has not been saved.  " +
1233                                                         "Do you want to save it?",
1234                                         "Design not saved", JOptionPane.YES_NO_CANCEL_OPTION,
1235                                         JOptionPane.QUESTION_MESSAGE);
1236                         if (result == JOptionPane.YES_OPTION) {
1237                                 // Save
1238                                 log.user("User requested file save");
1239                                 if (!saveAction()) {
1240                                         log.info("File save was interrupted, not closing");
1241                                         return false;
1242                                 }
1243                         } else if (result == JOptionPane.NO_OPTION) {
1244                                 // Don't save: No-op
1245                                 log.user("User requested to discard design");
1246                         } else {
1247                                 // Cancel or close
1248                                 log.user("User cancelled closing, result=" + result);
1249                                 return false;
1250                         }
1251                 }
1252                 
1253                 // Rocket has been saved or discarded
1254                 log.debug("Disposing window");
1255                 this.dispose();
1256                 
1257                 ComponentConfigDialog.hideDialog();
1258                 ComponentAnalysisDialog.hideDialog();
1259                 
1260                 frames.remove(this);
1261                 if (frames.isEmpty()) {
1262                         log.info("Last frame closed, exiting");
1263                         System.exit(0);
1264                 }
1265                 return true;
1266         }
1267         
1268         
1269
1270         /**
1271          * Open a new design window with a basic rocket+stage.
1272          */
1273         public static void newAction() {
1274                 log.info("New action initiated");
1275                 
1276                 Rocket rocket = new Rocket();
1277                 Stage stage = new Stage();
1278                 stage.setName("Sustainer");
1279                 rocket.addChild(stage);
1280                 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1281                 doc.setSaved(true);
1282                 
1283                 BasicFrame frame = new BasicFrame(doc);
1284                 frame.replaceable = true;
1285                 frame.setVisible(true);
1286                 ComponentConfigDialog.showDialog(frame, doc, rocket);
1287         }
1288         
1289         /**
1290          * Quit the application.  Confirms saving unsaved designs.  The action of File->Quit.
1291          */
1292         public static void quitAction() {
1293                 log.info("Quit action initiated");
1294                 for (int i = frames.size() - 1; i >= 0; i--) {
1295                         log.debug("Closing frame " + frames.get(i));
1296                         if (!frames.get(i).closeAction()) {
1297                                 // Close canceled
1298                                 log.info("Quit was cancelled");
1299                                 return;
1300                         }
1301                 }
1302                 // Should not be reached, but just in case
1303                 log.error("Should already have exited application");
1304                 System.exit(0);
1305         }
1306         
1307         
1308         /**
1309          * Set the title of the frame, taking into account the name of the rocket, file it 
1310          * has been saved to (if any) and saved status.
1311          */
1312         private void setTitle() {
1313                 File file = document.getFile();
1314                 boolean saved = document.isSaved();
1315                 String title;
1316                 
1317                 title = rocket.getName();
1318                 if (file != null) {
1319                         title = title + " (" + file.getName() + ")";
1320                 }
1321                 if (!saved)
1322                         title = "*" + title;
1323                 
1324                 setTitle(title);
1325         }
1326         
1327         
1328
1329         /**
1330          * Find a currently open BasicFrame containing the specified rocket.  This method
1331          * can be used to map a Rocket to a BasicFrame from GUI methods.
1332          * 
1333          * @param rocket the Rocket.
1334          * @return               the corresponding BasicFrame, or <code>null</code> if none found.
1335          */
1336         public static BasicFrame findFrame(Rocket rocket) {
1337                 for (BasicFrame f : frames) {
1338                         if (f.rocket == rocket) {
1339                                 log.debug("Found frame " + f + " for rocket " + rocket);
1340                                 return f;
1341                         }
1342                 }
1343                 log.debug("Could not find frame for rocket " + rocket);
1344                 return null;
1345         }
1346         
1347         /**
1348          * Find a currently open document by the rocket object.  This method can be used
1349          * to map a Rocket to OpenRocketDocument from GUI methods.
1350          * 
1351          * @param rocket the Rocket.
1352          * @return               the corresponding OpenRocketDocument, or <code>null</code> if not found.
1353          */
1354         public static OpenRocketDocument findDocument(Rocket rocket) {
1355                 BasicFrame frame = findFrame(rocket);
1356                 if (frame != null) {
1357                         return frame.document;
1358                 } else {
1359                         return null;
1360                 }
1361         }
1362 }