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