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