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