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.JSeparator;
45 import javax.swing.JSplitPane;
46 import javax.swing.JTabbedPane;
47 import javax.swing.JTextField;
48 import javax.swing.KeyStroke;
49 import javax.swing.ListSelectionModel;
50 import javax.swing.ScrollPaneConstants;
51 import javax.swing.SwingUtilities;
52 import javax.swing.border.TitledBorder;
53 import javax.swing.event.TreeSelectionEvent;
54 import javax.swing.event.TreeSelectionListener;
55 import javax.swing.filechooser.FileFilter;
56 import javax.swing.tree.DefaultTreeSelectionModel;
57 import javax.swing.tree.TreePath;
58 import javax.swing.tree.TreeSelectionModel;
60 import net.miginfocom.swing.MigLayout;
61 import net.sf.openrocket.aerodynamics.WarningSet;
62 import net.sf.openrocket.document.OpenRocketDocument;
63 import net.sf.openrocket.file.GeneralRocketLoader;
64 import net.sf.openrocket.file.RocketLoadException;
65 import net.sf.openrocket.file.RocketLoader;
66 import net.sf.openrocket.file.RocketSaver;
67 import net.sf.openrocket.file.openrocket.OpenRocketSaver;
68 import net.sf.openrocket.gui.StorageOptionChooser;
69 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
70 import net.sf.openrocket.gui.dialogs.AboutDialog;
71 import net.sf.openrocket.gui.dialogs.BugReportDialog;
72 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
73 import net.sf.openrocket.gui.dialogs.DebugLogDialog;
74 import net.sf.openrocket.gui.dialogs.DetailDialog;
75 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
76 import net.sf.openrocket.gui.dialogs.LicenseDialog;
77 import net.sf.openrocket.gui.dialogs.MotorDatabaseLoadingDialog;
78 import net.sf.openrocket.gui.dialogs.PrintDialog;
79 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
80 import net.sf.openrocket.gui.dialogs.WarningDialog;
81 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
82 import net.sf.openrocket.gui.main.componenttree.ComponentTree;
83 import net.sf.openrocket.gui.scalefigure.RocketPanel;
84 import net.sf.openrocket.logging.LogHelper;
85 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
86 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
87 import net.sf.openrocket.rocketcomponent.Rocket;
88 import net.sf.openrocket.rocketcomponent.RocketComponent;
89 import net.sf.openrocket.rocketcomponent.Stage;
90 import net.sf.openrocket.startup.Application;
91 import net.sf.openrocket.util.BugException;
92 import net.sf.openrocket.util.GUIUtil;
93 import net.sf.openrocket.util.Icons;
94 import net.sf.openrocket.util.MemoryManagement;
95 import net.sf.openrocket.util.MemoryManagement.MemoryData;
96 import net.sf.openrocket.util.OpenFileWorker;
97 import net.sf.openrocket.util.Prefs;
98 import net.sf.openrocket.util.Reflection;
99 import net.sf.openrocket.util.SaveFileWorker;
100 import net.sf.openrocket.util.TestRockets;
102 public class BasicFrame extends JFrame {
103 private static final LogHelper log = Application.getLogger();
106 * The RocketLoader instance used for loading all rocket designs.
108 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
110 private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
113 // FileFilters for different types of rocket design files
114 private static final FileFilter ALL_DESIGNS_FILTER =
115 new SimpleFileFilter("All rocket designs (*.ork; *.rkt)",
116 ".ork", ".ork.gz", ".rkt", ".rkt.gz");
118 private static final FileFilter OPENROCKET_DESIGN_FILTER =
119 new SimpleFileFilter("OpenRocket designs (*.ork)", ".ork", ".ork.gz");
121 private static final FileFilter ROCKSIM_DESIGN_FILTER =
122 new SimpleFileFilter("RockSim designs (*.rkt)", ".rkt", ".rkt.gz");
127 public static final int COMPONENT_TAB = 0;
128 public static final int SIMULATION_TAB = 1;
132 * List of currently open frames. When the list goes empty
133 * it is time to exit the application.
135 private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
142 * Whether "New" and "Open" should replace this frame.
143 * Should be set to false on the first rocket modification.
145 private boolean replaceable = false;
149 private final OpenRocketDocument document;
150 private final Rocket rocket;
152 private JTabbedPane tabbedPane;
153 private RocketPanel rocketpanel;
154 private ComponentTree tree = null;
156 private final DocumentSelectionModel selectionModel;
157 private final TreeSelectionModel componentSelectionModel;
158 private final ListSelectionModel simulationSelectionModel;
160 /** Actions available for rocket modifications */
161 private final RocketActions actions;
166 * Sole constructor. Creates a new frame based on the supplied document
167 * and adds it to the current frames list.
169 * @param document the document to show.
171 public BasicFrame(OpenRocketDocument document) {
172 log.debug("Instantiating new BasicFrame");
174 this.document = document;
175 this.rocket = document.getRocket();
176 this.rocket.getDefaultConfiguration().setAllStages();
179 // Set replaceable flag to false at first modification
180 rocket.addComponentChangeListener(new ComponentChangeListener() {
182 public void componentChanged(ComponentChangeEvent e) {
184 BasicFrame.this.rocket.removeComponentChangeListener(this);
189 // Create the component tree selection model that will be used
190 componentSelectionModel = new DefaultTreeSelectionModel();
191 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
193 // Obtain the simulation selection model that will be used
194 SimulationPanel simulationPanel = new SimulationPanel(document);
195 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
197 // Combine into a DocumentSelectionModel
198 selectionModel = new DocumentSelectionModel(document);
199 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
200 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
203 actions = new RocketActions(document, selectionModel, this);
206 log.debug("Constructing the BasicFrame UI");
208 // The main vertical split pane
209 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
210 vertical.setResizeWeight(0.5);
214 // The top tabbed pane
215 tabbedPane = new JTabbedPane();
216 tabbedPane.addTab("Rocket design", null, designTab());
217 tabbedPane.addTab("Flight simulations", null, simulationPanel);
219 vertical.setTopComponent(tabbedPane);
223 // Bottom segment, rocket figure
225 rocketpanel = new RocketPanel(document);
226 vertical.setBottomComponent(rocketpanel);
228 rocketpanel.setSelectionModel(tree.getSelectionModel());
234 rocket.addComponentChangeListener(new ComponentChangeListener() {
236 public void componentChanged(ComponentChangeEvent e) {
244 Dimension size = Prefs.getWindowSize(this.getClass());
246 size = Toolkit.getDefaultToolkit().getScreenSize();
247 size.width = size.width * 9 / 10;
248 size.height = size.height * 9 / 10;
251 this.addComponentListener(new ComponentAdapter() {
253 public void componentResized(ComponentEvent e) {
254 Prefs.setWindowSize(BasicFrame.this.getClass(), BasicFrame.this.getSize());
257 this.setLocationByPlatform(true);
259 GUIUtil.setWindowIcons(this);
262 vertical.setDividerLocation(0.4);
263 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
264 addWindowListener(new WindowAdapter() {
266 public void windowClosing(WindowEvent e) {
272 log.debug("BasicFrame instantiation complete");
277 * Construct the "Rocket design" tab. This contains a horizontal split pane
278 * with the left component the design tree and the right component buttons
279 * for adding components.
281 private JComponent designTab() {
282 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
283 horizontal.setResizeWeight(0.5);
286 // Upper-left segment, component tree
288 JPanel panel = new JPanel(new MigLayout("fill, flowy", "", "[grow]"));
290 tree = new ComponentTree(document);
291 tree.setSelectionModel(componentSelectionModel);
293 // Remove JTree key events that interfere with menu accelerators
294 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
295 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
296 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
297 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
298 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
299 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
300 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
301 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
305 // Double-click opens config dialog
306 MouseListener ml = new MouseAdapter() {
308 public void mousePressed(MouseEvent e) {
309 int selRow = tree.getRowForLocation(e.getX(), e.getY());
310 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
312 if ((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
314 RocketComponent c = (RocketComponent) selPath.getLastPathComponent();
315 ComponentConfigDialog.showDialog(BasicFrame.this,
316 BasicFrame.this.document, c);
321 tree.addMouseListener(ml);
323 // Update dialog when selection is changed
324 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
326 public void valueChanged(TreeSelectionEvent e) {
327 // Scroll tree to the selected item
328 TreePath path = componentSelectionModel.getSelectionPath();
331 tree.scrollPathToVisible(path);
333 if (!ComponentConfigDialog.isDialogVisible())
335 RocketComponent c = (RocketComponent) path.getLastPathComponent();
336 ComponentConfigDialog.showDialog(BasicFrame.this,
337 BasicFrame.this.document, c);
341 // Place tree inside scroll pane
342 JScrollPane scroll = new JScrollPane(tree);
343 panel.add(scroll, "spany, grow, wrap");
347 JButton button = new JButton(actions.getMoveUpAction());
348 panel.add(button, "sizegroup buttons, aligny 65%");
350 button = new JButton(actions.getMoveDownAction());
351 panel.add(button, "sizegroup buttons, aligny 0%");
353 button = new JButton(actions.getEditAction());
354 panel.add(button, "sizegroup buttons");
356 button = new JButton(actions.getNewStageAction());
357 panel.add(button, "sizegroup buttons");
359 button = new JButton(actions.getDeleteAction());
360 button.setIcon(null);
361 button.setMnemonic(0);
362 panel.add(button, "sizegroup buttons");
364 horizontal.setLeftComponent(panel);
367 // Upper-right segment, component addition buttons
369 panel = new JPanel(new MigLayout("fill, insets 0", "[0::]"));
371 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
372 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
373 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
374 scroll.getViewport()));
375 scroll.setBorder(null);
376 scroll.setViewportBorder(null);
378 TitledBorder border = new TitledBorder("Add new component");
379 border.setTitleFont(border.getTitleFont().deriveFont(Font.BOLD));
380 scroll.setBorder(border);
382 panel.add(scroll, "grow");
384 horizontal.setRightComponent(panel);
392 * Creates the menu for the window.
394 private void createMenu() {
395 JMenuBar menubar = new JMenuBar();
400 menu = new JMenu("File");
401 menu.setMnemonic(KeyEvent.VK_F);
402 menu.getAccessibleContext().setAccessibleDescription("File-handling related tasks");
405 item = new JMenuItem("New", KeyEvent.VK_N);
406 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
407 item.setMnemonic(KeyEvent.VK_N);
408 item.getAccessibleContext().setAccessibleDescription("Create a new rocket design");
409 item.setIcon(Icons.FILE_NEW);
410 item.addActionListener(new ActionListener() {
412 public void actionPerformed(ActionEvent e) {
413 log.user("New... selected");
416 log.info("Closing previous window");
423 item = new JMenuItem("Open...", KeyEvent.VK_O);
424 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
425 item.getAccessibleContext().setAccessibleDescription("Open a rocket design");
426 item.setIcon(Icons.FILE_OPEN);
427 item.addActionListener(new ActionListener() {
429 public void actionPerformed(ActionEvent e) {
430 log.user("Open... selected");
436 item = new JMenuItem("Open example...");
437 item.getAccessibleContext().setAccessibleDescription("Open an example rocket design");
438 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
439 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
440 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
441 item.addActionListener(new ActionListener() {
443 public void actionPerformed(ActionEvent e) {
444 log.user("Open example... selected");
445 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
448 log.user("Opening example " + u);
449 open(u, BasicFrame.this);
458 item = new JMenuItem("Save", KeyEvent.VK_S);
459 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
460 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design");
461 item.setIcon(Icons.FILE_SAVE);
462 item.addActionListener(new ActionListener() {
464 public void actionPerformed(ActionEvent e) {
465 log.user("Save selected");
471 item = new JMenuItem("Save as...", KeyEvent.VK_A);
472 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
473 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
474 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design " +
476 item.setIcon(Icons.FILE_SAVE_AS);
477 item.addActionListener(new ActionListener() {
479 public void actionPerformed(ActionEvent e) {
480 log.user("Save as... selected");
487 item = new JMenuItem("Print...", KeyEvent.VK_P);
488 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
489 item.getAccessibleContext().setAccessibleDescription("Print parts list and fin template");
490 item.setIcon(Icons.FILE_PRINT);
491 item.addActionListener(new ActionListener() {
493 public void actionPerformed(ActionEvent e) {
502 item = new JMenuItem("Close", KeyEvent.VK_C);
503 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
504 item.getAccessibleContext().setAccessibleDescription("Close the current rocket design");
505 item.setIcon(Icons.FILE_CLOSE);
506 item.addActionListener(new ActionListener() {
508 public void actionPerformed(ActionEvent e) {
509 log.user("Close selected");
517 item = new JMenuItem("Quit", KeyEvent.VK_Q);
518 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
519 item.getAccessibleContext().setAccessibleDescription("Quit the program");
520 item.setIcon(Icons.FILE_QUIT);
521 item.addActionListener(new ActionListener() {
523 public void actionPerformed(ActionEvent e) {
524 log.user("Quit selected");
533 menu = new JMenu("Edit");
534 menu.setMnemonic(KeyEvent.VK_E);
535 menu.getAccessibleContext().setAccessibleDescription("Rocket editing");
539 Action action = document.getUndoAction();
540 item = new JMenuItem(action);
541 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
542 item.setMnemonic(KeyEvent.VK_U);
543 item.getAccessibleContext().setAccessibleDescription("Undo the previous operation");
547 action = document.getRedoAction();
548 item = new JMenuItem(action);
549 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
550 item.setMnemonic(KeyEvent.VK_R);
551 item.getAccessibleContext().setAccessibleDescription("Redo the previously undone " +
558 item = new JMenuItem(actions.getCutAction());
561 item = new JMenuItem(actions.getCopyAction());
564 item = new JMenuItem(actions.getPasteAction());
567 item = new JMenuItem(actions.getDeleteAction());
572 item = new JMenuItem("Preferences");
573 item.setIcon(Icons.PREFERENCES);
574 item.getAccessibleContext().setAccessibleDescription("Setup the application " +
576 item.addActionListener(new ActionListener() {
578 public void actionPerformed(ActionEvent e) {
579 log.user("Preferences selected");
580 PreferencesDialog.showPreferences();
589 menu = new JMenu("Analyze");
590 menu.setMnemonic(KeyEvent.VK_A);
591 menu.getAccessibleContext().setAccessibleDescription("Analyzing the rocket");
594 item = new JMenuItem("Component analysis", KeyEvent.VK_C);
595 item.getAccessibleContext().setAccessibleDescription("Analyze the rocket components " +
597 item.addActionListener(new ActionListener() {
599 public void actionPerformed(ActionEvent e) {
600 log.user("Component analysis selected");
601 ComponentAnalysisDialog.showDialog(rocketpanel);
608 // (shown if openrocket.debug.menu is defined)
609 if (System.getProperty("openrocket.debug.menu") != null) {
610 menubar.add(makeDebugMenu());
617 menu = new JMenu("Help");
618 menu.setMnemonic(KeyEvent.VK_H);
619 menu.getAccessibleContext().setAccessibleDescription("Information about OpenRocket");
624 item = new JMenuItem("License", KeyEvent.VK_L);
625 item.getAccessibleContext().setAccessibleDescription("OpenRocket license information");
626 item.addActionListener(new ActionListener() {
628 public void actionPerformed(ActionEvent e) {
629 log.user("License selected");
630 new LicenseDialog(BasicFrame.this).setVisible(true);
637 item = new JMenuItem("Bug report", KeyEvent.VK_B);
638 item.getAccessibleContext().setAccessibleDescription("Information about reporting " +
639 "bugs in OpenRocket");
640 item.addActionListener(new ActionListener() {
642 public void actionPerformed(ActionEvent e) {
643 log.user("Bug report selected");
644 BugReportDialog.showBugReportDialog(BasicFrame.this);
649 item = new JMenuItem("Debug log");
650 item.getAccessibleContext().setAccessibleDescription("View the OpenRocket debug log");
651 item.addActionListener(new ActionListener() {
653 public void actionPerformed(ActionEvent e) {
654 log.user("Debug log selected");
655 new DebugLogDialog(BasicFrame.this).setVisible(true);
662 item = new JMenuItem("About", KeyEvent.VK_A);
663 item.getAccessibleContext().setAccessibleDescription("About OpenRocket");
664 item.addActionListener(new ActionListener() {
666 public void actionPerformed(ActionEvent e) {
667 log.user("About selected");
668 new AboutDialog(BasicFrame.this).setVisible(true);
674 this.setJMenuBar(menubar);
678 private JMenu makeDebugMenu() {
683 menu = new JMenu("Debug");
684 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
686 item = new JMenuItem("What is this menu?");
687 item.addActionListener(new ActionListener() {
689 public void actionPerformed(ActionEvent e) {
690 log.user("What is this menu? selected");
691 JOptionPane.showMessageDialog(BasicFrame.this,
693 "The 'Debug' menu includes actions for testing and debugging " +
695 "The menu is made visible by defining the system property " +
696 "'openrocket.debug.menu' when starting OpenRocket.",
697 "It should not be visible by default." },
698 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
705 item = new JMenuItem("Create test rocket");
706 item.addActionListener(new ActionListener() {
708 public void actionPerformed(ActionEvent e) {
709 log.user("Create test rocket selected");
710 JTextField field = new JTextField();
711 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
712 "Input text key to generate random rocket:",
714 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
715 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
721 r = new TestRockets(null).makeTestRocket();
722 } else if (sel == 1) {
723 r = new TestRockets(field.getText()).makeTestRocket();
728 OpenRocketDocument doc = new OpenRocketDocument(r);
730 BasicFrame frame = new BasicFrame(doc);
731 frame.setVisible(true);
738 item = new JMenuItem("Create 'Iso-Haisu'");
739 item.addActionListener(new ActionListener() {
741 public void actionPerformed(ActionEvent e) {
742 log.user("Create Iso-Haisu selected");
743 Rocket r = TestRockets.makeIsoHaisu();
744 OpenRocketDocument doc = new OpenRocketDocument(r);
746 BasicFrame frame = new BasicFrame(doc);
747 frame.setVisible(true);
753 item = new JMenuItem("Create 'Big Blue'");
754 item.addActionListener(new ActionListener() {
756 public void actionPerformed(ActionEvent e) {
757 log.user("Create Big Blue selected");
758 Rocket r = TestRockets.makeBigBlue();
759 OpenRocketDocument doc = new OpenRocketDocument(r);
761 BasicFrame frame = new BasicFrame(doc);
762 frame.setVisible(true);
770 item = new JMenuItem("Memory statistics");
771 item.addActionListener(new ActionListener() {
773 public void actionPerformed(ActionEvent e) {
774 log.user("Memory statistics selected");
776 // Get discarded but remaining objects (this also runs System.gc multiple times)
777 List<MemoryData> objects = MemoryManagement.getRemainingCollectableObjects();
778 StringBuilder sb = new StringBuilder();
779 sb.append("Objects that should have been garbage-collected but have not been:\n");
781 for (MemoryData data : objects) {
782 Object o = data.getReference().get();
785 sb.append("Age ").append(System.currentTimeMillis() - data.getRegistrationTime())
786 .append(" ms: ").append(o).append('\n');
788 // Explicitly null the strong reference to avoid possibility of invisible references
791 sb.append("Total: " + count);
793 // Get basic memory stats
795 long max = Runtime.getRuntime().maxMemory();
796 long free = Runtime.getRuntime().freeMemory();
797 long used = max - free;
798 String[] stats = new String[4];
799 stats[0] = "Memory usage:";
800 stats[1] = String.format(" Max memory: %.1f MB", max / 1024.0 / 1024.0);
801 stats[2] = String.format(" Used memory: %.1f MB (%.0f%%)", used / 1024.0 / 1024.0, 100.0 * used / max);
802 stats[3] = String.format(" Free memory: %.1f MB (%.0f%%)", free / 1024.0 / 1024.0, 100.0 * free / max);
805 DetailDialog.showDetailedMessageDialog(BasicFrame.this, stats, sb.toString(),
806 "Memory statistics", JOptionPane.INFORMATION_MESSAGE);
812 item = new JMenuItem("Exhaust memory");
813 item.addActionListener(new ActionListener() {
815 public void actionPerformed(ActionEvent e) {
816 log.user("Exhaust memory selected");
817 LinkedList<byte[]> data = new LinkedList<byte[]>();
819 final int bytesPerArray = 10240;
822 byte[] array = new byte[bytesPerArray];
823 for (int i = 0; i < bytesPerArray; i++) {
829 } catch (OutOfMemoryError error) {
831 long size = bytesPerArray * (long) count;
832 String s = String.format("OutOfMemory occurred after %d iterations (approx. %.1f MB consumed)",
833 count, size / 1024.0 / 1024.0);
835 JOptionPane.showMessageDialog(BasicFrame.this, s);
844 item = new JMenuItem("Exception here");
845 item.addActionListener(new ActionListener() {
847 public void actionPerformed(ActionEvent e) {
848 log.user("Exception here selected");
849 throw new RuntimeException("Testing exception from menu action listener");
854 item = new JMenuItem("Exception from EDT");
855 item.addActionListener(new ActionListener() {
857 public void actionPerformed(ActionEvent e) {
858 log.user("Exception from EDT selected");
859 SwingUtilities.invokeLater(new Runnable() {
862 throw new RuntimeException("Testing exception from " +
863 "later invoked EDT thread");
870 item = new JMenuItem("Exception from other thread");
871 item.addActionListener(new ActionListener() {
873 public void actionPerformed(ActionEvent e) {
874 log.user("Exception from other thread selected");
878 throw new RuntimeException("Testing exception from newly created thread");
885 item = new JMenuItem("OutOfMemoryError here");
886 item.addActionListener(new ActionListener() {
888 public void actionPerformed(ActionEvent e) {
889 log.user("OutOfMemoryError here selected");
890 throw new OutOfMemoryError("Testing OutOfMemoryError from menu action listener");
902 * Select the tab on the main pane.
904 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
906 public void selectTab(int tab) {
907 tabbedPane.setSelectedIndex(tab);
912 private void openAction() {
913 JFileChooser chooser = new JFileChooser();
915 chooser.addChoosableFileFilter(ALL_DESIGNS_FILTER);
916 chooser.addChoosableFileFilter(OPENROCKET_DESIGN_FILTER);
917 chooser.addChoosableFileFilter(ROCKSIM_DESIGN_FILTER);
918 chooser.setFileFilter(ALL_DESIGNS_FILTER);
920 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
921 chooser.setMultiSelectionEnabled(true);
922 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
923 int option = chooser.showOpenDialog(this);
924 if (option != JFileChooser.APPROVE_OPTION) {
925 log.user("Decided not to open files, option=" + option);
929 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
931 File[] files = chooser.getSelectedFiles();
932 log.user("Opening files " + Arrays.toString(files));
934 for (File file : files) {
935 log.info("Opening file: " + file);
936 if (open(file, this)) {
938 // Close previous window if replacing
939 if (replaceable && document.isSaved()) {
940 log.info("Closing window because it is replaceable");
950 * Open a file based on a URL.
951 * @param url the file to open.
952 * @param parent the parent window for dialogs.
953 * @return <code>true</code> if opened successfully.
955 private static boolean open(URL url, BasicFrame parent) {
956 String filename = null;
958 // First figure out the file name from the URL
960 // Try using URI.getPath();
962 URI uri = url.toURI();
963 filename = uri.getPath();
964 } catch (URISyntaxException ignore) {
967 // Try URL-decoding the URL
968 if (filename == null) {
970 filename = URLDecoder.decode(url.toString(), "UTF-8");
971 } catch (UnsupportedEncodingException ignore) {
976 if (filename == null) {
980 // Remove path from filename
981 if (filename.lastIndexOf('/') >= 0) {
982 filename = filename.substring(filename.lastIndexOf('/') + 1);
987 log.info("Opening file from url=" + url + " filename=" + filename);
989 InputStream is = url.openStream();
990 if (open(is, filename, parent)) {
991 // Close previous window if replacing
992 if (parent.replaceable && parent.document.isSaved()) {
993 parent.closeAction();
994 parent.replaceable = false;
997 } catch (IOException e) {
998 log.warn("Error opening file" + e);
999 JOptionPane.showMessageDialog(parent,
1000 "An error occurred while opening the file " + filename,
1001 "Error loading file", JOptionPane.ERROR_MESSAGE);
1009 * Open the specified file from an InputStream in a new design frame. If an error
1010 * occurs, an error dialog is shown and <code>false</code> is returned.
1012 * @param stream the stream to load from.
1013 * @param filename the file name to display in dialogs (not set to the document).
1014 * @param parent the parent component for which a progress dialog is opened.
1015 * @return whether the file was successfully loaded and opened.
1017 private static boolean open(InputStream stream, String filename, Window parent) {
1018 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
1019 return open(worker, filename, null, parent);
1024 * Open the specified file in a new design frame. If an error occurs, an error
1025 * dialog is shown and <code>false</code> is returned.
1027 * @param file the file to open.
1028 * @param parent the parent component for which a progress dialog is opened.
1029 * @return whether the file was successfully loaded and opened.
1031 public static boolean open(File file, Window parent) {
1032 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
1033 return open(worker, file.getName(), file, parent);
1038 * Open the specified file using the provided worker.
1040 * @param worker the OpenFileWorker that loads the file.
1041 * @param filename the file name to display in dialogs.
1042 * @param file the File to set the document to (may be null).
1046 private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) {
1048 MotorDatabaseLoadingDialog.check(parent);
1050 // Open the file in a Swing worker thread
1051 log.info("Starting OpenFileWorker");
1052 if (!SwingWorkerDialog.runWorker(parent, "Opening file", "Reading " + filename + "...", worker)) {
1053 // User cancelled the operation
1054 log.info("User cancelled the OpenFileWorker");
1059 // Handle the document
1060 OpenRocketDocument doc = null;
1065 } catch (ExecutionException e) {
1067 Throwable cause = e.getCause();
1069 if (cause instanceof FileNotFoundException) {
1071 log.warn("File not found", cause);
1072 JOptionPane.showMessageDialog(parent,
1073 "File not found: " + filename,
1074 "Error opening file", JOptionPane.ERROR_MESSAGE);
1077 } else if (cause instanceof RocketLoadException) {
1079 log.warn("Error loading the file", cause);
1080 JOptionPane.showMessageDialog(parent,
1081 "Unable to open file '" + filename + "': "
1082 + cause.getMessage(),
1083 "Error opening file", JOptionPane.ERROR_MESSAGE);
1088 throw new BugException("Unknown error when opening file", e);
1092 } catch (InterruptedException e) {
1093 throw new BugException("EDT was interrupted", e);
1097 throw new BugException("Document loader returned null");
1102 WarningSet warnings = worker.getRocketLoader().getWarnings();
1103 if (!warnings.isEmpty()) {
1104 log.info("Warnings while reading file: " + warnings);
1105 WarningDialog.showWarnings(parent,
1107 "The following problems were encountered while opening " + filename + ".",
1108 "Some design features may not have been loaded correctly."
1110 "Warnings while opening file", warnings);
1114 // Set document state
1119 log.debug("Opening new frame with the document");
1120 BasicFrame frame = new BasicFrame(doc);
1121 frame.setVisible(true);
1130 private boolean saveAction() {
1131 File file = document.getFile();
1133 log.info("Document does not contain file, opening save as dialog instead");
1134 return saveAsAction();
1136 log.info("Saving document to " + file);
1138 // Saving RockSim designs is not supported
1139 if (ROCKSIM_DESIGN_FILTER.accept(file)) {
1140 file = new File(file.getAbsolutePath().replaceAll(".[rR][kK][tT](.[gG][zZ])?$",
1143 log.info("Attempting to save in RockSim format, renaming to " + file);
1144 int option = JOptionPane.showConfirmDialog(this, new Object[] {
1145 "Saving designs in RockSim format is not supported.",
1146 "Save in OpenRocket format instead (" + file.getName() + ")?"
1147 }, "Save " + file.getName(), JOptionPane.YES_NO_OPTION,
1148 JOptionPane.QUESTION_MESSAGE, null);
1149 if (option != JOptionPane.YES_OPTION) {
1150 log.user("User chose not to save");
1154 document.setFile(file);
1156 return saveAs(file);
1160 private boolean saveAsAction() {
1163 // TODO: HIGH: what if *.rkt chosen?
1164 StorageOptionChooser storageChooser =
1165 new StorageOptionChooser(document, document.getDefaultStorageOptions());
1166 JFileChooser chooser = new JFileChooser();
1167 chooser.setFileFilter(OPENROCKET_DESIGN_FILTER);
1168 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
1169 chooser.setAccessory(storageChooser);
1170 if (document.getFile() != null)
1171 chooser.setSelectedFile(document.getFile());
1173 int option = chooser.showSaveDialog(BasicFrame.this);
1174 if (option != JFileChooser.APPROVE_OPTION) {
1175 log.user("User decided not to save, option=" + option);
1179 file = chooser.getSelectedFile();
1181 log.user("User did not select a file");
1185 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
1186 storageChooser.storeOptions(document.getDefaultStorageOptions());
1188 if (file.getName().indexOf('.') < 0) {
1189 log.debug("File name does not contain extension, adding .ork");
1190 String name = file.getAbsolutePath();
1191 name = name + ".ork";
1192 file = new File(name);
1195 if (file.exists()) {
1196 log.info("File " + file + " exists, confirming overwrite from user");
1197 int result = JOptionPane.showConfirmDialog(this,
1198 "File '" + file.getName() + "' exists. Do you want to overwrite it?",
1199 "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
1200 if (result != JOptionPane.YES_OPTION) {
1201 log.user("User decided not to overwrite the file");
1206 return saveAs(file);
1209 private boolean saveAs(File file) {
1210 log.info("Saving document as " + file);
1211 boolean saved = false;
1213 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1214 // User cancelled the dialog
1215 log.user("User cancelled saving in storage options dialog");
1220 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1222 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1223 "Writing " + file.getName() + "...", worker)) {
1225 // User cancelled the save
1226 log.user("User cancelled the save, deleting the file");
1233 document.setFile(file);
1234 document.setSaved(true);
1237 } catch (ExecutionException e) {
1239 Throwable cause = e.getCause();
1241 if (cause instanceof IOException) {
1242 log.warn("An I/O error occurred while saving " + file, cause);
1243 JOptionPane.showMessageDialog(this, new String[] {
1244 "An I/O error occurred while saving:",
1245 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1248 Reflection.handleWrappedException(e);
1251 } catch (InterruptedException e) {
1252 throw new BugException("EDT was interrupted", e);
1259 private boolean closeAction() {
1260 if (!document.isSaved()) {
1261 log.info("Confirming whether to save the design");
1262 ComponentConfigDialog.hideDialog();
1263 int result = JOptionPane.showConfirmDialog(this,
1264 "Design '" + rocket.getName() + "' has not been saved. " +
1265 "Do you want to save it?",
1266 "Design not saved", JOptionPane.YES_NO_CANCEL_OPTION,
1267 JOptionPane.QUESTION_MESSAGE);
1268 if (result == JOptionPane.YES_OPTION) {
1270 log.user("User requested file save");
1271 if (!saveAction()) {
1272 log.info("File save was interrupted, not closing");
1275 } else if (result == JOptionPane.NO_OPTION) {
1276 // Don't save: No-op
1277 log.user("User requested to discard design");
1280 log.user("User cancelled closing, result=" + result);
1285 // Rocket has been saved or discarded
1286 log.debug("Disposing window");
1289 ComponentConfigDialog.hideDialog();
1290 ComponentAnalysisDialog.hideDialog();
1292 frames.remove(this);
1293 if (frames.isEmpty()) {
1294 log.info("Last frame closed, exiting");
1305 public void printAction() {
1306 new PrintDialog(document);
1310 * Open a new design window with a basic rocket+stage.
1312 public static void newAction() {
1313 log.info("New action initiated");
1315 Rocket rocket = new Rocket();
1316 Stage stage = new Stage();
1317 stage.setName("Sustainer");
1318 rocket.addChild(stage);
1319 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1322 BasicFrame frame = new BasicFrame(doc);
1323 frame.replaceable = true;
1324 frame.setVisible(true);
1325 ComponentConfigDialog.showDialog(frame, doc, rocket);
1329 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1331 public static void quitAction() {
1332 log.info("Quit action initiated");
1333 for (int i = frames.size() - 1; i >= 0; i--) {
1334 log.debug("Closing frame " + frames.get(i));
1335 if (!frames.get(i).closeAction()) {
1337 log.info("Quit was cancelled");
1341 // Should not be reached, but just in case
1342 log.error("Should already have exited application");
1348 * Set the title of the frame, taking into account the name of the rocket, file it
1349 * has been saved to (if any) and saved status.
1351 private void setTitle() {
1352 File file = document.getFile();
1353 boolean saved = document.isSaved();
1356 title = rocket.getName();
1358 title = title + " (" + file.getName() + ")";
1361 title = "*" + title;
1369 * Find a currently open BasicFrame containing the specified rocket. This method
1370 * can be used to map a Rocket to a BasicFrame from GUI methods.
1372 * @param rocket the Rocket.
1373 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1375 public static BasicFrame findFrame(Rocket rocket) {
1376 for (BasicFrame f : frames) {
1377 if (f.rocket == rocket) {
1378 log.debug("Found frame " + f + " for rocket " + rocket);
1382 log.debug("Could not find frame for rocket " + rocket);
1387 * Find a currently open document by the rocket object. This method can be used
1388 * to map a Rocket to OpenRocketDocument from GUI methods.
1390 * @param rocket the Rocket.
1391 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1393 public static OpenRocketDocument findDocument(Rocket rocket) {
1394 BasicFrame frame = findFrame(rocket);
1395 if (frame != null) {
1396 return frame.document;