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.tree.DefaultTreeSelectionModel;
55 import javax.swing.tree.TreePath;
56 import javax.swing.tree.TreeSelectionModel;
58 import net.miginfocom.swing.MigLayout;
59 import net.sf.openrocket.aerodynamics.WarningSet;
60 import net.sf.openrocket.document.OpenRocketDocument;
61 import net.sf.openrocket.file.GeneralRocketLoader;
62 import net.sf.openrocket.file.RocketLoadException;
63 import net.sf.openrocket.file.RocketLoader;
64 import net.sf.openrocket.file.RocketSaver;
65 import net.sf.openrocket.file.openrocket.OpenRocketSaver;
66 import net.sf.openrocket.gui.StorageOptionChooser;
67 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
68 import net.sf.openrocket.gui.dialogs.AboutDialog;
69 import net.sf.openrocket.gui.dialogs.BugReportDialog;
70 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
71 import net.sf.openrocket.gui.dialogs.DebugLogDialog;
72 import net.sf.openrocket.gui.dialogs.DetailDialog;
73 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
74 import net.sf.openrocket.gui.dialogs.LicenseDialog;
75 import net.sf.openrocket.gui.dialogs.MotorDatabaseLoadingDialog;
76 import net.sf.openrocket.gui.dialogs.PrintDialog;
77 import net.sf.openrocket.gui.dialogs.ScaleDialog;
78 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
79 import net.sf.openrocket.gui.dialogs.WarningDialog;
80 import net.sf.openrocket.gui.dialogs.optimization.GeneralOptimizationDialog;
81 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
82 import net.sf.openrocket.gui.main.componenttree.ComponentTree;
83 import net.sf.openrocket.gui.optimization.OptimizationTestDialog;
84 import net.sf.openrocket.gui.scalefigure.RocketPanel;
85 import net.sf.openrocket.l10n.Translator;
86 import net.sf.openrocket.logging.LogHelper;
87 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
88 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
89 import net.sf.openrocket.rocketcomponent.Rocket;
90 import net.sf.openrocket.rocketcomponent.RocketComponent;
91 import net.sf.openrocket.rocketcomponent.Stage;
92 import net.sf.openrocket.startup.Application;
93 import net.sf.openrocket.util.BugException;
94 import net.sf.openrocket.util.FileHelper;
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 public static final int COMPONENT_TAB = 0;
118 public static final int SIMULATION_TAB = 1;
122 * List of currently open frames. When the list goes empty
123 * it is time to exit the application.
125 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 = new TitledBorder(trans.get("BasicFrame.title.Addnewcomp"));
371 border.setTitleFont(border.getTitleFont().deriveFont(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);
652 // (shown if openrocket.debug.menu is defined)
653 if (System.getProperty("openrocket.debug.menu") != null) {
654 menubar.add(makeDebugMenu());
661 menu = new JMenu(trans.get("main.menu.help"));
662 menu.setMnemonic(KeyEvent.VK_H);
663 //// Information about OpenRocket
664 menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.desc"));
669 item = new JMenuItem(trans.get("main.menu.help.license"), KeyEvent.VK_L);
670 //// OpenRocket license information
671 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.license.desc"));
672 item.addActionListener(new ActionListener() {
674 public void actionPerformed(ActionEvent e) {
675 log.user("License selected");
676 new LicenseDialog(BasicFrame.this).setVisible(true);
684 item = new JMenuItem(trans.get("main.menu.help.bugReport"), KeyEvent.VK_B);
685 //// Information about reporting bugs in OpenRocket
686 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.bugReport.desc"));
687 item.addActionListener(new ActionListener() {
689 public void actionPerformed(ActionEvent e) {
690 log.user("Bug report selected");
691 BugReportDialog.showBugReportDialog(BasicFrame.this);
697 item = new JMenuItem(trans.get("main.menu.help.debugLog"));
698 //// View the OpenRocket debug log
699 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.debugLog.desc"));
700 item.addActionListener(new ActionListener() {
702 public void actionPerformed(ActionEvent e) {
703 log.user("Debug log selected");
704 new DebugLogDialog(BasicFrame.this).setVisible(true);
712 item = new JMenuItem(trans.get("main.menu.help.about"), KeyEvent.VK_A);
713 //// About OpenRocket
714 item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.about.desc"));
715 item.addActionListener(new ActionListener() {
717 public void actionPerformed(ActionEvent e) {
718 log.user("About selected");
719 new AboutDialog(BasicFrame.this).setVisible(true);
725 this.setJMenuBar(menubar);
728 private JMenu makeDebugMenu() {
733 * This menu is intentionally left untranslated.
737 menu = new JMenu("Debug");
738 //// OpenRocket debugging tasks
739 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
741 //// What is this menu?
742 item = new JMenuItem("What is this menu?");
743 item.addActionListener(new ActionListener() {
745 public void actionPerformed(ActionEvent e) {
746 log.user("What is this menu? selected");
747 JOptionPane.showMessageDialog(BasicFrame.this,
749 "The 'Debug' menu includes actions for testing and debugging " +
751 "The menu is made visible by defining the system property " +
752 "'openrocket.debug.menu' when starting OpenRocket.",
753 "It should not be visible by default." },
754 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
761 //// Create test rocket
762 item = new JMenuItem("Create test rocket");
763 item.addActionListener(new ActionListener() {
765 public void actionPerformed(ActionEvent e) {
766 log.user("Create test rocket selected");
767 JTextField field = new JTextField();
768 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
769 "Input text key to generate random rocket:",
771 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
772 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
778 r = new TestRockets(null).makeTestRocket();
779 } else if (sel == 1) {
780 r = new TestRockets(field.getText()).makeTestRocket();
785 OpenRocketDocument doc = new OpenRocketDocument(r);
787 BasicFrame frame = new BasicFrame(doc);
788 frame.setVisible(true);
795 item = new JMenuItem("Create 'Iso-Haisu'");
796 item.addActionListener(new ActionListener() {
798 public void actionPerformed(ActionEvent e) {
799 log.user("Create Iso-Haisu selected");
800 Rocket r = TestRockets.makeIsoHaisu();
801 OpenRocketDocument doc = new OpenRocketDocument(r);
803 BasicFrame frame = new BasicFrame(doc);
804 frame.setVisible(true);
810 item = new JMenuItem("Create 'Big Blue'");
811 item.addActionListener(new ActionListener() {
813 public void actionPerformed(ActionEvent e) {
814 log.user("Create Big Blue selected");
815 Rocket r = TestRockets.makeBigBlue();
816 OpenRocketDocument doc = new OpenRocketDocument(r);
818 BasicFrame frame = new BasicFrame(doc);
819 frame.setVisible(true);
827 item = new JMenuItem("Memory statistics");
828 item.addActionListener(new ActionListener() {
830 public void actionPerformed(ActionEvent e) {
831 log.user("Memory statistics selected");
833 // Get discarded but remaining objects (this also runs System.gc multiple times)
834 List<MemoryData> objects = MemoryManagement.getRemainingCollectableObjects();
835 StringBuilder sb = new StringBuilder();
836 sb.append("Objects that should have been garbage-collected but have not been:\n");
838 for (MemoryData data : objects) {
839 Object o = data.getReference().get();
842 sb.append("Age ").append(System.currentTimeMillis() - data.getRegistrationTime())
843 .append(" ms: ").append(o).append('\n');
845 // Explicitly null the strong reference to avoid possibility of invisible references
848 sb.append("Total: " + count);
850 // Get basic memory stats
852 long max = Runtime.getRuntime().maxMemory();
853 long free = Runtime.getRuntime().freeMemory();
854 long used = max - free;
855 String[] stats = new String[4];
856 stats[0] = "Memory usage:";
857 stats[1] = String.format(" Max memory: %.1f MB", max / 1024.0 / 1024.0);
858 stats[2] = String.format(" Used memory: %.1f MB (%.0f%%)", used / 1024.0 / 1024.0, 100.0 * used / max);
859 stats[3] = String.format(" Free memory: %.1f MB (%.0f%%)", free / 1024.0 / 1024.0, 100.0 * free / max);
862 DetailDialog.showDetailedMessageDialog(BasicFrame.this, stats, sb.toString(),
863 "Memory statistics", JOptionPane.INFORMATION_MESSAGE);
869 item = new JMenuItem("Exhaust memory");
870 item.addActionListener(new ActionListener() {
872 public void actionPerformed(ActionEvent e) {
873 log.user("Exhaust memory selected");
874 LinkedList<byte[]> data = new LinkedList<byte[]>();
876 final int bytesPerArray = 10240;
879 byte[] array = new byte[bytesPerArray];
880 for (int i = 0; i < bytesPerArray; i++) {
886 } catch (OutOfMemoryError error) {
888 long size = bytesPerArray * (long) count;
889 String s = String.format("OutOfMemory occurred after %d iterations (approx. %.1f MB consumed)",
890 count, size / 1024.0 / 1024.0);
892 JOptionPane.showMessageDialog(BasicFrame.this, s);
902 item = new JMenuItem("Exception here");
903 item.addActionListener(new ActionListener() {
905 public void actionPerformed(ActionEvent e) {
906 log.user("Exception here selected");
907 throw new RuntimeException("Testing exception from menu action listener");
912 item = new JMenuItem("Exception from EDT");
913 item.addActionListener(new ActionListener() {
915 public void actionPerformed(ActionEvent e) {
916 log.user("Exception from EDT selected");
917 SwingUtilities.invokeLater(new Runnable() {
920 throw new RuntimeException("Testing exception from " +
921 "later invoked EDT thread");
928 item = new JMenuItem("Exception from other thread");
929 item.addActionListener(new ActionListener() {
931 public void actionPerformed(ActionEvent e) {
932 log.user("Exception from other thread selected");
936 throw new RuntimeException("Testing exception from newly created thread");
943 item = new JMenuItem("OutOfMemoryError here");
944 item.addActionListener(new ActionListener() {
946 public void actionPerformed(ActionEvent e) {
947 log.user("OutOfMemoryError here selected");
948 throw new OutOfMemoryError("Testing OutOfMemoryError from menu action listener");
954 item = new JMenuItem("General optimization test");
955 item.addActionListener(new ActionListener() {
957 public void actionPerformed(ActionEvent e) {
958 new GeneralOptimizationDialog(document, BasicFrame.this).setVisible(true);
964 item = new JMenuItem("Optimization test");
965 item.addActionListener(new ActionListener() {
967 public void actionPerformed(ActionEvent e) {
968 new OptimizationTestDialog(BasicFrame.this, document).setVisible(true);
978 * Select the tab on the main pane.
980 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
982 public void selectTab(int tab) {
983 tabbedPane.setSelectedIndex(tab);
988 private void openAction() {
989 JFileChooser chooser = new JFileChooser();
991 chooser.addChoosableFileFilter(FileHelper.ALL_DESIGNS_FILTER);
992 chooser.addChoosableFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
993 chooser.addChoosableFileFilter(FileHelper.ROCKSIM_DESIGN_FILTER);
994 chooser.setFileFilter(FileHelper.ALL_DESIGNS_FILTER);
996 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
997 chooser.setMultiSelectionEnabled(true);
998 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
999 int option = chooser.showOpenDialog(this);
1000 if (option != JFileChooser.APPROVE_OPTION) {
1001 log.user("Decided not to open files, option=" + option);
1005 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
1007 File[] files = chooser.getSelectedFiles();
1008 log.user("Opening files " + Arrays.toString(files));
1010 for (File file : files) {
1011 log.info("Opening file: " + file);
1012 if (open(file, this)) {
1014 // Close previous window if replacing
1015 if (replaceable && document.isSaved()) {
1016 log.info("Closing window because it is replaceable");
1018 replaceable = false;
1026 * Open a file based on a URL.
1027 * @param url the file to open.
1028 * @param parent the parent window for dialogs.
1029 * @return <code>true</code> if opened successfully.
1031 private static boolean open(URL url, BasicFrame parent) {
1032 String filename = null;
1034 // First figure out the file name from the URL
1036 // Try using URI.getPath();
1038 URI uri = url.toURI();
1039 filename = uri.getPath();
1040 } catch (URISyntaxException ignore) {
1043 // Try URL-decoding the URL
1044 if (filename == null) {
1046 filename = URLDecoder.decode(url.toString(), "UTF-8");
1047 } catch (UnsupportedEncodingException ignore) {
1052 if (filename == null) {
1056 // Remove path from filename
1057 if (filename.lastIndexOf('/') >= 0) {
1058 filename = filename.substring(filename.lastIndexOf('/') + 1);
1063 log.info("Opening file from url=" + url + " filename=" + filename);
1065 InputStream is = url.openStream();
1066 if (open(is, filename, parent)) {
1067 // Close previous window if replacing
1068 if (parent.replaceable && parent.document.isSaved()) {
1069 parent.closeAction();
1070 parent.replaceable = false;
1073 } catch (IOException e) {
1074 log.warn("Error opening file" + e);
1075 JOptionPane.showMessageDialog(parent,
1076 "An error occurred while opening the file " + filename,
1077 "Error loading file", JOptionPane.ERROR_MESSAGE);
1085 * Open the specified file from an InputStream in a new design frame. If an error
1086 * occurs, an error dialog is shown and <code>false</code> is returned.
1088 * @param stream the stream to load from.
1089 * @param filename the file name to display in dialogs (not set to the document).
1090 * @param parent the parent component for which a progress dialog is opened.
1091 * @return whether the file was successfully loaded and opened.
1093 private static boolean open(InputStream stream, String filename, Window parent) {
1094 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
1095 return open(worker, filename, null, parent);
1100 * Open the specified file in a new design frame. If an error occurs, an error
1101 * dialog is shown and <code>false</code> is returned.
1103 * @param file the file to open.
1104 * @param parent the parent component for which a progress dialog is opened.
1105 * @return whether the file was successfully loaded and opened.
1107 public static boolean open(File file, Window parent) {
1108 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
1109 return open(worker, file.getName(), file, parent);
1114 * Open the specified file using the provided worker.
1116 * @param worker the OpenFileWorker that loads the file.
1117 * @param filename the file name to display in dialogs.
1118 * @param file the File to set the document to (may be null).
1122 private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) {
1124 MotorDatabaseLoadingDialog.check(parent);
1126 // Open the file in a Swing worker thread
1127 log.info("Starting OpenFileWorker");
1128 if (!SwingWorkerDialog.runWorker(parent, "Opening file", "Reading " + filename + "...", worker)) {
1129 // User cancelled the operation
1130 log.info("User cancelled the OpenFileWorker");
1135 // Handle the document
1136 OpenRocketDocument doc = null;
1141 } catch (ExecutionException e) {
1143 Throwable cause = e.getCause();
1145 if (cause instanceof FileNotFoundException) {
1147 log.warn("File not found", cause);
1148 JOptionPane.showMessageDialog(parent,
1149 "File not found: " + filename,
1150 "Error opening file", JOptionPane.ERROR_MESSAGE);
1153 } else if (cause instanceof RocketLoadException) {
1155 log.warn("Error loading the file", cause);
1156 JOptionPane.showMessageDialog(parent,
1157 "Unable to open file '" + filename + "': "
1158 + cause.getMessage(),
1159 "Error opening file", JOptionPane.ERROR_MESSAGE);
1164 throw new BugException("Unknown error when opening file", e);
1168 } catch (InterruptedException e) {
1169 throw new BugException("EDT was interrupted", e);
1173 throw new BugException("Document loader returned null");
1178 WarningSet warnings = worker.getRocketLoader().getWarnings();
1179 if (!warnings.isEmpty()) {
1180 log.info("Warnings while reading file: " + warnings);
1181 WarningDialog.showWarnings(parent,
1183 //// The following problems were encountered while opening
1184 trans.get("BasicFrame.WarningDialog.txt1") + " " + filename + ".",
1185 //// Some design features may not have been loaded correctly.
1186 trans.get("BasicFrame.WarningDialog.txt2")
1188 //// Warnings while opening file
1189 trans.get("BasicFrame.WarningDialog.title"), warnings);
1193 // Set document state
1198 log.debug("Opening new frame with the document");
1199 BasicFrame frame = new BasicFrame(doc);
1200 frame.setVisible(true);
1209 private boolean saveAction() {
1210 File file = document.getFile();
1212 log.info("Document does not contain file, opening save as dialog instead");
1213 return saveAsAction();
1215 log.info("Saving document to " + file);
1217 // Saving RockSim designs is not supported
1218 if (FileHelper.ROCKSIM_DESIGN_FILTER.accept(file)) {
1219 file = new File(file.getAbsolutePath().replaceAll(".[rR][kK][tT](.[gG][zZ])?$",
1222 log.info("Attempting to save in RockSim format, renaming to " + file);
1223 int option = JOptionPane.showConfirmDialog(this, new Object[] {
1224 "Saving designs in RockSim format is not supported.",
1225 "Save in OpenRocket format instead (" + file.getName() + ")?"
1226 }, "Save " + file.getName(), JOptionPane.YES_NO_OPTION,
1227 JOptionPane.QUESTION_MESSAGE, null);
1228 if (option != JOptionPane.YES_OPTION) {
1229 log.user("User chose not to save");
1233 document.setFile(file);
1235 return saveAs(file);
1239 private boolean saveAsAction() {
1242 // TODO: HIGH: what if *.rkt chosen?
1243 StorageOptionChooser storageChooser =
1244 new StorageOptionChooser(document, document.getDefaultStorageOptions());
1245 JFileChooser chooser = new JFileChooser();
1246 chooser.setFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
1247 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
1248 chooser.setAccessory(storageChooser);
1249 if (document.getFile() != null)
1250 chooser.setSelectedFile(document.getFile());
1252 int option = chooser.showSaveDialog(BasicFrame.this);
1253 if (option != JFileChooser.APPROVE_OPTION) {
1254 log.user("User decided not to save, option=" + option);
1258 file = chooser.getSelectedFile();
1260 log.user("User did not select a file");
1264 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
1265 storageChooser.storeOptions(document.getDefaultStorageOptions());
1267 file = FileHelper.ensureExtension(file, "ork");
1268 if (!FileHelper.confirmWrite(file, this)) {
1272 return saveAs(file);
1275 private boolean saveAs(File file) {
1276 log.info("Saving document as " + file);
1277 boolean saved = false;
1279 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1280 // User cancelled the dialog
1281 log.user("User cancelled saving in storage options dialog");
1286 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1288 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1289 "Writing " + file.getName() + "...", worker)) {
1291 // User cancelled the save
1292 log.user("User cancelled the save, deleting the file");
1299 document.setFile(file);
1300 document.setSaved(true);
1303 } catch (ExecutionException e) {
1305 Throwable cause = e.getCause();
1307 if (cause instanceof IOException) {
1308 log.warn("An I/O error occurred while saving " + file, cause);
1309 JOptionPane.showMessageDialog(this, new String[] {
1310 "An I/O error occurred while saving:",
1311 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1314 Reflection.handleWrappedException(e);
1317 } catch (InterruptedException e) {
1318 throw new BugException("EDT was interrupted", e);
1325 private boolean closeAction() {
1326 if (!document.isSaved()) {
1327 log.info("Confirming whether to save the design");
1328 ComponentConfigDialog.hideDialog();
1329 int result = JOptionPane.showConfirmDialog(this,
1330 trans.get("BasicFrame.dlg.lbl1") + rocket.getName() +
1331 trans.get("BasicFrame.dlg.lbl2") + " " +
1332 trans.get("BasicFrame.dlg.lbl3"),
1333 trans.get("BasicFrame.dlg.title"), JOptionPane.YES_NO_CANCEL_OPTION,
1334 JOptionPane.QUESTION_MESSAGE);
1335 if (result == JOptionPane.YES_OPTION) {
1337 log.user("User requested file save");
1338 if (!saveAction()) {
1339 log.info("File save was interrupted, not closing");
1342 } else if (result == JOptionPane.NO_OPTION) {
1343 // Don't save: No-op
1344 log.user("User requested to discard design");
1347 log.user("User cancelled closing, result=" + result);
1352 // Rocket has been saved or discarded
1353 log.debug("Disposing window");
1356 ComponentConfigDialog.hideDialog();
1357 ComponentAnalysisDialog.hideDialog();
1359 frames.remove(this);
1360 if (frames.isEmpty()) {
1361 log.info("Last frame closed, exiting");
1372 public void printAction() {
1373 if (!Prefs.getBoolean("printing.experimental.communicated", false)) {
1374 log.info("Showing printing is experimental warning to the user");
1375 JOptionPane.showMessageDialog(this, "Printing is an currently an experimental feature " +
1376 "and might not fully work on all platforms",
1377 "Experimental feature", JOptionPane.WARNING_MESSAGE);
1378 Prefs.putBoolean("printing.experimental.communicated", true);
1380 new PrintDialog(this, document).setVisible(true);
1384 * Open a new design window with a basic rocket+stage.
1386 public static void newAction() {
1387 log.info("New action initiated");
1389 Rocket rocket = new Rocket();
1390 Stage stage = new Stage();
1392 stage.setName(trans.get("BasicFrame.StageName.Sustainer"));
1393 rocket.addChild(stage);
1394 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1397 BasicFrame frame = new BasicFrame(doc);
1398 frame.replaceable = true;
1399 frame.setVisible(true);
1400 ComponentConfigDialog.showDialog(frame, doc, rocket);
1404 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1406 public static void quitAction() {
1407 log.info("Quit action initiated");
1408 for (int i = frames.size() - 1; i >= 0; i--) {
1409 log.debug("Closing frame " + frames.get(i));
1410 if (!frames.get(i).closeAction()) {
1412 log.info("Quit was cancelled");
1416 // Should not be reached, but just in case
1417 log.error("Should already have exited application");
1423 * Set the title of the frame, taking into account the name of the rocket, file it
1424 * has been saved to (if any) and saved status.
1426 private void setTitle() {
1427 File file = document.getFile();
1428 boolean saved = document.isSaved();
1431 title = rocket.getName();
1433 title = title + " (" + file.getName() + ")";
1436 title = "*" + title;
1444 * Find a currently open BasicFrame containing the specified rocket. This method
1445 * can be used to map a Rocket to a BasicFrame from GUI methods.
1447 * @param rocket the Rocket.
1448 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1450 public static BasicFrame findFrame(Rocket rocket) {
1451 for (BasicFrame f : frames) {
1452 if (f.rocket == rocket) {
1453 log.debug("Found frame " + f + " for rocket " + rocket);
1457 log.debug("Could not find frame for rocket " + rocket);
1462 * Find a currently open document by the rocket object. This method can be used
1463 * to map a Rocket to OpenRocketDocument from GUI methods.
1465 * @param rocket the Rocket.
1466 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1468 public static OpenRocketDocument findDocument(Rocket rocket) {
1469 BasicFrame frame = findFrame(rocket);
1470 if (frame != null) {
1471 return frame.document;