1 package net.sf.openrocket.gui.main;
3 import net.miginfocom.swing.MigLayout;
4 import net.sf.openrocket.aerodynamics.WarningSet;
5 import net.sf.openrocket.document.OpenRocketDocument;
6 import net.sf.openrocket.file.GeneralRocketLoader;
7 import net.sf.openrocket.file.RocketLoadException;
8 import net.sf.openrocket.file.RocketLoader;
9 import net.sf.openrocket.file.RocketSaver;
10 import net.sf.openrocket.file.openrocket.OpenRocketSaver;
11 import net.sf.openrocket.file.rocksim.export.RocksimSaver;
12 import net.sf.openrocket.gui.StorageOptionChooser;
13 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
14 import net.sf.openrocket.gui.dialogs.AboutDialog;
15 import net.sf.openrocket.gui.dialogs.BugReportDialog;
16 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
17 import net.sf.openrocket.gui.dialogs.DebugLogDialog;
18 import net.sf.openrocket.gui.dialogs.DetailDialog;
19 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
20 import net.sf.openrocket.gui.dialogs.LicenseDialog;
21 import net.sf.openrocket.gui.dialogs.MotorDatabaseLoadingDialog;
22 import net.sf.openrocket.gui.dialogs.PrintDialog;
23 import net.sf.openrocket.gui.dialogs.ScaleDialog;
24 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
25 import net.sf.openrocket.gui.dialogs.WarningDialog;
26 import net.sf.openrocket.gui.dialogs.optimization.GeneralOptimizationDialog;
27 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
28 import net.sf.openrocket.gui.help.tours.GuidedTourSelectionDialog;
29 import net.sf.openrocket.gui.main.componenttree.ComponentTree;
30 import net.sf.openrocket.gui.scalefigure.RocketPanel;
31 import net.sf.openrocket.gui.util.FileHelper;
32 import net.sf.openrocket.gui.util.GUIUtil;
33 import net.sf.openrocket.gui.util.Icons;
34 import net.sf.openrocket.gui.util.OpenFileWorker;
35 import net.sf.openrocket.gui.util.SaveFileWorker;
36 import net.sf.openrocket.gui.util.SwingPreferences;
37 import net.sf.openrocket.l10n.Translator;
38 import net.sf.openrocket.logging.LogHelper;
39 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
40 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
41 import net.sf.openrocket.rocketcomponent.Rocket;
42 import net.sf.openrocket.rocketcomponent.RocketComponent;
43 import net.sf.openrocket.rocketcomponent.Stage;
44 import net.sf.openrocket.startup.Application;
45 import net.sf.openrocket.util.BugException;
46 import net.sf.openrocket.util.MemoryManagement;
47 import net.sf.openrocket.util.MemoryManagement.MemoryData;
48 import net.sf.openrocket.util.Reflection;
49 import net.sf.openrocket.util.TestRockets;
51 import javax.swing.Action;
52 import javax.swing.BorderFactory;
53 import javax.swing.InputMap;
54 import javax.swing.JButton;
55 import javax.swing.JComponent;
56 import javax.swing.JFileChooser;
57 import javax.swing.JFrame;
58 import javax.swing.JMenu;
59 import javax.swing.JMenuBar;
60 import javax.swing.JMenuItem;
61 import javax.swing.JOptionPane;
62 import javax.swing.JPanel;
63 import javax.swing.JPopupMenu;
64 import javax.swing.JScrollPane;
65 import javax.swing.JSpinner;
66 import javax.swing.JSplitPane;
67 import javax.swing.JTabbedPane;
68 import javax.swing.JTextField;
69 import javax.swing.KeyStroke;
70 import javax.swing.ListSelectionModel;
71 import javax.swing.ScrollPaneConstants;
72 import javax.swing.SwingUtilities;
73 import javax.swing.border.BevelBorder;
74 import javax.swing.border.TitledBorder;
75 import javax.swing.event.TreeSelectionEvent;
76 import javax.swing.event.TreeSelectionListener;
77 import javax.swing.tree.DefaultTreeSelectionModel;
78 import javax.swing.tree.TreePath;
79 import javax.swing.tree.TreeSelectionModel;
80 import java.awt.Dimension;
82 import java.awt.Toolkit;
83 import java.awt.Window;
84 import java.awt.event.ActionEvent;
85 import java.awt.event.ActionListener;
86 import java.awt.event.KeyEvent;
87 import java.awt.event.MouseAdapter;
88 import java.awt.event.MouseEvent;
89 import java.awt.event.MouseListener;
90 import java.awt.event.WindowAdapter;
91 import java.awt.event.WindowEvent;
93 import java.io.FileNotFoundException;
94 import java.io.IOException;
95 import java.io.InputStream;
96 import java.io.UnsupportedEncodingException;
98 import java.net.URISyntaxException;
100 import java.net.URLDecoder;
101 import java.util.ArrayList;
102 import java.util.Arrays;
103 import java.util.LinkedList;
104 import java.util.List;
105 import java.util.concurrent.ExecutionException;
107 public class BasicFrame extends JFrame {
108 private static final LogHelper log = Application.getLogger();
111 * The RocketLoader instance used for loading all rocket designs.
113 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
115 private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
117 private static final Translator trans = Application.getTranslator();
119 public static final int COMPONENT_TAB = 0;
120 public static final int SIMULATION_TAB = 1;
124 * List of currently open frames. When the list goes empty
125 * it is time to exit the application.
127 private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
131 * Whether "New" and "Open" should replace this frame.
132 * Should be set to false on the first rocket modification.
134 private boolean replaceable = false;
138 private final OpenRocketDocument document;
139 private final Rocket rocket;
141 private JTabbedPane tabbedPane;
142 private RocketPanel rocketpanel;
143 private ComponentTree tree = null;
145 private final DocumentSelectionModel selectionModel;
146 private final TreeSelectionModel componentSelectionModel;
147 private final ListSelectionModel simulationSelectionModel;
149 /** Actions available for rocket modifications */
150 private final RocketActions actions;
156 * Sole constructor. Creates a new frame based on the supplied document
157 * and adds it to the current frames list.
159 * @param document the document to show.
161 public BasicFrame(OpenRocketDocument document) {
162 log.debug("Instantiating new BasicFrame");
164 this.document = document;
165 this.rocket = document.getRocket();
166 this.rocket.getDefaultConfiguration().setAllStages();
168 // Create the component tree selection model that will be used
169 componentSelectionModel = new DefaultTreeSelectionModel();
170 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
172 // Obtain the simulation selection model that will be used
173 SimulationPanel simulationPanel = new SimulationPanel(document);
174 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
176 // Combine into a DocumentSelectionModel
177 selectionModel = new DocumentSelectionModel(document);
178 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
179 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
182 actions = new RocketActions(document, selectionModel, this);
185 log.debug("Constructing the BasicFrame UI");
187 // The main vertical split pane
188 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
189 vertical.setResizeWeight(0.5);
193 // The top tabbed pane
194 tabbedPane = new JTabbedPane();
196 tabbedPane.addTab(trans.get("BasicFrame.tab.Rocketdesign"), null, designTab());
197 //// Flight simulations
198 tabbedPane.addTab(trans.get("BasicFrame.tab.Flightsim"), null, simulationPanel);
200 vertical.setTopComponent(tabbedPane);
204 // Bottom segment, rocket figure
206 rocketpanel = new RocketPanel(document);
207 vertical.setBottomComponent(rocketpanel);
209 rocketpanel.setSelectionModel(tree.getSelectionModel());
215 rocket.addComponentChangeListener(new ComponentChangeListener() {
217 public void componentChanged(ComponentChangeEvent e) {
226 // Set initial window size
227 Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
228 size.width = size.width * 9 / 10;
229 size.height = size.height * 9 / 10;
232 // Remember changed size
233 GUIUtil.rememberWindowSize(this);
235 this.setLocationByPlatform(true);
237 GUIUtil.setWindowIcons(this);
240 vertical.setDividerLocation(0.4);
241 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
242 addWindowListener(new WindowAdapter() {
244 public void windowClosing(WindowEvent e) {
250 log.debug("BasicFrame instantiation complete");
255 * Construct the "Rocket design" tab. This contains a horizontal split pane
256 * with the left component the design tree and the right component buttons
257 * for adding components.
259 private JComponent designTab() {
260 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
261 horizontal.setResizeWeight(0.5);
264 // Upper-left segment, component tree
266 JPanel panel = new JPanel(new MigLayout("fill, flowy", "", "[grow]"));
268 tree = new ComponentTree(document);
269 tree.setSelectionModel(componentSelectionModel);
271 // Remove JTree key events that interfere with menu accelerators
272 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
273 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
274 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
275 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
276 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
277 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
278 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
279 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
283 // Double-click opens config dialog
284 MouseListener ml = new MouseAdapter() {
286 public void mousePressed(MouseEvent e) {
287 int selRow = tree.getRowForLocation(e.getX(), e.getY());
288 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
290 if ((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
292 RocketComponent c = (RocketComponent) selPath.getLastPathComponent();
293 ComponentConfigDialog.showDialog(BasicFrame.this,
294 BasicFrame.this.document, c);
299 tree.addMouseListener(ml);
301 // Update dialog when selection is changed
302 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
304 public void valueChanged(TreeSelectionEvent e) {
305 // Scroll tree to the selected item
306 TreePath path = componentSelectionModel.getSelectionPath();
309 tree.scrollPathToVisible(path);
311 if (!ComponentConfigDialog.isDialogVisible())
313 RocketComponent c = (RocketComponent) path.getLastPathComponent();
314 ComponentConfigDialog.showDialog(BasicFrame.this,
315 BasicFrame.this.document, c);
319 // Place tree inside scroll pane
320 JScrollPane scroll = new JScrollPane(tree);
321 panel.add(scroll, "spany, grow, wrap");
325 JButton button = new JButton(actions.getMoveUpAction());
326 panel.add(button, "sizegroup buttons, aligny 65%");
328 button = new JButton(actions.getMoveDownAction());
329 panel.add(button, "sizegroup buttons, aligny 0%");
331 button = new JButton(actions.getEditAction());
332 panel.add(button, "sizegroup buttons");
334 button = new JButton(actions.getNewStageAction());
335 panel.add(button, "sizegroup buttons");
337 button = new JButton(actions.getDeleteAction());
338 button.setIcon(null);
339 button.setMnemonic(0);
340 panel.add(button, "sizegroup buttons");
342 horizontal.setLeftComponent(panel);
345 // Upper-right segment, component addition buttons
347 panel = new JPanel(new MigLayout("fill, insets 0", "[0::]"));
349 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
350 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
351 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
352 scroll.getViewport()));
353 scroll.setBorder(null);
354 scroll.setViewportBorder(null);
356 TitledBorder border = BorderFactory.createTitledBorder(trans.get("BasicFrame.title.Addnewcomp"));
357 GUIUtil.changeFontStyle(border, Font.BOLD);
358 scroll.setBorder(border);
360 panel.add(scroll, "grow");
362 horizontal.setRightComponent(panel);
370 * Return the currently selected rocket component, or <code>null</code> if none selected.
372 private RocketComponent getSelectedComponent() {
373 TreePath path = componentSelectionModel.getSelectionPath();
376 tree.scrollPathToVisible(path);
378 return (RocketComponent) path.getLastPathComponent();
383 * Creates the menu for the window.
385 private void createMenu() {
386 JMenuBar menubar = new JMenuBar();
391 menu = new JMenu(trans.get("main.menu.file"));
392 menu.setMnemonic(KeyEvent.VK_F);
393 //// File-handling related tasks
394 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.desc"));
398 item = new JMenuItem(trans.get("main.menu.file.new"), KeyEvent.VK_N);
399 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
400 item.setMnemonic(KeyEvent.VK_N);
401 //// Create a new rocket design
402 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.new.desc"));
403 item.setIcon(Icons.FILE_NEW);
404 item.addActionListener(new ActionListener() {
406 public void actionPerformed(ActionEvent e) {
407 log.user("New... selected");
409 closeIfReplaceable();
415 item = new JMenuItem(trans.get("main.menu.file.open"), KeyEvent.VK_O);
416 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
417 //// Open a rocket design
418 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openrocketdesign"));
419 item.setIcon(Icons.FILE_OPEN);
420 item.addActionListener(new ActionListener() {
422 public void actionPerformed(ActionEvent e) {
423 log.user("Open... selected");
430 item = new MRUDesignFileAction(trans.get("main.menu.file.openRecent"), this);
431 //// Open a recent rocket design
432 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openrecentrocketdesign"));
433 item.setIcon(Icons.FILE_OPEN);
437 item = new JMenuItem(trans.get("main.menu.file.openExample"));
438 //// Open an example rocket design
439 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openexamplerocketdesign"));
440 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
441 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
442 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
443 item.addActionListener(new ActionListener() {
445 public void actionPerformed(ActionEvent e) {
446 log.user("Open example... selected");
447 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
450 log.user("Opening example " + u);
451 open(u, BasicFrame.this);
461 item = new JMenuItem(trans.get("main.menu.file.save"), KeyEvent.VK_S);
462 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
463 //// Save the current rocket design
464 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesign"));
465 item.setIcon(Icons.FILE_SAVE);
466 item.addActionListener(new ActionListener() {
468 public void actionPerformed(ActionEvent e) {
469 log.user("Save selected");
476 item = new JMenuItem(trans.get("main.menu.file.saveAs"), KeyEvent.VK_A);
477 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
478 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
479 //// Save the current rocket design to a new file
480 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesnewfile"));
481 item.setIcon(Icons.FILE_SAVE_AS);
482 item.addActionListener(new ActionListener() {
484 public void actionPerformed(ActionEvent e) {
485 log.user("Save as... selected");
492 item = new JMenuItem(trans.get("main.menu.file.print"), KeyEvent.VK_P);
493 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
494 //// Print parts list and fin template
495 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.print.desc"));
496 item.setIcon(Icons.FILE_PRINT);
497 item.addActionListener(new ActionListener() {
499 public void actionPerformed(ActionEvent e) {
500 log.user("Print action selected");
510 item = new JMenuItem(trans.get("main.menu.file.close"), KeyEvent.VK_C);
511 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
512 //// Close the current rocket design
513 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Closedesign"));
514 item.setIcon(Icons.FILE_CLOSE);
515 item.addActionListener(new ActionListener() {
517 public void actionPerformed(ActionEvent e) {
518 log.user("Close selected");
527 item = new JMenuItem(trans.get("main.menu.file.quit"), KeyEvent.VK_Q);
528 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
529 //// Quit the program
530 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Quitprogram"));
531 item.setIcon(Icons.FILE_QUIT);
532 item.addActionListener(new ActionListener() {
534 public void actionPerformed(ActionEvent e) {
535 log.user("Quit selected");
544 menu = new JMenu(trans.get("main.menu.edit"));
545 menu.setMnemonic(KeyEvent.VK_E);
547 menu.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.menu.Rocketedt"));
551 Action action = UndoRedoAction.newUndoAction(document);
552 item = new JMenuItem(action);
553 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
554 item.setMnemonic(KeyEvent.VK_U);
555 //// Undo the previous operation
556 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.undo.desc"));
560 action = UndoRedoAction.newRedoAction(document);
561 item = new JMenuItem(action);
562 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
563 item.setMnemonic(KeyEvent.VK_R);
564 //// Redo the previously undone operation
565 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.redo.desc"));
571 item = new JMenuItem(actions.getCutAction());
574 item = new JMenuItem(actions.getCopyAction());
577 item = new JMenuItem(actions.getPasteAction());
580 item = new JMenuItem(actions.getDeleteAction());
587 item = new JMenuItem(trans.get("main.menu.edit.resize"));
588 item.setIcon(Icons.EDIT_SCALE);
589 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.resize.desc"));
590 item.addActionListener(new ActionListener() {
592 public void actionPerformed(ActionEvent e) {
593 log.user("Scale... selected");
594 ScaleDialog dialog = new ScaleDialog(document, getSelectedComponent(), BasicFrame.this);
595 dialog.setVisible(true);
604 item = new JMenuItem(trans.get("main.menu.edit.preferences"));
605 item.setIcon(Icons.PREFERENCES);
606 //// Setup the application preferences
607 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.preferences.desc"));
608 item.addActionListener(new ActionListener() {
610 public void actionPerformed(ActionEvent e) {
611 log.user("Preferences selected");
612 PreferencesDialog.showPreferences(BasicFrame.this);
621 menu = new JMenu(trans.get("main.menu.analyze"));
622 menu.setMnemonic(KeyEvent.VK_A);
623 //// Analyzing the rocket
624 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.desc"));
627 //// Component analysis
628 item = new JMenuItem(trans.get("main.menu.analyze.componentAnalysis"), KeyEvent.VK_C);
629 //// Analyze the rocket components separately
630 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.componentAnalysis.desc"));
631 item.addActionListener(new ActionListener() {
633 public void actionPerformed(ActionEvent e) {
634 log.user("Component analysis selected");
635 ComponentAnalysisDialog.showDialog(rocketpanel);
641 item = new JMenuItem(trans.get("main.menu.analyze.optimization"), KeyEvent.VK_O);
642 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.optimization.desc"));
643 item.addActionListener(new ActionListener() {
645 public void actionPerformed(ActionEvent e) {
646 log.user("Rocket optimization selected");
647 new GeneralOptimizationDialog(document, BasicFrame.this).setVisible(true);
655 // (shown if openrocket.debug.menu is defined)
656 if (System.getProperty("openrocket.debug.menu") != null) {
657 menubar.add(makeDebugMenu());
664 menu = new JMenu(trans.get("main.menu.help"));
665 menu.setMnemonic(KeyEvent.VK_H);
666 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.desc"));
672 item = new JMenuItem(trans.get("main.menu.help.tours"), KeyEvent.VK_L);
673 item.setIcon(Icons.HELP_TOURS);
674 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.tours.desc"));
675 item.addActionListener(new ActionListener() {
677 public void actionPerformed(ActionEvent e) {
678 log.user("Guided tours selected");
679 GuidedTourSelectionDialog.showDialog(BasicFrame.this);
687 item = new JMenuItem(trans.get("main.menu.help.bugReport"), KeyEvent.VK_B);
688 item.setIcon(Icons.HELP_BUG_REPORT);
689 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.bugReport.desc"));
690 item.addActionListener(new ActionListener() {
692 public void actionPerformed(ActionEvent e) {
693 log.user("Bug report selected");
694 BugReportDialog.showBugReportDialog(BasicFrame.this);
700 item = new JMenuItem(trans.get("main.menu.help.debugLog"));
701 item.setIcon(Icons.HELP_DEBUG_LOG);
702 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.debugLog.desc"));
703 item.addActionListener(new ActionListener() {
705 public void actionPerformed(ActionEvent e) {
706 log.user("Debug log selected");
707 new DebugLogDialog(BasicFrame.this).setVisible(true);
716 item = new JMenuItem(trans.get("main.menu.help.license"), KeyEvent.VK_L);
717 item.setIcon(Icons.HELP_LICENSE);
718 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.license.desc"));
719 item.addActionListener(new ActionListener() {
721 public void actionPerformed(ActionEvent e) {
722 log.user("License selected");
723 new LicenseDialog(BasicFrame.this).setVisible(true);
730 item = new JMenuItem(trans.get("main.menu.help.about"), KeyEvent.VK_A);
731 item.setIcon(Icons.HELP_ABOUT);
732 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.about.desc"));
733 item.addActionListener(new ActionListener() {
735 public void actionPerformed(ActionEvent e) {
736 log.user("About selected");
737 new AboutDialog(BasicFrame.this).setVisible(true);
743 this.setJMenuBar(menubar);
746 private JMenu makeDebugMenu() {
751 * This menu is intentionally left untranslated.
755 menu = new JMenu("Debug");
756 //// OpenRocket debugging tasks
757 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
759 //// What is this menu?
760 item = new JMenuItem("What is this menu?");
761 item.addActionListener(new ActionListener() {
763 public void actionPerformed(ActionEvent e) {
764 log.user("What is this menu? selected");
765 JOptionPane.showMessageDialog(BasicFrame.this,
767 "The 'Debug' menu includes actions for testing and debugging " +
769 "The menu is made visible by defining the system property " +
770 "'openrocket.debug.menu' when starting OpenRocket.",
771 "It should not be visible by default." },
772 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
779 //// Create test rocket
780 item = new JMenuItem("Create test rocket");
781 item.addActionListener(new ActionListener() {
783 public void actionPerformed(ActionEvent e) {
784 log.user("Create test rocket selected");
785 JTextField field = new JTextField();
786 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
787 "Input text key to generate random rocket:",
789 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
790 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
796 r = new TestRockets(null).makeTestRocket();
797 } else if (sel == 1) {
798 r = new TestRockets(field.getText()).makeTestRocket();
803 OpenRocketDocument doc = new OpenRocketDocument(r);
805 BasicFrame frame = new BasicFrame(doc);
806 frame.setVisible(true);
813 item = new JMenuItem("Create 'Iso-Haisu'");
814 item.addActionListener(new ActionListener() {
816 public void actionPerformed(ActionEvent e) {
817 log.user("Create Iso-Haisu selected");
818 Rocket r = TestRockets.makeIsoHaisu();
819 OpenRocketDocument doc = new OpenRocketDocument(r);
821 BasicFrame frame = new BasicFrame(doc);
822 frame.setVisible(true);
828 item = new JMenuItem("Create 'Big Blue'");
829 item.addActionListener(new ActionListener() {
831 public void actionPerformed(ActionEvent e) {
832 log.user("Create Big Blue selected");
833 Rocket r = TestRockets.makeBigBlue();
834 OpenRocketDocument doc = new OpenRocketDocument(r);
836 BasicFrame frame = new BasicFrame(doc);
837 frame.setVisible(true);
845 item = new JMenuItem("Memory statistics");
846 item.addActionListener(new ActionListener() {
848 public void actionPerformed(ActionEvent e) {
849 log.user("Memory statistics selected");
851 // Get discarded but remaining objects (this also runs System.gc multiple times)
852 List<MemoryData> objects = MemoryManagement.getRemainingCollectableObjects();
853 StringBuilder sb = new StringBuilder();
854 sb.append("Objects that should have been garbage-collected but have not been:\n");
856 for (MemoryData data : objects) {
857 Object o = data.getReference().get();
860 sb.append("Age ").append(System.currentTimeMillis() - data.getRegistrationTime())
861 .append(" ms: ").append(o).append('\n');
863 // Explicitly null the strong reference to avoid possibility of invisible references
866 sb.append("Total: " + count);
868 // Get basic memory stats
870 long max = Runtime.getRuntime().maxMemory();
871 long free = Runtime.getRuntime().freeMemory();
872 long used = max - free;
873 String[] stats = new String[4];
874 stats[0] = "Memory usage:";
875 stats[1] = String.format(" Max memory: %.1f MB", max / 1024.0 / 1024.0);
876 stats[2] = String.format(" Used memory: %.1f MB (%.0f%%)", used / 1024.0 / 1024.0, 100.0 * used / max);
877 stats[3] = String.format(" Free memory: %.1f MB (%.0f%%)", free / 1024.0 / 1024.0, 100.0 * free / max);
880 DetailDialog.showDetailedMessageDialog(BasicFrame.this, stats, sb.toString(),
881 "Memory statistics", JOptionPane.INFORMATION_MESSAGE);
887 item = new JMenuItem("Exhaust memory");
888 item.addActionListener(new ActionListener() {
890 public void actionPerformed(ActionEvent e) {
891 log.user("Exhaust memory selected");
892 LinkedList<byte[]> data = new LinkedList<byte[]>();
894 final int bytesPerArray = 10240;
897 byte[] array = new byte[bytesPerArray];
898 for (int i = 0; i < bytesPerArray; i++) {
904 } catch (OutOfMemoryError error) {
906 long size = bytesPerArray * (long) count;
907 String s = String.format("OutOfMemory occurred after %d iterations (approx. %.1f MB consumed)",
908 count, size / 1024.0 / 1024.0);
910 JOptionPane.showMessageDialog(BasicFrame.this, s);
920 item = new JMenuItem("Exception here");
921 item.addActionListener(new ActionListener() {
923 public void actionPerformed(ActionEvent e) {
924 log.user("Exception here selected");
925 throw new RuntimeException("Testing exception from menu action listener");
930 item = new JMenuItem("Exception from EDT");
931 item.addActionListener(new ActionListener() {
933 public void actionPerformed(ActionEvent e) {
934 log.user("Exception from EDT selected");
935 SwingUtilities.invokeLater(new Runnable() {
938 throw new RuntimeException("Testing exception from " +
939 "later invoked EDT thread");
946 item = new JMenuItem("Exception from other thread");
947 item.addActionListener(new ActionListener() {
949 public void actionPerformed(ActionEvent e) {
950 log.user("Exception from other thread selected");
954 throw new RuntimeException("Testing exception from newly created thread");
961 item = new JMenuItem("OutOfMemoryError here");
962 item.addActionListener(new ActionListener() {
964 public void actionPerformed(ActionEvent e) {
965 log.user("OutOfMemoryError here selected");
966 throw new OutOfMemoryError("Testing OutOfMemoryError from menu action listener");
975 item = new JMenuItem("Test popup");
976 item.addActionListener(new ActionListener() {
978 public void actionPerformed(ActionEvent e) {
979 log.user("Test popup selected");
980 JPanel panel = new JPanel();
981 panel.add(new JTextField(40));
982 panel.add(new JSpinner());
983 JPopupMenu popup = new JPopupMenu();
984 popup.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
986 popup.show(BasicFrame.this, -50, 100);
999 * Select the tab on the main pane.
1001 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
1003 public void selectTab(int tab) {
1004 tabbedPane.setSelectedIndex(tab);
1009 private void openAction() {
1010 JFileChooser chooser = new JFileChooser();
1012 chooser.addChoosableFileFilter(FileHelper.ALL_DESIGNS_FILTER);
1013 chooser.addChoosableFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
1014 chooser.addChoosableFileFilter(FileHelper.ROCKSIM_DESIGN_FILTER);
1015 chooser.setFileFilter(FileHelper.ALL_DESIGNS_FILTER);
1017 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
1018 chooser.setMultiSelectionEnabled(true);
1019 chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory());
1020 int option = chooser.showOpenDialog(this);
1021 if (option != JFileChooser.APPROVE_OPTION) {
1022 log.user("Decided not to open files, option=" + option);
1026 ((SwingPreferences) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory());
1028 File[] files = chooser.getSelectedFiles();
1029 log.user("Opening files " + Arrays.toString(files));
1031 for (File file : files) {
1032 log.info("Opening file: " + file);
1033 if (open(file, this)) {
1034 MRUDesignFile opts = MRUDesignFile.getInstance();
1035 opts.addFile(file.getAbsolutePath());
1040 void closeIfReplaceable() {
1041 // Close previous window if replacing
1042 if (replaceable && document.isSaved()) {
1043 // We are replacing the frame, make new window have current location
1044 BasicFrame newFrame = frames.get(frames.size() - 1);
1045 newFrame.setLocation(this.getLocation());
1047 log.info("Closing window because it is replaceable");
1053 * Open a file based on a URL.
1054 * @param url the file to open.
1055 * @param parent the parent window for dialogs.
1056 * @return <code>true</code> if opened successfully.
1058 private static boolean open(URL url, BasicFrame parent) {
1059 String filename = null;
1061 // First figure out the file name from the URL
1063 // Try using URI.getPath();
1065 URI uri = url.toURI();
1066 filename = uri.getPath();
1067 } catch (URISyntaxException ignore) {
1070 // Try URL-decoding the URL
1071 if (filename == null) {
1073 filename = URLDecoder.decode(url.toString(), "UTF-8");
1074 } catch (UnsupportedEncodingException ignore) {
1079 if (filename == null) {
1083 // Remove path from filename
1084 if (filename.lastIndexOf('/') >= 0) {
1085 filename = filename.substring(filename.lastIndexOf('/') + 1);
1090 log.info("Opening file from url=" + url + " filename=" + filename);
1092 InputStream is = url.openStream();
1093 open(is, filename, parent);
1094 } catch (IOException e) {
1095 log.warn("Error opening file" + e);
1096 JOptionPane.showMessageDialog(parent,
1097 "An error occurred while opening the file " + filename,
1098 "Error loading file", JOptionPane.ERROR_MESSAGE);
1106 * Open the specified file from an InputStream in a new design frame. If an error
1107 * occurs, an error dialog is shown and <code>false</code> is returned.
1109 * @param stream the stream to load from.
1110 * @param filename the file name to display in dialogs (not set to the document).
1111 * @param parent the parent component for which a progress dialog is opened.
1112 * @return whether the file was successfully loaded and opened.
1114 private static boolean open(InputStream stream, String filename, Window parent) {
1115 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
1116 return open(worker, filename, null, parent);
1121 * Open the specified file in a new design frame. If an error occurs, an error
1122 * dialog is shown and <code>false</code> is returned.
1124 * @param file the file to open.
1125 * @param parent the parent component for which a progress dialog is opened.
1126 * @return whether the file was successfully loaded and opened.
1128 public static boolean open(File file, Window parent) {
1129 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
1130 return open(worker, file.getName(), file, parent);
1135 * Open the specified file using the provided worker.
1137 * @param worker the OpenFileWorker that loads the file.
1138 * @param filename the file name to display in dialogs.
1139 * @param file the File to set the document to (may be null).
1143 private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) {
1145 MotorDatabaseLoadingDialog.check(parent);
1147 // Open the file in a Swing worker thread
1148 log.info("Starting OpenFileWorker");
1149 if (!SwingWorkerDialog.runWorker(parent, "Opening file", "Reading " + filename + "...", worker)) {
1150 // User cancelled the operation
1151 log.info("User cancelled the OpenFileWorker");
1156 // Handle the document
1157 OpenRocketDocument doc = null;
1162 } catch (ExecutionException e) {
1164 Throwable cause = e.getCause();
1166 if (cause instanceof FileNotFoundException) {
1168 log.warn("File not found", cause);
1169 JOptionPane.showMessageDialog(parent,
1170 "File not found: " + filename,
1171 "Error opening file", JOptionPane.ERROR_MESSAGE);
1174 } else if (cause instanceof RocketLoadException) {
1176 log.warn("Error loading the file", cause);
1177 JOptionPane.showMessageDialog(parent,
1178 "Unable to open file '" + filename + "': "
1179 + cause.getMessage(),
1180 "Error opening file", JOptionPane.ERROR_MESSAGE);
1185 throw new BugException("Unknown error when opening file", e);
1189 } catch (InterruptedException e) {
1190 throw new BugException("EDT was interrupted", e);
1194 throw new BugException("Document loader returned null");
1199 WarningSet warnings = worker.getRocketLoader().getWarnings();
1200 if (!warnings.isEmpty()) {
1201 log.info("Warnings while reading file: " + warnings);
1202 WarningDialog.showWarnings(parent,
1204 //// The following problems were encountered while opening
1205 trans.get("BasicFrame.WarningDialog.txt1") + " " + filename + ".",
1206 //// Some design features may not have been loaded correctly.
1207 trans.get("BasicFrame.WarningDialog.txt2")
1209 //// Warnings while opening file
1210 trans.get("BasicFrame.WarningDialog.title"), warnings);
1214 // Set document state
1220 log.debug("Opening new frame with the document");
1221 BasicFrame frame = new BasicFrame(doc);
1222 frame.setVisible(true);
1224 if ( parent != null && parent instanceof BasicFrame ) {
1225 ((BasicFrame)parent).closeIfReplaceable();
1231 * "Save" action. If the design is new, then this is identical to "Save As", with a default file filter for .ork.
1232 * If the rocket being edited previously was opened from a .ork file, then it will be saved immediately to the same
1233 * file. But clicking on 'Save' for an existing design file with a .rkt will bring up a confirmation dialog because
1234 * it's potentially a destructive write (loss of some fidelity if it's truly an original Rocksim generated file).
1236 * @return true if the file was saved, false otherwise
1238 private boolean saveAction() {
1239 File file = document.getFile();
1241 log.info("Document does not contain file, opening save as dialog instead");
1242 return saveAsAction();
1244 log.info("Saving document to " + file);
1246 if (FileHelper.ROCKSIM_DESIGN_FILTER.accept(file)) {
1247 return saveAsRocksim(file);
1249 return saveAs(file);
1255 * Never should a .rkt file contain an OpenRocket content, or an .ork file contain a Rocksim design. Regardless of
1256 * what extension the user has chosen, it would violate the Principle of Least Astonishment to do otherwise
1257 * (and we want to make doing the wrong thing really hard to do). So always force the appropriate extension.
1259 * This can result in some odd looking filenames (MyDesign.rkt.ork, MyDesign.rkt.ork.rkt, etc.) if the user is
1260 * not paying attention, but the user can control that by modifying the filename in the dialog.
1262 * @return true if the file was saved, false otherwise
1264 private boolean saveAsAction() {
1267 StorageOptionChooser storageChooser =
1268 new StorageOptionChooser(document, document.getDefaultStorageOptions());
1269 final JFileChooser chooser = new JFileChooser();
1270 chooser.addChoosableFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
1271 chooser.addChoosableFileFilter(FileHelper.ROCKSIM_DESIGN_FILTER);
1273 //Force the file filter to match the file extension that was opened. Will default to OR if the file is null.
1274 if (FileHelper.ROCKSIM_DESIGN_FILTER.accept(document.getFile())) {
1275 chooser.setFileFilter(FileHelper.ROCKSIM_DESIGN_FILTER);
1278 chooser.setFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
1280 chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory());
1281 chooser.setAccessory(storageChooser);
1282 if (document.getFile() != null) {
1283 chooser.setSelectedFile(document.getFile());
1286 int option = chooser.showSaveDialog(BasicFrame.this);
1287 if (option != JFileChooser.APPROVE_OPTION) {
1288 log.user("User decided not to save, option=" + option);
1292 file = chooser.getSelectedFile();
1294 log.user("User did not select a file");
1298 ((SwingPreferences) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory());
1299 storageChooser.storeOptions(document.getDefaultStorageOptions());
1301 if (chooser.getFileFilter().equals(FileHelper.ROCKSIM_DESIGN_FILTER)) {
1302 return saveAsRocksim(file);
1305 file = FileHelper.forceExtension(file, "ork");
1306 return FileHelper.confirmWrite(file, this) && saveAs(file);
1311 * Perform the writing of the design to the given file in Rocksim format.
1313 * @param file the chosen file
1315 * @return true if the file was written
1317 private boolean saveAsRocksim(File file) {
1318 file = FileHelper.forceExtension(file, "rkt");
1319 if (!FileHelper.confirmWrite(file, this)) {
1324 new RocksimSaver().save(file, document);
1326 } catch (IOException e) {
1332 * Perform the writing of the design to the given file in OpenRocket format.
1334 * @param file the chosen file
1336 * @return true if the file was written
1338 private boolean saveAs(File file) {
1339 log.info("Saving document as " + file);
1340 boolean saved = false;
1342 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1343 // User cancelled the dialog
1344 log.user("User cancelled saving in storage options dialog");
1349 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1351 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1352 "Writing " + file.getName() + "...", worker)) {
1354 // User cancelled the save
1355 log.user("User cancelled the save, deleting the file");
1362 document.setFile(file);
1363 document.setSaved(true);
1366 } catch (ExecutionException e) {
1368 Throwable cause = e.getCause();
1370 if (cause instanceof IOException) {
1371 log.warn("An I/O error occurred while saving " + file, cause);
1372 JOptionPane.showMessageDialog(this, new String[] {
1373 "An I/O error occurred while saving:",
1374 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1377 Reflection.handleWrappedException(e);
1380 } catch (InterruptedException e) {
1381 throw new BugException("EDT was interrupted", e);
1388 private boolean closeAction() {
1389 if (!document.isSaved()) {
1390 log.info("Confirming whether to save the design");
1391 ComponentConfigDialog.hideDialog();
1392 int result = JOptionPane.showConfirmDialog(this,
1393 trans.get("BasicFrame.dlg.lbl1") + rocket.getName() +
1394 trans.get("BasicFrame.dlg.lbl2") + " " +
1395 trans.get("BasicFrame.dlg.lbl3"),
1396 trans.get("BasicFrame.dlg.title"), JOptionPane.YES_NO_CANCEL_OPTION,
1397 JOptionPane.QUESTION_MESSAGE);
1398 if (result == JOptionPane.YES_OPTION) {
1400 log.user("User requested file save");
1401 if (!saveAction()) {
1402 log.info("File save was interrupted, not closing");
1405 } else if (result == JOptionPane.NO_OPTION) {
1406 // Don't save: No-op
1407 log.user("User requested to discard design");
1410 log.user("User cancelled closing, result=" + result);
1415 // Rocket has been saved or discarded
1416 log.debug("Disposing window");
1419 ComponentConfigDialog.hideDialog();
1420 ComponentAnalysisDialog.hideDialog();
1422 frames.remove(this);
1423 if (frames.isEmpty()) {
1424 log.info("Last frame closed, exiting");
1435 public void printAction() {
1436 Double rotation = rocketpanel.getFigure().getRotation();
1437 if (rotation == null) {
1440 new PrintDialog(this, document, rotation).setVisible(true);
1444 * Open a new design window with a basic rocket+stage.
1446 public static void newAction() {
1447 log.info("New action initiated");
1449 Rocket rocket = new Rocket();
1450 Stage stage = new Stage();
1452 stage.setName(trans.get("BasicFrame.StageName.Sustainer"));
1453 rocket.addChild(stage);
1454 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1457 BasicFrame frame = new BasicFrame(doc);
1458 frame.replaceable = true;
1459 frame.setVisible(true);
1460 // FIXME - kruland commented this out - I don't like it.
1461 //ComponentConfigDialog.showDialog(frame, doc, rocket);
1465 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1467 public static void quitAction() {
1468 log.info("Quit action initiated");
1469 for (int i = frames.size() - 1; i >= 0; i--) {
1470 log.debug("Closing frame " + frames.get(i));
1471 if (!frames.get(i).closeAction()) {
1473 log.info("Quit was cancelled");
1477 // Should not be reached, but just in case
1478 log.error("Should already have exited application");
1484 * Set the title of the frame, taking into account the name of the rocket, file it
1485 * has been saved to (if any) and saved status.
1487 private void setTitle() {
1488 File file = document.getFile();
1489 boolean saved = document.isSaved();
1492 title = rocket.getName();
1494 title = title + " (" + file.getName() + ")";
1497 title = "*" + title;
1505 * Find a currently open BasicFrame containing the specified rocket. This method
1506 * can be used to map a Rocket to a BasicFrame from GUI methods.
1508 * @param rocket the Rocket.
1509 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1511 public static BasicFrame findFrame(Rocket rocket) {
1512 for (BasicFrame f : frames) {
1513 if (f.rocket == rocket) {
1514 log.debug("Found frame " + f + " for rocket " + rocket);
1518 log.debug("Could not find frame for rocket " + rocket);
1523 * Find a currently open document by the rocket object. This method can be used
1524 * to map a Rocket to OpenRocketDocument from GUI methods.
1526 * @param rocket the Rocket.
1527 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1529 public static OpenRocketDocument findDocument(Rocket rocket) {
1530 BasicFrame frame = findFrame(rocket);
1531 if (frame != null) {
1532 return frame.document;