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