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.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;
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;
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;
94 import java.io.FileNotFoundException;
95 import java.io.IOException;
96 import java.io.InputStream;
97 import java.io.UnsupportedEncodingException;
99 import java.net.URISyntaxException;
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;
108 public class BasicFrame extends JFrame {
109 private static final LogHelper log = Application.getLogger();
112 * The RocketLoader instance used for loading all rocket designs.
114 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
116 private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
118 private static final Translator trans = Application.getTranslator();
120 public static final int COMPONENT_TAB = 0;
121 public static final int SIMULATION_TAB = 1;
125 * List of currently open frames. When the list goes empty
126 * it is time to exit the application.
128 private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
132 * Whether "New" and "Open" should replace this frame.
133 * Should be set to false on the first rocket modification.
135 private boolean replaceable = false;
139 private final OpenRocketDocument document;
140 private final Rocket rocket;
142 private JTabbedPane tabbedPane;
143 private RocketPanel rocketpanel;
144 private ComponentTree tree = null;
146 private final DocumentSelectionModel selectionModel;
147 private final TreeSelectionModel componentSelectionModel;
148 private final ListSelectionModel simulationSelectionModel;
150 /** Actions available for rocket modifications */
151 private final RocketActions actions;
157 * Sole constructor. Creates a new frame based on the supplied document
158 * and adds it to the current frames list.
160 * @param document the document to show.
162 public BasicFrame(OpenRocketDocument document) {
163 log.debug("Instantiating new BasicFrame");
165 this.document = document;
166 this.rocket = document.getRocket();
167 this.rocket.getDefaultConfiguration().setAllStages();
169 // Create the component tree selection model that will be used
170 componentSelectionModel = new DefaultTreeSelectionModel();
171 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
173 // Obtain the simulation selection model that will be used
174 SimulationPanel simulationPanel = new SimulationPanel(document);
175 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
177 // Combine into a DocumentSelectionModel
178 selectionModel = new DocumentSelectionModel(document);
179 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
180 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
183 actions = new RocketActions(document, selectionModel, this);
186 log.debug("Constructing the BasicFrame UI");
188 // The main vertical split pane
189 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
190 vertical.setResizeWeight(0.5);
194 // The top tabbed pane
195 tabbedPane = new JTabbedPane();
197 tabbedPane.addTab(trans.get("BasicFrame.tab.Rocketdesign"), null, designTab());
198 //// Flight simulations
199 tabbedPane.addTab(trans.get("BasicFrame.tab.Flightsim"), null, simulationPanel);
201 vertical.setTopComponent(tabbedPane);
205 // Bottom segment, rocket figure
207 rocketpanel = new RocketPanel(document);
208 vertical.setBottomComponent(rocketpanel);
210 rocketpanel.setSelectionModel(tree.getSelectionModel());
216 rocket.addComponentChangeListener(new ComponentChangeListener() {
218 public void componentChanged(ComponentChangeEvent e) {
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;
233 // Remember changed size
234 GUIUtil.rememberWindowSize(this);
236 this.setLocationByPlatform(true);
238 GUIUtil.setWindowIcons(this);
241 vertical.setDividerLocation(0.4);
242 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
243 addWindowListener(new WindowAdapter() {
245 public void windowClosing(WindowEvent e) {
251 log.debug("BasicFrame instantiation complete");
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.
260 private JComponent designTab() {
261 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
262 horizontal.setResizeWeight(0.5);
265 // Upper-left segment, component tree
267 JPanel panel = new JPanel(new MigLayout("fill, flowy", "", "[grow]"));
269 tree = new ComponentTree(document);
270 tree.setSelectionModel(componentSelectionModel);
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);
284 // Double-click opens config dialog
285 MouseListener ml = new MouseAdapter() {
287 public void mousePressed(MouseEvent e) {
288 int selRow = tree.getRowForLocation(e.getX(), e.getY());
289 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
291 if ((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
293 RocketComponent c = (RocketComponent) selPath.getLastPathComponent();
294 ComponentConfigDialog.showDialog(BasicFrame.this,
295 BasicFrame.this.document, c);
300 tree.addMouseListener(ml);
302 // Update dialog when selection is changed
303 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
305 public void valueChanged(TreeSelectionEvent e) {
306 // Scroll tree to the selected item
307 TreePath path = componentSelectionModel.getSelectionPath();
310 tree.scrollPathToVisible(path);
312 if (!ComponentConfigDialog.isDialogVisible())
314 RocketComponent c = (RocketComponent) path.getLastPathComponent();
315 ComponentConfigDialog.showDialog(BasicFrame.this,
316 BasicFrame.this.document, c);
320 // Place tree inside scroll pane
321 JScrollPane scroll = new JScrollPane(tree);
322 panel.add(scroll, "spany, grow, wrap");
326 JButton button = new JButton(actions.getMoveUpAction());
327 panel.add(button, "sizegroup buttons, aligny 65%");
329 button = new JButton(actions.getMoveDownAction());
330 panel.add(button, "sizegroup buttons, aligny 0%");
332 button = new JButton(actions.getEditAction());
333 panel.add(button, "sizegroup buttons");
335 button = new JButton(actions.getNewStageAction());
336 panel.add(button, "sizegroup buttons");
338 button = new JButton(actions.getDeleteAction());
339 button.setIcon(null);
340 button.setMnemonic(0);
341 panel.add(button, "sizegroup buttons");
343 horizontal.setLeftComponent(panel);
346 // Upper-right segment, component addition buttons
348 panel = new JPanel(new MigLayout("fill, insets 0", "[0::]"));
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);
357 TitledBorder border = BorderFactory.createTitledBorder(trans.get("BasicFrame.title.Addnewcomp"));
358 GUIUtil.changeFontStyle(border, Font.BOLD);
359 scroll.setBorder(border);
361 panel.add(scroll, "grow");
363 horizontal.setRightComponent(panel);
371 * Return the currently selected rocket component, or <code>null</code> if none selected.
373 private RocketComponent getSelectedComponent() {
374 TreePath path = componentSelectionModel.getSelectionPath();
377 tree.scrollPathToVisible(path);
379 return (RocketComponent) path.getLastPathComponent();
384 * Creates the menu for the window.
386 private void createMenu() {
387 JMenuBar menubar = new JMenuBar();
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"));
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() {
407 public void actionPerformed(ActionEvent e) {
408 log.user("New... selected");
410 closeIfReplaceable();
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() {
423 public void actionPerformed(ActionEvent e) {
424 log.user("Open... selected");
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);
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() {
446 public void actionPerformed(ActionEvent e) {
447 log.user("Open example... selected");
448 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
451 log.user("Opening example " + u);
452 open(u, BasicFrame.this);
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() {
469 public void actionPerformed(ActionEvent e) {
470 log.user("Save selected");
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() {
485 public void actionPerformed(ActionEvent e) {
486 log.user("Save as... selected");
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() {
500 public void actionPerformed(ActionEvent e) {
501 log.user("Print action selected");
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() {
518 public void actionPerformed(ActionEvent e) {
519 log.user("Close selected");
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() {
535 public void actionPerformed(ActionEvent e) {
536 log.user("Quit selected");
545 menu = new JMenu(trans.get("main.menu.edit"));
546 menu.setMnemonic(KeyEvent.VK_E);
548 menu.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.menu.Rocketedt"));
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"));
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"));
572 item = new JMenuItem(actions.getCutAction());
575 item = new JMenuItem(actions.getCopyAction());
578 item = new JMenuItem(actions.getPasteAction());
581 item = new JMenuItem(actions.getDeleteAction());
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() {
593 public void actionPerformed(ActionEvent e) {
594 log.user("Scale... selected");
595 ScaleDialog dialog = new ScaleDialog(document, getSelectedComponent(), BasicFrame.this);
596 dialog.setVisible(true);
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() {
611 public void actionPerformed(ActionEvent e) {
612 log.user("Preferences selected");
613 PreferencesDialog.showPreferences(BasicFrame.this);
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"));
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() {
634 public void actionPerformed(ActionEvent e) {
635 log.user("Component analysis selected");
636 ComponentAnalysisDialog.showDialog(rocketpanel);
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() {
646 public void actionPerformed(ActionEvent e) {
647 log.user("Rocket optimization selected");
648 new GeneralOptimizationDialog(document, BasicFrame.this).setVisible(true);
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() {
658 public void actionPerformed(ActionEvent e) {
659 log.debug("Custom expressions selected");
660 new CustomExpressionDialog(document, BasicFrame.this).setVisible(true);
666 // (shown if openrocket.debug.menu is defined)
667 if (System.getProperty("openrocket.debug.menu") != null) {
668 menubar.add(makeDebugMenu());
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"));
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() {
688 public void actionPerformed(ActionEvent e) {
689 log.user("Guided tours selected");
690 GuidedTourSelectionDialog.showDialog(BasicFrame.this);
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() {
703 public void actionPerformed(ActionEvent e) {
704 log.user("Bug report selected");
705 BugReportDialog.showBugReportDialog(BasicFrame.this);
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() {
716 public void actionPerformed(ActionEvent e) {
717 log.user("Debug log selected");
718 new DebugLogDialog(BasicFrame.this).setVisible(true);
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() {
732 public void actionPerformed(ActionEvent e) {
733 log.user("License selected");
734 new LicenseDialog(BasicFrame.this).setVisible(true);
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() {
746 public void actionPerformed(ActionEvent e) {
747 log.user("About selected");
748 new AboutDialog(BasicFrame.this).setVisible(true);
754 this.setJMenuBar(menubar);
757 private JMenu makeDebugMenu() {
762 * This menu is intentionally left untranslated.
766 menu = new JMenu("Debug");
767 //// OpenRocket debugging tasks
768 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
770 //// What is this menu?
771 item = new JMenuItem("What is this menu?");
772 item.addActionListener(new ActionListener() {
774 public void actionPerformed(ActionEvent e) {
775 log.user("What is this menu? selected");
776 JOptionPane.showMessageDialog(BasicFrame.this,
778 "The 'Debug' menu includes actions for testing and debugging " +
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);
790 //// Create test rocket
791 item = new JMenuItem("Create test rocket");
792 item.addActionListener(new ActionListener() {
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:",
800 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
801 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
807 r = new TestRockets(null).makeTestRocket();
808 } else if (sel == 1) {
809 r = new TestRockets(field.getText()).makeTestRocket();
814 OpenRocketDocument doc = new OpenRocketDocument(r);
816 BasicFrame frame = new BasicFrame(doc);
817 frame.setVisible(true);
824 item = new JMenuItem("Create 'Iso-Haisu'");
825 item.addActionListener(new ActionListener() {
827 public void actionPerformed(ActionEvent e) {
828 log.user("Create Iso-Haisu selected");
829 Rocket r = TestRockets.makeIsoHaisu();
830 OpenRocketDocument doc = new OpenRocketDocument(r);
832 BasicFrame frame = new BasicFrame(doc);
833 frame.setVisible(true);
839 item = new JMenuItem("Create 'Big Blue'");
840 item.addActionListener(new ActionListener() {
842 public void actionPerformed(ActionEvent e) {
843 log.user("Create Big Blue selected");
844 Rocket r = TestRockets.makeBigBlue();
845 OpenRocketDocument doc = new OpenRocketDocument(r);
847 BasicFrame frame = new BasicFrame(doc);
848 frame.setVisible(true);
856 item = new JMenuItem("Memory statistics");
857 item.addActionListener(new ActionListener() {
859 public void actionPerformed(ActionEvent e) {
860 log.user("Memory statistics selected");
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");
867 for (MemoryData data : objects) {
868 Object o = data.getReference().get();
871 sb.append("Age ").append(System.currentTimeMillis() - data.getRegistrationTime())
872 .append(" ms: ").append(o).append('\n');
874 // Explicitly null the strong reference to avoid possibility of invisible references
877 sb.append("Total: " + count);
879 // Get basic memory stats
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);
891 DetailDialog.showDetailedMessageDialog(BasicFrame.this, stats, sb.toString(),
892 "Memory statistics", JOptionPane.INFORMATION_MESSAGE);
898 item = new JMenuItem("Exhaust memory");
899 item.addActionListener(new ActionListener() {
901 public void actionPerformed(ActionEvent e) {
902 log.user("Exhaust memory selected");
903 LinkedList<byte[]> data = new LinkedList<byte[]>();
905 final int bytesPerArray = 10240;
908 byte[] array = new byte[bytesPerArray];
909 for (int i = 0; i < bytesPerArray; i++) {
915 } catch (OutOfMemoryError error) {
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);
921 JOptionPane.showMessageDialog(BasicFrame.this, s);
931 item = new JMenuItem("Exception here");
932 item.addActionListener(new ActionListener() {
934 public void actionPerformed(ActionEvent e) {
935 log.user("Exception here selected");
936 throw new RuntimeException("Testing exception from menu action listener");
941 item = new JMenuItem("Exception from EDT");
942 item.addActionListener(new ActionListener() {
944 public void actionPerformed(ActionEvent e) {
945 log.user("Exception from EDT selected");
946 SwingUtilities.invokeLater(new Runnable() {
949 throw new RuntimeException("Testing exception from " +
950 "later invoked EDT thread");
957 item = new JMenuItem("Exception from other thread");
958 item.addActionListener(new ActionListener() {
960 public void actionPerformed(ActionEvent e) {
961 log.user("Exception from other thread selected");
965 throw new RuntimeException("Testing exception from newly created thread");
972 item = new JMenuItem("OutOfMemoryError here");
973 item.addActionListener(new ActionListener() {
975 public void actionPerformed(ActionEvent e) {
976 log.user("OutOfMemoryError here selected");
977 throw new OutOfMemoryError("Testing OutOfMemoryError from menu action listener");
986 item = new JMenuItem("Test popup");
987 item.addActionListener(new ActionListener() {
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));
997 popup.show(BasicFrame.this, -50, 100);
1010 * Select the tab on the main pane.
1012 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
1014 public void selectTab(int tab) {
1015 tabbedPane.setSelectedIndex(tab);
1020 private void openAction() {
1021 JFileChooser chooser = new JFileChooser();
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);
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);
1037 ((SwingPreferences) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory());
1039 File[] files = chooser.getSelectedFiles();
1040 log.user("Opening files " + Arrays.toString(files));
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());
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());
1058 log.info("Closing window because it is replaceable");
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.
1069 private static boolean open(URL url, BasicFrame parent) {
1070 String filename = null;
1072 // First figure out the file name from the URL
1074 // Try using URI.getPath();
1076 URI uri = url.toURI();
1077 filename = uri.getPath();
1078 } catch (URISyntaxException ignore) {
1081 // Try URL-decoding the URL
1082 if (filename == null) {
1084 filename = URLDecoder.decode(url.toString(), "UTF-8");
1085 } catch (UnsupportedEncodingException ignore) {
1090 if (filename == null) {
1094 // Remove path from filename
1095 if (filename.lastIndexOf('/') >= 0) {
1096 filename = filename.substring(filename.lastIndexOf('/') + 1);
1101 log.info("Opening file from url=" + url + " filename=" + filename);
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);
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.
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.
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);
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.
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.
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);
1146 * Open the specified file using the provided worker.
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).
1154 private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) {
1156 MotorDatabaseLoadingDialog.check(parent);
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");
1167 // Handle the document
1168 OpenRocketDocument doc = null;
1173 } catch (ExecutionException e) {
1175 Throwable cause = e.getCause();
1177 if (cause instanceof FileNotFoundException) {
1179 log.warn("File not found", cause);
1180 JOptionPane.showMessageDialog(parent,
1181 "File not found: " + filename,
1182 "Error opening file", JOptionPane.ERROR_MESSAGE);
1185 } else if (cause instanceof RocketLoadException) {
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);
1196 throw new BugException("Unknown error when opening file", e);
1200 } catch (InterruptedException e) {
1201 throw new BugException("EDT was interrupted", e);
1205 throw new BugException("Document loader returned null");
1210 WarningSet warnings = worker.getRocketLoader().getWarnings();
1211 if (!warnings.isEmpty()) {
1212 log.info("Warnings while reading file: " + warnings);
1213 WarningDialog.showWarnings(parent,
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")
1220 //// Warnings while opening file
1221 trans.get("BasicFrame.WarningDialog.title"), warnings);
1225 // Set document state
1231 log.debug("Opening new frame with the document");
1232 BasicFrame frame = new BasicFrame(doc);
1233 frame.setVisible(true);
1235 if ( parent != null && parent instanceof BasicFrame ) {
1236 ((BasicFrame)parent).closeIfReplaceable();
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).
1247 * @return true if the file was saved, false otherwise
1249 private boolean saveAction() {
1250 File file = document.getFile();
1252 log.info("Document does not contain file, opening save as dialog instead");
1253 return saveAsAction();
1255 log.info("Saving document to " + file);
1257 if (FileHelper.ROCKSIM_DESIGN_FILTER.accept(file)) {
1258 return saveAsRocksim(file);
1260 return saveAs(file);
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.
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.
1273 * @return true if the file was saved, false otherwise
1275 private boolean saveAsAction() {
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);
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);
1289 chooser.setFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
1291 chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory());
1292 chooser.setAccessory(storageChooser);
1293 if (document.getFile() != null) {
1294 chooser.setSelectedFile(document.getFile());
1297 int option = chooser.showSaveDialog(BasicFrame.this);
1298 if (option != JFileChooser.APPROVE_OPTION) {
1299 log.user("User decided not to save, option=" + option);
1303 file = chooser.getSelectedFile();
1305 log.user("User did not select a file");
1309 ((SwingPreferences) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory());
1310 storageChooser.storeOptions(document.getDefaultStorageOptions());
1312 if (chooser.getFileFilter().equals(FileHelper.ROCKSIM_DESIGN_FILTER)) {
1313 return saveAsRocksim(file);
1316 file = FileHelper.forceExtension(file, "ork");
1317 return FileHelper.confirmWrite(file, this) && saveAs(file);
1322 * Perform the writing of the design to the given file in Rocksim format.
1324 * @param file the chosen file
1326 * @return true if the file was written
1328 private boolean saveAsRocksim(File file) {
1329 file = FileHelper.forceExtension(file, "rkt");
1330 if (!FileHelper.confirmWrite(file, this)) {
1335 new RocksimSaver().save(file, document);
1337 } catch (IOException e) {
1343 * Perform the writing of the design to the given file in OpenRocket format.
1345 * @param file the chosen file
1347 * @return true if the file was written
1349 private boolean saveAs(File file) {
1350 log.info("Saving document as " + file);
1351 boolean saved = false;
1353 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1354 // User cancelled the dialog
1355 log.user("User cancelled saving in storage options dialog");
1360 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1362 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1363 "Writing " + file.getName() + "...", worker)) {
1365 // User cancelled the save
1366 log.user("User cancelled the save, deleting the file");
1373 document.setFile(file);
1374 document.setSaved(true);
1377 } catch (ExecutionException e) {
1379 Throwable cause = e.getCause();
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);
1388 Reflection.handleWrappedException(e);
1391 } catch (InterruptedException e) {
1392 throw new BugException("EDT was interrupted", e);
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) {
1411 log.user("User requested file save");
1412 if (!saveAction()) {
1413 log.info("File save was interrupted, not closing");
1416 } else if (result == JOptionPane.NO_OPTION) {
1417 // Don't save: No-op
1418 log.user("User requested to discard design");
1421 log.user("User cancelled closing, result=" + result);
1426 // Rocket has been saved or discarded
1427 log.debug("Disposing window");
1430 ComponentConfigDialog.hideDialog();
1431 ComponentAnalysisDialog.hideDialog();
1433 frames.remove(this);
1434 if (frames.isEmpty()) {
1435 log.info("Last frame closed, exiting");
1446 public void printAction() {
1447 Double rotation = rocketpanel.getFigure().getRotation();
1448 if (rotation == null) {
1451 new PrintDialog(this, document, rotation).setVisible(true);
1455 * Open a new design window with a basic rocket+stage.
1457 public static void newAction() {
1458 log.info("New action initiated");
1460 Rocket rocket = new Rocket();
1461 Stage stage = new Stage();
1463 stage.setName(trans.get("BasicFrame.StageName.Sustainer"));
1464 rocket.addChild(stage);
1465 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1468 BasicFrame frame = new BasicFrame(doc);
1469 frame.replaceable = true;
1470 frame.setVisible(true);
1471 // FIXME - kruland commented this out - I don't like it.
1472 //ComponentConfigDialog.showDialog(frame, doc, rocket);
1476 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
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()) {
1484 log.info("Quit was cancelled");
1488 // Should not be reached, but just in case
1489 log.error("Should already have exited application");
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.
1498 private void setTitle() {
1499 File file = document.getFile();
1500 boolean saved = document.isSaved();
1503 title = rocket.getName();
1505 title = title + " (" + file.getName() + ")";
1508 title = "*" + title;
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.
1519 * @param rocket the Rocket.
1520 * @return the corresponding BasicFrame, or <code>null</code> if none found.
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);
1529 log.debug("Could not find frame for rocket " + rocket);
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.
1537 * @param rocket the Rocket.
1538 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1540 public static OpenRocketDocument findDocument(Rocket rocket) {
1541 BasicFrame frame = findFrame(rocket);
1542 if (frame != null) {
1543 return frame.document;