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