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