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