added svn:ignores
[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.JSplitPane;
45 import javax.swing.JTabbedPane;
46 import javax.swing.JTextField;
47 import javax.swing.KeyStroke;
48 import javax.swing.ListSelectionModel;
49 import javax.swing.ScrollPaneConstants;
50 import javax.swing.SwingUtilities;
51 import javax.swing.border.TitledBorder;
52 import javax.swing.event.TreeSelectionEvent;
53 import javax.swing.event.TreeSelectionListener;
54 import javax.swing.filechooser.FileFilter;
55 import javax.swing.tree.DefaultTreeSelectionModel;
56 import javax.swing.tree.TreePath;
57 import javax.swing.tree.TreeSelectionModel;
58
59 import net.miginfocom.swing.MigLayout;
60 import net.sf.openrocket.aerodynamics.WarningSet;
61 import net.sf.openrocket.document.OpenRocketDocument;
62 import net.sf.openrocket.file.GeneralRocketLoader;
63 import net.sf.openrocket.file.RocketLoadException;
64 import net.sf.openrocket.file.RocketLoader;
65 import net.sf.openrocket.file.RocketSaver;
66 import net.sf.openrocket.file.openrocket.OpenRocketSaver;
67 import net.sf.openrocket.gui.StorageOptionChooser;
68 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
69 import net.sf.openrocket.gui.dialogs.AboutDialog;
70 import net.sf.openrocket.gui.dialogs.BugReportDialog;
71 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
72 import net.sf.openrocket.gui.dialogs.DebugLogDialog;
73 import net.sf.openrocket.gui.dialogs.DetailDialog;
74 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
75 import net.sf.openrocket.gui.dialogs.LicenseDialog;
76 import net.sf.openrocket.gui.dialogs.MotorDatabaseLoadingDialog;
77 import net.sf.openrocket.gui.dialogs.PrintDialog;
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                         @Override
181                         public void componentChanged(ComponentChangeEvent e) {
182                                 replaceable = false;
183                                 BasicFrame.this.rocket.removeComponentChangeListener(this);
184                         }
185                 });
186                 
187
188                 // Create the component tree selection model that will be used
189                 componentSelectionModel = new DefaultTreeSelectionModel();
190                 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
191                 
192                 // Obtain the simulation selection model that will be used
193                 SimulationPanel simulationPanel = new SimulationPanel(document);
194                 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
195                 
196                 // Combine into a DocumentSelectionModel
197                 selectionModel = new DocumentSelectionModel(document);
198                 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
199                 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
200                 
201
202                 actions = new RocketActions(document, selectionModel, this);
203                 
204
205                 log.debug("Constructing the BasicFrame UI");
206                 
207                 // The main vertical split pane         
208                 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
209                 vertical.setResizeWeight(0.5);
210                 this.add(vertical);
211                 
212
213                 // The top tabbed pane
214                 tabbedPane = new JTabbedPane();
215                 tabbedPane.addTab("Rocket design", null, designTab());
216                 tabbedPane.addTab("Flight simulations", null, simulationPanel);
217                 
218                 vertical.setTopComponent(tabbedPane);
219                 
220
221
222                 //  Bottom segment, rocket figure
223                 
224                 rocketpanel = new RocketPanel(document);
225                 vertical.setBottomComponent(rocketpanel);
226                 
227                 rocketpanel.setSelectionModel(tree.getSelectionModel());
228                 
229
230                 createMenu();
231                 
232
233                 rocket.addComponentChangeListener(new ComponentChangeListener() {
234                         @Override
235                         public void componentChanged(ComponentChangeEvent e) {
236                                 setTitle();
237                         }
238                 });
239                 
240                 setTitle();
241                 this.pack();
242                 
243                 Dimension size = Prefs.getWindowSize(this.getClass());
244                 if (size == null) {
245                         size = Toolkit.getDefaultToolkit().getScreenSize();
246                         size.width = size.width * 9 / 10;
247                         size.height = size.height * 9 / 10;
248                 }
249                 this.setSize(size);
250                 this.addComponentListener(new ComponentAdapter() {
251                         @Override
252                         public void componentResized(ComponentEvent e) {
253                                 Prefs.setWindowSize(BasicFrame.this.getClass(), BasicFrame.this.getSize());
254                         }
255                 });
256                 this.setLocationByPlatform(true);
257                 
258                 GUIUtil.setWindowIcons(this);
259                 
260                 this.validate();
261                 vertical.setDividerLocation(0.4);
262                 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
263                 addWindowListener(new WindowAdapter() {
264                         @Override
265                         public void windowClosing(WindowEvent e) {
266                                 closeAction();
267                         }
268                 });
269                 frames.add(this);
270                 
271                 log.debug("BasicFrame instantiation complete");
272         }
273         
274         
275         /**
276          * Construct the "Rocket design" tab.  This contains a horizontal split pane
277          * with the left component the design tree and the right component buttons
278          * for adding components.
279          */
280         private JComponent designTab() {
281                 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
282                 horizontal.setResizeWeight(0.5);
283                 
284
285                 //  Upper-left segment, component tree
286                 
287                 JPanel panel = new JPanel(new MigLayout("fill, flowy", "", "[grow]"));
288                 
289                 tree = new ComponentTree(document);
290                 tree.setSelectionModel(componentSelectionModel);
291                 
292                 // Remove JTree key events that interfere with menu accelerators
293                 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
294                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
295                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
296                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
297                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
298                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
299                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
300                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
301                 
302
303
304                 // Double-click opens config dialog
305                 MouseListener ml = new MouseAdapter() {
306                         @Override
307                         public void mousePressed(MouseEvent e) {
308                                 int selRow = tree.getRowForLocation(e.getX(), e.getY());
309                                 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
310                                 if (selRow != -1) {
311                                         if ((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
312                                                 // Double-click
313                                                 RocketComponent c = (RocketComponent) selPath.getLastPathComponent();
314                                                 ComponentConfigDialog.showDialog(BasicFrame.this,
315                                                                 BasicFrame.this.document, c);
316                                         }
317                                 }
318                         }
319                 };
320                 tree.addMouseListener(ml);
321                 
322                 // Update dialog when selection is changed
323                 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
324                         @Override
325                         public void valueChanged(TreeSelectionEvent e) {
326                                 // Scroll tree to the selected item
327                                 TreePath path = componentSelectionModel.getSelectionPath();
328                                 if (path == null)
329                                         return;
330                                 tree.scrollPathToVisible(path);
331                                 
332                                 if (!ComponentConfigDialog.isDialogVisible())
333                                         return;
334                                 RocketComponent c = (RocketComponent) path.getLastPathComponent();
335                                 ComponentConfigDialog.showDialog(BasicFrame.this,
336                                                 BasicFrame.this.document, c);
337                         }
338                 });
339                 
340                 // Place tree inside scroll pane
341                 JScrollPane scroll = new JScrollPane(tree);
342                 panel.add(scroll, "spany, grow, wrap");
343                 
344
345                 // Buttons
346                 JButton button = new JButton(actions.getMoveUpAction());
347                 panel.add(button, "sizegroup buttons, aligny 65%");
348                 
349                 button = new JButton(actions.getMoveDownAction());
350                 panel.add(button, "sizegroup buttons, aligny 0%");
351                 
352                 button = new JButton(actions.getEditAction());
353                 panel.add(button, "sizegroup buttons");
354                 
355                 button = new JButton(actions.getNewStageAction());
356                 panel.add(button, "sizegroup buttons");
357                 
358                 button = new JButton(actions.getDeleteAction());
359                 button.setIcon(null);
360                 button.setMnemonic(0);
361                 panel.add(button, "sizegroup buttons");
362                 
363                 horizontal.setLeftComponent(panel);
364                 
365
366                 //  Upper-right segment, component addition buttons
367                 
368                 panel = new JPanel(new MigLayout("fill, insets 0", "[0::]"));
369                 
370                 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
371                                 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
372                 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
373                                 scroll.getViewport()));
374                 scroll.setBorder(null);
375                 scroll.setViewportBorder(null);
376                 
377                 TitledBorder border = new TitledBorder("Add new component");
378                 border.setTitleFont(border.getTitleFont().deriveFont(Font.BOLD));
379                 scroll.setBorder(border);
380                 
381                 panel.add(scroll, "grow");
382                 
383                 horizontal.setRightComponent(panel);
384                 
385                 return horizontal;
386         }
387         
388         
389
390         /**
391          * Creates the menu for the window.
392          */
393         private void createMenu() {
394                 JMenuBar menubar = new JMenuBar();
395                 JMenu menu;
396                 JMenuItem item;
397                 
398                 ////  File
399                 menu = new JMenu("File");
400                 menu.setMnemonic(KeyEvent.VK_F);
401                 menu.getAccessibleContext().setAccessibleDescription("File-handling related tasks");
402                 menubar.add(menu);
403                 
404                 item = new JMenuItem("New", KeyEvent.VK_N);
405                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
406                 item.setMnemonic(KeyEvent.VK_N);
407                 item.getAccessibleContext().setAccessibleDescription("Create a new rocket design");
408                 item.setIcon(Icons.FILE_NEW);
409                 item.addActionListener(new ActionListener() {
410                         @Override
411                         public void actionPerformed(ActionEvent e) {
412                                 log.user("New... selected");
413                                 newAction();
414                                 if (replaceable) {
415                                         log.info("Closing previous window");
416                                         closeAction();
417                                 }
418                         }
419                 });
420                 menu.add(item);
421                 
422                 item = new JMenuItem("Open...", KeyEvent.VK_O);
423                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
424                 item.getAccessibleContext().setAccessibleDescription("Open a rocket design");
425                 item.setIcon(Icons.FILE_OPEN);
426                 item.addActionListener(new ActionListener() {
427                         @Override
428                         public void actionPerformed(ActionEvent e) {
429                                 log.user("Open... selected");
430                                 openAction();
431                         }
432                 });
433                 menu.add(item);
434                 
435                 item = new JMenuItem("Open example...");
436                 item.getAccessibleContext().setAccessibleDescription("Open an example rocket design");
437                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
438                                 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
439                 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
440                 item.addActionListener(new ActionListener() {
441                         @Override
442                         public void actionPerformed(ActionEvent e) {
443                                 log.user("Open example... selected");
444                                 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
445                                 if (urls != null) {
446                                         for (URL u : urls) {
447                                                 log.user("Opening example " + u);
448                                                 open(u, BasicFrame.this);
449                                         }
450                                 }
451                         }
452                 });
453                 menu.add(item);
454                 
455                 menu.addSeparator();
456                 
457                 item = new JMenuItem("Save", KeyEvent.VK_S);
458                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
459                 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design");
460                 item.setIcon(Icons.FILE_SAVE);
461                 item.addActionListener(new ActionListener() {
462                         @Override
463                         public void actionPerformed(ActionEvent e) {
464                                 log.user("Save selected");
465                                 saveAction();
466                         }
467                 });
468                 menu.add(item);
469                 
470                 item = new JMenuItem("Save as...", KeyEvent.VK_A);
471                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
472                                 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
473                 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design " +
474                                 "to a new file");
475                 item.setIcon(Icons.FILE_SAVE_AS);
476                 item.addActionListener(new ActionListener() {
477                         @Override
478                         public void actionPerformed(ActionEvent e) {
479                                 log.user("Save as... selected");
480                                 saveAsAction();
481                         }
482                 });
483                 menu.add(item);
484                 
485
486                 item = new JMenuItem("Print / Export PDF...", KeyEvent.VK_P);
487                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
488                 item.getAccessibleContext().setAccessibleDescription("Print parts list and fin template");
489                 item.setIcon(Icons.FILE_PRINT);
490                 item.addActionListener(new ActionListener() {
491                         @Override
492                         public void actionPerformed(ActionEvent e) {
493                                 log.user("Print action selected");
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                 if (!Prefs.getBoolean("printing.experimental.communicated", false)) {
1307                         log.info("Showing printing is experimental warning to the user");
1308                         JOptionPane.showMessageDialog(this, "Printing is an currently an experimental feature " +
1309                                         "and might not fully work on all platforms",
1310                                         "Experimental feature", JOptionPane.WARNING_MESSAGE);
1311                         Prefs.putBoolean("printing.experimental.communicated", true);
1312                 }
1313                 new PrintDialog(this, document).setVisible(true);
1314         }
1315         
1316         /**
1317          * Open a new design window with a basic rocket+stage.
1318          */
1319         public static void newAction() {
1320                 log.info("New action initiated");
1321                 
1322                 Rocket rocket = new Rocket();
1323                 Stage stage = new Stage();
1324                 stage.setName("Sustainer");
1325                 rocket.addChild(stage);
1326                 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1327                 doc.setSaved(true);
1328                 
1329                 BasicFrame frame = new BasicFrame(doc);
1330                 frame.replaceable = true;
1331                 frame.setVisible(true);
1332                 ComponentConfigDialog.showDialog(frame, doc, rocket);
1333         }
1334         
1335         /**
1336          * Quit the application.  Confirms saving unsaved designs.  The action of File->Quit.
1337          */
1338         public static void quitAction() {
1339                 log.info("Quit action initiated");
1340                 for (int i = frames.size() - 1; i >= 0; i--) {
1341                         log.debug("Closing frame " + frames.get(i));
1342                         if (!frames.get(i).closeAction()) {
1343                                 // Close canceled
1344                                 log.info("Quit was cancelled");
1345                                 return;
1346                         }
1347                 }
1348                 // Should not be reached, but just in case
1349                 log.error("Should already have exited application");
1350                 System.exit(0);
1351         }
1352         
1353         
1354         /**
1355          * Set the title of the frame, taking into account the name of the rocket, file it 
1356          * has been saved to (if any) and saved status.
1357          */
1358         private void setTitle() {
1359                 File file = document.getFile();
1360                 boolean saved = document.isSaved();
1361                 String title;
1362                 
1363                 title = rocket.getName();
1364                 if (file != null) {
1365                         title = title + " (" + file.getName() + ")";
1366                 }
1367                 if (!saved)
1368                         title = "*" + title;
1369                 
1370                 setTitle(title);
1371         }
1372         
1373         
1374
1375         /**
1376          * Find a currently open BasicFrame containing the specified rocket.  This method
1377          * can be used to map a Rocket to a BasicFrame from GUI methods.
1378          * 
1379          * @param rocket the Rocket.
1380          * @return               the corresponding BasicFrame, or <code>null</code> if none found.
1381          */
1382         public static BasicFrame findFrame(Rocket rocket) {
1383                 for (BasicFrame f : frames) {
1384                         if (f.rocket == rocket) {
1385                                 log.debug("Found frame " + f + " for rocket " + rocket);
1386                                 return f;
1387                         }
1388                 }
1389                 log.debug("Could not find frame for rocket " + rocket);
1390                 return null;
1391         }
1392         
1393         /**
1394          * Find a currently open document by the rocket object.  This method can be used
1395          * to map a Rocket to OpenRocketDocument from GUI methods.
1396          * 
1397          * @param rocket the Rocket.
1398          * @return               the corresponding OpenRocketDocument, or <code>null</code> if not found.
1399          */
1400         public static OpenRocketDocument findDocument(Rocket rocket) {
1401                 BasicFrame frame = findFrame(rocket);
1402                 if (frame != null) {
1403                         return frame.document;
1404                 } else {
1405                         return null;
1406                 }
1407         }
1408 }