1 package net.sf.openrocket.gui.main;
3 import net.miginfocom.swing.MigLayout;
4 import net.sf.openrocket.aerodynamics.WarningSet;
5 import net.sf.openrocket.document.OpenRocketDocument;
6 import net.sf.openrocket.file.GeneralRocketLoader;
7 import net.sf.openrocket.file.RocketLoadException;
8 import net.sf.openrocket.file.RocketLoader;
9 import net.sf.openrocket.file.RocketSaver;
10 import net.sf.openrocket.file.openrocket.OpenRocketSaver;
11 import net.sf.openrocket.file.rocksim.export.RocksimSaver;
12 import net.sf.openrocket.gui.StorageOptionChooser;
13 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
14 import net.sf.openrocket.gui.dialogs.AboutDialog;
15 import net.sf.openrocket.gui.dialogs.BugReportDialog;
16 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
17 import net.sf.openrocket.gui.dialogs.DebugLogDialog;
18 import net.sf.openrocket.gui.dialogs.DetailDialog;
19 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
20 import net.sf.openrocket.gui.dialogs.LicenseDialog;
21 import net.sf.openrocket.gui.dialogs.MotorDatabaseLoadingDialog;
22 import net.sf.openrocket.gui.dialogs.PrintDialog;
23 import net.sf.openrocket.gui.dialogs.ScaleDialog;
24 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
25 import net.sf.openrocket.gui.dialogs.WarningDialog;
26 import net.sf.openrocket.gui.dialogs.optimization.GeneralOptimizationDialog;
27 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
28 import net.sf.openrocket.gui.help.tours.GuidedTourSelectionDialog;
29 import net.sf.openrocket.gui.main.componenttree.ComponentTree;
30 import net.sf.openrocket.gui.scalefigure.RocketPanel;
31 import net.sf.openrocket.gui.util.FileHelper;
32 import net.sf.openrocket.gui.util.GUIUtil;
33 import net.sf.openrocket.gui.util.Icons;
34 import net.sf.openrocket.gui.util.OpenFileWorker;
35 import net.sf.openrocket.gui.util.SaveFileWorker;
36 import net.sf.openrocket.gui.util.SwingPreferences;
37 import net.sf.openrocket.l10n.Translator;
38 import net.sf.openrocket.logging.LogHelper;
39 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
40 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
41 import net.sf.openrocket.rocketcomponent.Rocket;
42 import net.sf.openrocket.rocketcomponent.RocketComponent;
43 import net.sf.openrocket.rocketcomponent.Stage;
44 import net.sf.openrocket.startup.Application;
45 import net.sf.openrocket.util.BugException;
46 import net.sf.openrocket.util.MemoryManagement;
47 import net.sf.openrocket.util.MemoryManagement.MemoryData;
48 import net.sf.openrocket.util.Reflection;
49 import net.sf.openrocket.util.TestRockets;
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 java.awt.event.ActionEvent;
61 import java.awt.event.ActionListener;
62 import java.awt.event.KeyEvent;
63 import java.awt.event.MouseAdapter;
64 import java.awt.event.MouseEvent;
65 import java.awt.event.MouseListener;
66 import java.awt.event.WindowAdapter;
67 import java.awt.event.WindowEvent;
69 import java.io.FileNotFoundException;
70 import java.io.IOException;
71 import java.io.InputStream;
72 import java.io.UnsupportedEncodingException;
74 import java.net.URISyntaxException;
76 import java.net.URLDecoder;
77 import java.util.ArrayList;
78 import java.util.Arrays;
79 import java.util.LinkedList;
80 import java.util.List;
81 import java.util.concurrent.ExecutionException;
83 public class BasicFrame extends JFrame {
84 private static final LogHelper log = Application.getLogger();
87 * The RocketLoader instance used for loading all rocket designs.
89 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
91 private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
93 private static final Translator trans = Application.getTranslator();
95 public static final int COMPONENT_TAB = 0;
96 public static final int SIMULATION_TAB = 1;
100 * List of currently open frames. When the list goes empty
101 * it is time to exit the application.
103 private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
107 * Whether "New" and "Open" should replace this frame.
108 * Should be set to false on the first rocket modification.
110 private boolean replaceable = false;
114 private final OpenRocketDocument document;
115 private final Rocket rocket;
117 private JTabbedPane tabbedPane;
118 private RocketPanel rocketpanel;
119 private ComponentTree tree = null;
121 private final DocumentSelectionModel selectionModel;
122 private final TreeSelectionModel componentSelectionModel;
123 private final ListSelectionModel simulationSelectionModel;
125 /** Actions available for rocket modifications */
126 private final RocketActions actions;
131 * Sole constructor. Creates a new frame based on the supplied document
132 * and adds it to the current frames list.
134 * @param document the document to show.
136 public BasicFrame(OpenRocketDocument document) {
137 log.debug("Instantiating new BasicFrame");
139 this.document = document;
140 this.rocket = document.getRocket();
141 this.rocket.getDefaultConfiguration().setAllStages();
144 // Set replaceable flag to false at first modification
145 rocket.addComponentChangeListener(new ComponentChangeListener() {
147 public void componentChanged(ComponentChangeEvent e) {
149 BasicFrame.this.rocket.removeComponentChangeListener(this);
154 // Create the component tree selection model that will be used
155 componentSelectionModel = new DefaultTreeSelectionModel();
156 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
158 // Obtain the simulation selection model that will be used
159 SimulationPanel simulationPanel = new SimulationPanel(document);
160 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
162 // Combine into a DocumentSelectionModel
163 selectionModel = new DocumentSelectionModel(document);
164 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
165 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
168 actions = new RocketActions(document, selectionModel, this);
171 log.debug("Constructing the BasicFrame UI");
173 // The main vertical split pane
174 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
175 vertical.setResizeWeight(0.5);
179 // The top tabbed pane
180 tabbedPane = new JTabbedPane();
182 tabbedPane.addTab(trans.get("BasicFrame.tab.Rocketdesign"), null, designTab());
183 //// Flight simulations
184 tabbedPane.addTab(trans.get("BasicFrame.tab.Flightsim"), null, simulationPanel);
186 vertical.setTopComponent(tabbedPane);
190 // Bottom segment, rocket figure
192 rocketpanel = new RocketPanel(document);
193 vertical.setBottomComponent(rocketpanel);
195 rocketpanel.setSelectionModel(tree.getSelectionModel());
201 rocket.addComponentChangeListener(new ComponentChangeListener() {
203 public void componentChanged(ComponentChangeEvent e) {
212 // Set initial window size
213 Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
214 size.width = size.width * 9 / 10;
215 size.height = size.height * 9 / 10;
218 // Remember changed size
219 GUIUtil.rememberWindowSize(this);
221 this.setLocationByPlatform(true);
223 GUIUtil.setWindowIcons(this);
226 vertical.setDividerLocation(0.4);
227 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
228 addWindowListener(new WindowAdapter() {
230 public void windowClosing(WindowEvent e) {
236 log.debug("BasicFrame instantiation complete");
241 * Construct the "Rocket design" tab. This contains a horizontal split pane
242 * with the left component the design tree and the right component buttons
243 * for adding components.
245 private JComponent designTab() {
246 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
247 horizontal.setResizeWeight(0.5);
250 // Upper-left segment, component tree
252 JPanel panel = new JPanel(new MigLayout("fill, flowy", "", "[grow]"));
254 tree = new ComponentTree(document);
255 tree.setSelectionModel(componentSelectionModel);
257 // Remove JTree key events that interfere with menu accelerators
258 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
259 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
260 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
261 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
262 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
263 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
264 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
265 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
269 // Double-click opens config dialog
270 MouseListener ml = new MouseAdapter() {
272 public void mousePressed(MouseEvent e) {
273 int selRow = tree.getRowForLocation(e.getX(), e.getY());
274 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
276 if ((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
278 RocketComponent c = (RocketComponent) selPath.getLastPathComponent();
279 ComponentConfigDialog.showDialog(BasicFrame.this,
280 BasicFrame.this.document, c);
285 tree.addMouseListener(ml);
287 // Update dialog when selection is changed
288 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
290 public void valueChanged(TreeSelectionEvent e) {
291 // Scroll tree to the selected item
292 TreePath path = componentSelectionModel.getSelectionPath();
295 tree.scrollPathToVisible(path);
297 if (!ComponentConfigDialog.isDialogVisible())
299 RocketComponent c = (RocketComponent) path.getLastPathComponent();
300 ComponentConfigDialog.showDialog(BasicFrame.this,
301 BasicFrame.this.document, c);
305 // Place tree inside scroll pane
306 JScrollPane scroll = new JScrollPane(tree);
307 panel.add(scroll, "spany, grow, wrap");
311 JButton button = new JButton(actions.getMoveUpAction());
312 panel.add(button, "sizegroup buttons, aligny 65%");
314 button = new JButton(actions.getMoveDownAction());
315 panel.add(button, "sizegroup buttons, aligny 0%");
317 button = new JButton(actions.getEditAction());
318 panel.add(button, "sizegroup buttons");
320 button = new JButton(actions.getNewStageAction());
321 panel.add(button, "sizegroup buttons");
323 button = new JButton(actions.getDeleteAction());
324 button.setIcon(null);
325 button.setMnemonic(0);
326 panel.add(button, "sizegroup buttons");
328 horizontal.setLeftComponent(panel);
331 // Upper-right segment, component addition buttons
333 panel = new JPanel(new MigLayout("fill, insets 0", "[0::]"));
335 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
336 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
337 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
338 scroll.getViewport()));
339 scroll.setBorder(null);
340 scroll.setViewportBorder(null);
342 TitledBorder border = BorderFactory.createTitledBorder(trans.get("BasicFrame.title.Addnewcomp"));
343 GUIUtil.changeFontStyle(border, Font.BOLD);
344 scroll.setBorder(border);
346 panel.add(scroll, "grow");
348 horizontal.setRightComponent(panel);
356 * Return the currently selected rocket component, or <code>null</code> if none selected.
358 private RocketComponent getSelectedComponent() {
359 TreePath path = componentSelectionModel.getSelectionPath();
362 tree.scrollPathToVisible(path);
364 return (RocketComponent) path.getLastPathComponent();
369 * Creates the menu for the window.
371 private void createMenu() {
372 JMenuBar menubar = new JMenuBar();
377 menu = new JMenu(trans.get("main.menu.file"));
378 menu.setMnemonic(KeyEvent.VK_F);
379 //// File-handling related tasks
380 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.desc"));
384 item = new JMenuItem(trans.get("main.menu.file.new"), KeyEvent.VK_N);
385 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
386 item.setMnemonic(KeyEvent.VK_N);
387 //// Create a new rocket design
388 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.new.desc"));
389 item.setIcon(Icons.FILE_NEW);
390 item.addActionListener(new ActionListener() {
392 public void actionPerformed(ActionEvent e) {
393 log.user("New... selected");
396 log.info("Closing previous window");
404 item = new JMenuItem(trans.get("main.menu.file.open"), KeyEvent.VK_O);
405 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
406 //// Open a rocket design
407 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openrocketdesign"));
408 item.setIcon(Icons.FILE_OPEN);
409 item.addActionListener(new ActionListener() {
411 public void actionPerformed(ActionEvent e) {
412 log.user("Open... selected");
419 item = new JMenuItem(trans.get("main.menu.file.openExample"));
420 //// Open an example rocket design
421 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openexamplerocketdesign"));
422 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
423 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
424 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
425 item.addActionListener(new ActionListener() {
427 public void actionPerformed(ActionEvent e) {
428 log.user("Open example... selected");
429 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
432 log.user("Opening example " + u);
433 open(u, BasicFrame.this);
443 item = new JMenuItem(trans.get("main.menu.file.save"), KeyEvent.VK_S);
444 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
445 //// Save the current rocket design
446 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesign"));
447 item.setIcon(Icons.FILE_SAVE);
448 item.addActionListener(new ActionListener() {
450 public void actionPerformed(ActionEvent e) {
451 log.user("Save selected");
458 item = new JMenuItem(trans.get("main.menu.file.saveAs"), KeyEvent.VK_A);
459 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
460 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
461 //// Save the current rocket design to a new file
462 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesnewfile"));
463 item.setIcon(Icons.FILE_SAVE_AS);
464 item.addActionListener(new ActionListener() {
466 public void actionPerformed(ActionEvent e) {
467 log.user("Save as... selected");
474 item = new JMenuItem(trans.get("main.menu.file.print"), KeyEvent.VK_P);
475 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
476 //// Print parts list and fin template
477 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.print.desc"));
478 item.setIcon(Icons.FILE_PRINT);
479 item.addActionListener(new ActionListener() {
481 public void actionPerformed(ActionEvent e) {
482 log.user("Print action selected");
492 item = new JMenuItem(trans.get("main.menu.file.close"), KeyEvent.VK_C);
493 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
494 //// Close the current rocket design
495 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Closedesign"));
496 item.setIcon(Icons.FILE_CLOSE);
497 item.addActionListener(new ActionListener() {
499 public void actionPerformed(ActionEvent e) {
500 log.user("Close selected");
509 item = new JMenuItem(trans.get("main.menu.file.quit"), KeyEvent.VK_Q);
510 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
511 //// Quit the program
512 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Quitprogram"));
513 item.setIcon(Icons.FILE_QUIT);
514 item.addActionListener(new ActionListener() {
516 public void actionPerformed(ActionEvent e) {
517 log.user("Quit selected");
526 menu = new JMenu(trans.get("main.menu.edit"));
527 menu.setMnemonic(KeyEvent.VK_E);
529 menu.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.menu.Rocketedt"));
533 Action action = UndoRedoAction.newUndoAction(document);
534 item = new JMenuItem(action);
535 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
536 item.setMnemonic(KeyEvent.VK_U);
537 //// Undo the previous operation
538 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.undo.desc"));
542 action = UndoRedoAction.newRedoAction(document);
543 item = new JMenuItem(action);
544 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
545 item.setMnemonic(KeyEvent.VK_R);
546 //// Redo the previously undone operation
547 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.redo.desc"));
553 item = new JMenuItem(actions.getCutAction());
556 item = new JMenuItem(actions.getCopyAction());
559 item = new JMenuItem(actions.getPasteAction());
562 item = new JMenuItem(actions.getDeleteAction());
569 item = new JMenuItem(trans.get("main.menu.edit.resize"));
570 item.setIcon(Icons.EDIT_SCALE);
571 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.resize.desc"));
572 item.addActionListener(new ActionListener() {
574 public void actionPerformed(ActionEvent e) {
575 log.user("Scale... selected");
576 ScaleDialog dialog = new ScaleDialog(document, getSelectedComponent(), BasicFrame.this);
577 dialog.setVisible(true);
586 item = new JMenuItem(trans.get("main.menu.edit.preferences"));
587 item.setIcon(Icons.PREFERENCES);
588 //// Setup the application preferences
589 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.preferences.desc"));
590 item.addActionListener(new ActionListener() {
592 public void actionPerformed(ActionEvent e) {
593 log.user("Preferences selected");
594 PreferencesDialog.showPreferences(BasicFrame.this);
603 menu = new JMenu(trans.get("main.menu.analyze"));
604 menu.setMnemonic(KeyEvent.VK_A);
605 //// Analyzing the rocket
606 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.desc"));
609 //// Component analysis
610 item = new JMenuItem(trans.get("main.menu.analyze.componentAnalysis"), KeyEvent.VK_C);
611 //// Analyze the rocket components separately
612 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.componentAnalysis.desc"));
613 item.addActionListener(new ActionListener() {
615 public void actionPerformed(ActionEvent e) {
616 log.user("Component analysis selected");
617 ComponentAnalysisDialog.showDialog(rocketpanel);
623 item = new JMenuItem(trans.get("main.menu.analyze.optimization"), KeyEvent.VK_O);
624 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.optimization.desc"));
625 item.addActionListener(new ActionListener() {
627 public void actionPerformed(ActionEvent e) {
628 log.user("Rocket optimization selected");
629 new GeneralOptimizationDialog(document, BasicFrame.this).setVisible(true);
637 // (shown if openrocket.debug.menu is defined)
638 if (System.getProperty("openrocket.debug.menu") != null) {
639 menubar.add(makeDebugMenu());
646 menu = new JMenu(trans.get("main.menu.help"));
647 menu.setMnemonic(KeyEvent.VK_H);
648 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.desc"));
654 item = new JMenuItem(trans.get("main.menu.help.tours"), KeyEvent.VK_L);
656 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.tours.desc"));
657 item.addActionListener(new ActionListener() {
659 public void actionPerformed(ActionEvent e) {
660 log.user("Guided tours selected");
662 new GuidedTourSelectionDialog(BasicFrame.this).setVisible(true);
671 item = new JMenuItem(trans.get("main.menu.help.license"), KeyEvent.VK_L);
672 item.setIcon(Icons.HELP_LICENSE);
673 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.license.desc"));
674 item.addActionListener(new ActionListener() {
676 public void actionPerformed(ActionEvent e) {
677 log.user("License selected");
678 new LicenseDialog(BasicFrame.this).setVisible(true);
686 item = new JMenuItem(trans.get("main.menu.help.bugReport"), KeyEvent.VK_B);
687 item.setIcon(Icons.HELP_BUG_REPORT);
688 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.bugReport.desc"));
689 item.addActionListener(new ActionListener() {
691 public void actionPerformed(ActionEvent e) {
692 log.user("Bug report selected");
693 BugReportDialog.showBugReportDialog(BasicFrame.this);
699 item = new JMenuItem(trans.get("main.menu.help.debugLog"));
700 item.setIcon(Icons.HELP_DEBUG_LOG);
701 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.debugLog.desc"));
702 item.addActionListener(new ActionListener() {
704 public void actionPerformed(ActionEvent e) {
705 log.user("Debug log selected");
706 new DebugLogDialog(BasicFrame.this).setVisible(true);
714 item = new JMenuItem(trans.get("main.menu.help.about"), KeyEvent.VK_A);
715 item.setIcon(Icons.HELP_ABOUT);
716 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.about.desc"));
717 item.addActionListener(new ActionListener() {
719 public void actionPerformed(ActionEvent e) {
720 log.user("About selected");
721 new AboutDialog(BasicFrame.this).setVisible(true);
727 this.setJMenuBar(menubar);
730 private JMenu makeDebugMenu() {
735 * This menu is intentionally left untranslated.
739 menu = new JMenu("Debug");
740 //// OpenRocket debugging tasks
741 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
743 //// What is this menu?
744 item = new JMenuItem("What is this menu?");
745 item.addActionListener(new ActionListener() {
747 public void actionPerformed(ActionEvent e) {
748 log.user("What is this menu? selected");
749 JOptionPane.showMessageDialog(BasicFrame.this,
751 "The 'Debug' menu includes actions for testing and debugging " +
753 "The menu is made visible by defining the system property " +
754 "'openrocket.debug.menu' when starting OpenRocket.",
755 "It should not be visible by default." },
756 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
763 //// Create test rocket
764 item = new JMenuItem("Create test rocket");
765 item.addActionListener(new ActionListener() {
767 public void actionPerformed(ActionEvent e) {
768 log.user("Create test rocket selected");
769 JTextField field = new JTextField();
770 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
771 "Input text key to generate random rocket:",
773 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
774 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
780 r = new TestRockets(null).makeTestRocket();
781 } else if (sel == 1) {
782 r = new TestRockets(field.getText()).makeTestRocket();
787 OpenRocketDocument doc = new OpenRocketDocument(r);
789 BasicFrame frame = new BasicFrame(doc);
790 frame.setVisible(true);
797 item = new JMenuItem("Create 'Iso-Haisu'");
798 item.addActionListener(new ActionListener() {
800 public void actionPerformed(ActionEvent e) {
801 log.user("Create Iso-Haisu selected");
802 Rocket r = TestRockets.makeIsoHaisu();
803 OpenRocketDocument doc = new OpenRocketDocument(r);
805 BasicFrame frame = new BasicFrame(doc);
806 frame.setVisible(true);
812 item = new JMenuItem("Create 'Big Blue'");
813 item.addActionListener(new ActionListener() {
815 public void actionPerformed(ActionEvent e) {
816 log.user("Create Big Blue selected");
817 Rocket r = TestRockets.makeBigBlue();
818 OpenRocketDocument doc = new OpenRocketDocument(r);
820 BasicFrame frame = new BasicFrame(doc);
821 frame.setVisible(true);
829 item = new JMenuItem("Memory statistics");
830 item.addActionListener(new ActionListener() {
832 public void actionPerformed(ActionEvent e) {
833 log.user("Memory statistics selected");
835 // Get discarded but remaining objects (this also runs System.gc multiple times)
836 List<MemoryData> objects = MemoryManagement.getRemainingCollectableObjects();
837 StringBuilder sb = new StringBuilder();
838 sb.append("Objects that should have been garbage-collected but have not been:\n");
840 for (MemoryData data : objects) {
841 Object o = data.getReference().get();
844 sb.append("Age ").append(System.currentTimeMillis() - data.getRegistrationTime())
845 .append(" ms: ").append(o).append('\n');
847 // Explicitly null the strong reference to avoid possibility of invisible references
850 sb.append("Total: " + count);
852 // Get basic memory stats
854 long max = Runtime.getRuntime().maxMemory();
855 long free = Runtime.getRuntime().freeMemory();
856 long used = max - free;
857 String[] stats = new String[4];
858 stats[0] = "Memory usage:";
859 stats[1] = String.format(" Max memory: %.1f MB", max / 1024.0 / 1024.0);
860 stats[2] = String.format(" Used memory: %.1f MB (%.0f%%)", used / 1024.0 / 1024.0, 100.0 * used / max);
861 stats[3] = String.format(" Free memory: %.1f MB (%.0f%%)", free / 1024.0 / 1024.0, 100.0 * free / max);
864 DetailDialog.showDetailedMessageDialog(BasicFrame.this, stats, sb.toString(),
865 "Memory statistics", JOptionPane.INFORMATION_MESSAGE);
871 item = new JMenuItem("Exhaust memory");
872 item.addActionListener(new ActionListener() {
874 public void actionPerformed(ActionEvent e) {
875 log.user("Exhaust memory selected");
876 LinkedList<byte[]> data = new LinkedList<byte[]>();
878 final int bytesPerArray = 10240;
881 byte[] array = new byte[bytesPerArray];
882 for (int i = 0; i < bytesPerArray; i++) {
888 } catch (OutOfMemoryError error) {
890 long size = bytesPerArray * (long) count;
891 String s = String.format("OutOfMemory occurred after %d iterations (approx. %.1f MB consumed)",
892 count, size / 1024.0 / 1024.0);
894 JOptionPane.showMessageDialog(BasicFrame.this, s);
904 item = new JMenuItem("Exception here");
905 item.addActionListener(new ActionListener() {
907 public void actionPerformed(ActionEvent e) {
908 log.user("Exception here selected");
909 throw new RuntimeException("Testing exception from menu action listener");
914 item = new JMenuItem("Exception from EDT");
915 item.addActionListener(new ActionListener() {
917 public void actionPerformed(ActionEvent e) {
918 log.user("Exception from EDT selected");
919 SwingUtilities.invokeLater(new Runnable() {
922 throw new RuntimeException("Testing exception from " +
923 "later invoked EDT thread");
930 item = new JMenuItem("Exception from other thread");
931 item.addActionListener(new ActionListener() {
933 public void actionPerformed(ActionEvent e) {
934 log.user("Exception from other thread selected");
938 throw new RuntimeException("Testing exception from newly created thread");
945 item = new JMenuItem("OutOfMemoryError here");
946 item.addActionListener(new ActionListener() {
948 public void actionPerformed(ActionEvent e) {
949 log.user("OutOfMemoryError here selected");
950 throw new OutOfMemoryError("Testing OutOfMemoryError from menu action listener");
959 item = new JMenuItem("Test popup");
960 item.addActionListener(new ActionListener() {
962 public void actionPerformed(ActionEvent e) {
963 log.user("Test popup selected");
964 JPanel panel = new JPanel();
965 panel.add(new JTextField(40));
966 panel.add(new JSpinner());
967 JPopupMenu popup = new JPopupMenu();
968 popup.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
970 popup.show(BasicFrame.this, -50, 100);
983 * Select the tab on the main pane.
985 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
987 public void selectTab(int tab) {
988 tabbedPane.setSelectedIndex(tab);
993 private void openAction() {
994 JFileChooser chooser = new JFileChooser();
996 chooser.addChoosableFileFilter(FileHelper.ALL_DESIGNS_FILTER);
997 chooser.addChoosableFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
998 chooser.addChoosableFileFilter(FileHelper.ROCKSIM_DESIGN_FILTER);
999 chooser.setFileFilter(FileHelper.ALL_DESIGNS_FILTER);
1001 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
1002 chooser.setMultiSelectionEnabled(true);
1003 chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory());
1004 int option = chooser.showOpenDialog(this);
1005 if (option != JFileChooser.APPROVE_OPTION) {
1006 log.user("Decided not to open files, option=" + option);
1010 ((SwingPreferences) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory());
1012 File[] files = chooser.getSelectedFiles();
1013 log.user("Opening files " + Arrays.toString(files));
1015 for (File file : files) {
1016 log.info("Opening file: " + file);
1017 if (open(file, this)) {
1019 // Close previous window if replacing
1020 if (replaceable && document.isSaved()) {
1021 // We are replacing the frame, make new window have current location
1022 BasicFrame newFrame = frames.get(frames.size() - 1);
1023 newFrame.setLocation(this.getLocation());
1025 log.info("Closing window because it is replaceable");
1027 replaceable = false;
1035 * Open a file based on a URL.
1036 * @param url the file to open.
1037 * @param parent the parent window for dialogs.
1038 * @return <code>true</code> if opened successfully.
1040 private static boolean open(URL url, BasicFrame parent) {
1041 String filename = null;
1043 // First figure out the file name from the URL
1045 // Try using URI.getPath();
1047 URI uri = url.toURI();
1048 filename = uri.getPath();
1049 } catch (URISyntaxException ignore) {
1052 // Try URL-decoding the URL
1053 if (filename == null) {
1055 filename = URLDecoder.decode(url.toString(), "UTF-8");
1056 } catch (UnsupportedEncodingException ignore) {
1061 if (filename == null) {
1065 // Remove path from filename
1066 if (filename.lastIndexOf('/') >= 0) {
1067 filename = filename.substring(filename.lastIndexOf('/') + 1);
1072 log.info("Opening file from url=" + url + " filename=" + filename);
1074 InputStream is = url.openStream();
1075 if (open(is, filename, parent)) {
1076 // Close previous window if replacing
1077 if (parent.replaceable && parent.document.isSaved()) {
1078 parent.closeAction();
1079 parent.replaceable = false;
1082 } catch (IOException e) {
1083 log.warn("Error opening file" + e);
1084 JOptionPane.showMessageDialog(parent,
1085 "An error occurred while opening the file " + filename,
1086 "Error loading file", JOptionPane.ERROR_MESSAGE);
1094 * Open the specified file from an InputStream in a new design frame. If an error
1095 * occurs, an error dialog is shown and <code>false</code> is returned.
1097 * @param stream the stream to load from.
1098 * @param filename the file name to display in dialogs (not set to the document).
1099 * @param parent the parent component for which a progress dialog is opened.
1100 * @return whether the file was successfully loaded and opened.
1102 private static boolean open(InputStream stream, String filename, Window parent) {
1103 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
1104 return open(worker, filename, null, parent);
1109 * Open the specified file in a new design frame. If an error occurs, an error
1110 * dialog is shown and <code>false</code> is returned.
1112 * @param file the file to open.
1113 * @param parent the parent component for which a progress dialog is opened.
1114 * @return whether the file was successfully loaded and opened.
1116 public static boolean open(File file, Window parent) {
1117 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
1118 return open(worker, file.getName(), file, parent);
1123 * Open the specified file using the provided worker.
1125 * @param worker the OpenFileWorker that loads the file.
1126 * @param filename the file name to display in dialogs.
1127 * @param file the File to set the document to (may be null).
1131 private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) {
1133 MotorDatabaseLoadingDialog.check(parent);
1135 // Open the file in a Swing worker thread
1136 log.info("Starting OpenFileWorker");
1137 if (!SwingWorkerDialog.runWorker(parent, "Opening file", "Reading " + filename + "...", worker)) {
1138 // User cancelled the operation
1139 log.info("User cancelled the OpenFileWorker");
1144 // Handle the document
1145 OpenRocketDocument doc = null;
1150 } catch (ExecutionException e) {
1152 Throwable cause = e.getCause();
1154 if (cause instanceof FileNotFoundException) {
1156 log.warn("File not found", cause);
1157 JOptionPane.showMessageDialog(parent,
1158 "File not found: " + filename,
1159 "Error opening file", JOptionPane.ERROR_MESSAGE);
1162 } else if (cause instanceof RocketLoadException) {
1164 log.warn("Error loading the file", cause);
1165 JOptionPane.showMessageDialog(parent,
1166 "Unable to open file '" + filename + "': "
1167 + cause.getMessage(),
1168 "Error opening file", JOptionPane.ERROR_MESSAGE);
1173 throw new BugException("Unknown error when opening file", e);
1177 } catch (InterruptedException e) {
1178 throw new BugException("EDT was interrupted", e);
1182 throw new BugException("Document loader returned null");
1187 WarningSet warnings = worker.getRocketLoader().getWarnings();
1188 if (!warnings.isEmpty()) {
1189 log.info("Warnings while reading file: " + warnings);
1190 WarningDialog.showWarnings(parent,
1192 //// The following problems were encountered while opening
1193 trans.get("BasicFrame.WarningDialog.txt1") + " " + filename + ".",
1194 //// Some design features may not have been loaded correctly.
1195 trans.get("BasicFrame.WarningDialog.txt2")
1197 //// Warnings while opening file
1198 trans.get("BasicFrame.WarningDialog.title"), warnings);
1202 // Set document state
1208 log.debug("Opening new frame with the document");
1209 BasicFrame frame = new BasicFrame(doc);
1210 frame.setVisible(true);
1216 * "Save" action. If the design is new, then this is identical to "Save As", with a default file filter for .ork.
1217 * If the rocket being edited previously was opened from a .ork file, then it will be saved immediately to the same
1218 * file. But clicking on 'Save' for an existing design file with a .rkt will bring up a confirmation dialog because
1219 * it's potentially a destructive write (loss of some fidelity if it's truly an original Rocksim generated file).
1221 * @return true if the file was saved, false otherwise
1223 private boolean saveAction() {
1224 File file = document.getFile();
1226 log.info("Document does not contain file, opening save as dialog instead");
1227 return saveAsAction();
1229 log.info("Saving document to " + file);
1231 if (FileHelper.ROCKSIM_DESIGN_FILTER.accept(file)) {
1232 return saveAsRocksim(file);
1234 return saveAs(file);
1240 * Never should a .rkt file contain an OpenRocket content, or an .ork file contain a Rocksim design. Regardless of
1241 * what extension the user has chosen, it would violate the Principle of Least Astonishment to do otherwise
1242 * (and we want to make doing the wrong thing really hard to do). So always force the appropriate extension.
1244 * This can result in some odd looking filenames (MyDesign.rkt.ork, MyDesign.rkt.ork.rkt, etc.) if the user is
1245 * not paying attention, but the user can control that by modifying the filename in the dialog.
1247 * @return true if the file was saved, false otherwise
1249 private boolean saveAsAction() {
1252 StorageOptionChooser storageChooser =
1253 new StorageOptionChooser(document, document.getDefaultStorageOptions());
1254 final JFileChooser chooser = new JFileChooser();
1255 chooser.addChoosableFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
1256 chooser.addChoosableFileFilter(FileHelper.ROCKSIM_DESIGN_FILTER);
1258 //Force the file filter to match the file extension that was opened. Will default to OR if the file is null.
1259 if (FileHelper.ROCKSIM_DESIGN_FILTER.accept(document.getFile())) {
1260 chooser.setFileFilter(FileHelper.ROCKSIM_DESIGN_FILTER);
1263 chooser.setFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
1265 chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory());
1266 chooser.setAccessory(storageChooser);
1267 if (document.getFile() != null) {
1268 chooser.setSelectedFile(document.getFile());
1271 int option = chooser.showSaveDialog(BasicFrame.this);
1272 if (option != JFileChooser.APPROVE_OPTION) {
1273 log.user("User decided not to save, option=" + option);
1277 file = chooser.getSelectedFile();
1279 log.user("User did not select a file");
1283 ((SwingPreferences) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory());
1284 storageChooser.storeOptions(document.getDefaultStorageOptions());
1286 if (chooser.getFileFilter().equals(FileHelper.ROCKSIM_DESIGN_FILTER)) {
1287 return saveAsRocksim(file);
1290 file = FileHelper.forceExtension(file, "ork");
1291 return FileHelper.confirmWrite(file, this) && saveAs(file);
1296 * Perform the writing of the design to the given file in Rocksim format.
1298 * @param file the chosen file
1300 * @return true if the file was written
1302 private boolean saveAsRocksim(File file) {
1303 file = FileHelper.forceExtension(file, "rkt");
1304 if (!FileHelper.confirmWrite(file, this)) {
1309 new RocksimSaver().save(file, document);
1311 } catch (IOException e) {
1317 * Perform the writing of the design to the given file in OpenRocket format.
1319 * @param file the chosen file
1321 * @return true if the file was written
1323 private boolean saveAs(File file) {
1324 log.info("Saving document as " + file);
1325 boolean saved = false;
1327 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1328 // User cancelled the dialog
1329 log.user("User cancelled saving in storage options dialog");
1334 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1336 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1337 "Writing " + file.getName() + "...", worker)) {
1339 // User cancelled the save
1340 log.user("User cancelled the save, deleting the file");
1347 document.setFile(file);
1348 document.setSaved(true);
1351 } catch (ExecutionException e) {
1353 Throwable cause = e.getCause();
1355 if (cause instanceof IOException) {
1356 log.warn("An I/O error occurred while saving " + file, cause);
1357 JOptionPane.showMessageDialog(this, new String[] {
1358 "An I/O error occurred while saving:",
1359 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1362 Reflection.handleWrappedException(e);
1365 } catch (InterruptedException e) {
1366 throw new BugException("EDT was interrupted", e);
1373 private boolean closeAction() {
1374 if (!document.isSaved()) {
1375 log.info("Confirming whether to save the design");
1376 ComponentConfigDialog.hideDialog();
1377 int result = JOptionPane.showConfirmDialog(this,
1378 trans.get("BasicFrame.dlg.lbl1") + rocket.getName() +
1379 trans.get("BasicFrame.dlg.lbl2") + " " +
1380 trans.get("BasicFrame.dlg.lbl3"),
1381 trans.get("BasicFrame.dlg.title"), JOptionPane.YES_NO_CANCEL_OPTION,
1382 JOptionPane.QUESTION_MESSAGE);
1383 if (result == JOptionPane.YES_OPTION) {
1385 log.user("User requested file save");
1386 if (!saveAction()) {
1387 log.info("File save was interrupted, not closing");
1390 } else if (result == JOptionPane.NO_OPTION) {
1391 // Don't save: No-op
1392 log.user("User requested to discard design");
1395 log.user("User cancelled closing, result=" + result);
1400 // Rocket has been saved or discarded
1401 log.debug("Disposing window");
1404 ComponentConfigDialog.hideDialog();
1405 ComponentAnalysisDialog.hideDialog();
1407 frames.remove(this);
1408 if (frames.isEmpty()) {
1409 log.info("Last frame closed, exiting");
1420 public void printAction() {
1421 new PrintDialog(this, document).setVisible(true);
1425 * Open a new design window with a basic rocket+stage.
1427 public static void newAction() {
1428 log.info("New action initiated");
1430 Rocket rocket = new Rocket();
1431 Stage stage = new Stage();
1433 stage.setName(trans.get("BasicFrame.StageName.Sustainer"));
1434 rocket.addChild(stage);
1435 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1438 BasicFrame frame = new BasicFrame(doc);
1439 frame.replaceable = true;
1440 frame.setVisible(true);
1441 ComponentConfigDialog.showDialog(frame, doc, rocket);
1445 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1447 public static void quitAction() {
1448 log.info("Quit action initiated");
1449 for (int i = frames.size() - 1; i >= 0; i--) {
1450 log.debug("Closing frame " + frames.get(i));
1451 if (!frames.get(i).closeAction()) {
1453 log.info("Quit was cancelled");
1457 // Should not be reached, but just in case
1458 log.error("Should already have exited application");
1464 * Set the title of the frame, taking into account the name of the rocket, file it
1465 * has been saved to (if any) and saved status.
1467 private void setTitle() {
1468 File file = document.getFile();
1469 boolean saved = document.isSaved();
1472 title = rocket.getName();
1474 title = title + " (" + file.getName() + ")";
1477 title = "*" + title;
1485 * Find a currently open BasicFrame containing the specified rocket. This method
1486 * can be used to map a Rocket to a BasicFrame from GUI methods.
1488 * @param rocket the Rocket.
1489 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1491 public static BasicFrame findFrame(Rocket rocket) {
1492 for (BasicFrame f : frames) {
1493 if (f.rocket == rocket) {
1494 log.debug("Found frame " + f + " for rocket " + rocket);
1498 log.debug("Could not find frame for rocket " + rocket);
1503 * Find a currently open document by the rocket object. This method can be used
1504 * to map a Rocket to OpenRocketDocument from GUI methods.
1506 * @param rocket the Rocket.
1507 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1509 public static OpenRocketDocument findDocument(Rocket rocket) {
1510 BasicFrame frame = findFrame(rocket);
1511 if (frame != null) {
1512 return frame.document;