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.gui.StorageOptionChooser;
69 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
70 import net.sf.openrocket.gui.dialogs.AboutDialog;
71 import net.sf.openrocket.gui.dialogs.BugReportDialog;
72 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
73 import net.sf.openrocket.gui.dialogs.DebugLogDialog;
74 import net.sf.openrocket.gui.dialogs.DetailDialog;
75 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
76 import net.sf.openrocket.gui.dialogs.LicenseDialog;
77 import net.sf.openrocket.gui.dialogs.MotorDatabaseLoadingDialog;
78 import net.sf.openrocket.gui.dialogs.PrintDialog;
79 import net.sf.openrocket.gui.dialogs.ScaleDialog;
80 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
81 import net.sf.openrocket.gui.dialogs.WarningDialog;
82 import net.sf.openrocket.gui.dialogs.optimization.GeneralOptimizationDialog;
83 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
84 import net.sf.openrocket.gui.main.componenttree.ComponentTree;
85 import net.sf.openrocket.gui.scalefigure.RocketPanel;
86 import net.sf.openrocket.gui.util.FileHelper;
87 import net.sf.openrocket.gui.util.GUIUtil;
88 import net.sf.openrocket.gui.util.Icons;
89 import net.sf.openrocket.gui.util.OpenFileWorker;
90 import net.sf.openrocket.gui.util.SwingPreferences;
91 import net.sf.openrocket.gui.util.SaveFileWorker;
92 import net.sf.openrocket.l10n.Translator;
93 import net.sf.openrocket.logging.LogHelper;
94 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
95 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
96 import net.sf.openrocket.rocketcomponent.Rocket;
97 import net.sf.openrocket.rocketcomponent.RocketComponent;
98 import net.sf.openrocket.rocketcomponent.Stage;
99 import net.sf.openrocket.startup.Application;
100 import net.sf.openrocket.util.BugException;
101 import net.sf.openrocket.util.MemoryManagement;
102 import net.sf.openrocket.util.MemoryManagement.MemoryData;
103 import net.sf.openrocket.util.Reflection;
104 import net.sf.openrocket.util.TestRockets;
106 public class BasicFrame extends JFrame {
107 private static final LogHelper log = Application.getLogger();
110 * The RocketLoader instance used for loading all rocket designs.
112 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
114 private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
116 private static final Translator trans = Application.getTranslator();
118 public static final int COMPONENT_TAB = 0;
119 public static final int SIMULATION_TAB = 1;
123 * List of currently open frames. When the list goes empty
124 * it is time to exit the application.
126 private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
130 * Whether "New" and "Open" should replace this frame.
131 * Should be set to false on the first rocket modification.
133 private boolean replaceable = false;
137 private final OpenRocketDocument document;
138 private final Rocket rocket;
140 private JTabbedPane tabbedPane;
141 private RocketPanel rocketpanel;
142 private ComponentTree tree = null;
144 private final DocumentSelectionModel selectionModel;
145 private final TreeSelectionModel componentSelectionModel;
146 private final ListSelectionModel simulationSelectionModel;
148 /** Actions available for rocket modifications */
149 private final RocketActions actions;
154 * Sole constructor. Creates a new frame based on the supplied document
155 * and adds it to the current frames list.
157 * @param document the document to show.
159 public BasicFrame(OpenRocketDocument document) {
160 log.debug("Instantiating new BasicFrame");
162 this.document = document;
163 this.rocket = document.getRocket();
164 this.rocket.getDefaultConfiguration().setAllStages();
167 // Set replaceable flag to false at first modification
168 rocket.addComponentChangeListener(new ComponentChangeListener() {
170 public void componentChanged(ComponentChangeEvent e) {
172 BasicFrame.this.rocket.removeComponentChangeListener(this);
177 // Create the component tree selection model that will be used
178 componentSelectionModel = new DefaultTreeSelectionModel();
179 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
181 // Obtain the simulation selection model that will be used
182 SimulationPanel simulationPanel = new SimulationPanel(document);
183 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
185 // Combine into a DocumentSelectionModel
186 selectionModel = new DocumentSelectionModel(document);
187 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
188 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
191 actions = new RocketActions(document, selectionModel, this);
194 log.debug("Constructing the BasicFrame UI");
196 // The main vertical split pane
197 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
198 vertical.setResizeWeight(0.5);
202 // The top tabbed pane
203 tabbedPane = new JTabbedPane();
205 tabbedPane.addTab(trans.get("BasicFrame.tab.Rocketdesign"), null, designTab());
206 //// Flight simulations
207 tabbedPane.addTab(trans.get("BasicFrame.tab.Flightsim"), null, simulationPanel);
209 vertical.setTopComponent(tabbedPane);
213 // Bottom segment, rocket figure
215 rocketpanel = new RocketPanel(document);
216 vertical.setBottomComponent(rocketpanel);
218 rocketpanel.setSelectionModel(tree.getSelectionModel());
224 rocket.addComponentChangeListener(new ComponentChangeListener() {
226 public void componentChanged(ComponentChangeEvent e) {
235 // Set initial window size
236 Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
237 size.width = size.width * 9 / 10;
238 size.height = size.height * 9 / 10;
241 // Remember changed size
242 GUIUtil.rememberWindowSize(this);
244 this.setLocationByPlatform(true);
246 GUIUtil.setWindowIcons(this);
249 vertical.setDividerLocation(0.4);
250 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
251 addWindowListener(new WindowAdapter() {
253 public void windowClosing(WindowEvent e) {
259 log.debug("BasicFrame instantiation complete");
264 * Construct the "Rocket design" tab. This contains a horizontal split pane
265 * with the left component the design tree and the right component buttons
266 * for adding components.
268 private JComponent designTab() {
269 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
270 horizontal.setResizeWeight(0.5);
273 // Upper-left segment, component tree
275 JPanel panel = new JPanel(new MigLayout("fill, flowy", "", "[grow]"));
277 tree = new ComponentTree(document);
278 tree.setSelectionModel(componentSelectionModel);
280 // Remove JTree key events that interfere with menu accelerators
281 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
282 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
283 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
284 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
285 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
286 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
287 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
288 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
292 // Double-click opens config dialog
293 MouseListener ml = new MouseAdapter() {
295 public void mousePressed(MouseEvent e) {
296 int selRow = tree.getRowForLocation(e.getX(), e.getY());
297 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
299 if ((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
301 RocketComponent c = (RocketComponent) selPath.getLastPathComponent();
302 ComponentConfigDialog.showDialog(BasicFrame.this,
303 BasicFrame.this.document, c);
308 tree.addMouseListener(ml);
310 // Update dialog when selection is changed
311 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
313 public void valueChanged(TreeSelectionEvent e) {
314 // Scroll tree to the selected item
315 TreePath path = componentSelectionModel.getSelectionPath();
318 tree.scrollPathToVisible(path);
320 if (!ComponentConfigDialog.isDialogVisible())
322 RocketComponent c = (RocketComponent) path.getLastPathComponent();
323 ComponentConfigDialog.showDialog(BasicFrame.this,
324 BasicFrame.this.document, c);
328 // Place tree inside scroll pane
329 JScrollPane scroll = new JScrollPane(tree);
330 panel.add(scroll, "spany, grow, wrap");
334 JButton button = new JButton(actions.getMoveUpAction());
335 panel.add(button, "sizegroup buttons, aligny 65%");
337 button = new JButton(actions.getMoveDownAction());
338 panel.add(button, "sizegroup buttons, aligny 0%");
340 button = new JButton(actions.getEditAction());
341 panel.add(button, "sizegroup buttons");
343 button = new JButton(actions.getNewStageAction());
344 panel.add(button, "sizegroup buttons");
346 button = new JButton(actions.getDeleteAction());
347 button.setIcon(null);
348 button.setMnemonic(0);
349 panel.add(button, "sizegroup buttons");
351 horizontal.setLeftComponent(panel);
354 // Upper-right segment, component addition buttons
356 panel = new JPanel(new MigLayout("fill, insets 0", "[0::]"));
358 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
359 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
360 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
361 scroll.getViewport()));
362 scroll.setBorder(null);
363 scroll.setViewportBorder(null);
365 TitledBorder border = BorderFactory.createTitledBorder(trans.get("BasicFrame.title.Addnewcomp"));
366 GUIUtil.changeFontStyle(border, Font.BOLD);
367 scroll.setBorder(border);
369 panel.add(scroll, "grow");
371 horizontal.setRightComponent(panel);
379 * Return the currently selected rocket component, or <code>null</code> if none selected.
381 private RocketComponent getSelectedComponent() {
382 TreePath path = componentSelectionModel.getSelectionPath();
385 tree.scrollPathToVisible(path);
387 return (RocketComponent) path.getLastPathComponent();
392 * Creates the menu for the window.
394 private void createMenu() {
395 JMenuBar menubar = new JMenuBar();
400 menu = new JMenu(trans.get("main.menu.file"));
401 menu.setMnemonic(KeyEvent.VK_F);
402 //// File-handling related tasks
403 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.desc"));
407 item = new JMenuItem(trans.get("main.menu.file.new"), KeyEvent.VK_N);
408 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
409 item.setMnemonic(KeyEvent.VK_N);
410 //// Create a new rocket design
411 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.new.desc"));
412 item.setIcon(Icons.FILE_NEW);
413 item.addActionListener(new ActionListener() {
415 public void actionPerformed(ActionEvent e) {
416 log.user("New... selected");
419 log.info("Closing previous window");
427 item = new JMenuItem(trans.get("main.menu.file.open"), KeyEvent.VK_O);
428 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
429 //// Open a rocket design
430 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openrocketdesign"));
431 item.setIcon(Icons.FILE_OPEN);
432 item.addActionListener(new ActionListener() {
434 public void actionPerformed(ActionEvent e) {
435 log.user("Open... selected");
442 item = new JMenuItem(trans.get("main.menu.file.openExample"));
443 //// Open an example rocket design
444 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openexamplerocketdesign"));
445 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
446 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
447 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
448 item.addActionListener(new ActionListener() {
450 public void actionPerformed(ActionEvent e) {
451 log.user("Open example... selected");
452 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
455 log.user("Opening example " + u);
456 open(u, BasicFrame.this);
466 item = new JMenuItem(trans.get("main.menu.file.save"), KeyEvent.VK_S);
467 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
468 //// Save the current rocket design
469 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesign"));
470 item.setIcon(Icons.FILE_SAVE);
471 item.addActionListener(new ActionListener() {
473 public void actionPerformed(ActionEvent e) {
474 log.user("Save selected");
481 item = new JMenuItem(trans.get("main.menu.file.saveAs"), KeyEvent.VK_A);
482 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
483 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
484 //// Save the current rocket design to a new file
485 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesnewfile"));
486 item.setIcon(Icons.FILE_SAVE_AS);
487 item.addActionListener(new ActionListener() {
489 public void actionPerformed(ActionEvent e) {
490 log.user("Save as... selected");
497 item = new JMenuItem(trans.get("main.menu.file.print"), KeyEvent.VK_P);
498 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
499 //// Print parts list and fin template
500 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.print.desc"));
501 item.setIcon(Icons.FILE_PRINT);
502 item.addActionListener(new ActionListener() {
504 public void actionPerformed(ActionEvent e) {
505 log.user("Print action selected");
515 item = new JMenuItem(trans.get("main.menu.file.close"), KeyEvent.VK_C);
516 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
517 //// Close the current rocket design
518 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Closedesign"));
519 item.setIcon(Icons.FILE_CLOSE);
520 item.addActionListener(new ActionListener() {
522 public void actionPerformed(ActionEvent e) {
523 log.user("Close selected");
532 item = new JMenuItem(trans.get("main.menu.file.quit"), KeyEvent.VK_Q);
533 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
534 //// Quit the program
535 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Quitprogram"));
536 item.setIcon(Icons.FILE_QUIT);
537 item.addActionListener(new ActionListener() {
539 public void actionPerformed(ActionEvent e) {
540 log.user("Quit selected");
549 menu = new JMenu(trans.get("main.menu.edit"));
550 menu.setMnemonic(KeyEvent.VK_E);
552 menu.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.menu.Rocketedt"));
556 Action action = document.getUndoAction();
557 item = new JMenuItem(action);
558 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
559 item.setMnemonic(KeyEvent.VK_U);
560 //// Undo the previous operation
561 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.undo.desc"));
565 action = document.getRedoAction();
566 item = new JMenuItem(action);
567 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
568 item.setMnemonic(KeyEvent.VK_R);
569 //// Redo the previously undone operation
570 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.redo.desc"));
576 item = new JMenuItem(actions.getCutAction());
579 item = new JMenuItem(actions.getCopyAction());
582 item = new JMenuItem(actions.getPasteAction());
585 item = new JMenuItem(actions.getDeleteAction());
592 item = new JMenuItem(trans.get("main.menu.edit.resize"));
593 item.setIcon(Icons.EDIT_SCALE);
594 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.resize.desc"));
595 item.addActionListener(new ActionListener() {
597 public void actionPerformed(ActionEvent e) {
598 log.user("Scale... selected");
599 ScaleDialog dialog = new ScaleDialog(document, getSelectedComponent(), BasicFrame.this);
600 dialog.setVisible(true);
609 item = new JMenuItem(trans.get("main.menu.edit.preferences"));
610 item.setIcon(Icons.PREFERENCES);
611 //// Setup the application preferences
612 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.preferences.desc"));
613 item.addActionListener(new ActionListener() {
615 public void actionPerformed(ActionEvent e) {
616 log.user("Preferences selected");
617 PreferencesDialog.showPreferences(BasicFrame.this);
626 menu = new JMenu(trans.get("main.menu.analyze"));
627 menu.setMnemonic(KeyEvent.VK_A);
628 //// Analyzing the rocket
629 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.desc"));
632 //// Component analysis
633 item = new JMenuItem(trans.get("main.menu.analyze.componentAnalysis"), KeyEvent.VK_C);
634 //// Analyze the rocket components separately
635 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.componentAnalysis.desc"));
636 item.addActionListener(new ActionListener() {
638 public void actionPerformed(ActionEvent e) {
639 log.user("Component analysis selected");
640 ComponentAnalysisDialog.showDialog(rocketpanel);
646 item = new JMenuItem(trans.get("main.menu.analyze.optimization"), KeyEvent.VK_O);
647 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.optimization.desc"));
648 item.addActionListener(new ActionListener() {
650 public void actionPerformed(ActionEvent e) {
651 log.user("Rocket optimization selected");
652 new GeneralOptimizationDialog(document, BasicFrame.this).setVisible(true);
660 // (shown if openrocket.debug.menu is defined)
661 if (System.getProperty("openrocket.debug.menu") != null) {
662 menubar.add(makeDebugMenu());
669 menu = new JMenu(trans.get("main.menu.help"));
670 menu.setMnemonic(KeyEvent.VK_H);
671 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.desc"));
676 item = new JMenuItem(trans.get("main.menu.help.license"), KeyEvent.VK_L);
677 item.setIcon(Icons.HELP_LICENSE);
678 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.license.desc"));
679 item.addActionListener(new ActionListener() {
681 public void actionPerformed(ActionEvent e) {
682 log.user("License selected");
683 new LicenseDialog(BasicFrame.this).setVisible(true);
691 item = new JMenuItem(trans.get("main.menu.help.bugReport"), KeyEvent.VK_B);
692 item.setIcon(Icons.HELP_BUG_REPORT);
693 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.bugReport.desc"));
694 item.addActionListener(new ActionListener() {
696 public void actionPerformed(ActionEvent e) {
697 log.user("Bug report selected");
698 BugReportDialog.showBugReportDialog(BasicFrame.this);
704 item = new JMenuItem(trans.get("main.menu.help.debugLog"));
705 item.setIcon(Icons.HELP_DEBUG_LOG);
706 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.debugLog.desc"));
707 item.addActionListener(new ActionListener() {
709 public void actionPerformed(ActionEvent e) {
710 log.user("Debug log selected");
711 new DebugLogDialog(BasicFrame.this).setVisible(true);
719 item = new JMenuItem(trans.get("main.menu.help.about"), KeyEvent.VK_A);
720 item.setIcon(Icons.HELP_ABOUT);
721 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.about.desc"));
722 item.addActionListener(new ActionListener() {
724 public void actionPerformed(ActionEvent e) {
725 log.user("About selected");
726 new AboutDialog(BasicFrame.this).setVisible(true);
732 this.setJMenuBar(menubar);
735 private JMenu makeDebugMenu() {
740 * This menu is intentionally left untranslated.
744 menu = new JMenu("Debug");
745 //// OpenRocket debugging tasks
746 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
748 //// What is this menu?
749 item = new JMenuItem("What is this menu?");
750 item.addActionListener(new ActionListener() {
752 public void actionPerformed(ActionEvent e) {
753 log.user("What is this menu? selected");
754 JOptionPane.showMessageDialog(BasicFrame.this,
756 "The 'Debug' menu includes actions for testing and debugging " +
758 "The menu is made visible by defining the system property " +
759 "'openrocket.debug.menu' when starting OpenRocket.",
760 "It should not be visible by default." },
761 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
768 //// Create test rocket
769 item = new JMenuItem("Create test rocket");
770 item.addActionListener(new ActionListener() {
772 public void actionPerformed(ActionEvent e) {
773 log.user("Create test rocket selected");
774 JTextField field = new JTextField();
775 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
776 "Input text key to generate random rocket:",
778 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
779 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
785 r = new TestRockets(null).makeTestRocket();
786 } else if (sel == 1) {
787 r = new TestRockets(field.getText()).makeTestRocket();
792 OpenRocketDocument doc = new OpenRocketDocument(r);
794 BasicFrame frame = new BasicFrame(doc);
795 frame.setVisible(true);
802 item = new JMenuItem("Create 'Iso-Haisu'");
803 item.addActionListener(new ActionListener() {
805 public void actionPerformed(ActionEvent e) {
806 log.user("Create Iso-Haisu selected");
807 Rocket r = TestRockets.makeIsoHaisu();
808 OpenRocketDocument doc = new OpenRocketDocument(r);
810 BasicFrame frame = new BasicFrame(doc);
811 frame.setVisible(true);
817 item = new JMenuItem("Create 'Big Blue'");
818 item.addActionListener(new ActionListener() {
820 public void actionPerformed(ActionEvent e) {
821 log.user("Create Big Blue selected");
822 Rocket r = TestRockets.makeBigBlue();
823 OpenRocketDocument doc = new OpenRocketDocument(r);
825 BasicFrame frame = new BasicFrame(doc);
826 frame.setVisible(true);
834 item = new JMenuItem("Memory statistics");
835 item.addActionListener(new ActionListener() {
837 public void actionPerformed(ActionEvent e) {
838 log.user("Memory statistics selected");
840 // Get discarded but remaining objects (this also runs System.gc multiple times)
841 List<MemoryData> objects = MemoryManagement.getRemainingCollectableObjects();
842 StringBuilder sb = new StringBuilder();
843 sb.append("Objects that should have been garbage-collected but have not been:\n");
845 for (MemoryData data : objects) {
846 Object o = data.getReference().get();
849 sb.append("Age ").append(System.currentTimeMillis() - data.getRegistrationTime())
850 .append(" ms: ").append(o).append('\n');
852 // Explicitly null the strong reference to avoid possibility of invisible references
855 sb.append("Total: " + count);
857 // Get basic memory stats
859 long max = Runtime.getRuntime().maxMemory();
860 long free = Runtime.getRuntime().freeMemory();
861 long used = max - free;
862 String[] stats = new String[4];
863 stats[0] = "Memory usage:";
864 stats[1] = String.format(" Max memory: %.1f MB", max / 1024.0 / 1024.0);
865 stats[2] = String.format(" Used memory: %.1f MB (%.0f%%)", used / 1024.0 / 1024.0, 100.0 * used / max);
866 stats[3] = String.format(" Free memory: %.1f MB (%.0f%%)", free / 1024.0 / 1024.0, 100.0 * free / max);
869 DetailDialog.showDetailedMessageDialog(BasicFrame.this, stats, sb.toString(),
870 "Memory statistics", JOptionPane.INFORMATION_MESSAGE);
876 item = new JMenuItem("Exhaust memory");
877 item.addActionListener(new ActionListener() {
879 public void actionPerformed(ActionEvent e) {
880 log.user("Exhaust memory selected");
881 LinkedList<byte[]> data = new LinkedList<byte[]>();
883 final int bytesPerArray = 10240;
886 byte[] array = new byte[bytesPerArray];
887 for (int i = 0; i < bytesPerArray; i++) {
893 } catch (OutOfMemoryError error) {
895 long size = bytesPerArray * (long) count;
896 String s = String.format("OutOfMemory occurred after %d iterations (approx. %.1f MB consumed)",
897 count, size / 1024.0 / 1024.0);
899 JOptionPane.showMessageDialog(BasicFrame.this, s);
909 item = new JMenuItem("Exception here");
910 item.addActionListener(new ActionListener() {
912 public void actionPerformed(ActionEvent e) {
913 log.user("Exception here selected");
914 throw new RuntimeException("Testing exception from menu action listener");
919 item = new JMenuItem("Exception from EDT");
920 item.addActionListener(new ActionListener() {
922 public void actionPerformed(ActionEvent e) {
923 log.user("Exception from EDT selected");
924 SwingUtilities.invokeLater(new Runnable() {
927 throw new RuntimeException("Testing exception from " +
928 "later invoked EDT thread");
935 item = new JMenuItem("Exception from other thread");
936 item.addActionListener(new ActionListener() {
938 public void actionPerformed(ActionEvent e) {
939 log.user("Exception from other thread selected");
943 throw new RuntimeException("Testing exception from newly created thread");
950 item = new JMenuItem("OutOfMemoryError here");
951 item.addActionListener(new ActionListener() {
953 public void actionPerformed(ActionEvent e) {
954 log.user("OutOfMemoryError here selected");
955 throw new OutOfMemoryError("Testing OutOfMemoryError from menu action listener");
964 item = new JMenuItem("Test popup");
965 item.addActionListener(new ActionListener() {
967 public void actionPerformed(ActionEvent e) {
968 log.user("Test popup selected");
969 JPanel panel = new JPanel();
970 panel.add(new JTextField(40));
971 panel.add(new JSpinner());
972 JPopupMenu popup = new JPopupMenu();
973 popup.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
975 popup.show(BasicFrame.this, -50, 100);
988 * Select the tab on the main pane.
990 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
992 public void selectTab(int tab) {
993 tabbedPane.setSelectedIndex(tab);
998 private void openAction() {
999 JFileChooser chooser = new JFileChooser();
1001 chooser.addChoosableFileFilter(FileHelper.ALL_DESIGNS_FILTER);
1002 chooser.addChoosableFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
1003 chooser.addChoosableFileFilter(FileHelper.ROCKSIM_DESIGN_FILTER);
1004 chooser.setFileFilter(FileHelper.ALL_DESIGNS_FILTER);
1006 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
1007 chooser.setMultiSelectionEnabled(true);
1008 chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory());
1009 int option = chooser.showOpenDialog(this);
1010 if (option != JFileChooser.APPROVE_OPTION) {
1011 log.user("Decided not to open files, option=" + option);
1015 ((SwingPreferences) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory());
1017 File[] files = chooser.getSelectedFiles();
1018 log.user("Opening files " + Arrays.toString(files));
1020 for (File file : files) {
1021 log.info("Opening file: " + file);
1022 if (open(file, this)) {
1024 // Close previous window if replacing
1025 if (replaceable && document.isSaved()) {
1026 // We are replacing the frame, make new window have current location
1027 BasicFrame newFrame = frames.get(frames.size() - 1);
1028 newFrame.setLocation(this.getLocation());
1030 log.info("Closing window because it is replaceable");
1032 replaceable = false;
1040 * Open a file based on a URL.
1041 * @param url the file to open.
1042 * @param parent the parent window for dialogs.
1043 * @return <code>true</code> if opened successfully.
1045 private static boolean open(URL url, BasicFrame parent) {
1046 String filename = null;
1048 // First figure out the file name from the URL
1050 // Try using URI.getPath();
1052 URI uri = url.toURI();
1053 filename = uri.getPath();
1054 } catch (URISyntaxException ignore) {
1057 // Try URL-decoding the URL
1058 if (filename == null) {
1060 filename = URLDecoder.decode(url.toString(), "UTF-8");
1061 } catch (UnsupportedEncodingException ignore) {
1066 if (filename == null) {
1070 // Remove path from filename
1071 if (filename.lastIndexOf('/') >= 0) {
1072 filename = filename.substring(filename.lastIndexOf('/') + 1);
1077 log.info("Opening file from url=" + url + " filename=" + filename);
1079 InputStream is = url.openStream();
1080 if (open(is, filename, parent)) {
1081 // Close previous window if replacing
1082 if (parent.replaceable && parent.document.isSaved()) {
1083 parent.closeAction();
1084 parent.replaceable = false;
1087 } catch (IOException e) {
1088 log.warn("Error opening file" + e);
1089 JOptionPane.showMessageDialog(parent,
1090 "An error occurred while opening the file " + filename,
1091 "Error loading file", JOptionPane.ERROR_MESSAGE);
1099 * Open the specified file from an InputStream in a new design frame. If an error
1100 * occurs, an error dialog is shown and <code>false</code> is returned.
1102 * @param stream the stream to load from.
1103 * @param filename the file name to display in dialogs (not set to the document).
1104 * @param parent the parent component for which a progress dialog is opened.
1105 * @return whether the file was successfully loaded and opened.
1107 private static boolean open(InputStream stream, String filename, Window parent) {
1108 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
1109 return open(worker, filename, null, parent);
1114 * Open the specified file in a new design frame. If an error occurs, an error
1115 * dialog is shown and <code>false</code> is returned.
1117 * @param file the file to open.
1118 * @param parent the parent component for which a progress dialog is opened.
1119 * @return whether the file was successfully loaded and opened.
1121 public static boolean open(File file, Window parent) {
1122 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
1123 return open(worker, file.getName(), file, parent);
1128 * Open the specified file using the provided worker.
1130 * @param worker the OpenFileWorker that loads the file.
1131 * @param filename the file name to display in dialogs.
1132 * @param file the File to set the document to (may be null).
1136 private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) {
1138 MotorDatabaseLoadingDialog.check(parent);
1140 // Open the file in a Swing worker thread
1141 log.info("Starting OpenFileWorker");
1142 if (!SwingWorkerDialog.runWorker(parent, "Opening file", "Reading " + filename + "...", worker)) {
1143 // User cancelled the operation
1144 log.info("User cancelled the OpenFileWorker");
1149 // Handle the document
1150 OpenRocketDocument doc = null;
1155 } catch (ExecutionException e) {
1157 Throwable cause = e.getCause();
1159 if (cause instanceof FileNotFoundException) {
1161 log.warn("File not found", cause);
1162 JOptionPane.showMessageDialog(parent,
1163 "File not found: " + filename,
1164 "Error opening file", JOptionPane.ERROR_MESSAGE);
1167 } else if (cause instanceof RocketLoadException) {
1169 log.warn("Error loading the file", cause);
1170 JOptionPane.showMessageDialog(parent,
1171 "Unable to open file '" + filename + "': "
1172 + cause.getMessage(),
1173 "Error opening file", JOptionPane.ERROR_MESSAGE);
1178 throw new BugException("Unknown error when opening file", e);
1182 } catch (InterruptedException e) {
1183 throw new BugException("EDT was interrupted", e);
1187 throw new BugException("Document loader returned null");
1192 WarningSet warnings = worker.getRocketLoader().getWarnings();
1193 if (!warnings.isEmpty()) {
1194 log.info("Warnings while reading file: " + warnings);
1195 WarningDialog.showWarnings(parent,
1197 //// The following problems were encountered while opening
1198 trans.get("BasicFrame.WarningDialog.txt1") + " " + filename + ".",
1199 //// Some design features may not have been loaded correctly.
1200 trans.get("BasicFrame.WarningDialog.txt2")
1202 //// Warnings while opening file
1203 trans.get("BasicFrame.WarningDialog.title"), warnings);
1207 // Set document state
1213 log.debug("Opening new frame with the document");
1214 BasicFrame frame = new BasicFrame(doc);
1215 frame.setVisible(true);
1224 private boolean saveAction() {
1225 File file = document.getFile();
1227 log.info("Document does not contain file, opening save as dialog instead");
1228 return saveAsAction();
1230 log.info("Saving document to " + file);
1232 // Saving RockSim designs is not supported
1233 if (FileHelper.ROCKSIM_DESIGN_FILTER.accept(file)) {
1234 file = new File(file.getAbsolutePath().replaceAll(".[rR][kK][tT](.[gG][zZ])?$",
1237 log.info("Attempting to save in RockSim format, renaming to " + file);
1238 int option = JOptionPane.showConfirmDialog(this, new Object[] {
1239 "Saving designs in RockSim format is not supported.",
1240 "Save in OpenRocket format instead (" + file.getName() + ")?"
1241 }, "Save " + file.getName(), JOptionPane.YES_NO_OPTION,
1242 JOptionPane.QUESTION_MESSAGE, null);
1243 if (option != JOptionPane.YES_OPTION) {
1244 log.user("User chose not to save");
1248 document.setFile(file);
1250 return saveAs(file);
1254 private boolean saveAsAction() {
1257 // TODO: HIGH: what if *.rkt chosen?
1258 StorageOptionChooser storageChooser =
1259 new StorageOptionChooser(document, document.getDefaultStorageOptions());
1260 JFileChooser chooser = new JFileChooser();
1261 chooser.setFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
1262 chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory());
1263 chooser.setAccessory(storageChooser);
1264 if (document.getFile() != null)
1265 chooser.setSelectedFile(document.getFile());
1267 int option = chooser.showSaveDialog(BasicFrame.this);
1268 if (option != JFileChooser.APPROVE_OPTION) {
1269 log.user("User decided not to save, option=" + option);
1273 file = chooser.getSelectedFile();
1275 log.user("User did not select a file");
1279 ((SwingPreferences) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory());
1280 storageChooser.storeOptions(document.getDefaultStorageOptions());
1282 file = FileHelper.ensureExtension(file, "ork");
1283 if (!FileHelper.confirmWrite(file, this)) {
1287 return saveAs(file);
1290 private boolean saveAs(File file) {
1291 log.info("Saving document as " + file);
1292 boolean saved = false;
1294 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1295 // User cancelled the dialog
1296 log.user("User cancelled saving in storage options dialog");
1301 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1303 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1304 "Writing " + file.getName() + "...", worker)) {
1306 // User cancelled the save
1307 log.user("User cancelled the save, deleting the file");
1314 document.setFile(file);
1315 document.setSaved(true);
1318 } catch (ExecutionException e) {
1320 Throwable cause = e.getCause();
1322 if (cause instanceof IOException) {
1323 log.warn("An I/O error occurred while saving " + file, cause);
1324 JOptionPane.showMessageDialog(this, new String[] {
1325 "An I/O error occurred while saving:",
1326 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1329 Reflection.handleWrappedException(e);
1332 } catch (InterruptedException e) {
1333 throw new BugException("EDT was interrupted", e);
1340 private boolean closeAction() {
1341 if (!document.isSaved()) {
1342 log.info("Confirming whether to save the design");
1343 ComponentConfigDialog.hideDialog();
1344 int result = JOptionPane.showConfirmDialog(this,
1345 trans.get("BasicFrame.dlg.lbl1") + rocket.getName() +
1346 trans.get("BasicFrame.dlg.lbl2") + " " +
1347 trans.get("BasicFrame.dlg.lbl3"),
1348 trans.get("BasicFrame.dlg.title"), JOptionPane.YES_NO_CANCEL_OPTION,
1349 JOptionPane.QUESTION_MESSAGE);
1350 if (result == JOptionPane.YES_OPTION) {
1352 log.user("User requested file save");
1353 if (!saveAction()) {
1354 log.info("File save was interrupted, not closing");
1357 } else if (result == JOptionPane.NO_OPTION) {
1358 // Don't save: No-op
1359 log.user("User requested to discard design");
1362 log.user("User cancelled closing, result=" + result);
1367 // Rocket has been saved or discarded
1368 log.debug("Disposing window");
1371 ComponentConfigDialog.hideDialog();
1372 ComponentAnalysisDialog.hideDialog();
1374 frames.remove(this);
1375 if (frames.isEmpty()) {
1376 log.info("Last frame closed, exiting");
1387 public void printAction() {
1388 new PrintDialog(this, document).setVisible(true);
1392 * Open a new design window with a basic rocket+stage.
1394 public static void newAction() {
1395 log.info("New action initiated");
1397 Rocket rocket = new Rocket();
1398 Stage stage = new Stage();
1400 stage.setName(trans.get("BasicFrame.StageName.Sustainer"));
1401 rocket.addChild(stage);
1402 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1405 BasicFrame frame = new BasicFrame(doc);
1406 frame.replaceable = true;
1407 frame.setVisible(true);
1408 ComponentConfigDialog.showDialog(frame, doc, rocket);
1412 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1414 public static void quitAction() {
1415 log.info("Quit action initiated");
1416 for (int i = frames.size() - 1; i >= 0; i--) {
1417 log.debug("Closing frame " + frames.get(i));
1418 if (!frames.get(i).closeAction()) {
1420 log.info("Quit was cancelled");
1424 // Should not be reached, but just in case
1425 log.error("Should already have exited application");
1431 * Set the title of the frame, taking into account the name of the rocket, file it
1432 * has been saved to (if any) and saved status.
1434 private void setTitle() {
1435 File file = document.getFile();
1436 boolean saved = document.isSaved();
1439 title = rocket.getName();
1441 title = title + " (" + file.getName() + ")";
1444 title = "*" + title;
1452 * Find a currently open BasicFrame containing the specified rocket. This method
1453 * can be used to map a Rocket to a BasicFrame from GUI methods.
1455 * @param rocket the Rocket.
1456 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1458 public static BasicFrame findFrame(Rocket rocket) {
1459 for (BasicFrame f : frames) {
1460 if (f.rocket == rocket) {
1461 log.debug("Found frame " + f + " for rocket " + rocket);
1465 log.debug("Could not find frame for rocket " + rocket);
1470 * Find a currently open document by the rocket object. This method can be used
1471 * to map a Rocket to OpenRocketDocument from GUI methods.
1473 * @param rocket the Rocket.
1474 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1476 public static OpenRocketDocument findDocument(Rocket rocket) {
1477 BasicFrame frame = findFrame(rocket);
1478 if (frame != null) {
1479 return frame.document;