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