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