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