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