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