1 package net.sf.openrocket.gui.main;
3 import net.miginfocom.swing.MigLayout;
4 import net.sf.openrocket.aerodynamics.WarningSet;
5 import net.sf.openrocket.document.OpenRocketDocument;
6 import net.sf.openrocket.file.GeneralRocketLoader;
7 import net.sf.openrocket.file.RocketLoadException;
8 import net.sf.openrocket.file.RocketLoader;
9 import net.sf.openrocket.file.RocketSaver;
10 import net.sf.openrocket.file.openrocket.OpenRocketSaver;
11 import net.sf.openrocket.gui.StorageOptionChooser;
12 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
13 import net.sf.openrocket.gui.dialogs.AboutDialog;
14 import net.sf.openrocket.gui.dialogs.BugReportDialog;
15 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
16 import net.sf.openrocket.gui.dialogs.DebugLogDialog;
17 import net.sf.openrocket.gui.dialogs.DetailDialog;
18 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
19 import net.sf.openrocket.gui.dialogs.LicenseDialog;
20 import net.sf.openrocket.gui.dialogs.MotorDatabaseLoadingDialog;
21 import net.sf.openrocket.gui.dialogs.PrintDialog;
22 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
23 import net.sf.openrocket.gui.dialogs.WarningDialog;
24 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
25 import net.sf.openrocket.gui.main.componenttree.ComponentTree;
26 import net.sf.openrocket.gui.scalefigure.RocketPanel;
27 import net.sf.openrocket.logging.LogHelper;
28 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
29 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
30 import net.sf.openrocket.rocketcomponent.Rocket;
31 import net.sf.openrocket.rocketcomponent.RocketComponent;
32 import net.sf.openrocket.rocketcomponent.Stage;
33 import net.sf.openrocket.startup.Application;
34 import net.sf.openrocket.util.BugException;
35 import net.sf.openrocket.util.GUIUtil;
36 import net.sf.openrocket.util.Icons;
37 import net.sf.openrocket.util.MemoryManagement;
38 import net.sf.openrocket.util.MemoryManagement.MemoryData;
39 import net.sf.openrocket.util.OpenFileWorker;
40 import net.sf.openrocket.util.Prefs;
41 import net.sf.openrocket.util.Reflection;
42 import net.sf.openrocket.util.SaveFileWorker;
43 import net.sf.openrocket.util.TestRockets;
45 import javax.swing.Action;
46 import javax.swing.InputMap;
47 import javax.swing.JButton;
48 import javax.swing.JComponent;
49 import javax.swing.JFileChooser;
50 import javax.swing.JFrame;
51 import javax.swing.JMenu;
52 import javax.swing.JMenuBar;
53 import javax.swing.JMenuItem;
54 import javax.swing.JOptionPane;
55 import javax.swing.JPanel;
56 import javax.swing.JScrollPane;
57 import javax.swing.JSeparator;
58 import javax.swing.JSplitPane;
59 import javax.swing.JTabbedPane;
60 import javax.swing.JTextField;
61 import javax.swing.KeyStroke;
62 import javax.swing.ListSelectionModel;
63 import javax.swing.ScrollPaneConstants;
64 import javax.swing.SwingUtilities;
65 import javax.swing.border.TitledBorder;
66 import javax.swing.event.TreeSelectionEvent;
67 import javax.swing.event.TreeSelectionListener;
68 import javax.swing.filechooser.FileFilter;
69 import javax.swing.tree.DefaultTreeSelectionModel;
70 import javax.swing.tree.TreePath;
71 import javax.swing.tree.TreeSelectionModel;
72 import java.awt.Dimension;
74 import java.awt.Toolkit;
75 import java.awt.Window;
76 import java.awt.event.ActionEvent;
77 import java.awt.event.ActionListener;
78 import java.awt.event.ComponentAdapter;
79 import java.awt.event.ComponentEvent;
80 import java.awt.event.KeyEvent;
81 import java.awt.event.MouseAdapter;
82 import java.awt.event.MouseEvent;
83 import java.awt.event.MouseListener;
84 import java.awt.event.WindowAdapter;
85 import java.awt.event.WindowEvent;
87 import java.io.FileNotFoundException;
88 import java.io.IOException;
89 import java.io.InputStream;
90 import java.io.UnsupportedEncodingException;
92 import java.net.URISyntaxException;
94 import java.net.URLDecoder;
95 import java.util.ArrayList;
96 import java.util.Arrays;
97 import java.util.LinkedList;
98 import java.util.List;
99 import java.util.concurrent.ExecutionException;
101 public class BasicFrame extends JFrame {
102 private static final LogHelper log = Application.getLogger();
105 * The RocketLoader instance used for loading all rocket designs.
107 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
109 private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
112 // FileFilters for different types of rocket design files
113 private static final FileFilter ALL_DESIGNS_FILTER =
114 new SimpleFileFilter("All rocket designs (*.ork; *.rkt)",
115 ".ork", ".ork.gz", ".rkt", ".rkt.gz");
117 private static final FileFilter OPENROCKET_DESIGN_FILTER =
118 new SimpleFileFilter("OpenRocket designs (*.ork)", ".ork", ".ork.gz");
120 private static final FileFilter ROCKSIM_DESIGN_FILTER =
121 new SimpleFileFilter("RockSim designs (*.rkt)", ".rkt", ".rkt.gz");
126 public static final int COMPONENT_TAB = 0;
127 public static final int SIMULATION_TAB = 1;
131 * List of currently open frames. When the list goes empty
132 * it is time to exit the application.
134 private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
141 * Whether "New" and "Open" should replace this frame.
142 * Should be set to false on the first rocket modification.
144 private boolean replaceable = false;
148 private final OpenRocketDocument document;
149 private final Rocket rocket;
151 private JTabbedPane tabbedPane;
152 private RocketPanel rocketpanel;
153 private ComponentTree tree = null;
155 private final DocumentSelectionModel selectionModel;
156 private final TreeSelectionModel componentSelectionModel;
157 private final ListSelectionModel simulationSelectionModel;
159 /** Actions available for rocket modifications */
160 private final RocketActions actions;
165 * Sole constructor. Creates a new frame based on the supplied document
166 * and adds it to the current frames list.
168 * @param document the document to show.
170 public BasicFrame(OpenRocketDocument document) {
171 log.debug("Instantiating new BasicFrame");
173 this.document = document;
174 this.rocket = document.getRocket();
175 this.rocket.getDefaultConfiguration().setAllStages();
178 // Set replaceable flag to false at first modification
179 rocket.addComponentChangeListener(new ComponentChangeListener() {
180 public void componentChanged(ComponentChangeEvent e) {
182 BasicFrame.this.rocket.removeComponentChangeListener(this);
187 // Create the component tree selection model that will be used
188 componentSelectionModel = new DefaultTreeSelectionModel();
189 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
191 // Obtain the simulation selection model that will be used
192 SimulationPanel simulationPanel = new SimulationPanel(document);
193 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
195 // Combine into a DocumentSelectionModel
196 selectionModel = new DocumentSelectionModel(document);
197 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
198 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
201 actions = new RocketActions(document, selectionModel, this);
204 log.debug("Constructing the BasicFrame UI");
206 // The main vertical split pane
207 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
208 vertical.setResizeWeight(0.5);
212 // The top tabbed pane
213 tabbedPane = new JTabbedPane();
214 tabbedPane.addTab("Rocket design", null, designTab());
215 tabbedPane.addTab("Flight simulations", null, simulationPanel);
217 vertical.setTopComponent(tabbedPane);
221 // Bottom segment, rocket figure
223 rocketpanel = new RocketPanel(document);
224 vertical.setBottomComponent(rocketpanel);
226 rocketpanel.setSelectionModel(tree.getSelectionModel());
232 rocket.addComponentChangeListener(new ComponentChangeListener() {
233 public void componentChanged(ComponentChangeEvent e) {
241 Dimension size = Prefs.getWindowSize(this.getClass());
243 size = Toolkit.getDefaultToolkit().getScreenSize();
244 size.width = size.width * 9 / 10;
245 size.height = size.height * 9 / 10;
248 this.addComponentListener(new ComponentAdapter() {
250 public void componentResized(ComponentEvent e) {
251 Prefs.setWindowSize(BasicFrame.this.getClass(), BasicFrame.this.getSize());
254 this.setLocationByPlatform(true);
256 GUIUtil.setWindowIcons(this);
259 vertical.setDividerLocation(0.4);
260 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
261 addWindowListener(new WindowAdapter() {
263 public void windowClosing(WindowEvent e) {
269 log.debug("BasicFrame instantiation complete");
274 * Construct the "Rocket design" tab. This contains a horizontal split pane
275 * with the left component the design tree and the right component buttons
276 * for adding components.
278 private JComponent designTab() {
279 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
280 horizontal.setResizeWeight(0.5);
283 // Upper-left segment, component tree
285 JPanel panel = new JPanel(new MigLayout("fill, flowy", "", "[grow]"));
287 tree = new ComponentTree(document);
288 tree.setSelectionModel(componentSelectionModel);
290 // Remove JTree key events that interfere with menu accelerators
291 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
292 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
293 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
294 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
295 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
296 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
297 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
298 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
302 // Double-click opens config dialog
303 MouseListener ml = new MouseAdapter() {
305 public void mousePressed(MouseEvent e) {
306 int selRow = tree.getRowForLocation(e.getX(), e.getY());
307 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
309 if ((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
311 RocketComponent c = (RocketComponent) selPath.getLastPathComponent();
312 ComponentConfigDialog.showDialog(BasicFrame.this,
313 BasicFrame.this.document, c);
318 tree.addMouseListener(ml);
320 // Update dialog when selection is changed
321 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
322 public void valueChanged(TreeSelectionEvent e) {
323 // Scroll tree to the selected item
324 TreePath path = componentSelectionModel.getSelectionPath();
327 tree.scrollPathToVisible(path);
329 if (!ComponentConfigDialog.isDialogVisible())
331 RocketComponent c = (RocketComponent) path.getLastPathComponent();
332 ComponentConfigDialog.showDialog(BasicFrame.this,
333 BasicFrame.this.document, c);
337 // Place tree inside scroll pane
338 JScrollPane scroll = new JScrollPane(tree);
339 panel.add(scroll, "spany, grow, wrap");
343 JButton button = new JButton(actions.getMoveUpAction());
344 panel.add(button, "sizegroup buttons, aligny 65%");
346 button = new JButton(actions.getMoveDownAction());
347 panel.add(button, "sizegroup buttons, aligny 0%");
349 button = new JButton(actions.getEditAction());
350 panel.add(button, "sizegroup buttons");
352 button = new JButton(actions.getNewStageAction());
353 panel.add(button, "sizegroup buttons");
355 button = new JButton(actions.getDeleteAction());
356 button.setIcon(null);
357 button.setMnemonic(0);
358 panel.add(button, "sizegroup buttons");
360 horizontal.setLeftComponent(panel);
363 // Upper-right segment, component addition buttons
365 panel = new JPanel(new MigLayout("fill, insets 0", "[0::]"));
367 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
368 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
369 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
370 scroll.getViewport()));
371 scroll.setBorder(null);
372 scroll.setViewportBorder(null);
374 TitledBorder border = new TitledBorder("Add new component");
375 border.setTitleFont(border.getTitleFont().deriveFont(Font.BOLD));
376 scroll.setBorder(border);
378 panel.add(scroll, "grow");
380 horizontal.setRightComponent(panel);
388 * Creates the menu for the window.
390 private void createMenu() {
391 JMenuBar menubar = new JMenuBar();
396 menu = new JMenu("File");
397 menu.setMnemonic(KeyEvent.VK_F);
398 menu.getAccessibleContext().setAccessibleDescription("File-handling related tasks");
401 item = new JMenuItem("New", KeyEvent.VK_N);
402 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
403 item.setMnemonic(KeyEvent.VK_N);
404 item.getAccessibleContext().setAccessibleDescription("Create a new rocket design");
405 item.setIcon(Icons.FILE_NEW);
406 item.addActionListener(new ActionListener() {
407 public void actionPerformed(ActionEvent e) {
408 log.user("New... selected");
411 log.info("Closing previous window");
418 item = new JMenuItem("Open...", KeyEvent.VK_O);
419 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
420 item.getAccessibleContext().setAccessibleDescription("Open a rocket design");
421 item.setIcon(Icons.FILE_OPEN);
422 item.addActionListener(new ActionListener() {
423 public void actionPerformed(ActionEvent e) {
424 log.user("Open... selected");
430 item = new JMenuItem("Open example...");
431 item.getAccessibleContext().setAccessibleDescription("Open an example rocket design");
432 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
433 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
434 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
435 item.addActionListener(new ActionListener() {
436 public void actionPerformed(ActionEvent e) {
437 log.user("Open example... selected");
438 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
441 log.user("Opening example " + u);
442 open(u, BasicFrame.this);
451 item = new JMenuItem("Save", KeyEvent.VK_S);
452 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
453 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design");
454 item.setIcon(Icons.FILE_SAVE);
455 item.addActionListener(new ActionListener() {
456 public void actionPerformed(ActionEvent e) {
457 log.user("Save selected");
463 item = new JMenuItem("Save as...", KeyEvent.VK_A);
464 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
465 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
466 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design " +
468 item.setIcon(Icons.FILE_SAVE_AS);
469 item.addActionListener(new ActionListener() {
470 public void actionPerformed(ActionEvent e) {
471 log.user("Save as... selected");
477 // menu.addSeparator();
478 menu.add(new JSeparator());
480 item = new JMenuItem("Close", KeyEvent.VK_C);
481 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
482 item.getAccessibleContext().setAccessibleDescription("Close the current rocket design");
483 item.setIcon(Icons.FILE_CLOSE);
484 item.addActionListener(new ActionListener() {
485 public void actionPerformed(ActionEvent e) {
486 log.user("Close selected");
495 item = new JMenuItem("Print...", KeyEvent.VK_P);
496 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
497 item.getAccessibleContext().setAccessibleDescription("Print parts list and fin template");
498 item.addActionListener(new ActionListener() {
499 public void actionPerformed(ActionEvent e) {
505 item = new JMenuItem("Quit", KeyEvent.VK_Q);
506 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
507 item.getAccessibleContext().setAccessibleDescription("Quit the program");
508 item.setIcon(Icons.FILE_QUIT);
509 item.addActionListener(new ActionListener() {
510 public void actionPerformed(ActionEvent e) {
511 log.user("Quit selected");
520 menu = new JMenu("Edit");
521 menu.setMnemonic(KeyEvent.VK_E);
522 menu.getAccessibleContext().setAccessibleDescription("Rocket editing");
526 Action action = document.getUndoAction();
527 item = new JMenuItem(action);
528 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
529 item.setMnemonic(KeyEvent.VK_U);
530 item.getAccessibleContext().setAccessibleDescription("Undo the previous operation");
534 action = document.getRedoAction();
535 item = new JMenuItem(action);
536 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
537 item.setMnemonic(KeyEvent.VK_R);
538 item.getAccessibleContext().setAccessibleDescription("Redo the previously undone " +
545 item = new JMenuItem(actions.getCutAction());
548 item = new JMenuItem(actions.getCopyAction());
551 item = new JMenuItem(actions.getPasteAction());
554 item = new JMenuItem(actions.getDeleteAction());
559 item = new JMenuItem("Preferences");
560 item.setIcon(Icons.PREFERENCES);
561 item.getAccessibleContext().setAccessibleDescription("Setup the application " +
563 item.addActionListener(new ActionListener() {
564 public void actionPerformed(ActionEvent e) {
565 log.user("Preferences selected");
566 PreferencesDialog.showPreferences();
575 menu = new JMenu("Analyze");
576 menu.setMnemonic(KeyEvent.VK_A);
577 menu.getAccessibleContext().setAccessibleDescription("Analyzing the rocket");
580 item = new JMenuItem("Component analysis", KeyEvent.VK_C);
581 item.getAccessibleContext().setAccessibleDescription("Analyze the rocket components " +
583 item.addActionListener(new ActionListener() {
584 public void actionPerformed(ActionEvent e) {
585 log.user("Component analysis selected");
586 ComponentAnalysisDialog.showDialog(rocketpanel);
593 // (shown if openrocket.debug.menu is defined)
594 if (System.getProperty("openrocket.debug.menu") != null) {
595 menubar.add(makeDebugMenu());
602 menu = new JMenu("Help");
603 menu.setMnemonic(KeyEvent.VK_H);
604 menu.getAccessibleContext().setAccessibleDescription("Information about OpenRocket");
609 item = new JMenuItem("License", KeyEvent.VK_L);
610 item.getAccessibleContext().setAccessibleDescription("OpenRocket license information");
611 item.addActionListener(new ActionListener() {
612 public void actionPerformed(ActionEvent e) {
613 log.user("License selected");
614 new LicenseDialog(BasicFrame.this).setVisible(true);
621 item = new JMenuItem("Bug report", KeyEvent.VK_B);
622 item.getAccessibleContext().setAccessibleDescription("Information about reporting " +
623 "bugs in OpenRocket");
624 item.addActionListener(new ActionListener() {
625 public void actionPerformed(ActionEvent e) {
626 log.user("Bug report selected");
627 BugReportDialog.showBugReportDialog(BasicFrame.this);
632 item = new JMenuItem("Debug log");
633 item.getAccessibleContext().setAccessibleDescription("View the OpenRocket debug log");
634 item.addActionListener(new ActionListener() {
635 public void actionPerformed(ActionEvent e) {
636 log.user("Debug log selected");
637 new DebugLogDialog(BasicFrame.this).setVisible(true);
644 item = new JMenuItem("About", KeyEvent.VK_A);
645 item.getAccessibleContext().setAccessibleDescription("About OpenRocket");
646 item.addActionListener(new ActionListener() {
647 public void actionPerformed(ActionEvent e) {
648 log.user("About selected");
649 new AboutDialog(BasicFrame.this).setVisible(true);
655 this.setJMenuBar(menubar);
659 private JMenu makeDebugMenu() {
664 menu = new JMenu("Debug");
665 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
667 item = new JMenuItem("What is this menu?");
668 item.addActionListener(new ActionListener() {
669 public void actionPerformed(ActionEvent e) {
670 log.user("What is this menu? selected");
671 JOptionPane.showMessageDialog(BasicFrame.this,
673 "The 'Debug' menu includes actions for testing and debugging " +
675 "The menu is made visible by defining the system property " +
676 "'openrocket.debug.menu' when starting OpenRocket.",
677 "It should not be visible by default." },
678 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
685 item = new JMenuItem("Create test rocket");
686 item.addActionListener(new ActionListener() {
688 public void actionPerformed(ActionEvent e) {
689 log.user("Create test rocket selected");
690 JTextField field = new JTextField();
691 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
692 "Input text key to generate random rocket:",
694 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
695 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
701 r = new TestRockets(null).makeTestRocket();
702 } else if (sel == 1) {
703 r = new TestRockets(field.getText()).makeTestRocket();
708 OpenRocketDocument doc = new OpenRocketDocument(r);
710 BasicFrame frame = new BasicFrame(doc);
711 frame.setVisible(true);
718 item = new JMenuItem("Create 'Iso-Haisu'");
719 item.addActionListener(new ActionListener() {
721 public void actionPerformed(ActionEvent e) {
722 log.user("Create Iso-Haisu selected");
723 Rocket r = TestRockets.makeIsoHaisu();
724 OpenRocketDocument doc = new OpenRocketDocument(r);
726 BasicFrame frame = new BasicFrame(doc);
727 frame.setVisible(true);
733 item = new JMenuItem("Create 'Big Blue'");
734 item.addActionListener(new ActionListener() {
736 public void actionPerformed(ActionEvent e) {
737 log.user("Create Big Blue selected");
738 Rocket r = TestRockets.makeBigBlue();
739 OpenRocketDocument doc = new OpenRocketDocument(r);
741 BasicFrame frame = new BasicFrame(doc);
742 frame.setVisible(true);
750 item = new JMenuItem("Memory statistics");
751 item.addActionListener(new ActionListener() {
753 public void actionPerformed(ActionEvent e) {
754 log.user("Memory statistics selected");
756 // Get discarded but remaining objects (this also runs System.gc multiple times)
757 List<MemoryData> objects = MemoryManagement.getRemainingObjects();
758 StringBuilder sb = new StringBuilder();
759 sb.append("Objects that should have been garbage-collected but have not been:\n");
761 for (MemoryData data : objects) {
762 Object o = data.getReference().get();
765 sb.append("Age ").append(System.currentTimeMillis() - data.getRegistrationTime())
766 .append(" ms: ").append(o).append('\n');
768 // Explicitly null the strong reference to avoid possibility of invisible references
771 sb.append("Total: " + count);
773 // Get basic memory stats
775 long max = Runtime.getRuntime().maxMemory();
776 long free = Runtime.getRuntime().freeMemory();
777 long used = max - free;
778 String[] stats = new String[4];
779 stats[0] = "Memory usage:";
780 stats[1] = String.format(" Max memory: %.1f MB", max / 1024.0 / 1024.0);
781 stats[2] = String.format(" Used memory: %.1f MB (%.0f%%)", used / 1024.0 / 1024.0, 100.0 * used / max);
782 stats[3] = String.format(" Free memory: %.1f MB (%.0f%%)", free / 1024.0 / 1024.0, 100.0 * free / max);
785 DetailDialog.showDetailedMessageDialog(BasicFrame.this, stats, sb.toString(),
786 "Memory statistics", JOptionPane.INFORMATION_MESSAGE);
792 item = new JMenuItem("Exhaust memory");
793 item.addActionListener(new ActionListener() {
795 public void actionPerformed(ActionEvent e) {
796 log.user("Exhaust memory selected");
797 LinkedList<byte[]> data = new LinkedList<byte[]>();
799 final int bytesPerArray = 10240;
802 byte[] array = new byte[bytesPerArray];
803 for (int i = 0; i < bytesPerArray; i++) {
809 } catch (OutOfMemoryError error) {
811 long size = bytesPerArray * (long) count;
812 String s = String.format("OutOfMemory occurred after %d iterations (approx. %.1f MB consumed)",
813 count, size / 1024.0 / 1024.0);
815 JOptionPane.showMessageDialog(BasicFrame.this, s);
824 item = new JMenuItem("Exception here");
825 item.addActionListener(new ActionListener() {
827 public void actionPerformed(ActionEvent e) {
828 log.user("Exception here selected");
829 throw new RuntimeException("Testing exception from menu action listener");
834 item = new JMenuItem("Exception from EDT");
835 item.addActionListener(new ActionListener() {
836 public void actionPerformed(ActionEvent e) {
837 log.user("Exception from EDT selected");
838 SwingUtilities.invokeLater(new Runnable() {
841 throw new RuntimeException("Testing exception from " +
842 "later invoked EDT thread");
849 item = new JMenuItem("Exception from other thread");
850 item.addActionListener(new ActionListener() {
851 public void actionPerformed(ActionEvent e) {
852 log.user("Exception from other thread selected");
856 throw new RuntimeException("Testing exception from " +
857 "newly created thread");
864 item = new JMenuItem("OutOfMemoryError here");
865 item.addActionListener(new ActionListener() {
867 public void actionPerformed(ActionEvent e) {
868 log.user("OutOfMemoryError here selected");
869 throw new OutOfMemoryError("Testing OutOfMemoryError from menu action listener");
881 * Select the tab on the main pane.
883 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
885 public void selectTab(int tab) {
886 tabbedPane.setSelectedIndex(tab);
891 private void openAction() {
892 JFileChooser chooser = new JFileChooser();
894 chooser.addChoosableFileFilter(ALL_DESIGNS_FILTER);
895 chooser.addChoosableFileFilter(OPENROCKET_DESIGN_FILTER);
896 chooser.addChoosableFileFilter(ROCKSIM_DESIGN_FILTER);
897 chooser.setFileFilter(ALL_DESIGNS_FILTER);
899 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
900 chooser.setMultiSelectionEnabled(true);
901 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
902 int option = chooser.showOpenDialog(this);
903 if (option != JFileChooser.APPROVE_OPTION) {
904 log.user("Decided not to open files, option=" + option);
908 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
910 File[] files = chooser.getSelectedFiles();
911 log.user("Opening files " + Arrays.toString(files));
913 for (File file : files) {
914 log.info("Opening file: " + file);
915 if (open(file, this)) {
917 // Close previous window if replacing
918 if (replaceable && document.isSaved()) {
919 log.info("Closing window because it is replaceable");
929 * Open a file based on a URL.
930 * @param url the file to open.
931 * @param parent the parent window for dialogs.
932 * @return <code>true</code> if opened successfully.
934 private static boolean open(URL url, BasicFrame parent) {
935 String filename = null;
937 // First figure out the file name from the URL
939 // Try using URI.getPath();
941 URI uri = url.toURI();
942 filename = uri.getPath();
943 } catch (URISyntaxException ignore) {
946 // Try URL-decoding the URL
947 if (filename == null) {
949 filename = URLDecoder.decode(url.toString(), "UTF-8");
950 } catch (UnsupportedEncodingException ignore) {
955 if (filename == null) {
959 // Remove path from filename
960 if (filename.lastIndexOf('/') >= 0) {
961 filename = filename.substring(filename.lastIndexOf('/') + 1);
966 log.info("Opening file from url=" + url + " filename=" + filename);
968 InputStream is = url.openStream();
969 if (open(is, filename, parent)) {
970 // Close previous window if replacing
971 if (parent.replaceable && parent.document.isSaved()) {
972 parent.closeAction();
973 parent.replaceable = false;
976 } catch (IOException e) {
977 log.warn("Error opening file" + e);
978 JOptionPane.showMessageDialog(parent,
979 "An error occurred while opening the file " + filename,
980 "Error loading file", JOptionPane.ERROR_MESSAGE);
988 * Open the specified file from an InputStream in a new design frame. If an error
989 * occurs, an error dialog is shown and <code>false</code> is returned.
991 * @param stream the stream to load from.
992 * @param filename the file name to display in dialogs (not set to the document).
993 * @param parent the parent component for which a progress dialog is opened.
994 * @return whether the file was successfully loaded and opened.
996 private static boolean open(InputStream stream, String filename, Window parent) {
997 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
998 return open(worker, filename, null, parent);
1003 * Open the specified file in a new design frame. If an error occurs, an error
1004 * dialog is shown and <code>false</code> is returned.
1006 * @param file the file to open.
1007 * @param parent the parent component for which a progress dialog is opened.
1008 * @return whether the file was successfully loaded and opened.
1010 public static boolean open(File file, Window parent) {
1011 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
1012 return open(worker, file.getName(), file, parent);
1017 * Open the specified file using the provided worker.
1019 * @param worker the OpenFileWorker that loads the file.
1020 * @param filename the file name to display in dialogs.
1021 * @param file the File to set the document to (may be null).
1025 private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) {
1027 MotorDatabaseLoadingDialog.check(parent);
1029 // Open the file in a Swing worker thread
1030 log.info("Starting OpenFileWorker");
1031 if (!SwingWorkerDialog.runWorker(parent, "Opening file", "Reading " + filename + "...", worker)) {
1032 // User cancelled the operation
1033 log.info("User cancelled the OpenFileWorker");
1038 // Handle the document
1039 OpenRocketDocument doc = null;
1044 } catch (ExecutionException e) {
1046 Throwable cause = e.getCause();
1048 if (cause instanceof FileNotFoundException) {
1050 log.warn("File not found", cause);
1051 JOptionPane.showMessageDialog(parent,
1052 "File not found: " + filename,
1053 "Error opening file", JOptionPane.ERROR_MESSAGE);
1056 } else if (cause instanceof RocketLoadException) {
1058 log.warn("Error loading the file", cause);
1059 JOptionPane.showMessageDialog(parent,
1060 "Unable to open file '" + filename + "': "
1061 + cause.getMessage(),
1062 "Error opening file", JOptionPane.ERROR_MESSAGE);
1067 throw new BugException("Unknown error when opening file", e);
1071 } catch (InterruptedException e) {
1072 throw new BugException("EDT was interrupted", e);
1076 throw new BugException("Document loader returned null");
1081 WarningSet warnings = worker.getRocketLoader().getWarnings();
1082 if (!warnings.isEmpty()) {
1083 log.info("Warnings while reading file: " + warnings);
1084 WarningDialog.showWarnings(parent,
1086 "The following problems were encountered while opening " + filename + ".",
1087 "Some design features may not have been loaded correctly."
1089 "Warnings while opening file", warnings);
1093 // Set document state
1098 log.debug("Opening new frame with the document");
1099 BasicFrame frame = new BasicFrame(doc);
1100 frame.setVisible(true);
1109 private boolean saveAction() {
1110 File file = document.getFile();
1112 log.info("Document does not contain file, opening save as dialog instead");
1113 return saveAsAction();
1115 log.info("Saving document to " + file);
1117 // Saving RockSim designs is not supported
1118 if (ROCKSIM_DESIGN_FILTER.accept(file)) {
1119 file = new File(file.getAbsolutePath().replaceAll(".[rR][kK][tT](.[gG][zZ])?$",
1122 log.info("Attempting to save in RockSim format, renaming to " + file);
1123 int option = JOptionPane.showConfirmDialog(this, new Object[] {
1124 "Saving designs in RockSim format is not supported.",
1125 "Save in OpenRocket format instead (" + file.getName() + ")?"
1126 }, "Save " + file.getName(), JOptionPane.YES_NO_OPTION,
1127 JOptionPane.QUESTION_MESSAGE, null);
1128 if (option != JOptionPane.YES_OPTION) {
1129 log.user("User chose not to save");
1133 document.setFile(file);
1135 return saveAs(file);
1139 private boolean saveAsAction() {
1142 // TODO: HIGH: what if *.rkt chosen?
1143 StorageOptionChooser storageChooser =
1144 new StorageOptionChooser(document, document.getDefaultStorageOptions());
1145 JFileChooser chooser = new JFileChooser();
1146 chooser.setFileFilter(OPENROCKET_DESIGN_FILTER);
1147 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
1148 chooser.setAccessory(storageChooser);
1149 if (document.getFile() != null)
1150 chooser.setSelectedFile(document.getFile());
1152 int option = chooser.showSaveDialog(BasicFrame.this);
1153 if (option != JFileChooser.APPROVE_OPTION) {
1154 log.user("User decided not to save, option=" + option);
1158 file = chooser.getSelectedFile();
1160 log.user("User did not select a file");
1164 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
1165 storageChooser.storeOptions(document.getDefaultStorageOptions());
1167 if (file.getName().indexOf('.') < 0) {
1168 log.debug("File name does not contain extension, adding .ork");
1169 String name = file.getAbsolutePath();
1170 name = name + ".ork";
1171 file = new File(name);
1174 if (file.exists()) {
1175 log.info("File " + file + " exists, confirming overwrite from user");
1176 int result = JOptionPane.showConfirmDialog(this,
1177 "File '" + file.getName() + "' exists. Do you want to overwrite it?",
1178 "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
1179 if (result != JOptionPane.YES_OPTION) {
1180 log.user("User decided not to overwrite the file");
1185 return saveAs(file);
1188 private boolean saveAs(File file) {
1189 log.info("Saving document as " + file);
1190 boolean saved = false;
1192 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1193 // User cancelled the dialog
1194 log.user("User cancelled saving in storage options dialog");
1199 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1201 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1202 "Writing " + file.getName() + "...", worker)) {
1204 // User cancelled the save
1205 log.user("User cancelled the save, deleting the file");
1212 document.setFile(file);
1213 document.setSaved(true);
1216 } catch (ExecutionException e) {
1218 Throwable cause = e.getCause();
1220 if (cause instanceof IOException) {
1221 log.warn("An I/O error occurred while saving " + file, cause);
1222 JOptionPane.showMessageDialog(this, new String[] {
1223 "An I/O error occurred while saving:",
1224 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1227 Reflection.handleWrappedException(e);
1230 } catch (InterruptedException e) {
1231 throw new BugException("EDT was interrupted", e);
1238 private boolean closeAction() {
1239 if (!document.isSaved()) {
1240 log.info("Confirming whether to save the design");
1241 ComponentConfigDialog.hideDialog();
1242 int result = JOptionPane.showConfirmDialog(this,
1243 "Design '" + rocket.getName() + "' has not been saved. " +
1244 "Do you want to save it?",
1245 "Design not saved", JOptionPane.YES_NO_CANCEL_OPTION,
1246 JOptionPane.QUESTION_MESSAGE);
1247 if (result == JOptionPane.YES_OPTION) {
1249 log.user("User requested file save");
1250 if (!saveAction()) {
1251 log.info("File save was interrupted, not closing");
1254 } else if (result == JOptionPane.NO_OPTION) {
1255 // Don't save: No-op
1256 log.user("User requested to discard design");
1259 log.user("User cancelled closing, result=" + result);
1264 // Rocket has been saved or discarded
1265 log.debug("Disposing window");
1268 ComponentConfigDialog.hideDialog();
1269 ComponentAnalysisDialog.hideDialog();
1271 frames.remove(this);
1272 if (frames.isEmpty()) {
1273 log.info("Last frame closed, exiting");
1284 public void printAction() {
1285 new PrintDialog(document);
1289 * Open a new design window with a basic rocket+stage.
1291 public static void newAction() {
1292 log.info("New action initiated");
1294 Rocket rocket = new Rocket();
1295 Stage stage = new Stage();
1296 stage.setName("Sustainer");
1297 rocket.addChild(stage);
1298 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1301 BasicFrame frame = new BasicFrame(doc);
1302 frame.replaceable = true;
1303 frame.setVisible(true);
1304 ComponentConfigDialog.showDialog(frame, doc, rocket);
1308 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1310 public static void quitAction() {
1311 log.info("Quit action initiated");
1312 for (int i = frames.size() - 1; i >= 0; i--) {
1313 log.debug("Closing frame " + frames.get(i));
1314 if (!frames.get(i).closeAction()) {
1316 log.info("Quit was cancelled");
1320 // Should not be reached, but just in case
1321 log.error("Should already have exited application");
1327 * Set the title of the frame, taking into account the name of the rocket, file it
1328 * has been saved to (if any) and saved status.
1330 private void setTitle() {
1331 File file = document.getFile();
1332 boolean saved = document.isSaved();
1335 title = rocket.getName();
1337 title = title + " (" + file.getName() + ")";
1340 title = "*" + title;
1348 * Find a currently open BasicFrame containing the specified rocket. This method
1349 * can be used to map a Rocket to a BasicFrame from GUI methods.
1351 * @param rocket the Rocket.
1352 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1354 public static BasicFrame findFrame(Rocket rocket) {
1355 for (BasicFrame f : frames) {
1356 if (f.rocket == rocket) {
1357 log.debug("Found frame " + f + " for rocket " + rocket);
1361 log.debug("Could not find frame for rocket " + rocket);
1366 * Find a currently open document by the rocket object. This method can be used
1367 * to map a Rocket to OpenRocketDocument from GUI methods.
1369 * @param rocket the Rocket.
1370 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1372 public static OpenRocketDocument findDocument(Rocket rocket) {
1373 BasicFrame frame = findFrame(rocket);
1374 if (frame != null) {
1375 return frame.document;