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.InputMap;
34 import javax.swing.JButton;
35 import javax.swing.JComponent;
36 import javax.swing.JFileChooser;
37 import javax.swing.JFrame;
38 import javax.swing.JMenu;
39 import javax.swing.JMenuBar;
40 import javax.swing.JMenuItem;
41 import javax.swing.JOptionPane;
42 import javax.swing.JPanel;
43 import javax.swing.JScrollPane;
44 import javax.swing.JSplitPane;
45 import javax.swing.JTabbedPane;
46 import javax.swing.JTextField;
47 import javax.swing.KeyStroke;
48 import javax.swing.ListSelectionModel;
49 import javax.swing.ScrollPaneConstants;
50 import javax.swing.SwingUtilities;
51 import javax.swing.border.TitledBorder;
52 import javax.swing.event.TreeSelectionEvent;
53 import javax.swing.event.TreeSelectionListener;
54 import javax.swing.filechooser.FileFilter;
55 import javax.swing.tree.DefaultTreeSelectionModel;
56 import javax.swing.tree.TreePath;
57 import javax.swing.tree.TreeSelectionModel;
59 import net.miginfocom.swing.MigLayout;
60 import net.sf.openrocket.aerodynamics.WarningSet;
61 import net.sf.openrocket.document.OpenRocketDocument;
62 import net.sf.openrocket.file.GeneralRocketLoader;
63 import net.sf.openrocket.file.RocketLoadException;
64 import net.sf.openrocket.file.RocketLoader;
65 import net.sf.openrocket.file.RocketSaver;
66 import net.sf.openrocket.file.openrocket.OpenRocketSaver;
67 import net.sf.openrocket.gui.StorageOptionChooser;
68 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
69 import net.sf.openrocket.gui.dialogs.AboutDialog;
70 import net.sf.openrocket.gui.dialogs.BugReportDialog;
71 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
72 import net.sf.openrocket.gui.dialogs.DebugLogDialog;
73 import net.sf.openrocket.gui.dialogs.DetailDialog;
74 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
75 import net.sf.openrocket.gui.dialogs.LicenseDialog;
76 import net.sf.openrocket.gui.dialogs.MotorDatabaseLoadingDialog;
77 import net.sf.openrocket.gui.dialogs.PrintDialog;
78 import net.sf.openrocket.gui.dialogs.ScaleDialog;
79 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
80 import net.sf.openrocket.gui.dialogs.WarningDialog;
81 import net.sf.openrocket.gui.dialogs.optimization.GeneralOptimizationDialog;
82 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
83 import net.sf.openrocket.gui.main.componenttree.ComponentTree;
84 import net.sf.openrocket.gui.optimization.OptimizationTestDialog;
85 import net.sf.openrocket.gui.scalefigure.RocketPanel;
86 import net.sf.openrocket.l10n.Translator;
87 import net.sf.openrocket.logging.LogHelper;
88 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
89 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
90 import net.sf.openrocket.rocketcomponent.Rocket;
91 import net.sf.openrocket.rocketcomponent.RocketComponent;
92 import net.sf.openrocket.rocketcomponent.Stage;
93 import net.sf.openrocket.startup.Application;
94 import net.sf.openrocket.util.BugException;
95 import net.sf.openrocket.util.GUIUtil;
96 import net.sf.openrocket.util.Icons;
97 import net.sf.openrocket.util.MemoryManagement;
98 import net.sf.openrocket.util.MemoryManagement.MemoryData;
99 import net.sf.openrocket.util.OpenFileWorker;
100 import net.sf.openrocket.util.Prefs;
101 import net.sf.openrocket.util.Reflection;
102 import net.sf.openrocket.util.SaveFileWorker;
103 import net.sf.openrocket.util.TestRockets;
105 public class BasicFrame extends JFrame {
106 private static final LogHelper log = Application.getLogger();
109 * The RocketLoader instance used for loading all rocket designs.
111 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
113 private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
115 private static final Translator trans = Application.getTranslator();
117 // FileFilters for different types of rocket design files
118 private static final FileFilter ALL_DESIGNS_FILTER =
119 //// All rocket designs (*.ork; *.rkt)
120 new SimpleFileFilter(trans.get("BasicFrame.SimpleFileFilter1"),
121 ".ork", ".ork.gz", ".rkt", ".rkt.gz");
123 private static final FileFilter OPENROCKET_DESIGN_FILTER =
124 //// OpenRocket designs (*.ork)
125 new SimpleFileFilter(trans.get("BasicFrame.SimpleFileFilter2"), ".ork", ".ork.gz");
127 private static final FileFilter ROCKSIM_DESIGN_FILTER =
128 //// RockSim designs (*.rkt)
129 new SimpleFileFilter(trans.get("BasicFrame.SimpleFileFilter3"), ".rkt", ".rkt.gz");
134 public static final int COMPONENT_TAB = 0;
135 public static final int SIMULATION_TAB = 1;
139 * List of currently open frames. When the list goes empty
140 * it is time to exit the application.
142 private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
149 * Whether "New" and "Open" should replace this frame.
150 * Should be set to false on the first rocket modification.
152 private boolean replaceable = false;
156 private final OpenRocketDocument document;
157 private final Rocket rocket;
159 private JTabbedPane tabbedPane;
160 private RocketPanel rocketpanel;
161 private ComponentTree tree = null;
163 private final DocumentSelectionModel selectionModel;
164 private final TreeSelectionModel componentSelectionModel;
165 private final ListSelectionModel simulationSelectionModel;
167 /** Actions available for rocket modifications */
168 private final RocketActions actions;
173 * Sole constructor. Creates a new frame based on the supplied document
174 * and adds it to the current frames list.
176 * @param document the document to show.
178 public BasicFrame(OpenRocketDocument document) {
179 log.debug("Instantiating new BasicFrame");
181 this.document = document;
182 this.rocket = document.getRocket();
183 this.rocket.getDefaultConfiguration().setAllStages();
186 // Set replaceable flag to false at first modification
187 rocket.addComponentChangeListener(new ComponentChangeListener() {
189 public void componentChanged(ComponentChangeEvent e) {
191 BasicFrame.this.rocket.removeComponentChangeListener(this);
196 // Create the component tree selection model that will be used
197 componentSelectionModel = new DefaultTreeSelectionModel();
198 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
200 // Obtain the simulation selection model that will be used
201 SimulationPanel simulationPanel = new SimulationPanel(document);
202 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
204 // Combine into a DocumentSelectionModel
205 selectionModel = new DocumentSelectionModel(document);
206 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
207 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
210 actions = new RocketActions(document, selectionModel, this);
213 log.debug("Constructing the BasicFrame UI");
215 // The main vertical split pane
216 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
217 vertical.setResizeWeight(0.5);
221 // The top tabbed pane
222 tabbedPane = new JTabbedPane();
224 tabbedPane.addTab(trans.get("BasicFrame.tab.Rocketdesign"), null, designTab());
225 //// Flight simulations
226 tabbedPane.addTab(trans.get("BasicFrame.tab.Flightsim"), null, simulationPanel);
228 vertical.setTopComponent(tabbedPane);
232 // Bottom segment, rocket figure
234 rocketpanel = new RocketPanel(document);
235 vertical.setBottomComponent(rocketpanel);
237 rocketpanel.setSelectionModel(tree.getSelectionModel());
243 rocket.addComponentChangeListener(new ComponentChangeListener() {
245 public void componentChanged(ComponentChangeEvent e) {
253 Dimension size = Prefs.getWindowSize(this.getClass());
255 size = Toolkit.getDefaultToolkit().getScreenSize();
256 size.width = size.width * 9 / 10;
257 size.height = size.height * 9 / 10;
260 this.addComponentListener(new ComponentAdapter() {
262 public void componentResized(ComponentEvent e) {
263 Prefs.setWindowSize(BasicFrame.this.getClass(), BasicFrame.this.getSize());
266 this.setLocationByPlatform(true);
268 GUIUtil.setWindowIcons(this);
271 vertical.setDividerLocation(0.4);
272 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
273 addWindowListener(new WindowAdapter() {
275 public void windowClosing(WindowEvent e) {
281 log.debug("BasicFrame instantiation complete");
286 * Construct the "Rocket design" tab. This contains a horizontal split pane
287 * with the left component the design tree and the right component buttons
288 * for adding components.
290 private JComponent designTab() {
291 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
292 horizontal.setResizeWeight(0.5);
295 // Upper-left segment, component tree
297 JPanel panel = new JPanel(new MigLayout("fill, flowy", "", "[grow]"));
299 tree = new ComponentTree(document);
300 tree.setSelectionModel(componentSelectionModel);
302 // Remove JTree key events that interfere with menu accelerators
303 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
304 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
305 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
306 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
307 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
308 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
309 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
310 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
314 // Double-click opens config dialog
315 MouseListener ml = new MouseAdapter() {
317 public void mousePressed(MouseEvent e) {
318 int selRow = tree.getRowForLocation(e.getX(), e.getY());
319 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
321 if ((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
323 RocketComponent c = (RocketComponent) selPath.getLastPathComponent();
324 ComponentConfigDialog.showDialog(BasicFrame.this,
325 BasicFrame.this.document, c);
330 tree.addMouseListener(ml);
332 // Update dialog when selection is changed
333 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
335 public void valueChanged(TreeSelectionEvent e) {
336 // Scroll tree to the selected item
337 TreePath path = componentSelectionModel.getSelectionPath();
340 tree.scrollPathToVisible(path);
342 if (!ComponentConfigDialog.isDialogVisible())
344 RocketComponent c = (RocketComponent) path.getLastPathComponent();
345 ComponentConfigDialog.showDialog(BasicFrame.this,
346 BasicFrame.this.document, c);
350 // Place tree inside scroll pane
351 JScrollPane scroll = new JScrollPane(tree);
352 panel.add(scroll, "spany, grow, wrap");
356 JButton button = new JButton(actions.getMoveUpAction());
357 panel.add(button, "sizegroup buttons, aligny 65%");
359 button = new JButton(actions.getMoveDownAction());
360 panel.add(button, "sizegroup buttons, aligny 0%");
362 button = new JButton(actions.getEditAction());
363 panel.add(button, "sizegroup buttons");
365 button = new JButton(actions.getNewStageAction());
366 panel.add(button, "sizegroup buttons");
368 button = new JButton(actions.getDeleteAction());
369 button.setIcon(null);
370 button.setMnemonic(0);
371 panel.add(button, "sizegroup buttons");
373 horizontal.setLeftComponent(panel);
376 // Upper-right segment, component addition buttons
378 panel = new JPanel(new MigLayout("fill, insets 0", "[0::]"));
380 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
381 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
382 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
383 scroll.getViewport()));
384 scroll.setBorder(null);
385 scroll.setViewportBorder(null);
387 TitledBorder border = new TitledBorder(trans.get("BasicFrame.title.Addnewcomp"));
388 border.setTitleFont(border.getTitleFont().deriveFont(Font.BOLD));
389 scroll.setBorder(border);
391 panel.add(scroll, "grow");
393 horizontal.setRightComponent(panel);
401 * Return the currently selected rocket component, or <code>null</code> if none selected.
403 private RocketComponent getSelectedComponent() {
404 TreePath path = componentSelectionModel.getSelectionPath();
407 tree.scrollPathToVisible(path);
409 return (RocketComponent) path.getLastPathComponent();
414 * Creates the menu for the window.
416 private void createMenu() {
417 JMenuBar menubar = new JMenuBar();
422 menu = new JMenu(trans.get("main.menu.file"));
423 menu.setMnemonic(KeyEvent.VK_F);
424 //// File-handling related tasks
425 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.desc"));
429 item = new JMenuItem(trans.get("main.menu.file.new"), KeyEvent.VK_N);
430 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
431 item.setMnemonic(KeyEvent.VK_N);
432 //// Create a new rocket design
433 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.new.desc"));
434 item.setIcon(Icons.FILE_NEW);
435 item.addActionListener(new ActionListener() {
437 public void actionPerformed(ActionEvent e) {
438 log.user("New... selected");
441 log.info("Closing previous window");
449 item = new JMenuItem(trans.get("main.menu.file.open"), KeyEvent.VK_O);
450 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
451 //// Open a rocket design
452 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openrocketdesign"));
453 item.setIcon(Icons.FILE_OPEN);
454 item.addActionListener(new ActionListener() {
456 public void actionPerformed(ActionEvent e) {
457 log.user("Open... selected");
464 item = new JMenuItem(trans.get("main.menu.file.openExample"));
465 //// Open an example rocket design
466 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openexamplerocketdesign"));
467 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
468 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
469 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
470 item.addActionListener(new ActionListener() {
472 public void actionPerformed(ActionEvent e) {
473 log.user("Open example... selected");
474 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
477 log.user("Opening example " + u);
478 open(u, BasicFrame.this);
488 item = new JMenuItem(trans.get("main.menu.file.save"), KeyEvent.VK_S);
489 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
490 //// Save the current rocket design
491 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesign"));
492 item.setIcon(Icons.FILE_SAVE);
493 item.addActionListener(new ActionListener() {
495 public void actionPerformed(ActionEvent e) {
496 log.user("Save selected");
503 item = new JMenuItem(trans.get("main.menu.file.saveAs"), KeyEvent.VK_A);
504 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
505 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
506 //// Save the current rocket design to a new file
507 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesnewfile"));
508 item.setIcon(Icons.FILE_SAVE_AS);
509 item.addActionListener(new ActionListener() {
511 public void actionPerformed(ActionEvent e) {
512 log.user("Save as... selected");
519 item = new JMenuItem(trans.get("main.menu.file.print"), KeyEvent.VK_P);
520 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
521 //// Print parts list and fin template
522 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.print.desc"));
523 item.setIcon(Icons.FILE_PRINT);
524 item.addActionListener(new ActionListener() {
526 public void actionPerformed(ActionEvent e) {
527 log.user("Print action selected");
537 item = new JMenuItem(trans.get("main.menu.file.close"), KeyEvent.VK_C);
538 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
539 //// Close the current rocket design
540 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Closedesign"));
541 item.setIcon(Icons.FILE_CLOSE);
542 item.addActionListener(new ActionListener() {
544 public void actionPerformed(ActionEvent e) {
545 log.user("Close selected");
554 item = new JMenuItem(trans.get("main.menu.file.quit"), KeyEvent.VK_Q);
555 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
556 //// Quit the program
557 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Quitprogram"));
558 item.setIcon(Icons.FILE_QUIT);
559 item.addActionListener(new ActionListener() {
561 public void actionPerformed(ActionEvent e) {
562 log.user("Quit selected");
571 menu = new JMenu(trans.get("main.menu.edit"));
572 menu.setMnemonic(KeyEvent.VK_E);
574 menu.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.menu.Rocketedt"));
578 Action action = document.getUndoAction();
579 item = new JMenuItem(action);
580 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
581 item.setMnemonic(KeyEvent.VK_U);
582 //// Undo the previous operation
583 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.undo.desc"));
587 action = document.getRedoAction();
588 item = new JMenuItem(action);
589 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
590 item.setMnemonic(KeyEvent.VK_R);
591 //// Redo the previously undone operation
592 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.redo.desc"));
598 item = new JMenuItem(actions.getCutAction());
601 item = new JMenuItem(actions.getCopyAction());
604 item = new JMenuItem(actions.getPasteAction());
607 item = new JMenuItem(actions.getDeleteAction());
614 item = new JMenuItem(trans.get("main.menu.edit.resize"));
616 //item.setIcon(Icons.PREFERENCES);
617 //// Setup the application preferences
618 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.resize.desc"));
619 item.addActionListener(new ActionListener() {
621 public void actionPerformed(ActionEvent e) {
622 log.user("Scale... selected");
623 ScaleDialog dialog = new ScaleDialog(document, getSelectedComponent(), BasicFrame.this);
624 dialog.setVisible(true);
633 item = new JMenuItem(trans.get("main.menu.edit.preferences"));
634 item.setIcon(Icons.PREFERENCES);
635 //// Setup the application preferences
636 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.preferences.desc"));
637 item.addActionListener(new ActionListener() {
639 public void actionPerformed(ActionEvent e) {
640 log.user("Preferences selected");
641 PreferencesDialog.showPreferences();
650 menu = new JMenu(trans.get("main.menu.analyze"));
651 menu.setMnemonic(KeyEvent.VK_A);
652 //// Analyzing the rocket
653 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.desc"));
656 //// Component analysis
657 item = new JMenuItem(trans.get("main.menu.analyze.componentAnalysis"), KeyEvent.VK_C);
658 //// Analyze the rocket components separately
659 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.componentAnalysis.desc"));
660 item.addActionListener(new ActionListener() {
662 public void actionPerformed(ActionEvent e) {
663 log.user("Component analysis selected");
664 ComponentAnalysisDialog.showDialog(rocketpanel);
671 // (shown if openrocket.debug.menu is defined)
672 if (System.getProperty("openrocket.debug.menu") != null) {
673 menubar.add(makeDebugMenu());
680 menu = new JMenu(trans.get("main.menu.help"));
681 menu.setMnemonic(KeyEvent.VK_H);
682 //// Information about OpenRocket
683 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.desc"));
688 item = new JMenuItem(trans.get("main.menu.help.license"), KeyEvent.VK_L);
689 //// OpenRocket license information
690 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.license.desc"));
691 item.addActionListener(new ActionListener() {
693 public void actionPerformed(ActionEvent e) {
694 log.user("License selected");
695 new LicenseDialog(BasicFrame.this).setVisible(true);
703 item = new JMenuItem(trans.get("main.menu.help.bugReport"), KeyEvent.VK_B);
704 //// Information about reporting bugs in OpenRocket
705 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.bugReport.desc"));
706 item.addActionListener(new ActionListener() {
708 public void actionPerformed(ActionEvent e) {
709 log.user("Bug report selected");
710 BugReportDialog.showBugReportDialog(BasicFrame.this);
716 item = new JMenuItem(trans.get("main.menu.help.debugLog"));
717 //// View the OpenRocket debug log
718 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.debugLog.desc"));
719 item.addActionListener(new ActionListener() {
721 public void actionPerformed(ActionEvent e) {
722 log.user("Debug log selected");
723 new DebugLogDialog(BasicFrame.this).setVisible(true);
731 item = new JMenuItem(trans.get("main.menu.help.about"), KeyEvent.VK_A);
732 //// About OpenRocket
733 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.about.desc"));
734 item.addActionListener(new ActionListener() {
736 public void actionPerformed(ActionEvent e) {
737 log.user("About selected");
738 new AboutDialog(BasicFrame.this).setVisible(true);
744 this.setJMenuBar(menubar);
747 private JMenu makeDebugMenu() {
752 * This menu is intentionally left untranslated.
756 menu = new JMenu("Debug");
757 //// OpenRocket debugging tasks
758 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
760 //// What is this menu?
761 item = new JMenuItem("What is this menu?");
762 item.addActionListener(new ActionListener() {
764 public void actionPerformed(ActionEvent e) {
765 log.user("What is this menu? selected");
766 JOptionPane.showMessageDialog(BasicFrame.this,
768 "The 'Debug' menu includes actions for testing and debugging " +
770 "The menu is made visible by defining the system property " +
771 "'openrocket.debug.menu' when starting OpenRocket.",
772 "It should not be visible by default." },
773 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
780 //// Create test rocket
781 item = new JMenuItem("Create test rocket");
782 item.addActionListener(new ActionListener() {
784 public void actionPerformed(ActionEvent e) {
785 log.user("Create test rocket selected");
786 JTextField field = new JTextField();
787 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
788 "Input text key to generate random rocket:",
790 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
791 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
797 r = new TestRockets(null).makeTestRocket();
798 } else if (sel == 1) {
799 r = new TestRockets(field.getText()).makeTestRocket();
804 OpenRocketDocument doc = new OpenRocketDocument(r);
806 BasicFrame frame = new BasicFrame(doc);
807 frame.setVisible(true);
814 item = new JMenuItem("Create 'Iso-Haisu'");
815 item.addActionListener(new ActionListener() {
817 public void actionPerformed(ActionEvent e) {
818 log.user("Create Iso-Haisu selected");
819 Rocket r = TestRockets.makeIsoHaisu();
820 OpenRocketDocument doc = new OpenRocketDocument(r);
822 BasicFrame frame = new BasicFrame(doc);
823 frame.setVisible(true);
829 item = new JMenuItem("Create 'Big Blue'");
830 item.addActionListener(new ActionListener() {
832 public void actionPerformed(ActionEvent e) {
833 log.user("Create Big Blue selected");
834 Rocket r = TestRockets.makeBigBlue();
835 OpenRocketDocument doc = new OpenRocketDocument(r);
837 BasicFrame frame = new BasicFrame(doc);
838 frame.setVisible(true);
846 item = new JMenuItem("Memory statistics");
847 item.addActionListener(new ActionListener() {
849 public void actionPerformed(ActionEvent e) {
850 log.user("Memory statistics selected");
852 // Get discarded but remaining objects (this also runs System.gc multiple times)
853 List<MemoryData> objects = MemoryManagement.getRemainingCollectableObjects();
854 StringBuilder sb = new StringBuilder();
855 sb.append("Objects that should have been garbage-collected but have not been:\n");
857 for (MemoryData data : objects) {
858 Object o = data.getReference().get();
861 sb.append("Age ").append(System.currentTimeMillis() - data.getRegistrationTime())
862 .append(" ms: ").append(o).append('\n');
864 // Explicitly null the strong reference to avoid possibility of invisible references
867 sb.append("Total: " + count);
869 // Get basic memory stats
871 long max = Runtime.getRuntime().maxMemory();
872 long free = Runtime.getRuntime().freeMemory();
873 long used = max - free;
874 String[] stats = new String[4];
875 stats[0] = "Memory usage:";
876 stats[1] = String.format(" Max memory: %.1f MB", max / 1024.0 / 1024.0);
877 stats[2] = String.format(" Used memory: %.1f MB (%.0f%%)", used / 1024.0 / 1024.0, 100.0 * used / max);
878 stats[3] = String.format(" Free memory: %.1f MB (%.0f%%)", free / 1024.0 / 1024.0, 100.0 * free / max);
881 DetailDialog.showDetailedMessageDialog(BasicFrame.this, stats, sb.toString(),
882 "Memory statistics", JOptionPane.INFORMATION_MESSAGE);
888 item = new JMenuItem("Exhaust memory");
889 item.addActionListener(new ActionListener() {
891 public void actionPerformed(ActionEvent e) {
892 log.user("Exhaust memory selected");
893 LinkedList<byte[]> data = new LinkedList<byte[]>();
895 final int bytesPerArray = 10240;
898 byte[] array = new byte[bytesPerArray];
899 for (int i = 0; i < bytesPerArray; i++) {
905 } catch (OutOfMemoryError error) {
907 long size = bytesPerArray * (long) count;
908 String s = String.format("OutOfMemory occurred after %d iterations (approx. %.1f MB consumed)",
909 count, size / 1024.0 / 1024.0);
911 JOptionPane.showMessageDialog(BasicFrame.this, s);
921 item = new JMenuItem("Exception here");
922 item.addActionListener(new ActionListener() {
924 public void actionPerformed(ActionEvent e) {
925 log.user("Exception here selected");
926 throw new RuntimeException("Testing exception from menu action listener");
931 item = new JMenuItem("Exception from EDT");
932 item.addActionListener(new ActionListener() {
934 public void actionPerformed(ActionEvent e) {
935 log.user("Exception from EDT selected");
936 SwingUtilities.invokeLater(new Runnable() {
939 throw new RuntimeException("Testing exception from " +
940 "later invoked EDT thread");
947 item = new JMenuItem("Exception from other thread");
948 item.addActionListener(new ActionListener() {
950 public void actionPerformed(ActionEvent e) {
951 log.user("Exception from other thread selected");
955 throw new RuntimeException("Testing exception from newly created thread");
962 item = new JMenuItem("OutOfMemoryError here");
963 item.addActionListener(new ActionListener() {
965 public void actionPerformed(ActionEvent e) {
966 log.user("OutOfMemoryError here selected");
967 throw new OutOfMemoryError("Testing OutOfMemoryError from menu action listener");
973 item = new JMenuItem("General optimization test");
974 item.addActionListener(new ActionListener() {
976 public void actionPerformed(ActionEvent e) {
977 new GeneralOptimizationDialog(document, BasicFrame.this).setVisible(true);
983 item = new JMenuItem("Optimization test");
984 item.addActionListener(new ActionListener() {
986 public void actionPerformed(ActionEvent e) {
987 new OptimizationTestDialog(BasicFrame.this, document).setVisible(true);
997 * Select the tab on the main pane.
999 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
1001 public void selectTab(int tab) {
1002 tabbedPane.setSelectedIndex(tab);
1007 private void openAction() {
1008 JFileChooser chooser = new JFileChooser();
1010 chooser.addChoosableFileFilter(ALL_DESIGNS_FILTER);
1011 chooser.addChoosableFileFilter(OPENROCKET_DESIGN_FILTER);
1012 chooser.addChoosableFileFilter(ROCKSIM_DESIGN_FILTER);
1013 chooser.setFileFilter(ALL_DESIGNS_FILTER);
1015 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
1016 chooser.setMultiSelectionEnabled(true);
1017 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
1018 int option = chooser.showOpenDialog(this);
1019 if (option != JFileChooser.APPROVE_OPTION) {
1020 log.user("Decided not to open files, option=" + option);
1024 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
1026 File[] files = chooser.getSelectedFiles();
1027 log.user("Opening files " + Arrays.toString(files));
1029 for (File file : files) {
1030 log.info("Opening file: " + file);
1031 if (open(file, this)) {
1033 // Close previous window if replacing
1034 if (replaceable && document.isSaved()) {
1035 log.info("Closing window because it is replaceable");
1037 replaceable = false;
1045 * Open a file based on a URL.
1046 * @param url the file to open.
1047 * @param parent the parent window for dialogs.
1048 * @return <code>true</code> if opened successfully.
1050 private static boolean open(URL url, BasicFrame parent) {
1051 String filename = null;
1053 // First figure out the file name from the URL
1055 // Try using URI.getPath();
1057 URI uri = url.toURI();
1058 filename = uri.getPath();
1059 } catch (URISyntaxException ignore) {
1062 // Try URL-decoding the URL
1063 if (filename == null) {
1065 filename = URLDecoder.decode(url.toString(), "UTF-8");
1066 } catch (UnsupportedEncodingException ignore) {
1071 if (filename == null) {
1075 // Remove path from filename
1076 if (filename.lastIndexOf('/') >= 0) {
1077 filename = filename.substring(filename.lastIndexOf('/') + 1);
1082 log.info("Opening file from url=" + url + " filename=" + filename);
1084 InputStream is = url.openStream();
1085 if (open(is, filename, parent)) {
1086 // Close previous window if replacing
1087 if (parent.replaceable && parent.document.isSaved()) {
1088 parent.closeAction();
1089 parent.replaceable = false;
1092 } catch (IOException e) {
1093 log.warn("Error opening file" + e);
1094 JOptionPane.showMessageDialog(parent,
1095 "An error occurred while opening the file " + filename,
1096 "Error loading file", JOptionPane.ERROR_MESSAGE);
1104 * Open the specified file from an InputStream in a new design frame. If an error
1105 * occurs, an error dialog is shown and <code>false</code> is returned.
1107 * @param stream the stream to load from.
1108 * @param filename the file name to display in dialogs (not set to the document).
1109 * @param parent the parent component for which a progress dialog is opened.
1110 * @return whether the file was successfully loaded and opened.
1112 private static boolean open(InputStream stream, String filename, Window parent) {
1113 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
1114 return open(worker, filename, null, parent);
1119 * Open the specified file in a new design frame. If an error occurs, an error
1120 * dialog is shown and <code>false</code> is returned.
1122 * @param file the file to open.
1123 * @param parent the parent component for which a progress dialog is opened.
1124 * @return whether the file was successfully loaded and opened.
1126 public static boolean open(File file, Window parent) {
1127 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
1128 return open(worker, file.getName(), file, parent);
1133 * Open the specified file using the provided worker.
1135 * @param worker the OpenFileWorker that loads the file.
1136 * @param filename the file name to display in dialogs.
1137 * @param file the File to set the document to (may be null).
1141 private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) {
1143 MotorDatabaseLoadingDialog.check(parent);
1145 // Open the file in a Swing worker thread
1146 log.info("Starting OpenFileWorker");
1147 if (!SwingWorkerDialog.runWorker(parent, "Opening file", "Reading " + filename + "...", worker)) {
1148 // User cancelled the operation
1149 log.info("User cancelled the OpenFileWorker");
1154 // Handle the document
1155 OpenRocketDocument doc = null;
1160 } catch (ExecutionException e) {
1162 Throwable cause = e.getCause();
1164 if (cause instanceof FileNotFoundException) {
1166 log.warn("File not found", cause);
1167 JOptionPane.showMessageDialog(parent,
1168 "File not found: " + filename,
1169 "Error opening file", JOptionPane.ERROR_MESSAGE);
1172 } else if (cause instanceof RocketLoadException) {
1174 log.warn("Error loading the file", cause);
1175 JOptionPane.showMessageDialog(parent,
1176 "Unable to open file '" + filename + "': "
1177 + cause.getMessage(),
1178 "Error opening file", JOptionPane.ERROR_MESSAGE);
1183 throw new BugException("Unknown error when opening file", e);
1187 } catch (InterruptedException e) {
1188 throw new BugException("EDT was interrupted", e);
1192 throw new BugException("Document loader returned null");
1197 WarningSet warnings = worker.getRocketLoader().getWarnings();
1198 if (!warnings.isEmpty()) {
1199 log.info("Warnings while reading file: " + warnings);
1200 WarningDialog.showWarnings(parent,
1202 //// The following problems were encountered while opening
1203 trans.get("BasicFrame.WarningDialog.txt1") + " " + filename + ".",
1204 //// Some design features may not have been loaded correctly.
1205 trans.get("BasicFrame.WarningDialog.txt2")
1207 //// Warnings while opening file
1208 trans.get("BasicFrame.WarningDialog.title"), warnings);
1212 // Set document state
1217 log.debug("Opening new frame with the document");
1218 BasicFrame frame = new BasicFrame(doc);
1219 frame.setVisible(true);
1228 private boolean saveAction() {
1229 File file = document.getFile();
1231 log.info("Document does not contain file, opening save as dialog instead");
1232 return saveAsAction();
1234 log.info("Saving document to " + file);
1236 // Saving RockSim designs is not supported
1237 if (ROCKSIM_DESIGN_FILTER.accept(file)) {
1238 file = new File(file.getAbsolutePath().replaceAll(".[rR][kK][tT](.[gG][zZ])?$",
1241 log.info("Attempting to save in RockSim format, renaming to " + file);
1242 int option = JOptionPane.showConfirmDialog(this, new Object[] {
1243 "Saving designs in RockSim format is not supported.",
1244 "Save in OpenRocket format instead (" + file.getName() + ")?"
1245 }, "Save " + file.getName(), JOptionPane.YES_NO_OPTION,
1246 JOptionPane.QUESTION_MESSAGE, null);
1247 if (option != JOptionPane.YES_OPTION) {
1248 log.user("User chose not to save");
1252 document.setFile(file);
1254 return saveAs(file);
1258 private boolean saveAsAction() {
1261 // TODO: HIGH: what if *.rkt chosen?
1262 StorageOptionChooser storageChooser =
1263 new StorageOptionChooser(document, document.getDefaultStorageOptions());
1264 JFileChooser chooser = new JFileChooser();
1265 chooser.setFileFilter(OPENROCKET_DESIGN_FILTER);
1266 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
1267 chooser.setAccessory(storageChooser);
1268 if (document.getFile() != null)
1269 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 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
1284 storageChooser.storeOptions(document.getDefaultStorageOptions());
1286 if (file.getName().indexOf('.') < 0) {
1287 log.debug("File name does not contain extension, adding .ork");
1288 String name = file.getAbsolutePath();
1289 name = name + ".ork";
1290 file = new File(name);
1293 if (file.exists()) {
1294 log.info("File " + file + " exists, confirming overwrite from user");
1295 int result = JOptionPane.showConfirmDialog(this,
1296 "File '" + file.getName() + "' exists. Do you want to overwrite it?",
1297 "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
1298 if (result != JOptionPane.YES_OPTION) {
1299 log.user("User decided not to overwrite the file");
1304 return saveAs(file);
1307 private boolean saveAs(File file) {
1308 log.info("Saving document as " + file);
1309 boolean saved = false;
1311 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1312 // User cancelled the dialog
1313 log.user("User cancelled saving in storage options dialog");
1318 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1320 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1321 "Writing " + file.getName() + "...", worker)) {
1323 // User cancelled the save
1324 log.user("User cancelled the save, deleting the file");
1331 document.setFile(file);
1332 document.setSaved(true);
1335 } catch (ExecutionException e) {
1337 Throwable cause = e.getCause();
1339 if (cause instanceof IOException) {
1340 log.warn("An I/O error occurred while saving " + file, cause);
1341 JOptionPane.showMessageDialog(this, new String[] {
1342 "An I/O error occurred while saving:",
1343 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1346 Reflection.handleWrappedException(e);
1349 } catch (InterruptedException e) {
1350 throw new BugException("EDT was interrupted", e);
1357 private boolean closeAction() {
1358 if (!document.isSaved()) {
1359 log.info("Confirming whether to save the design");
1360 ComponentConfigDialog.hideDialog();
1361 int result = JOptionPane.showConfirmDialog(this,
1362 trans.get("BasicFrame.dlg.lbl1") + rocket.getName() +
1363 trans.get("BasicFrame.dlg.lbl2") + " " +
1364 trans.get("BasicFrame.dlg.lbl3"),
1365 trans.get("BasicFrame.dlg.title"), JOptionPane.YES_NO_CANCEL_OPTION,
1366 JOptionPane.QUESTION_MESSAGE);
1367 if (result == JOptionPane.YES_OPTION) {
1369 log.user("User requested file save");
1370 if (!saveAction()) {
1371 log.info("File save was interrupted, not closing");
1374 } else if (result == JOptionPane.NO_OPTION) {
1375 // Don't save: No-op
1376 log.user("User requested to discard design");
1379 log.user("User cancelled closing, result=" + result);
1384 // Rocket has been saved or discarded
1385 log.debug("Disposing window");
1388 ComponentConfigDialog.hideDialog();
1389 ComponentAnalysisDialog.hideDialog();
1391 frames.remove(this);
1392 if (frames.isEmpty()) {
1393 log.info("Last frame closed, exiting");
1404 public void printAction() {
1405 if (!Prefs.getBoolean("printing.experimental.communicated", false)) {
1406 log.info("Showing printing is experimental warning to the user");
1407 JOptionPane.showMessageDialog(this, "Printing is an currently an experimental feature " +
1408 "and might not fully work on all platforms",
1409 "Experimental feature", JOptionPane.WARNING_MESSAGE);
1410 Prefs.putBoolean("printing.experimental.communicated", true);
1412 new PrintDialog(this, document).setVisible(true);
1416 * Open a new design window with a basic rocket+stage.
1418 public static void newAction() {
1419 log.info("New action initiated");
1421 Rocket rocket = new Rocket();
1422 Stage stage = new Stage();
1424 stage.setName(trans.get("BasicFrame.StageName.Sustainer"));
1425 rocket.addChild(stage);
1426 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1429 BasicFrame frame = new BasicFrame(doc);
1430 frame.replaceable = true;
1431 frame.setVisible(true);
1432 ComponentConfigDialog.showDialog(frame, doc, rocket);
1436 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1438 public static void quitAction() {
1439 log.info("Quit action initiated");
1440 for (int i = frames.size() - 1; i >= 0; i--) {
1441 log.debug("Closing frame " + frames.get(i));
1442 if (!frames.get(i).closeAction()) {
1444 log.info("Quit was cancelled");
1448 // Should not be reached, but just in case
1449 log.error("Should already have exited application");
1455 * Set the title of the frame, taking into account the name of the rocket, file it
1456 * has been saved to (if any) and saved status.
1458 private void setTitle() {
1459 File file = document.getFile();
1460 boolean saved = document.isSaved();
1463 title = rocket.getName();
1465 title = title + " (" + file.getName() + ")";
1468 title = "*" + title;
1476 * Find a currently open BasicFrame containing the specified rocket. This method
1477 * can be used to map a Rocket to a BasicFrame from GUI methods.
1479 * @param rocket the Rocket.
1480 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1482 public static BasicFrame findFrame(Rocket rocket) {
1483 for (BasicFrame f : frames) {
1484 if (f.rocket == rocket) {
1485 log.debug("Found frame " + f + " for rocket " + rocket);
1489 log.debug("Could not find frame for rocket " + rocket);
1494 * Find a currently open document by the rocket object. This method can be used
1495 * to map a Rocket to OpenRocketDocument from GUI methods.
1497 * @param rocket the Rocket.
1498 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1500 public static OpenRocketDocument findDocument(Rocket rocket) {
1501 BasicFrame frame = findFrame(rocket);
1502 if (frame != null) {
1503 return frame.document;