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.ComponentAdapter;
10 import java.awt.event.ComponentEvent;
11 import java.awt.event.KeyEvent;
12 import java.awt.event.MouseAdapter;
13 import java.awt.event.MouseEvent;
14 import java.awt.event.MouseListener;
15 import java.awt.event.WindowAdapter;
16 import java.awt.event.WindowEvent;
18 import java.io.FileNotFoundException;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.UnsupportedEncodingException;
23 import java.net.URISyntaxException;
25 import java.net.URLDecoder;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.LinkedList;
29 import java.util.List;
30 import java.util.concurrent.ExecutionException;
32 import javax.swing.Action;
33 import javax.swing.BorderFactory;
34 import javax.swing.InputMap;
35 import javax.swing.JButton;
36 import javax.swing.JComponent;
37 import javax.swing.JFileChooser;
38 import javax.swing.JFrame;
39 import javax.swing.JMenu;
40 import javax.swing.JMenuBar;
41 import javax.swing.JMenuItem;
42 import javax.swing.JOptionPane;
43 import javax.swing.JPanel;
44 import javax.swing.JPopupMenu;
45 import javax.swing.JScrollPane;
46 import javax.swing.JSpinner;
47 import javax.swing.JSplitPane;
48 import javax.swing.JTabbedPane;
49 import javax.swing.JTextField;
50 import javax.swing.KeyStroke;
51 import javax.swing.ListSelectionModel;
52 import javax.swing.ScrollPaneConstants;
53 import javax.swing.SwingUtilities;
54 import javax.swing.border.BevelBorder;
55 import javax.swing.border.TitledBorder;
56 import javax.swing.event.TreeSelectionEvent;
57 import javax.swing.event.TreeSelectionListener;
58 import javax.swing.tree.DefaultTreeSelectionModel;
59 import javax.swing.tree.TreePath;
60 import javax.swing.tree.TreeSelectionModel;
62 import net.miginfocom.swing.MigLayout;
63 import net.sf.openrocket.aerodynamics.WarningSet;
64 import net.sf.openrocket.document.OpenRocketDocument;
65 import net.sf.openrocket.file.GeneralRocketLoader;
66 import net.sf.openrocket.file.RocketLoadException;
67 import net.sf.openrocket.file.RocketLoader;
68 import net.sf.openrocket.file.RocketSaver;
69 import net.sf.openrocket.file.openrocket.OpenRocketSaver;
70 import net.sf.openrocket.gui.StorageOptionChooser;
71 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
72 import net.sf.openrocket.gui.dialogs.AboutDialog;
73 import net.sf.openrocket.gui.dialogs.BugReportDialog;
74 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
75 import net.sf.openrocket.gui.dialogs.DebugLogDialog;
76 import net.sf.openrocket.gui.dialogs.DetailDialog;
77 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
78 import net.sf.openrocket.gui.dialogs.LicenseDialog;
79 import net.sf.openrocket.gui.dialogs.MotorDatabaseLoadingDialog;
80 import net.sf.openrocket.gui.dialogs.PrintDialog;
81 import net.sf.openrocket.gui.dialogs.ScaleDialog;
82 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
83 import net.sf.openrocket.gui.dialogs.WarningDialog;
84 import net.sf.openrocket.gui.dialogs.optimization.GeneralOptimizationDialog;
85 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
86 import net.sf.openrocket.gui.main.componenttree.ComponentTree;
87 import net.sf.openrocket.gui.scalefigure.RocketPanel;
88 import net.sf.openrocket.l10n.Translator;
89 import net.sf.openrocket.logging.LogHelper;
90 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
91 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
92 import net.sf.openrocket.rocketcomponent.Rocket;
93 import net.sf.openrocket.rocketcomponent.RocketComponent;
94 import net.sf.openrocket.rocketcomponent.Stage;
95 import net.sf.openrocket.startup.Application;
96 import net.sf.openrocket.util.BugException;
97 import net.sf.openrocket.util.FileHelper;
98 import net.sf.openrocket.util.GUIUtil;
99 import net.sf.openrocket.util.Icons;
100 import net.sf.openrocket.util.MemoryManagement;
101 import net.sf.openrocket.util.MemoryManagement.MemoryData;
102 import net.sf.openrocket.util.OpenFileWorker;
103 import net.sf.openrocket.util.Prefs;
104 import net.sf.openrocket.util.Reflection;
105 import net.sf.openrocket.util.SaveFileWorker;
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;
156 * Sole constructor. Creates a new frame based on the supplied document
157 * and adds it to the current frames list.
159 * @param document the document to show.
161 public BasicFrame(OpenRocketDocument document) {
162 log.debug("Instantiating new BasicFrame");
164 this.document = document;
165 this.rocket = document.getRocket();
166 this.rocket.getDefaultConfiguration().setAllStages();
169 // Set replaceable flag to false at first modification
170 rocket.addComponentChangeListener(new ComponentChangeListener() {
172 public void componentChanged(ComponentChangeEvent e) {
174 BasicFrame.this.rocket.removeComponentChangeListener(this);
179 // Create the component tree selection model that will be used
180 componentSelectionModel = new DefaultTreeSelectionModel();
181 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
183 // Obtain the simulation selection model that will be used
184 SimulationPanel simulationPanel = new SimulationPanel(document);
185 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
187 // Combine into a DocumentSelectionModel
188 selectionModel = new DocumentSelectionModel(document);
189 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
190 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
193 actions = new RocketActions(document, selectionModel, this);
196 log.debug("Constructing the BasicFrame UI");
198 // The main vertical split pane
199 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
200 vertical.setResizeWeight(0.5);
204 // The top tabbed pane
205 tabbedPane = new JTabbedPane();
207 tabbedPane.addTab(trans.get("BasicFrame.tab.Rocketdesign"), null, designTab());
208 //// Flight simulations
209 tabbedPane.addTab(trans.get("BasicFrame.tab.Flightsim"), null, simulationPanel);
211 vertical.setTopComponent(tabbedPane);
215 // Bottom segment, rocket figure
217 rocketpanel = new RocketPanel(document);
218 vertical.setBottomComponent(rocketpanel);
220 rocketpanel.setSelectionModel(tree.getSelectionModel());
226 rocket.addComponentChangeListener(new ComponentChangeListener() {
228 public void componentChanged(ComponentChangeEvent e) {
236 Dimension size = Prefs.getWindowSize(this.getClass());
238 size = Toolkit.getDefaultToolkit().getScreenSize();
239 size.width = size.width * 9 / 10;
240 size.height = size.height * 9 / 10;
243 this.addComponentListener(new ComponentAdapter() {
245 public void componentResized(ComponentEvent e) {
246 Prefs.setWindowSize(BasicFrame.this.getClass(), BasicFrame.this.getSize());
249 this.setLocationByPlatform(true);
251 GUIUtil.setWindowIcons(this);
254 vertical.setDividerLocation(0.4);
255 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
256 addWindowListener(new WindowAdapter() {
258 public void windowClosing(WindowEvent e) {
264 log.debug("BasicFrame instantiation complete");
269 * Construct the "Rocket design" tab. This contains a horizontal split pane
270 * with the left component the design tree and the right component buttons
271 * for adding components.
273 private JComponent designTab() {
274 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
275 horizontal.setResizeWeight(0.5);
278 // Upper-left segment, component tree
280 JPanel panel = new JPanel(new MigLayout("fill, flowy", "", "[grow]"));
282 tree = new ComponentTree(document);
283 tree.setSelectionModel(componentSelectionModel);
285 // Remove JTree key events that interfere with menu accelerators
286 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
287 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
288 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
289 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
290 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
291 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
292 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
293 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
297 // Double-click opens config dialog
298 MouseListener ml = new MouseAdapter() {
300 public void mousePressed(MouseEvent e) {
301 int selRow = tree.getRowForLocation(e.getX(), e.getY());
302 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
304 if ((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
306 RocketComponent c = (RocketComponent) selPath.getLastPathComponent();
307 ComponentConfigDialog.showDialog(BasicFrame.this,
308 BasicFrame.this.document, c);
313 tree.addMouseListener(ml);
315 // Update dialog when selection is changed
316 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
318 public void valueChanged(TreeSelectionEvent e) {
319 // Scroll tree to the selected item
320 TreePath path = componentSelectionModel.getSelectionPath();
323 tree.scrollPathToVisible(path);
325 if (!ComponentConfigDialog.isDialogVisible())
327 RocketComponent c = (RocketComponent) path.getLastPathComponent();
328 ComponentConfigDialog.showDialog(BasicFrame.this,
329 BasicFrame.this.document, c);
333 // Place tree inside scroll pane
334 JScrollPane scroll = new JScrollPane(tree);
335 panel.add(scroll, "spany, grow, wrap");
339 JButton button = new JButton(actions.getMoveUpAction());
340 panel.add(button, "sizegroup buttons, aligny 65%");
342 button = new JButton(actions.getMoveDownAction());
343 panel.add(button, "sizegroup buttons, aligny 0%");
345 button = new JButton(actions.getEditAction());
346 panel.add(button, "sizegroup buttons");
348 button = new JButton(actions.getNewStageAction());
349 panel.add(button, "sizegroup buttons");
351 button = new JButton(actions.getDeleteAction());
352 button.setIcon(null);
353 button.setMnemonic(0);
354 panel.add(button, "sizegroup buttons");
356 horizontal.setLeftComponent(panel);
359 // Upper-right segment, component addition buttons
361 panel = new JPanel(new MigLayout("fill, insets 0", "[0::]"));
363 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
364 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
365 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
366 scroll.getViewport()));
367 scroll.setBorder(null);
368 scroll.setViewportBorder(null);
370 TitledBorder border = BorderFactory.createTitledBorder(trans.get("BasicFrame.title.Addnewcomp"));
371 GUIUtil.changeFontStyle(border, Font.BOLD);
372 scroll.setBorder(border);
374 panel.add(scroll, "grow");
376 horizontal.setRightComponent(panel);
384 * Return the currently selected rocket component, or <code>null</code> if none selected.
386 private RocketComponent getSelectedComponent() {
387 TreePath path = componentSelectionModel.getSelectionPath();
390 tree.scrollPathToVisible(path);
392 return (RocketComponent) path.getLastPathComponent();
397 * Creates the menu for the window.
399 private void createMenu() {
400 JMenuBar menubar = new JMenuBar();
405 menu = new JMenu(trans.get("main.menu.file"));
406 menu.setMnemonic(KeyEvent.VK_F);
407 //// File-handling related tasks
408 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.desc"));
412 item = new JMenuItem(trans.get("main.menu.file.new"), KeyEvent.VK_N);
413 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
414 item.setMnemonic(KeyEvent.VK_N);
415 //// Create a new rocket design
416 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.new.desc"));
417 item.setIcon(Icons.FILE_NEW);
418 item.addActionListener(new ActionListener() {
420 public void actionPerformed(ActionEvent e) {
421 log.user("New... selected");
424 log.info("Closing previous window");
432 item = new JMenuItem(trans.get("main.menu.file.open"), KeyEvent.VK_O);
433 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
434 //// Open a rocket design
435 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openrocketdesign"));
436 item.setIcon(Icons.FILE_OPEN);
437 item.addActionListener(new ActionListener() {
439 public void actionPerformed(ActionEvent e) {
440 log.user("Open... selected");
447 item = new JMenuItem(trans.get("main.menu.file.openExample"));
448 //// Open an example rocket design
449 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openexamplerocketdesign"));
450 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
451 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
452 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
453 item.addActionListener(new ActionListener() {
455 public void actionPerformed(ActionEvent e) {
456 log.user("Open example... selected");
457 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
460 log.user("Opening example " + u);
461 open(u, BasicFrame.this);
471 item = new JMenuItem(trans.get("main.menu.file.save"), KeyEvent.VK_S);
472 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
473 //// Save the current rocket design
474 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesign"));
475 item.setIcon(Icons.FILE_SAVE);
476 item.addActionListener(new ActionListener() {
478 public void actionPerformed(ActionEvent e) {
479 log.user("Save selected");
486 item = new JMenuItem(trans.get("main.menu.file.saveAs"), KeyEvent.VK_A);
487 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
488 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
489 //// Save the current rocket design to a new file
490 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesnewfile"));
491 item.setIcon(Icons.FILE_SAVE_AS);
492 item.addActionListener(new ActionListener() {
494 public void actionPerformed(ActionEvent e) {
495 log.user("Save as... selected");
502 item = new JMenuItem(trans.get("main.menu.file.print"), KeyEvent.VK_P);
503 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
504 //// Print parts list and fin template
505 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.print.desc"));
506 item.setIcon(Icons.FILE_PRINT);
507 item.addActionListener(new ActionListener() {
509 public void actionPerformed(ActionEvent e) {
510 log.user("Print action selected");
520 item = new JMenuItem(trans.get("main.menu.file.close"), KeyEvent.VK_C);
521 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
522 //// Close the current rocket design
523 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Closedesign"));
524 item.setIcon(Icons.FILE_CLOSE);
525 item.addActionListener(new ActionListener() {
527 public void actionPerformed(ActionEvent e) {
528 log.user("Close selected");
537 item = new JMenuItem(trans.get("main.menu.file.quit"), KeyEvent.VK_Q);
538 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
539 //// Quit the program
540 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Quitprogram"));
541 item.setIcon(Icons.FILE_QUIT);
542 item.addActionListener(new ActionListener() {
544 public void actionPerformed(ActionEvent e) {
545 log.user("Quit selected");
554 menu = new JMenu(trans.get("main.menu.edit"));
555 menu.setMnemonic(KeyEvent.VK_E);
557 menu.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.menu.Rocketedt"));
561 Action action = document.getUndoAction();
562 item = new JMenuItem(action);
563 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
564 item.setMnemonic(KeyEvent.VK_U);
565 //// Undo the previous operation
566 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.undo.desc"));
570 action = document.getRedoAction();
571 item = new JMenuItem(action);
572 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
573 item.setMnemonic(KeyEvent.VK_R);
574 //// Redo the previously undone operation
575 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.redo.desc"));
581 item = new JMenuItem(actions.getCutAction());
584 item = new JMenuItem(actions.getCopyAction());
587 item = new JMenuItem(actions.getPasteAction());
590 item = new JMenuItem(actions.getDeleteAction());
597 item = new JMenuItem(trans.get("main.menu.edit.resize"));
598 item.setIcon(Icons.EDIT_SCALE);
599 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.resize.desc"));
600 item.addActionListener(new ActionListener() {
602 public void actionPerformed(ActionEvent e) {
603 log.user("Scale... selected");
604 ScaleDialog dialog = new ScaleDialog(document, getSelectedComponent(), BasicFrame.this);
605 dialog.setVisible(true);
614 item = new JMenuItem(trans.get("main.menu.edit.preferences"));
615 item.setIcon(Icons.PREFERENCES);
616 //// Setup the application preferences
617 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.preferences.desc"));
618 item.addActionListener(new ActionListener() {
620 public void actionPerformed(ActionEvent e) {
621 log.user("Preferences selected");
622 PreferencesDialog.showPreferences(BasicFrame.this);
631 menu = new JMenu(trans.get("main.menu.analyze"));
632 menu.setMnemonic(KeyEvent.VK_A);
633 //// Analyzing the rocket
634 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.desc"));
637 //// Component analysis
638 item = new JMenuItem(trans.get("main.menu.analyze.componentAnalysis"), KeyEvent.VK_C);
639 //// Analyze the rocket components separately
640 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.componentAnalysis.desc"));
641 item.addActionListener(new ActionListener() {
643 public void actionPerformed(ActionEvent e) {
644 log.user("Component analysis selected");
645 ComponentAnalysisDialog.showDialog(rocketpanel);
651 item = new JMenuItem(trans.get("main.menu.analyze.optimization"), KeyEvent.VK_O);
652 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.optimization.desc"));
653 item.addActionListener(new ActionListener() {
655 public void actionPerformed(ActionEvent e) {
656 log.user("Rocket optimization selected");
657 new GeneralOptimizationDialog(document, BasicFrame.this).setVisible(true);
665 // (shown if openrocket.debug.menu is defined)
666 if (System.getProperty("openrocket.debug.menu") != null) {
667 menubar.add(makeDebugMenu());
674 menu = new JMenu(trans.get("main.menu.help"));
675 menu.setMnemonic(KeyEvent.VK_H);
676 //// Information about OpenRocket
677 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.desc"));
682 item = new JMenuItem(trans.get("main.menu.help.license"), KeyEvent.VK_L);
683 //// OpenRocket license information
684 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.license.desc"));
685 item.addActionListener(new ActionListener() {
687 public void actionPerformed(ActionEvent e) {
688 log.user("License selected");
689 new LicenseDialog(BasicFrame.this).setVisible(true);
697 item = new JMenuItem(trans.get("main.menu.help.bugReport"), KeyEvent.VK_B);
698 //// Information about reporting bugs in OpenRocket
699 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.bugReport.desc"));
700 item.addActionListener(new ActionListener() {
702 public void actionPerformed(ActionEvent e) {
703 log.user("Bug report selected");
704 BugReportDialog.showBugReportDialog(BasicFrame.this);
710 item = new JMenuItem(trans.get("main.menu.help.debugLog"));
711 //// View the OpenRocket debug log
712 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.debugLog.desc"));
713 item.addActionListener(new ActionListener() {
715 public void actionPerformed(ActionEvent e) {
716 log.user("Debug log selected");
717 new DebugLogDialog(BasicFrame.this).setVisible(true);
725 item = new JMenuItem(trans.get("main.menu.help.about"), KeyEvent.VK_A);
726 //// About OpenRocket
727 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.about.desc"));
728 item.addActionListener(new ActionListener() {
730 public void actionPerformed(ActionEvent e) {
731 log.user("About selected");
732 new AboutDialog(BasicFrame.this).setVisible(true);
738 this.setJMenuBar(menubar);
741 private JMenu makeDebugMenu() {
746 * This menu is intentionally left untranslated.
750 menu = new JMenu("Debug");
751 //// OpenRocket debugging tasks
752 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
754 //// What is this menu?
755 item = new JMenuItem("What is this menu?");
756 item.addActionListener(new ActionListener() {
758 public void actionPerformed(ActionEvent e) {
759 log.user("What is this menu? selected");
760 JOptionPane.showMessageDialog(BasicFrame.this,
762 "The 'Debug' menu includes actions for testing and debugging " +
764 "The menu is made visible by defining the system property " +
765 "'openrocket.debug.menu' when starting OpenRocket.",
766 "It should not be visible by default." },
767 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
774 //// Create test rocket
775 item = new JMenuItem("Create test rocket");
776 item.addActionListener(new ActionListener() {
778 public void actionPerformed(ActionEvent e) {
779 log.user("Create test rocket selected");
780 JTextField field = new JTextField();
781 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
782 "Input text key to generate random rocket:",
784 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
785 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
791 r = new TestRockets(null).makeTestRocket();
792 } else if (sel == 1) {
793 r = new TestRockets(field.getText()).makeTestRocket();
798 OpenRocketDocument doc = new OpenRocketDocument(r);
800 BasicFrame frame = new BasicFrame(doc);
801 frame.setVisible(true);
808 item = new JMenuItem("Create 'Iso-Haisu'");
809 item.addActionListener(new ActionListener() {
811 public void actionPerformed(ActionEvent e) {
812 log.user("Create Iso-Haisu selected");
813 Rocket r = TestRockets.makeIsoHaisu();
814 OpenRocketDocument doc = new OpenRocketDocument(r);
816 BasicFrame frame = new BasicFrame(doc);
817 frame.setVisible(true);
823 item = new JMenuItem("Create 'Big Blue'");
824 item.addActionListener(new ActionListener() {
826 public void actionPerformed(ActionEvent e) {
827 log.user("Create Big Blue selected");
828 Rocket r = TestRockets.makeBigBlue();
829 OpenRocketDocument doc = new OpenRocketDocument(r);
831 BasicFrame frame = new BasicFrame(doc);
832 frame.setVisible(true);
840 item = new JMenuItem("Memory statistics");
841 item.addActionListener(new ActionListener() {
843 public void actionPerformed(ActionEvent e) {
844 log.user("Memory statistics selected");
846 // Get discarded but remaining objects (this also runs System.gc multiple times)
847 List<MemoryData> objects = MemoryManagement.getRemainingCollectableObjects();
848 StringBuilder sb = new StringBuilder();
849 sb.append("Objects that should have been garbage-collected but have not been:\n");
851 for (MemoryData data : objects) {
852 Object o = data.getReference().get();
855 sb.append("Age ").append(System.currentTimeMillis() - data.getRegistrationTime())
856 .append(" ms: ").append(o).append('\n');
858 // Explicitly null the strong reference to avoid possibility of invisible references
861 sb.append("Total: " + count);
863 // Get basic memory stats
865 long max = Runtime.getRuntime().maxMemory();
866 long free = Runtime.getRuntime().freeMemory();
867 long used = max - free;
868 String[] stats = new String[4];
869 stats[0] = "Memory usage:";
870 stats[1] = String.format(" Max memory: %.1f MB", max / 1024.0 / 1024.0);
871 stats[2] = String.format(" Used memory: %.1f MB (%.0f%%)", used / 1024.0 / 1024.0, 100.0 * used / max);
872 stats[3] = String.format(" Free memory: %.1f MB (%.0f%%)", free / 1024.0 / 1024.0, 100.0 * free / max);
875 DetailDialog.showDetailedMessageDialog(BasicFrame.this, stats, sb.toString(),
876 "Memory statistics", JOptionPane.INFORMATION_MESSAGE);
882 item = new JMenuItem("Exhaust memory");
883 item.addActionListener(new ActionListener() {
885 public void actionPerformed(ActionEvent e) {
886 log.user("Exhaust memory selected");
887 LinkedList<byte[]> data = new LinkedList<byte[]>();
889 final int bytesPerArray = 10240;
892 byte[] array = new byte[bytesPerArray];
893 for (int i = 0; i < bytesPerArray; i++) {
899 } catch (OutOfMemoryError error) {
901 long size = bytesPerArray * (long) count;
902 String s = String.format("OutOfMemory occurred after %d iterations (approx. %.1f MB consumed)",
903 count, size / 1024.0 / 1024.0);
905 JOptionPane.showMessageDialog(BasicFrame.this, s);
915 item = new JMenuItem("Exception here");
916 item.addActionListener(new ActionListener() {
918 public void actionPerformed(ActionEvent e) {
919 log.user("Exception here selected");
920 throw new RuntimeException("Testing exception from menu action listener");
925 item = new JMenuItem("Exception from EDT");
926 item.addActionListener(new ActionListener() {
928 public void actionPerformed(ActionEvent e) {
929 log.user("Exception from EDT selected");
930 SwingUtilities.invokeLater(new Runnable() {
933 throw new RuntimeException("Testing exception from " +
934 "later invoked EDT thread");
941 item = new JMenuItem("Exception from other thread");
942 item.addActionListener(new ActionListener() {
944 public void actionPerformed(ActionEvent e) {
945 log.user("Exception from other thread selected");
949 throw new RuntimeException("Testing exception from newly created thread");
956 item = new JMenuItem("OutOfMemoryError here");
957 item.addActionListener(new ActionListener() {
959 public void actionPerformed(ActionEvent e) {
960 log.user("OutOfMemoryError here selected");
961 throw new OutOfMemoryError("Testing OutOfMemoryError from menu action listener");
970 item = new JMenuItem("Test popup");
971 item.addActionListener(new ActionListener() {
973 public void actionPerformed(ActionEvent e) {
974 log.user("Test popup selected");
975 JPanel panel = new JPanel();
976 panel.add(new JTextField(40));
977 panel.add(new JSpinner());
978 JPopupMenu popup = new JPopupMenu();
979 popup.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
981 popup.show(BasicFrame.this, -50, 100);
994 * Select the tab on the main pane.
996 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
998 public void selectTab(int tab) {
999 tabbedPane.setSelectedIndex(tab);
1004 private void openAction() {
1005 JFileChooser chooser = new JFileChooser();
1007 chooser.addChoosableFileFilter(FileHelper.ALL_DESIGNS_FILTER);
1008 chooser.addChoosableFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
1009 chooser.addChoosableFileFilter(FileHelper.ROCKSIM_DESIGN_FILTER);
1010 chooser.setFileFilter(FileHelper.ALL_DESIGNS_FILTER);
1012 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
1013 chooser.setMultiSelectionEnabled(true);
1014 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
1015 int option = chooser.showOpenDialog(this);
1016 if (option != JFileChooser.APPROVE_OPTION) {
1017 log.user("Decided not to open files, option=" + option);
1021 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
1023 File[] files = chooser.getSelectedFiles();
1024 log.user("Opening files " + Arrays.toString(files));
1026 for (File file : files) {
1027 log.info("Opening file: " + file);
1028 if (open(file, this)) {
1030 // Close previous window if replacing
1031 if (replaceable && document.isSaved()) {
1032 // We are replacing the frame, make new window have current location
1033 BasicFrame newFrame = frames.get(frames.size() - 1);
1034 newFrame.setLocation(this.getLocation());
1036 log.info("Closing window because it is replaceable");
1038 replaceable = false;
1046 * Open a file based on a URL.
1047 * @param url the file to open.
1048 * @param parent the parent window for dialogs.
1049 * @return <code>true</code> if opened successfully.
1051 private static boolean open(URL url, BasicFrame parent) {
1052 String filename = null;
1054 // First figure out the file name from the URL
1056 // Try using URI.getPath();
1058 URI uri = url.toURI();
1059 filename = uri.getPath();
1060 } catch (URISyntaxException ignore) {
1063 // Try URL-decoding the URL
1064 if (filename == null) {
1066 filename = URLDecoder.decode(url.toString(), "UTF-8");
1067 } catch (UnsupportedEncodingException ignore) {
1072 if (filename == null) {
1076 // Remove path from filename
1077 if (filename.lastIndexOf('/') >= 0) {
1078 filename = filename.substring(filename.lastIndexOf('/') + 1);
1083 log.info("Opening file from url=" + url + " filename=" + filename);
1085 InputStream is = url.openStream();
1086 if (open(is, filename, parent)) {
1087 // Close previous window if replacing
1088 if (parent.replaceable && parent.document.isSaved()) {
1089 parent.closeAction();
1090 parent.replaceable = false;
1093 } catch (IOException e) {
1094 log.warn("Error opening file" + e);
1095 JOptionPane.showMessageDialog(parent,
1096 "An error occurred while opening the file " + filename,
1097 "Error loading file", JOptionPane.ERROR_MESSAGE);
1105 * Open the specified file from an InputStream in a new design frame. If an error
1106 * occurs, an error dialog is shown and <code>false</code> is returned.
1108 * @param stream the stream to load from.
1109 * @param filename the file name to display in dialogs (not set to the document).
1110 * @param parent the parent component for which a progress dialog is opened.
1111 * @return whether the file was successfully loaded and opened.
1113 private static boolean open(InputStream stream, String filename, Window parent) {
1114 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
1115 return open(worker, filename, null, parent);
1120 * Open the specified file in a new design frame. If an error occurs, an error
1121 * dialog is shown and <code>false</code> is returned.
1123 * @param file the file to open.
1124 * @param parent the parent component for which a progress dialog is opened.
1125 * @return whether the file was successfully loaded and opened.
1127 public static boolean open(File file, Window parent) {
1128 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
1129 return open(worker, file.getName(), file, parent);
1134 * Open the specified file using the provided worker.
1136 * @param worker the OpenFileWorker that loads the file.
1137 * @param filename the file name to display in dialogs.
1138 * @param file the File to set the document to (may be null).
1142 private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) {
1144 MotorDatabaseLoadingDialog.check(parent);
1146 // Open the file in a Swing worker thread
1147 log.info("Starting OpenFileWorker");
1148 if (!SwingWorkerDialog.runWorker(parent, "Opening file", "Reading " + filename + "...", worker)) {
1149 // User cancelled the operation
1150 log.info("User cancelled the OpenFileWorker");
1155 // Handle the document
1156 OpenRocketDocument doc = null;
1161 } catch (ExecutionException e) {
1163 Throwable cause = e.getCause();
1165 if (cause instanceof FileNotFoundException) {
1167 log.warn("File not found", cause);
1168 JOptionPane.showMessageDialog(parent,
1169 "File not found: " + filename,
1170 "Error opening file", JOptionPane.ERROR_MESSAGE);
1173 } else if (cause instanceof RocketLoadException) {
1175 log.warn("Error loading the file", cause);
1176 JOptionPane.showMessageDialog(parent,
1177 "Unable to open file '" + filename + "': "
1178 + cause.getMessage(),
1179 "Error opening file", JOptionPane.ERROR_MESSAGE);
1184 throw new BugException("Unknown error when opening file", e);
1188 } catch (InterruptedException e) {
1189 throw new BugException("EDT was interrupted", e);
1193 throw new BugException("Document loader returned null");
1198 WarningSet warnings = worker.getRocketLoader().getWarnings();
1199 if (!warnings.isEmpty()) {
1200 log.info("Warnings while reading file: " + warnings);
1201 WarningDialog.showWarnings(parent,
1203 //// The following problems were encountered while opening
1204 trans.get("BasicFrame.WarningDialog.txt1") + " " + filename + ".",
1205 //// Some design features may not have been loaded correctly.
1206 trans.get("BasicFrame.WarningDialog.txt2")
1208 //// Warnings while opening file
1209 trans.get("BasicFrame.WarningDialog.title"), warnings);
1213 // Set document state
1219 log.debug("Opening new frame with the document");
1220 BasicFrame frame = new BasicFrame(doc);
1221 frame.setVisible(true);
1230 private boolean saveAction() {
1231 File file = document.getFile();
1233 log.info("Document does not contain file, opening save as dialog instead");
1234 return saveAsAction();
1236 log.info("Saving document to " + file);
1238 // Saving RockSim designs is not supported
1239 if (FileHelper.ROCKSIM_DESIGN_FILTER.accept(file)) {
1240 file = new File(file.getAbsolutePath().replaceAll(".[rR][kK][tT](.[gG][zZ])?$",
1243 log.info("Attempting to save in RockSim format, renaming to " + file);
1244 int option = JOptionPane.showConfirmDialog(this, new Object[] {
1245 "Saving designs in RockSim format is not supported.",
1246 "Save in OpenRocket format instead (" + file.getName() + ")?"
1247 }, "Save " + file.getName(), JOptionPane.YES_NO_OPTION,
1248 JOptionPane.QUESTION_MESSAGE, null);
1249 if (option != JOptionPane.YES_OPTION) {
1250 log.user("User chose not to save");
1254 document.setFile(file);
1256 return saveAs(file);
1260 private boolean saveAsAction() {
1263 // TODO: HIGH: what if *.rkt chosen?
1264 StorageOptionChooser storageChooser =
1265 new StorageOptionChooser(document, document.getDefaultStorageOptions());
1266 JFileChooser chooser = new JFileChooser();
1267 chooser.setFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
1268 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
1269 chooser.setAccessory(storageChooser);
1270 if (document.getFile() != null)
1271 chooser.setSelectedFile(document.getFile());
1273 int option = chooser.showSaveDialog(BasicFrame.this);
1274 if (option != JFileChooser.APPROVE_OPTION) {
1275 log.user("User decided not to save, option=" + option);
1279 file = chooser.getSelectedFile();
1281 log.user("User did not select a file");
1285 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
1286 storageChooser.storeOptions(document.getDefaultStorageOptions());
1288 file = FileHelper.ensureExtension(file, "ork");
1289 if (!FileHelper.confirmWrite(file, this)) {
1293 return saveAs(file);
1296 private boolean saveAs(File file) {
1297 log.info("Saving document as " + file);
1298 boolean saved = false;
1300 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1301 // User cancelled the dialog
1302 log.user("User cancelled saving in storage options dialog");
1307 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1309 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1310 "Writing " + file.getName() + "...", worker)) {
1312 // User cancelled the save
1313 log.user("User cancelled the save, deleting the file");
1320 document.setFile(file);
1321 document.setSaved(true);
1324 } catch (ExecutionException e) {
1326 Throwable cause = e.getCause();
1328 if (cause instanceof IOException) {
1329 log.warn("An I/O error occurred while saving " + file, cause);
1330 JOptionPane.showMessageDialog(this, new String[] {
1331 "An I/O error occurred while saving:",
1332 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1335 Reflection.handleWrappedException(e);
1338 } catch (InterruptedException e) {
1339 throw new BugException("EDT was interrupted", e);
1346 private boolean closeAction() {
1347 if (!document.isSaved()) {
1348 log.info("Confirming whether to save the design");
1349 ComponentConfigDialog.hideDialog();
1350 int result = JOptionPane.showConfirmDialog(this,
1351 trans.get("BasicFrame.dlg.lbl1") + rocket.getName() +
1352 trans.get("BasicFrame.dlg.lbl2") + " " +
1353 trans.get("BasicFrame.dlg.lbl3"),
1354 trans.get("BasicFrame.dlg.title"), JOptionPane.YES_NO_CANCEL_OPTION,
1355 JOptionPane.QUESTION_MESSAGE);
1356 if (result == JOptionPane.YES_OPTION) {
1358 log.user("User requested file save");
1359 if (!saveAction()) {
1360 log.info("File save was interrupted, not closing");
1363 } else if (result == JOptionPane.NO_OPTION) {
1364 // Don't save: No-op
1365 log.user("User requested to discard design");
1368 log.user("User cancelled closing, result=" + result);
1373 // Rocket has been saved or discarded
1374 log.debug("Disposing window");
1377 ComponentConfigDialog.hideDialog();
1378 ComponentAnalysisDialog.hideDialog();
1380 frames.remove(this);
1381 if (frames.isEmpty()) {
1382 log.info("Last frame closed, exiting");
1393 public void printAction() {
1394 new PrintDialog(this, document).setVisible(true);
1398 * Open a new design window with a basic rocket+stage.
1400 public static void newAction() {
1401 log.info("New action initiated");
1403 Rocket rocket = new Rocket();
1404 Stage stage = new Stage();
1406 stage.setName(trans.get("BasicFrame.StageName.Sustainer"));
1407 rocket.addChild(stage);
1408 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1411 BasicFrame frame = new BasicFrame(doc);
1412 frame.replaceable = true;
1413 frame.setVisible(true);
1414 ComponentConfigDialog.showDialog(frame, doc, rocket);
1418 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1420 public static void quitAction() {
1421 log.info("Quit action initiated");
1422 for (int i = frames.size() - 1; i >= 0; i--) {
1423 log.debug("Closing frame " + frames.get(i));
1424 if (!frames.get(i).closeAction()) {
1426 log.info("Quit was cancelled");
1430 // Should not be reached, but just in case
1431 log.error("Should already have exited application");
1437 * Set the title of the frame, taking into account the name of the rocket, file it
1438 * has been saved to (if any) and saved status.
1440 private void setTitle() {
1441 File file = document.getFile();
1442 boolean saved = document.isSaved();
1445 title = rocket.getName();
1447 title = title + " (" + file.getName() + ")";
1450 title = "*" + title;
1458 * Find a currently open BasicFrame containing the specified rocket. This method
1459 * can be used to map a Rocket to a BasicFrame from GUI methods.
1461 * @param rocket the Rocket.
1462 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1464 public static BasicFrame findFrame(Rocket rocket) {
1465 for (BasicFrame f : frames) {
1466 if (f.rocket == rocket) {
1467 log.debug("Found frame " + f + " for rocket " + rocket);
1471 log.debug("Could not find frame for rocket " + rocket);
1476 * Find a currently open document by the rocket object. This method can be used
1477 * to map a Rocket to OpenRocketDocument from GUI methods.
1479 * @param rocket the Rocket.
1480 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1482 public static OpenRocketDocument findDocument(Rocket rocket) {
1483 BasicFrame frame = findFrame(rocket);
1484 if (frame != null) {
1485 return frame.document;