1 package net.sf.openrocket.gui.main;
3 import java.awt.Dimension;
5 import java.awt.Toolkit;
6 import java.awt.Window;
7 import java.awt.event.ActionEvent;
8 import java.awt.event.ActionListener;
9 import java.awt.event.KeyEvent;
10 import java.awt.event.MouseAdapter;
11 import java.awt.event.MouseEvent;
12 import java.awt.event.MouseListener;
13 import java.awt.event.WindowAdapter;
14 import java.awt.event.WindowEvent;
16 import java.io.FileNotFoundException;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.io.UnsupportedEncodingException;
21 import java.net.URISyntaxException;
23 import java.net.URLDecoder;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.LinkedList;
27 import java.util.List;
28 import java.util.concurrent.ExecutionException;
30 import javax.swing.Action;
31 import javax.swing.BorderFactory;
32 import javax.swing.InputMap;
33 import javax.swing.JButton;
34 import javax.swing.JComponent;
35 import javax.swing.JFileChooser;
36 import javax.swing.JFrame;
37 import javax.swing.JMenu;
38 import javax.swing.JMenuBar;
39 import javax.swing.JMenuItem;
40 import javax.swing.JOptionPane;
41 import javax.swing.JPanel;
42 import javax.swing.JPopupMenu;
43 import javax.swing.JScrollPane;
44 import javax.swing.JSpinner;
45 import javax.swing.JSplitPane;
46 import javax.swing.JTabbedPane;
47 import javax.swing.JTextField;
48 import javax.swing.KeyStroke;
49 import javax.swing.ListSelectionModel;
50 import javax.swing.ScrollPaneConstants;
51 import javax.swing.SwingUtilities;
52 import javax.swing.border.BevelBorder;
53 import javax.swing.border.TitledBorder;
54 import javax.swing.event.TreeSelectionEvent;
55 import javax.swing.event.TreeSelectionListener;
56 import javax.swing.tree.DefaultTreeSelectionModel;
57 import javax.swing.tree.TreePath;
58 import javax.swing.tree.TreeSelectionModel;
60 import net.miginfocom.swing.MigLayout;
61 import net.sf.openrocket.aerodynamics.WarningSet;
62 import net.sf.openrocket.document.OpenRocketDocument;
63 import net.sf.openrocket.file.GeneralRocketLoader;
64 import net.sf.openrocket.file.RocketLoadException;
65 import net.sf.openrocket.file.RocketLoader;
66 import net.sf.openrocket.file.RocketSaver;
67 import net.sf.openrocket.file.openrocket.OpenRocketSaver;
68 import net.sf.openrocket.file.rocksim.export.RocksimSaver;
69 import net.sf.openrocket.gui.StorageOptionChooser;
70 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
71 import net.sf.openrocket.gui.dialogs.AboutDialog;
72 import net.sf.openrocket.gui.dialogs.BugReportDialog;
73 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
74 import net.sf.openrocket.gui.dialogs.DebugLogDialog;
75 import net.sf.openrocket.gui.dialogs.DetailDialog;
76 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
77 import net.sf.openrocket.gui.dialogs.LicenseDialog;
78 import net.sf.openrocket.gui.dialogs.MotorDatabaseLoadingDialog;
79 import net.sf.openrocket.gui.dialogs.PrintDialog;
80 import net.sf.openrocket.gui.dialogs.ScaleDialog;
81 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
82 import net.sf.openrocket.gui.dialogs.WarningDialog;
83 import net.sf.openrocket.gui.dialogs.optimization.GeneralOptimizationDialog;
84 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
85 import net.sf.openrocket.gui.help.tours.GuidedTourSelectionDialog;
86 import net.sf.openrocket.gui.main.componenttree.ComponentTree;
87 import net.sf.openrocket.gui.scalefigure.RocketPanel;
88 import net.sf.openrocket.gui.util.FileHelper;
89 import net.sf.openrocket.gui.util.GUIUtil;
90 import net.sf.openrocket.gui.util.Icons;
91 import net.sf.openrocket.gui.util.OpenFileWorker;
92 import net.sf.openrocket.gui.util.SaveFileWorker;
93 import net.sf.openrocket.gui.util.SwingPreferences;
94 import net.sf.openrocket.l10n.Translator;
95 import net.sf.openrocket.logging.LogHelper;
96 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
97 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
98 import net.sf.openrocket.rocketcomponent.Rocket;
99 import net.sf.openrocket.rocketcomponent.RocketComponent;
100 import net.sf.openrocket.rocketcomponent.Stage;
101 import net.sf.openrocket.startup.Application;
102 import net.sf.openrocket.util.BugException;
103 import net.sf.openrocket.util.MemoryManagement;
104 import net.sf.openrocket.util.MemoryManagement.MemoryData;
105 import net.sf.openrocket.util.Reflection;
106 import net.sf.openrocket.util.TestRockets;
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();
170 // Set replaceable flag to false at first modification
171 rocket.addComponentChangeListener(new ComponentChangeListener() {
173 public void componentChanged(ComponentChangeEvent e) {
175 BasicFrame.this.rocket.removeComponentChangeListener(this);
180 // Create the component tree selection model that will be used
181 componentSelectionModel = new DefaultTreeSelectionModel();
182 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
184 // Obtain the simulation selection model that will be used
185 SimulationPanel simulationPanel = new SimulationPanel(document);
186 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
188 // Combine into a DocumentSelectionModel
189 selectionModel = new DocumentSelectionModel(document);
190 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
191 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
194 actions = new RocketActions(document, selectionModel, this);
197 log.debug("Constructing the BasicFrame UI");
199 // The main vertical split pane
200 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
201 vertical.setResizeWeight(0.5);
205 // The top tabbed pane
206 tabbedPane = new JTabbedPane();
208 tabbedPane.addTab(trans.get("BasicFrame.tab.Rocketdesign"), null, designTab());
209 //// Flight simulations
210 tabbedPane.addTab(trans.get("BasicFrame.tab.Flightsim"), null, simulationPanel);
212 vertical.setTopComponent(tabbedPane);
216 // Bottom segment, rocket figure
218 rocketpanel = new RocketPanel(document);
219 vertical.setBottomComponent(rocketpanel);
221 rocketpanel.setSelectionModel(tree.getSelectionModel());
227 rocket.addComponentChangeListener(new ComponentChangeListener() {
229 public void componentChanged(ComponentChangeEvent e) {
238 // Set initial window size
239 Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
240 size.width = size.width * 9 / 10;
241 size.height = size.height * 9 / 10;
244 // Remember changed size
245 GUIUtil.rememberWindowSize(this);
247 this.setLocationByPlatform(true);
249 GUIUtil.setWindowIcons(this);
252 vertical.setDividerLocation(0.4);
253 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
254 addWindowListener(new WindowAdapter() {
256 public void windowClosing(WindowEvent e) {
262 log.debug("BasicFrame instantiation complete");
267 * Construct the "Rocket design" tab. This contains a horizontal split pane
268 * with the left component the design tree and the right component buttons
269 * for adding components.
271 private JComponent designTab() {
272 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
273 horizontal.setResizeWeight(0.5);
276 // Upper-left segment, component tree
278 JPanel panel = new JPanel(new MigLayout("fill, flowy", "", "[grow]"));
280 tree = new ComponentTree(document);
281 tree.setSelectionModel(componentSelectionModel);
283 // Remove JTree key events that interfere with menu accelerators
284 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
285 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
286 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
287 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
288 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
289 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
290 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
291 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
295 // Double-click opens config dialog
296 MouseListener ml = new MouseAdapter() {
298 public void mousePressed(MouseEvent e) {
299 int selRow = tree.getRowForLocation(e.getX(), e.getY());
300 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
302 if ((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
304 RocketComponent c = (RocketComponent) selPath.getLastPathComponent();
305 ComponentConfigDialog.showDialog(BasicFrame.this,
306 BasicFrame.this.document, c);
311 tree.addMouseListener(ml);
313 // Update dialog when selection is changed
314 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
316 public void valueChanged(TreeSelectionEvent e) {
317 // Scroll tree to the selected item
318 TreePath path = componentSelectionModel.getSelectionPath();
321 tree.scrollPathToVisible(path);
323 if (!ComponentConfigDialog.isDialogVisible())
325 RocketComponent c = (RocketComponent) path.getLastPathComponent();
326 ComponentConfigDialog.showDialog(BasicFrame.this,
327 BasicFrame.this.document, c);
331 // Place tree inside scroll pane
332 JScrollPane scroll = new JScrollPane(tree);
333 panel.add(scroll, "spany, grow, wrap");
337 JButton button = new JButton(actions.getMoveUpAction());
338 panel.add(button, "sizegroup buttons, aligny 65%");
340 button = new JButton(actions.getMoveDownAction());
341 panel.add(button, "sizegroup buttons, aligny 0%");
343 button = new JButton(actions.getEditAction());
344 panel.add(button, "sizegroup buttons");
346 button = new JButton(actions.getNewStageAction());
347 panel.add(button, "sizegroup buttons");
349 button = new JButton(actions.getDeleteAction());
350 button.setIcon(null);
351 button.setMnemonic(0);
352 panel.add(button, "sizegroup buttons");
354 horizontal.setLeftComponent(panel);
357 // Upper-right segment, component addition buttons
359 panel = new JPanel(new MigLayout("fill, insets 0", "[0::]"));
361 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
362 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
363 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
364 scroll.getViewport()));
365 scroll.setBorder(null);
366 scroll.setViewportBorder(null);
368 TitledBorder border = BorderFactory.createTitledBorder(trans.get("BasicFrame.title.Addnewcomp"));
369 GUIUtil.changeFontStyle(border, Font.BOLD);
370 scroll.setBorder(border);
372 panel.add(scroll, "grow");
374 horizontal.setRightComponent(panel);
382 * Return the currently selected rocket component, or <code>null</code> if none selected.
384 private RocketComponent getSelectedComponent() {
385 TreePath path = componentSelectionModel.getSelectionPath();
388 tree.scrollPathToVisible(path);
390 return (RocketComponent) path.getLastPathComponent();
395 * Creates the menu for the window.
397 private void createMenu() {
398 JMenuBar menubar = new JMenuBar();
403 menu = new JMenu(trans.get("main.menu.file"));
404 menu.setMnemonic(KeyEvent.VK_F);
405 //// File-handling related tasks
406 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.desc"));
410 item = new JMenuItem(trans.get("main.menu.file.new"), KeyEvent.VK_N);
411 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
412 item.setMnemonic(KeyEvent.VK_N);
413 //// Create a new rocket design
414 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.new.desc"));
415 item.setIcon(Icons.FILE_NEW);
416 item.addActionListener(new ActionListener() {
418 public void actionPerformed(ActionEvent e) {
419 log.user("New... selected");
422 log.info("Closing previous window");
430 item = new JMenuItem(trans.get("main.menu.file.open"), KeyEvent.VK_O);
431 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
432 //// Open a rocket design
433 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openrocketdesign"));
434 item.setIcon(Icons.FILE_OPEN);
435 item.addActionListener(new ActionListener() {
437 public void actionPerformed(ActionEvent e) {
438 log.user("Open... selected");
445 item = new JMenuItem(trans.get("main.menu.file.openExample"));
446 //// Open an example rocket design
447 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openexamplerocketdesign"));
448 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
449 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
450 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
451 item.addActionListener(new ActionListener() {
453 public void actionPerformed(ActionEvent e) {
454 log.user("Open example... selected");
455 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
458 log.user("Opening example " + u);
459 open(u, BasicFrame.this);
469 item = new JMenuItem(trans.get("main.menu.file.save"), KeyEvent.VK_S);
470 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
471 //// Save the current rocket design
472 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesign"));
473 item.setIcon(Icons.FILE_SAVE);
474 item.addActionListener(new ActionListener() {
476 public void actionPerformed(ActionEvent e) {
477 log.user("Save selected");
484 item = new JMenuItem(trans.get("main.menu.file.saveAs"), KeyEvent.VK_A);
485 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
486 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
487 //// Save the current rocket design to a new file
488 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesnewfile"));
489 item.setIcon(Icons.FILE_SAVE_AS);
490 item.addActionListener(new ActionListener() {
492 public void actionPerformed(ActionEvent e) {
493 log.user("Save as... selected");
500 item = new JMenuItem(trans.get("main.menu.file.print"), KeyEvent.VK_P);
501 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
502 //// Print parts list and fin template
503 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.print.desc"));
504 item.setIcon(Icons.FILE_PRINT);
505 item.addActionListener(new ActionListener() {
507 public void actionPerformed(ActionEvent e) {
508 log.user("Print action selected");
518 item = new JMenuItem(trans.get("main.menu.file.close"), KeyEvent.VK_C);
519 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
520 //// Close the current rocket design
521 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Closedesign"));
522 item.setIcon(Icons.FILE_CLOSE);
523 item.addActionListener(new ActionListener() {
525 public void actionPerformed(ActionEvent e) {
526 log.user("Close selected");
535 item = new JMenuItem(trans.get("main.menu.file.quit"), KeyEvent.VK_Q);
536 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
537 //// Quit the program
538 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Quitprogram"));
539 item.setIcon(Icons.FILE_QUIT);
540 item.addActionListener(new ActionListener() {
542 public void actionPerformed(ActionEvent e) {
543 log.user("Quit selected");
552 menu = new JMenu(trans.get("main.menu.edit"));
553 menu.setMnemonic(KeyEvent.VK_E);
555 menu.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.menu.Rocketedt"));
559 Action action = UndoRedoAction.newUndoAction(document);
560 item = new JMenuItem(action);
561 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
562 item.setMnemonic(KeyEvent.VK_U);
563 //// Undo the previous operation
564 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.undo.desc"));
568 action = UndoRedoAction.newRedoAction(document);
569 item = new JMenuItem(action);
570 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
571 item.setMnemonic(KeyEvent.VK_R);
572 //// Redo the previously undone operation
573 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.redo.desc"));
579 item = new JMenuItem(actions.getCutAction());
582 item = new JMenuItem(actions.getCopyAction());
585 item = new JMenuItem(actions.getPasteAction());
588 item = new JMenuItem(actions.getDeleteAction());
595 item = new JMenuItem(trans.get("main.menu.edit.resize"));
596 item.setIcon(Icons.EDIT_SCALE);
597 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.resize.desc"));
598 item.addActionListener(new ActionListener() {
600 public void actionPerformed(ActionEvent e) {
601 log.user("Scale... selected");
602 ScaleDialog dialog = new ScaleDialog(document, getSelectedComponent(), BasicFrame.this);
603 dialog.setVisible(true);
612 item = new JMenuItem(trans.get("main.menu.edit.preferences"));
613 item.setIcon(Icons.PREFERENCES);
614 //// Setup the application preferences
615 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.preferences.desc"));
616 item.addActionListener(new ActionListener() {
618 public void actionPerformed(ActionEvent e) {
619 log.user("Preferences selected");
620 PreferencesDialog.showPreferences(BasicFrame.this);
629 menu = new JMenu(trans.get("main.menu.analyze"));
630 menu.setMnemonic(KeyEvent.VK_A);
631 //// Analyzing the rocket
632 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.desc"));
635 //// Component analysis
636 item = new JMenuItem(trans.get("main.menu.analyze.componentAnalysis"), KeyEvent.VK_C);
637 //// Analyze the rocket components separately
638 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.componentAnalysis.desc"));
639 item.addActionListener(new ActionListener() {
641 public void actionPerformed(ActionEvent e) {
642 log.user("Component analysis selected");
643 ComponentAnalysisDialog.showDialog(rocketpanel);
649 item = new JMenuItem(trans.get("main.menu.analyze.optimization"), KeyEvent.VK_O);
650 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.optimization.desc"));
651 item.addActionListener(new ActionListener() {
653 public void actionPerformed(ActionEvent e) {
654 log.user("Rocket optimization selected");
655 new GeneralOptimizationDialog(document, BasicFrame.this).setVisible(true);
663 // (shown if openrocket.debug.menu is defined)
664 if (System.getProperty("openrocket.debug.menu") != null) {
665 menubar.add(makeDebugMenu());
672 menu = new JMenu(trans.get("main.menu.help"));
673 menu.setMnemonic(KeyEvent.VK_H);
674 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.desc"));
680 item = new JMenuItem(trans.get("main.menu.help.tours"), KeyEvent.VK_L);
681 item.setIcon(Icons.HELP_TOURS);
682 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.tours.desc"));
683 item.addActionListener(new ActionListener() {
685 public void actionPerformed(ActionEvent e) {
686 log.user("Guided tours selected");
687 GuidedTourSelectionDialog.showDialog(BasicFrame.this);
695 item = new JMenuItem(trans.get("main.menu.help.bugReport"), KeyEvent.VK_B);
696 item.setIcon(Icons.HELP_BUG_REPORT);
697 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.bugReport.desc"));
698 item.addActionListener(new ActionListener() {
700 public void actionPerformed(ActionEvent e) {
701 log.user("Bug report selected");
702 BugReportDialog.showBugReportDialog(BasicFrame.this);
708 item = new JMenuItem(trans.get("main.menu.help.debugLog"));
709 item.setIcon(Icons.HELP_DEBUG_LOG);
710 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.debugLog.desc"));
711 item.addActionListener(new ActionListener() {
713 public void actionPerformed(ActionEvent e) {
714 log.user("Debug log selected");
715 new DebugLogDialog(BasicFrame.this).setVisible(true);
724 item = new JMenuItem(trans.get("main.menu.help.license"), KeyEvent.VK_L);
725 item.setIcon(Icons.HELP_LICENSE);
726 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.license.desc"));
727 item.addActionListener(new ActionListener() {
729 public void actionPerformed(ActionEvent e) {
730 log.user("License selected");
731 new LicenseDialog(BasicFrame.this).setVisible(true);
738 item = new JMenuItem(trans.get("main.menu.help.about"), KeyEvent.VK_A);
739 item.setIcon(Icons.HELP_ABOUT);
740 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.about.desc"));
741 item.addActionListener(new ActionListener() {
743 public void actionPerformed(ActionEvent e) {
744 log.user("About selected");
745 new AboutDialog(BasicFrame.this).setVisible(true);
751 this.setJMenuBar(menubar);
754 private JMenu makeDebugMenu() {
759 * This menu is intentionally left untranslated.
763 menu = new JMenu("Debug");
764 //// OpenRocket debugging tasks
765 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
767 //// What is this menu?
768 item = new JMenuItem("What is this menu?");
769 item.addActionListener(new ActionListener() {
771 public void actionPerformed(ActionEvent e) {
772 log.user("What is this menu? selected");
773 JOptionPane.showMessageDialog(BasicFrame.this,
775 "The 'Debug' menu includes actions for testing and debugging " +
777 "The menu is made visible by defining the system property " +
778 "'openrocket.debug.menu' when starting OpenRocket.",
779 "It should not be visible by default." },
780 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
787 //// Create test rocket
788 item = new JMenuItem("Create test rocket");
789 item.addActionListener(new ActionListener() {
791 public void actionPerformed(ActionEvent e) {
792 log.user("Create test rocket selected");
793 JTextField field = new JTextField();
794 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
795 "Input text key to generate random rocket:",
797 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
798 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
804 r = new TestRockets(null).makeTestRocket();
805 } else if (sel == 1) {
806 r = new TestRockets(field.getText()).makeTestRocket();
811 OpenRocketDocument doc = new OpenRocketDocument(r);
813 BasicFrame frame = new BasicFrame(doc);
814 frame.setVisible(true);
821 item = new JMenuItem("Create 'Iso-Haisu'");
822 item.addActionListener(new ActionListener() {
824 public void actionPerformed(ActionEvent e) {
825 log.user("Create Iso-Haisu selected");
826 Rocket r = TestRockets.makeIsoHaisu();
827 OpenRocketDocument doc = new OpenRocketDocument(r);
829 BasicFrame frame = new BasicFrame(doc);
830 frame.setVisible(true);
836 item = new JMenuItem("Create 'Big Blue'");
837 item.addActionListener(new ActionListener() {
839 public void actionPerformed(ActionEvent e) {
840 log.user("Create Big Blue selected");
841 Rocket r = TestRockets.makeBigBlue();
842 OpenRocketDocument doc = new OpenRocketDocument(r);
844 BasicFrame frame = new BasicFrame(doc);
845 frame.setVisible(true);
853 item = new JMenuItem("Memory statistics");
854 item.addActionListener(new ActionListener() {
856 public void actionPerformed(ActionEvent e) {
857 log.user("Memory statistics selected");
859 // Get discarded but remaining objects (this also runs System.gc multiple times)
860 List<MemoryData> objects = MemoryManagement.getRemainingCollectableObjects();
861 StringBuilder sb = new StringBuilder();
862 sb.append("Objects that should have been garbage-collected but have not been:\n");
864 for (MemoryData data : objects) {
865 Object o = data.getReference().get();
868 sb.append("Age ").append(System.currentTimeMillis() - data.getRegistrationTime())
869 .append(" ms: ").append(o).append('\n');
871 // Explicitly null the strong reference to avoid possibility of invisible references
874 sb.append("Total: " + count);
876 // Get basic memory stats
878 long max = Runtime.getRuntime().maxMemory();
879 long free = Runtime.getRuntime().freeMemory();
880 long used = max - free;
881 String[] stats = new String[4];
882 stats[0] = "Memory usage:";
883 stats[1] = String.format(" Max memory: %.1f MB", max / 1024.0 / 1024.0);
884 stats[2] = String.format(" Used memory: %.1f MB (%.0f%%)", used / 1024.0 / 1024.0, 100.0 * used / max);
885 stats[3] = String.format(" Free memory: %.1f MB (%.0f%%)", free / 1024.0 / 1024.0, 100.0 * free / max);
888 DetailDialog.showDetailedMessageDialog(BasicFrame.this, stats, sb.toString(),
889 "Memory statistics", JOptionPane.INFORMATION_MESSAGE);
895 item = new JMenuItem("Exhaust memory");
896 item.addActionListener(new ActionListener() {
898 public void actionPerformed(ActionEvent e) {
899 log.user("Exhaust memory selected");
900 LinkedList<byte[]> data = new LinkedList<byte[]>();
902 final int bytesPerArray = 10240;
905 byte[] array = new byte[bytesPerArray];
906 for (int i = 0; i < bytesPerArray; i++) {
912 } catch (OutOfMemoryError error) {
914 long size = bytesPerArray * (long) count;
915 String s = String.format("OutOfMemory occurred after %d iterations (approx. %.1f MB consumed)",
916 count, size / 1024.0 / 1024.0);
918 JOptionPane.showMessageDialog(BasicFrame.this, s);
928 item = new JMenuItem("Exception here");
929 item.addActionListener(new ActionListener() {
931 public void actionPerformed(ActionEvent e) {
932 log.user("Exception here selected");
933 throw new RuntimeException("Testing exception from menu action listener");
938 item = new JMenuItem("Exception from EDT");
939 item.addActionListener(new ActionListener() {
941 public void actionPerformed(ActionEvent e) {
942 log.user("Exception from EDT selected");
943 SwingUtilities.invokeLater(new Runnable() {
946 throw new RuntimeException("Testing exception from " +
947 "later invoked EDT thread");
954 item = new JMenuItem("Exception from other thread");
955 item.addActionListener(new ActionListener() {
957 public void actionPerformed(ActionEvent e) {
958 log.user("Exception from other thread selected");
962 throw new RuntimeException("Testing exception from newly created thread");
969 item = new JMenuItem("OutOfMemoryError here");
970 item.addActionListener(new ActionListener() {
972 public void actionPerformed(ActionEvent e) {
973 log.user("OutOfMemoryError here selected");
974 throw new OutOfMemoryError("Testing OutOfMemoryError from menu action listener");
983 item = new JMenuItem("Test popup");
984 item.addActionListener(new ActionListener() {
986 public void actionPerformed(ActionEvent e) {
987 log.user("Test popup selected");
988 JPanel panel = new JPanel();
989 panel.add(new JTextField(40));
990 panel.add(new JSpinner());
991 JPopupMenu popup = new JPopupMenu();
992 popup.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
994 popup.show(BasicFrame.this, -50, 100);
1007 * Select the tab on the main pane.
1009 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
1011 public void selectTab(int tab) {
1012 tabbedPane.setSelectedIndex(tab);
1017 private void openAction() {
1018 JFileChooser chooser = new JFileChooser();
1020 chooser.addChoosableFileFilter(FileHelper.ALL_DESIGNS_FILTER);
1021 chooser.addChoosableFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
1022 chooser.addChoosableFileFilter(FileHelper.ROCKSIM_DESIGN_FILTER);
1023 chooser.setFileFilter(FileHelper.ALL_DESIGNS_FILTER);
1025 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
1026 chooser.setMultiSelectionEnabled(true);
1027 chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory());
1028 int option = chooser.showOpenDialog(this);
1029 if (option != JFileChooser.APPROVE_OPTION) {
1030 log.user("Decided not to open files, option=" + option);
1034 ((SwingPreferences) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory());
1036 File[] files = chooser.getSelectedFiles();
1037 log.user("Opening files " + Arrays.toString(files));
1039 for (File file : files) {
1040 log.info("Opening file: " + file);
1041 if (open(file, this)) {
1043 // Close previous window if replacing
1044 if (replaceable && document.isSaved()) {
1045 // We are replacing the frame, make new window have current location
1046 BasicFrame newFrame = frames.get(frames.size() - 1);
1047 newFrame.setLocation(this.getLocation());
1049 log.info("Closing window because it is replaceable");
1051 replaceable = false;
1059 * Open a file based on a URL.
1060 * @param url the file to open.
1061 * @param parent the parent window for dialogs.
1062 * @return <code>true</code> if opened successfully.
1064 private static boolean open(URL url, BasicFrame parent) {
1065 String filename = null;
1067 // First figure out the file name from the URL
1069 // Try using URI.getPath();
1071 URI uri = url.toURI();
1072 filename = uri.getPath();
1073 } catch (URISyntaxException ignore) {
1076 // Try URL-decoding the URL
1077 if (filename == null) {
1079 filename = URLDecoder.decode(url.toString(), "UTF-8");
1080 } catch (UnsupportedEncodingException ignore) {
1085 if (filename == null) {
1089 // Remove path from filename
1090 if (filename.lastIndexOf('/') >= 0) {
1091 filename = filename.substring(filename.lastIndexOf('/') + 1);
1096 log.info("Opening file from url=" + url + " filename=" + filename);
1098 InputStream is = url.openStream();
1099 if (open(is, filename, parent)) {
1100 // Close previous window if replacing
1101 if (parent.replaceable && parent.document.isSaved()) {
1102 parent.closeAction();
1103 parent.replaceable = false;
1106 } catch (IOException e) {
1107 log.warn("Error opening file" + e);
1108 JOptionPane.showMessageDialog(parent,
1109 "An error occurred while opening the file " + filename,
1110 "Error loading file", JOptionPane.ERROR_MESSAGE);
1118 * Open the specified file from an InputStream in a new design frame. If an error
1119 * occurs, an error dialog is shown and <code>false</code> is returned.
1121 * @param stream the stream to load from.
1122 * @param filename the file name to display in dialogs (not set to the document).
1123 * @param parent the parent component for which a progress dialog is opened.
1124 * @return whether the file was successfully loaded and opened.
1126 private static boolean open(InputStream stream, String filename, Window parent) {
1127 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
1128 return open(worker, filename, null, parent);
1133 * Open the specified file in a new design frame. If an error occurs, an error
1134 * dialog is shown and <code>false</code> is returned.
1136 * @param file the file to open.
1137 * @param parent the parent component for which a progress dialog is opened.
1138 * @return whether the file was successfully loaded and opened.
1140 public static boolean open(File file, Window parent) {
1141 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
1142 return open(worker, file.getName(), file, parent);
1147 * Open the specified file using the provided worker.
1149 * @param worker the OpenFileWorker that loads the file.
1150 * @param filename the file name to display in dialogs.
1151 * @param file the File to set the document to (may be null).
1155 private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) {
1157 MotorDatabaseLoadingDialog.check(parent);
1159 // Open the file in a Swing worker thread
1160 log.info("Starting OpenFileWorker");
1161 if (!SwingWorkerDialog.runWorker(parent, "Opening file", "Reading " + filename + "...", worker)) {
1162 // User cancelled the operation
1163 log.info("User cancelled the OpenFileWorker");
1168 // Handle the document
1169 OpenRocketDocument doc = null;
1174 } catch (ExecutionException e) {
1176 Throwable cause = e.getCause();
1178 if (cause instanceof FileNotFoundException) {
1180 log.warn("File not found", cause);
1181 JOptionPane.showMessageDialog(parent,
1182 "File not found: " + filename,
1183 "Error opening file", JOptionPane.ERROR_MESSAGE);
1186 } else if (cause instanceof RocketLoadException) {
1188 log.warn("Error loading the file", cause);
1189 JOptionPane.showMessageDialog(parent,
1190 "Unable to open file '" + filename + "': "
1191 + cause.getMessage(),
1192 "Error opening file", JOptionPane.ERROR_MESSAGE);
1197 throw new BugException("Unknown error when opening file", e);
1201 } catch (InterruptedException e) {
1202 throw new BugException("EDT was interrupted", e);
1206 throw new BugException("Document loader returned null");
1211 WarningSet warnings = worker.getRocketLoader().getWarnings();
1212 if (!warnings.isEmpty()) {
1213 log.info("Warnings while reading file: " + warnings);
1214 WarningDialog.showWarnings(parent,
1216 //// The following problems were encountered while opening
1217 trans.get("BasicFrame.WarningDialog.txt1") + " " + filename + ".",
1218 //// Some design features may not have been loaded correctly.
1219 trans.get("BasicFrame.WarningDialog.txt2")
1221 //// Warnings while opening file
1222 trans.get("BasicFrame.WarningDialog.title"), warnings);
1226 // Set document state
1232 log.debug("Opening new frame with the document");
1233 BasicFrame frame = new BasicFrame(doc);
1234 frame.setVisible(true);
1240 * "Save" action. If the design is new, then this is identical to "Save As", with a default file filter for .ork.
1241 * If the rocket being edited previously was opened from a .ork file, then it will be saved immediately to the same
1242 * file. But clicking on 'Save' for an existing design file with a .rkt will bring up a confirmation dialog because
1243 * it's potentially a destructive write (loss of some fidelity if it's truly an original Rocksim generated file).
1245 * @return true if the file was saved, false otherwise
1247 private boolean saveAction() {
1248 File file = document.getFile();
1250 log.info("Document does not contain file, opening save as dialog instead");
1251 return saveAsAction();
1253 log.info("Saving document to " + file);
1255 if (FileHelper.ROCKSIM_DESIGN_FILTER.accept(file)) {
1256 return saveAsRocksim(file);
1258 return saveAs(file);
1264 * Never should a .rkt file contain an OpenRocket content, or an .ork file contain a Rocksim design. Regardless of
1265 * what extension the user has chosen, it would violate the Principle of Least Astonishment to do otherwise
1266 * (and we want to make doing the wrong thing really hard to do). So always force the appropriate extension.
1268 * This can result in some odd looking filenames (MyDesign.rkt.ork, MyDesign.rkt.ork.rkt, etc.) if the user is
1269 * not paying attention, but the user can control that by modifying the filename in the dialog.
1271 * @return true if the file was saved, false otherwise
1273 private boolean saveAsAction() {
1276 StorageOptionChooser storageChooser =
1277 new StorageOptionChooser(document, document.getDefaultStorageOptions());
1278 final JFileChooser chooser = new JFileChooser();
1279 chooser.addChoosableFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
1280 chooser.addChoosableFileFilter(FileHelper.ROCKSIM_DESIGN_FILTER);
1282 //Force the file filter to match the file extension that was opened. Will default to OR if the file is null.
1283 if (FileHelper.ROCKSIM_DESIGN_FILTER.accept(document.getFile())) {
1284 chooser.setFileFilter(FileHelper.ROCKSIM_DESIGN_FILTER);
1287 chooser.setFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
1289 chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory());
1290 chooser.setAccessory(storageChooser);
1291 if (document.getFile() != null) {
1292 chooser.setSelectedFile(document.getFile());
1295 int option = chooser.showSaveDialog(BasicFrame.this);
1296 if (option != JFileChooser.APPROVE_OPTION) {
1297 log.user("User decided not to save, option=" + option);
1301 file = chooser.getSelectedFile();
1303 log.user("User did not select a file");
1307 ((SwingPreferences) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory());
1308 storageChooser.storeOptions(document.getDefaultStorageOptions());
1310 if (chooser.getFileFilter().equals(FileHelper.ROCKSIM_DESIGN_FILTER)) {
1311 return saveAsRocksim(file);
1314 file = FileHelper.forceExtension(file, "ork");
1315 return FileHelper.confirmWrite(file, this) && saveAs(file);
1320 * Perform the writing of the design to the given file in Rocksim format.
1322 * @param file the chosen file
1324 * @return true if the file was written
1326 private boolean saveAsRocksim(File file) {
1327 file = FileHelper.forceExtension(file, "rkt");
1328 if (!FileHelper.confirmWrite(file, this)) {
1333 new RocksimSaver().save(file, document);
1335 } catch (IOException e) {
1341 * Perform the writing of the design to the given file in OpenRocket format.
1343 * @param file the chosen file
1345 * @return true if the file was written
1347 private boolean saveAs(File file) {
1348 log.info("Saving document as " + file);
1349 boolean saved = false;
1351 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1352 // User cancelled the dialog
1353 log.user("User cancelled saving in storage options dialog");
1358 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1360 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1361 "Writing " + file.getName() + "...", worker)) {
1363 // User cancelled the save
1364 log.user("User cancelled the save, deleting the file");
1371 document.setFile(file);
1372 document.setSaved(true);
1375 } catch (ExecutionException e) {
1377 Throwable cause = e.getCause();
1379 if (cause instanceof IOException) {
1380 log.warn("An I/O error occurred while saving " + file, cause);
1381 JOptionPane.showMessageDialog(this, new String[] {
1382 "An I/O error occurred while saving:",
1383 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1386 Reflection.handleWrappedException(e);
1389 } catch (InterruptedException e) {
1390 throw new BugException("EDT was interrupted", e);
1397 private boolean closeAction() {
1398 if (!document.isSaved()) {
1399 log.info("Confirming whether to save the design");
1400 ComponentConfigDialog.hideDialog();
1401 int result = JOptionPane.showConfirmDialog(this,
1402 trans.get("BasicFrame.dlg.lbl1") + rocket.getName() +
1403 trans.get("BasicFrame.dlg.lbl2") + " " +
1404 trans.get("BasicFrame.dlg.lbl3"),
1405 trans.get("BasicFrame.dlg.title"), JOptionPane.YES_NO_CANCEL_OPTION,
1406 JOptionPane.QUESTION_MESSAGE);
1407 if (result == JOptionPane.YES_OPTION) {
1409 log.user("User requested file save");
1410 if (!saveAction()) {
1411 log.info("File save was interrupted, not closing");
1414 } else if (result == JOptionPane.NO_OPTION) {
1415 // Don't save: No-op
1416 log.user("User requested to discard design");
1419 log.user("User cancelled closing, result=" + result);
1424 // Rocket has been saved or discarded
1425 log.debug("Disposing window");
1428 ComponentConfigDialog.hideDialog();
1429 ComponentAnalysisDialog.hideDialog();
1431 frames.remove(this);
1432 if (frames.isEmpty()) {
1433 log.info("Last frame closed, exiting");
1444 public void printAction() {
1445 new PrintDialog(this, document).setVisible(true);
1449 * Open a new design window with a basic rocket+stage.
1451 public static void newAction() {
1452 log.info("New action initiated");
1454 Rocket rocket = new Rocket();
1455 Stage stage = new Stage();
1457 stage.setName(trans.get("BasicFrame.StageName.Sustainer"));
1458 rocket.addChild(stage);
1459 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1462 BasicFrame frame = new BasicFrame(doc);
1463 frame.replaceable = true;
1464 frame.setVisible(true);
1465 ComponentConfigDialog.showDialog(frame, doc, rocket);
1469 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1471 public static void quitAction() {
1472 log.info("Quit action initiated");
1473 for (int i = frames.size() - 1; i >= 0; i--) {
1474 log.debug("Closing frame " + frames.get(i));
1475 if (!frames.get(i).closeAction()) {
1477 log.info("Quit was cancelled");
1481 // Should not be reached, but just in case
1482 log.error("Should already have exited application");
1488 * Set the title of the frame, taking into account the name of the rocket, file it
1489 * has been saved to (if any) and saved status.
1491 private void setTitle() {
1492 File file = document.getFile();
1493 boolean saved = document.isSaved();
1496 title = rocket.getName();
1498 title = title + " (" + file.getName() + ")";
1501 title = "*" + title;
1509 * Find a currently open BasicFrame containing the specified rocket. This method
1510 * can be used to map a Rocket to a BasicFrame from GUI methods.
1512 * @param rocket the Rocket.
1513 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1515 public static BasicFrame findFrame(Rocket rocket) {
1516 for (BasicFrame f : frames) {
1517 if (f.rocket == rocket) {
1518 log.debug("Found frame " + f + " for rocket " + rocket);
1522 log.debug("Could not find frame for rocket " + rocket);
1527 * Find a currently open document by the rocket object. This method can be used
1528 * to map a Rocket to OpenRocketDocument from GUI methods.
1530 * @param rocket the Rocket.
1531 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1533 public static OpenRocketDocument findDocument(Rocket rocket) {
1534 BasicFrame frame = findFrame(rocket);
1535 if (frame != null) {
1536 return frame.document;