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