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