Fixing various issues
[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          * Sole constructor.  Creates a new frame based on the supplied document
157          * and adds it to the current frames list.
158          * 
159          * @param document      the document to show.
160          */
161         public BasicFrame(OpenRocketDocument document) {
162                 log.debug("Instantiating new BasicFrame");
163                 
164                 this.document = document;
165                 this.rocket = document.getRocket();
166                 this.rocket.getDefaultConfiguration().setAllStages();
167                 
168                 
169                 // Set replaceable flag to false at first modification
170                 rocket.addComponentChangeListener(new ComponentChangeListener() {
171                         @Override
172                         public void componentChanged(ComponentChangeEvent e) {
173                                 replaceable = false;
174                                 BasicFrame.this.rocket.removeComponentChangeListener(this);
175                         }
176                 });
177                 
178                 
179                 // Create the component tree selection model that will be used
180                 componentSelectionModel = new DefaultTreeSelectionModel();
181                 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
182                 
183                 // Obtain the simulation selection model that will be used
184                 SimulationPanel simulationPanel = new SimulationPanel(document);
185                 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
186                 
187                 // Combine into a DocumentSelectionModel
188                 selectionModel = new DocumentSelectionModel(document);
189                 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
190                 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
191                 
192                 
193                 actions = new RocketActions(document, selectionModel, this);
194                 
195                 
196                 log.debug("Constructing the BasicFrame UI");
197                 
198                 // The main vertical split pane         
199                 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
200                 vertical.setResizeWeight(0.5);
201                 this.add(vertical);
202                 
203                 
204                 // The top tabbed pane
205                 tabbedPane = new JTabbedPane();
206                 //// Rocket design
207                 tabbedPane.addTab(trans.get("BasicFrame.tab.Rocketdesign"), null, designTab());
208                 //// Flight simulations
209                 tabbedPane.addTab(trans.get("BasicFrame.tab.Flightsim"), null, simulationPanel);
210                 
211                 vertical.setTopComponent(tabbedPane);
212                 
213                 
214                 
215                 //  Bottom segment, rocket figure
216                 
217                 rocketpanel = new RocketPanel(document);
218                 vertical.setBottomComponent(rocketpanel);
219                 
220                 rocketpanel.setSelectionModel(tree.getSelectionModel());
221                 
222                 
223                 createMenu();
224                 
225                 
226                 rocket.addComponentChangeListener(new ComponentChangeListener() {
227                         @Override
228                         public void componentChanged(ComponentChangeEvent e) {
229                                 setTitle();
230                         }
231                 });
232                 
233                 setTitle();
234                 this.pack();
235                 
236                 
237                 // Set initial window size
238                 Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
239                 size.width = size.width * 9 / 10;
240                 size.height = size.height * 9 / 10;
241                 this.setSize(size);
242                 
243                 // Remember changed size
244                 GUIUtil.rememberWindowSize(this);
245                 
246                 this.setLocationByPlatform(true);
247                 
248                 GUIUtil.setWindowIcons(this);
249                 
250                 this.validate();
251                 vertical.setDividerLocation(0.4);
252                 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
253                 addWindowListener(new WindowAdapter() {
254                         @Override
255                         public void windowClosing(WindowEvent e) {
256                                 closeAction();
257                         }
258                 });
259                 
260                 frames.add(this);
261                 log.debug("BasicFrame instantiation complete");
262         }
263         
264         
265         /**
266          * Construct the "Rocket design" tab.  This contains a horizontal split pane
267          * with the left component the design tree and the right component buttons
268          * for adding components.
269          */
270         private JComponent designTab() {
271                 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
272                 horizontal.setResizeWeight(0.5);
273                 
274                 
275                 //  Upper-left segment, component tree
276                 
277                 JPanel panel = new JPanel(new MigLayout("fill, flowy", "", "[grow]"));
278                 
279                 tree = new ComponentTree(document);
280                 tree.setSelectionModel(componentSelectionModel);
281                 
282                 // Remove JTree key events that interfere with menu accelerators
283                 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
284                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
285                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
286                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
287                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
288                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
289                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
290                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
291                 
292                 
293                 
294                 // Double-click opens config dialog
295                 MouseListener ml = new MouseAdapter() {
296                         @Override
297                         public void mousePressed(MouseEvent e) {
298                                 int selRow = tree.getRowForLocation(e.getX(), e.getY());
299                                 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
300                                 if (selRow != -1) {
301                                         if ((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
302                                                 // Double-click
303                                                 RocketComponent c = (RocketComponent) selPath.getLastPathComponent();
304                                                 ComponentConfigDialog.showDialog(BasicFrame.this,
305                                                                 BasicFrame.this.document, c);
306                                         }
307                                 }
308                         }
309                 };
310                 tree.addMouseListener(ml);
311                 
312                 // Update dialog when selection is changed
313                 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
314                         @Override
315                         public void valueChanged(TreeSelectionEvent e) {
316                                 // Scroll tree to the selected item
317                                 TreePath path = componentSelectionModel.getSelectionPath();
318                                 if (path == null)
319                                         return;
320                                 tree.scrollPathToVisible(path);
321                                 
322                                 if (!ComponentConfigDialog.isDialogVisible())
323                                         return;
324                                 RocketComponent c = (RocketComponent) path.getLastPathComponent();
325                                 ComponentConfigDialog.showDialog(BasicFrame.this,
326                                                 BasicFrame.this.document, c);
327                         }
328                 });
329                 
330                 // Place tree inside scroll pane
331                 JScrollPane scroll = new JScrollPane(tree);
332                 panel.add(scroll, "spany, grow, wrap");
333                 
334                 
335                 // Buttons
336                 JButton button = new JButton(actions.getMoveUpAction());
337                 panel.add(button, "sizegroup buttons, aligny 65%");
338                 
339                 button = new JButton(actions.getMoveDownAction());
340                 panel.add(button, "sizegroup buttons, aligny 0%");
341                 
342                 button = new JButton(actions.getEditAction());
343                 panel.add(button, "sizegroup buttons");
344                 
345                 button = new JButton(actions.getNewStageAction());
346                 panel.add(button, "sizegroup buttons");
347                 
348                 button = new JButton(actions.getDeleteAction());
349                 button.setIcon(null);
350                 button.setMnemonic(0);
351                 panel.add(button, "sizegroup buttons");
352                 
353                 horizontal.setLeftComponent(panel);
354                 
355                 
356                 //  Upper-right segment, component addition buttons
357                 
358                 panel = new JPanel(new MigLayout("fill, insets 0", "[0::]"));
359                 
360                 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
361                                 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
362                 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
363                                 scroll.getViewport()));
364                 scroll.setBorder(null);
365                 scroll.setViewportBorder(null);
366                 
367                 TitledBorder border = BorderFactory.createTitledBorder(trans.get("BasicFrame.title.Addnewcomp"));
368                 GUIUtil.changeFontStyle(border, Font.BOLD);
369                 scroll.setBorder(border);
370                 
371                 panel.add(scroll, "grow");
372                 
373                 horizontal.setRightComponent(panel);
374                 
375                 return horizontal;
376         }
377         
378         
379         
380         /**
381          * Return the currently selected rocket component, or <code>null</code> if none selected.
382          */
383         private RocketComponent getSelectedComponent() {
384                 TreePath path = componentSelectionModel.getSelectionPath();
385                 if (path == null)
386                         return null;
387                 tree.scrollPathToVisible(path);
388                 
389                 return (RocketComponent) path.getLastPathComponent();
390         }
391         
392         
393         /**
394          * Creates the menu for the window.
395          */
396         private void createMenu() {
397                 JMenuBar menubar = new JMenuBar();
398                 JMenu menu;
399                 JMenuItem item;
400                 
401                 ////  File
402                 menu = new JMenu(trans.get("main.menu.file"));
403                 menu.setMnemonic(KeyEvent.VK_F);
404                 //// File-handling related tasks
405                 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.desc"));
406                 menubar.add(menu);
407                 
408                 //// New 
409                 item = new JMenuItem(trans.get("main.menu.file.new"), KeyEvent.VK_N);
410                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
411                 item.setMnemonic(KeyEvent.VK_N);
412                 //// Create a new rocket design
413                 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.new.desc"));
414                 item.setIcon(Icons.FILE_NEW);
415                 item.addActionListener(new ActionListener() {
416                         @Override
417                         public void actionPerformed(ActionEvent e) {
418                                 log.user("New... selected");
419                                 newAction();
420                                 if (replaceable) {
421                                         log.info("Closing previous window");
422                                         closeAction();
423                                 }
424                         }
425                 });
426                 menu.add(item);
427                 
428                 //// Open...
429                 item = new JMenuItem(trans.get("main.menu.file.open"), KeyEvent.VK_O);
430                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
431                 //// Open a rocket design
432                 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openrocketdesign"));
433                 item.setIcon(Icons.FILE_OPEN);
434                 item.addActionListener(new ActionListener() {
435                         @Override
436                         public void actionPerformed(ActionEvent e) {
437                                 log.user("Open... selected");
438                                 openAction();
439                         }
440                 });
441                 menu.add(item);
442                 
443                 //// Open example...
444                 item = new JMenuItem(trans.get("main.menu.file.openExample"));
445                 //// Open an example rocket design
446                 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openexamplerocketdesign"));
447                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
448                                 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
449                 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
450                 item.addActionListener(new ActionListener() {
451                         @Override
452                         public void actionPerformed(ActionEvent e) {
453                                 log.user("Open example... selected");
454                                 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
455                                 if (urls != null) {
456                                         for (URL u : urls) {
457                                                 log.user("Opening example " + u);
458                                                 open(u, BasicFrame.this);
459                                         }
460                                 }
461                         }
462                 });
463                 menu.add(item);
464                 
465                 menu.addSeparator();
466                 
467                 //// Save
468                 item = new JMenuItem(trans.get("main.menu.file.save"), KeyEvent.VK_S);
469                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
470                 //// Save the current rocket design
471                 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesign"));
472                 item.setIcon(Icons.FILE_SAVE);
473                 item.addActionListener(new ActionListener() {
474                         @Override
475                         public void actionPerformed(ActionEvent e) {
476                                 log.user("Save selected");
477                                 saveAction();
478                         }
479                 });
480                 menu.add(item);
481                 
482                 //// Save as...
483                 item = new JMenuItem(trans.get("main.menu.file.saveAs"), KeyEvent.VK_A);
484                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
485                                 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
486                 //// Save the current rocket design to a new file
487                 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesnewfile"));
488                 item.setIcon(Icons.FILE_SAVE_AS);
489                 item.addActionListener(new ActionListener() {
490                         @Override
491                         public void actionPerformed(ActionEvent e) {
492                                 log.user("Save as... selected");
493                                 saveAsAction();
494                         }
495                 });
496                 menu.add(item);
497                 
498                 //// Print...
499                 item = new JMenuItem(trans.get("main.menu.file.print"), KeyEvent.VK_P);
500                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
501                 //// Print parts list and fin template
502                 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.print.desc"));
503                 item.setIcon(Icons.FILE_PRINT);
504                 item.addActionListener(new ActionListener() {
505                         @Override
506                         public void actionPerformed(ActionEvent e) {
507                                 log.user("Print action selected");
508                                 printAction();
509                         }
510                 });
511                 menu.add(item);
512                 
513                 
514                 menu.addSeparator();
515                 
516                 //// Close
517                 item = new JMenuItem(trans.get("main.menu.file.close"), KeyEvent.VK_C);
518                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
519                 //// Close the current rocket design
520                 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Closedesign"));
521                 item.setIcon(Icons.FILE_CLOSE);
522                 item.addActionListener(new ActionListener() {
523                         @Override
524                         public void actionPerformed(ActionEvent e) {
525                                 log.user("Close selected");
526                                 closeAction();
527                         }
528                 });
529                 menu.add(item);
530                 
531                 menu.addSeparator();
532                 
533                 //// Quit
534                 item = new JMenuItem(trans.get("main.menu.file.quit"), KeyEvent.VK_Q);
535                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
536                 //// Quit the program
537                 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Quitprogram"));
538                 item.setIcon(Icons.FILE_QUIT);
539                 item.addActionListener(new ActionListener() {
540                         @Override
541                         public void actionPerformed(ActionEvent e) {
542                                 log.user("Quit selected");
543                                 quitAction();
544                         }
545                 });
546                 menu.add(item);
547                 
548                 
549                 
550                 ////  Edit
551                 menu = new JMenu(trans.get("main.menu.edit"));
552                 menu.setMnemonic(KeyEvent.VK_E);
553                 //// Rocket editing
554                 menu.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.menu.Rocketedt"));
555                 menubar.add(menu);
556                 
557                 
558                 Action action = UndoRedoAction.newUndoAction(document);
559                 item = new JMenuItem(action);
560                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
561                 item.setMnemonic(KeyEvent.VK_U);
562                 //// Undo the previous operation
563                 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.undo.desc"));
564                 
565                 menu.add(item);
566                 
567                 action = UndoRedoAction.newRedoAction(document);
568                 item = new JMenuItem(action);
569                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
570                 item.setMnemonic(KeyEvent.VK_R);
571                 //// Redo the previously undone operation
572                 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.redo.desc"));
573                 menu.add(item);
574                 
575                 menu.addSeparator();
576                 
577                 
578                 item = new JMenuItem(actions.getCutAction());
579                 menu.add(item);
580                 
581                 item = new JMenuItem(actions.getCopyAction());
582                 menu.add(item);
583                 
584                 item = new JMenuItem(actions.getPasteAction());
585                 menu.add(item);
586                 
587                 item = new JMenuItem(actions.getDeleteAction());
588                 menu.add(item);
589                 
590                 menu.addSeparator();
591                 
592                 
593                 
594                 item = new JMenuItem(trans.get("main.menu.edit.resize"));
595                 item.setIcon(Icons.EDIT_SCALE);
596                 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.resize.desc"));
597                 item.addActionListener(new ActionListener() {
598                         @Override
599                         public void actionPerformed(ActionEvent e) {
600                                 log.user("Scale... selected");
601                                 ScaleDialog dialog = new ScaleDialog(document, getSelectedComponent(), BasicFrame.this);
602                                 dialog.setVisible(true);
603                                 dialog.dispose();
604                         }
605                 });
606                 menu.add(item);
607                 
608                 
609                 
610                 //// Preferences
611                 item = new JMenuItem(trans.get("main.menu.edit.preferences"));
612                 item.setIcon(Icons.PREFERENCES);
613                 //// Setup the application preferences
614                 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.preferences.desc"));
615                 item.addActionListener(new ActionListener() {
616                         @Override
617                         public void actionPerformed(ActionEvent e) {
618                                 log.user("Preferences selected");
619                                 PreferencesDialog.showPreferences(BasicFrame.this);
620                         }
621                 });
622                 menu.add(item);
623                 
624                 
625                 
626                 
627                 ////  Analyze
628                 menu = new JMenu(trans.get("main.menu.analyze"));
629                 menu.setMnemonic(KeyEvent.VK_A);
630                 //// Analyzing the rocket
631                 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.desc"));
632                 menubar.add(menu);
633                 
634                 //// Component analysis
635                 item = new JMenuItem(trans.get("main.menu.analyze.componentAnalysis"), KeyEvent.VK_C);
636                 //// Analyze the rocket components separately
637                 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.componentAnalysis.desc"));
638                 item.addActionListener(new ActionListener() {
639                         @Override
640                         public void actionPerformed(ActionEvent e) {
641                                 log.user("Component analysis selected");
642                                 ComponentAnalysisDialog.showDialog(rocketpanel);
643                         }
644                 });
645                 menu.add(item);
646                 
647                 
648                 item = new JMenuItem(trans.get("main.menu.analyze.optimization"), KeyEvent.VK_O);
649                 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.optimization.desc"));
650                 item.addActionListener(new ActionListener() {
651                         @Override
652                         public void actionPerformed(ActionEvent e) {
653                                 log.user("Rocket optimization selected");
654                                 new GeneralOptimizationDialog(document, BasicFrame.this).setVisible(true);
655                         }
656                 });
657                 menu.add(item);
658                 
659                 
660                 
661                 ////  Debug
662                 // (shown if openrocket.debug.menu is defined)
663                 if (System.getProperty("openrocket.debug.menu") != null) {
664                         menubar.add(makeDebugMenu());
665                 }
666                 
667                 
668                 
669                 ////  Help
670                 
671                 menu = new JMenu(trans.get("main.menu.help"));
672                 menu.setMnemonic(KeyEvent.VK_H);
673                 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.desc"));
674                 menubar.add(menu);
675                 
676                 
677                 // Guided tours
678                 
679                 item = new JMenuItem(trans.get("main.menu.help.tours"), KeyEvent.VK_L);
680                 item.setIcon(Icons.HELP_TOURS);
681                 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.tours.desc"));
682                 item.addActionListener(new ActionListener() {
683                         @Override
684                         public void actionPerformed(ActionEvent e) {
685                                 log.user("Guided tours selected");
686                                 // FIXME:  Singleton
687                                 new GuidedTourSelectionDialog(BasicFrame.this).setVisible(true);
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 }