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.SwingWorkerDialog;
79 import net.sf.openrocket.gui.dialogs.WarningDialog;
80 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
81 import net.sf.openrocket.gui.main.componenttree.ComponentTree;
82 import net.sf.openrocket.gui.scalefigure.RocketPanel;
83 import net.sf.openrocket.logging.LogHelper;
84 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
85 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
86 import net.sf.openrocket.rocketcomponent.Rocket;
87 import net.sf.openrocket.rocketcomponent.RocketComponent;
88 import net.sf.openrocket.rocketcomponent.Stage;
89 import net.sf.openrocket.startup.Application;
90 import net.sf.openrocket.util.BugException;
91 import net.sf.openrocket.util.GUIUtil;
92 import net.sf.openrocket.util.Icons;
93 import net.sf.openrocket.util.MemoryManagement;
94 import net.sf.openrocket.util.MemoryManagement.MemoryData;
95 import net.sf.openrocket.util.OpenFileWorker;
96 import net.sf.openrocket.util.Prefs;
97 import net.sf.openrocket.util.Reflection;
98 import net.sf.openrocket.util.SaveFileWorker;
99 import net.sf.openrocket.util.TestRockets;
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");
494 item = new JMenuItem("Quit", KeyEvent.VK_Q);
495 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
496 item.getAccessibleContext().setAccessibleDescription("Quit the program");
497 item.setIcon(Icons.FILE_QUIT);
498 item.addActionListener(new ActionListener() {
499 public void actionPerformed(ActionEvent e) {
500 log.user("Quit selected");
509 menu = new JMenu("Edit");
510 menu.setMnemonic(KeyEvent.VK_E);
511 menu.getAccessibleContext().setAccessibleDescription("Rocket editing");
515 Action action = document.getUndoAction();
516 item = new JMenuItem(action);
517 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
518 item.setMnemonic(KeyEvent.VK_U);
519 item.getAccessibleContext().setAccessibleDescription("Undo the previous operation");
523 action = document.getRedoAction();
524 item = new JMenuItem(action);
525 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
526 item.setMnemonic(KeyEvent.VK_R);
527 item.getAccessibleContext().setAccessibleDescription("Redo the previously undone " +
534 item = new JMenuItem(actions.getCutAction());
537 item = new JMenuItem(actions.getCopyAction());
540 item = new JMenuItem(actions.getPasteAction());
543 item = new JMenuItem(actions.getDeleteAction());
548 item = new JMenuItem("Preferences");
549 item.setIcon(Icons.PREFERENCES);
550 item.getAccessibleContext().setAccessibleDescription("Setup the application " +
552 item.addActionListener(new ActionListener() {
553 public void actionPerformed(ActionEvent e) {
554 log.user("Preferences selected");
555 PreferencesDialog.showPreferences();
564 menu = new JMenu("Analyze");
565 menu.setMnemonic(KeyEvent.VK_A);
566 menu.getAccessibleContext().setAccessibleDescription("Analyzing the rocket");
569 item = new JMenuItem("Component analysis", KeyEvent.VK_C);
570 item.getAccessibleContext().setAccessibleDescription("Analyze the rocket components " +
572 item.addActionListener(new ActionListener() {
573 public void actionPerformed(ActionEvent e) {
574 log.user("Component analysis selected");
575 ComponentAnalysisDialog.showDialog(rocketpanel);
582 // (shown if openrocket.debug.menu is defined)
583 if (System.getProperty("openrocket.debug.menu") != null) {
584 menubar.add(makeDebugMenu());
591 menu = new JMenu("Help");
592 menu.setMnemonic(KeyEvent.VK_H);
593 menu.getAccessibleContext().setAccessibleDescription("Information about OpenRocket");
598 item = new JMenuItem("License", KeyEvent.VK_L);
599 item.getAccessibleContext().setAccessibleDescription("OpenRocket license information");
600 item.addActionListener(new ActionListener() {
601 public void actionPerformed(ActionEvent e) {
602 log.user("License selected");
603 new LicenseDialog(BasicFrame.this).setVisible(true);
610 item = new JMenuItem("Bug report", KeyEvent.VK_B);
611 item.getAccessibleContext().setAccessibleDescription("Information about reporting " +
612 "bugs in OpenRocket");
613 item.addActionListener(new ActionListener() {
614 public void actionPerformed(ActionEvent e) {
615 log.user("Bug report selected");
616 BugReportDialog.showBugReportDialog(BasicFrame.this);
621 item = new JMenuItem("Debug log");
622 item.getAccessibleContext().setAccessibleDescription("View the OpenRocket debug log");
623 item.addActionListener(new ActionListener() {
624 public void actionPerformed(ActionEvent e) {
625 log.user("Debug log selected");
626 new DebugLogDialog(BasicFrame.this).setVisible(true);
633 item = new JMenuItem("About", KeyEvent.VK_A);
634 item.getAccessibleContext().setAccessibleDescription("About OpenRocket");
635 item.addActionListener(new ActionListener() {
636 public void actionPerformed(ActionEvent e) {
637 log.user("About selected");
638 new AboutDialog(BasicFrame.this).setVisible(true);
644 this.setJMenuBar(menubar);
648 private JMenu makeDebugMenu() {
653 menu = new JMenu("Debug");
654 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
656 item = new JMenuItem("What is this menu?");
657 item.addActionListener(new ActionListener() {
658 public void actionPerformed(ActionEvent e) {
659 log.user("What is this menu? selected");
660 JOptionPane.showMessageDialog(BasicFrame.this,
662 "The 'Debug' menu includes actions for testing and debugging " +
664 "The menu is made visible by defining the system property " +
665 "'openrocket.debug.menu' when starting OpenRocket.",
666 "It should not be visible by default." },
667 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
674 item = new JMenuItem("Create test rocket");
675 item.addActionListener(new ActionListener() {
677 public void actionPerformed(ActionEvent e) {
678 log.user("Create test rocket selected");
679 JTextField field = new JTextField();
680 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
681 "Input text key to generate random rocket:",
683 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
684 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
690 r = new TestRockets(null).makeTestRocket();
691 } else if (sel == 1) {
692 r = new TestRockets(field.getText()).makeTestRocket();
697 OpenRocketDocument doc = new OpenRocketDocument(r);
699 BasicFrame frame = new BasicFrame(doc);
700 frame.setVisible(true);
707 item = new JMenuItem("Create 'Iso-Haisu'");
708 item.addActionListener(new ActionListener() {
710 public void actionPerformed(ActionEvent e) {
711 log.user("Create Iso-Haisu selected");
712 Rocket r = TestRockets.makeIsoHaisu();
713 OpenRocketDocument doc = new OpenRocketDocument(r);
715 BasicFrame frame = new BasicFrame(doc);
716 frame.setVisible(true);
722 item = new JMenuItem("Create 'Big Blue'");
723 item.addActionListener(new ActionListener() {
725 public void actionPerformed(ActionEvent e) {
726 log.user("Create Big Blue selected");
727 Rocket r = TestRockets.makeBigBlue();
728 OpenRocketDocument doc = new OpenRocketDocument(r);
730 BasicFrame frame = new BasicFrame(doc);
731 frame.setVisible(true);
739 item = new JMenuItem("Memory statistics");
740 item.addActionListener(new ActionListener() {
742 public void actionPerformed(ActionEvent e) {
743 log.user("Memory statistics selected");
745 // Get discarded but remaining objects (this also runs System.gc multiple times)
746 List<MemoryData> objects = MemoryManagement.getRemainingObjects();
747 StringBuilder sb = new StringBuilder();
748 sb.append("Objects that should have been garbage-collected but have not been:\n");
750 for (MemoryData data : objects) {
751 Object o = data.getReference().get();
754 sb.append("Age ").append(System.currentTimeMillis() - data.getRegistrationTime())
755 .append(" ms: ").append(o).append('\n');
757 // Explicitly null the strong reference to avoid possibility of invisible references
760 sb.append("Total: " + count);
762 // Get basic memory stats
764 long max = Runtime.getRuntime().maxMemory();
765 long free = Runtime.getRuntime().freeMemory();
766 long used = max - free;
767 String[] stats = new String[4];
768 stats[0] = "Memory usage:";
769 stats[1] = String.format(" Max memory: %.1f MB", max / 1024.0 / 1024.0);
770 stats[2] = String.format(" Used memory: %.1f MB (%.0f%%)", used / 1024.0 / 1024.0, 100.0 * used / max);
771 stats[3] = String.format(" Free memory: %.1f MB (%.0f%%)", free / 1024.0 / 1024.0, 100.0 * free / max);
774 DetailDialog.showDetailedMessageDialog(BasicFrame.this, stats, sb.toString(),
775 "Memory statistics", JOptionPane.INFORMATION_MESSAGE);
781 item = new JMenuItem("Exhaust memory");
782 item.addActionListener(new ActionListener() {
784 public void actionPerformed(ActionEvent e) {
785 log.user("Exhaust memory selected");
786 LinkedList<byte[]> data = new LinkedList<byte[]>();
788 final int bytesPerArray = 10240;
791 byte[] array = new byte[bytesPerArray];
792 for (int i = 0; i < bytesPerArray; i++) {
798 } catch (OutOfMemoryError error) {
800 long size = bytesPerArray * (long) count;
801 String s = String.format("OutOfMemory occurred after %d iterations (approx. %.1f MB consumed)",
802 count, size / 1024.0 / 1024.0);
804 JOptionPane.showMessageDialog(BasicFrame.this, s);
813 item = new JMenuItem("Exception here");
814 item.addActionListener(new ActionListener() {
816 public void actionPerformed(ActionEvent e) {
817 log.user("Exception here selected");
818 throw new RuntimeException("Testing exception from menu action listener");
823 item = new JMenuItem("Exception from EDT");
824 item.addActionListener(new ActionListener() {
825 public void actionPerformed(ActionEvent e) {
826 log.user("Exception from EDT selected");
827 SwingUtilities.invokeLater(new Runnable() {
830 throw new RuntimeException("Testing exception from " +
831 "later invoked EDT thread");
838 item = new JMenuItem("Exception from other thread");
839 item.addActionListener(new ActionListener() {
840 public void actionPerformed(ActionEvent e) {
841 log.user("Exception from other thread selected");
845 throw new RuntimeException("Testing exception from " +
846 "newly created thread");
853 item = new JMenuItem("OutOfMemoryError here");
854 item.addActionListener(new ActionListener() {
856 public void actionPerformed(ActionEvent e) {
857 log.user("OutOfMemoryError here selected");
858 throw new OutOfMemoryError("Testing OutOfMemoryError from menu action listener");
870 * Select the tab on the main pane.
872 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
874 public void selectTab(int tab) {
875 tabbedPane.setSelectedIndex(tab);
880 private void openAction() {
881 JFileChooser chooser = new JFileChooser();
883 chooser.addChoosableFileFilter(ALL_DESIGNS_FILTER);
884 chooser.addChoosableFileFilter(OPENROCKET_DESIGN_FILTER);
885 chooser.addChoosableFileFilter(ROCKSIM_DESIGN_FILTER);
886 chooser.setFileFilter(ALL_DESIGNS_FILTER);
888 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
889 chooser.setMultiSelectionEnabled(true);
890 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
891 int option = chooser.showOpenDialog(this);
892 if (option != JFileChooser.APPROVE_OPTION) {
893 log.user("Decided not to open files, option=" + option);
897 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
899 File[] files = chooser.getSelectedFiles();
900 log.user("Opening files " + Arrays.toString(files));
902 for (File file : files) {
903 log.info("Opening file: " + file);
904 if (open(file, this)) {
906 // Close previous window if replacing
907 if (replaceable && document.isSaved()) {
908 log.info("Closing window because it is replaceable");
918 * Open a file based on a URL.
919 * @param url the file to open.
920 * @param parent the parent window for dialogs.
921 * @return <code>true</code> if opened successfully.
923 private static boolean open(URL url, BasicFrame parent) {
924 String filename = null;
926 // First figure out the file name from the URL
928 // Try using URI.getPath();
930 URI uri = url.toURI();
931 filename = uri.getPath();
932 } catch (URISyntaxException ignore) {
935 // Try URL-decoding the URL
936 if (filename == null) {
938 filename = URLDecoder.decode(url.toString(), "UTF-8");
939 } catch (UnsupportedEncodingException ignore) {
944 if (filename == null) {
948 // Remove path from filename
949 if (filename.lastIndexOf('/') >= 0) {
950 filename = filename.substring(filename.lastIndexOf('/') + 1);
955 log.info("Opening file from url=" + url + " filename=" + filename);
957 InputStream is = url.openStream();
958 if (open(is, filename, parent)) {
959 // Close previous window if replacing
960 if (parent.replaceable && parent.document.isSaved()) {
961 parent.closeAction();
962 parent.replaceable = false;
965 } catch (IOException e) {
966 log.warn("Error opening file" + e);
967 JOptionPane.showMessageDialog(parent,
968 "An error occurred while opening the file " + filename,
969 "Error loading file", JOptionPane.ERROR_MESSAGE);
977 * Open the specified file from an InputStream in a new design frame. If an error
978 * occurs, an error dialog is shown and <code>false</code> is returned.
980 * @param stream the stream to load from.
981 * @param filename the file name to display in dialogs (not set to the document).
982 * @param parent the parent component for which a progress dialog is opened.
983 * @return whether the file was successfully loaded and opened.
985 private static boolean open(InputStream stream, String filename, Window parent) {
986 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
987 return open(worker, filename, null, parent);
992 * Open the specified file in a new design frame. If an error occurs, an error
993 * dialog is shown and <code>false</code> is returned.
995 * @param file the file to open.
996 * @param parent the parent component for which a progress dialog is opened.
997 * @return whether the file was successfully loaded and opened.
999 public static boolean open(File file, Window parent) {
1000 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
1001 return open(worker, file.getName(), file, parent);
1006 * Open the specified file using the provided worker.
1008 * @param worker the OpenFileWorker that loads the file.
1009 * @param filename the file name to display in dialogs.
1010 * @param file the File to set the document to (may be null).
1014 private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) {
1016 MotorDatabaseLoadingDialog.check(parent);
1018 // Open the file in a Swing worker thread
1019 log.info("Starting OpenFileWorker");
1020 if (!SwingWorkerDialog.runWorker(parent, "Opening file", "Reading " + filename + "...", worker)) {
1021 // User cancelled the operation
1022 log.info("User cancelled the OpenFileWorker");
1027 // Handle the document
1028 OpenRocketDocument doc = null;
1033 } catch (ExecutionException e) {
1035 Throwable cause = e.getCause();
1037 if (cause instanceof FileNotFoundException) {
1039 log.warn("File not found", cause);
1040 JOptionPane.showMessageDialog(parent,
1041 "File not found: " + filename,
1042 "Error opening file", JOptionPane.ERROR_MESSAGE);
1045 } else if (cause instanceof RocketLoadException) {
1047 log.warn("Error loading the file", cause);
1048 JOptionPane.showMessageDialog(parent,
1049 "Unable to open file '" + filename + "': "
1050 + cause.getMessage(),
1051 "Error opening file", JOptionPane.ERROR_MESSAGE);
1056 throw new BugException("Unknown error when opening file", e);
1060 } catch (InterruptedException e) {
1061 throw new BugException("EDT was interrupted", e);
1065 throw new BugException("Document loader returned null");
1070 WarningSet warnings = worker.getRocketLoader().getWarnings();
1071 if (!warnings.isEmpty()) {
1072 log.info("Warnings while reading file: " + warnings);
1073 WarningDialog.showWarnings(parent,
1075 "The following problems were encountered while opening " + filename + ".",
1076 "Some design features may not have been loaded correctly."
1078 "Warnings while opening file", warnings);
1082 // Set document state
1087 log.debug("Opening new frame with the document");
1088 BasicFrame frame = new BasicFrame(doc);
1089 frame.setVisible(true);
1098 private boolean saveAction() {
1099 File file = document.getFile();
1101 log.info("Document does not contain file, opening save as dialog instead");
1102 return saveAsAction();
1104 log.info("Saving document to " + file);
1106 // Saving RockSim designs is not supported
1107 if (ROCKSIM_DESIGN_FILTER.accept(file)) {
1108 file = new File(file.getAbsolutePath().replaceAll(".[rR][kK][tT](.[gG][zZ])?$",
1111 log.info("Attempting to save in RockSim format, renaming to " + file);
1112 int option = JOptionPane.showConfirmDialog(this, new Object[] {
1113 "Saving designs in RockSim format is not supported.",
1114 "Save in OpenRocket format instead (" + file.getName() + ")?"
1115 }, "Save " + file.getName(), JOptionPane.YES_NO_OPTION,
1116 JOptionPane.QUESTION_MESSAGE, null);
1117 if (option != JOptionPane.YES_OPTION) {
1118 log.user("User chose not to save");
1122 document.setFile(file);
1124 return saveAs(file);
1128 private boolean saveAsAction() {
1131 // TODO: HIGH: what if *.rkt chosen?
1132 StorageOptionChooser storageChooser =
1133 new StorageOptionChooser(document, document.getDefaultStorageOptions());
1134 JFileChooser chooser = new JFileChooser();
1135 chooser.setFileFilter(OPENROCKET_DESIGN_FILTER);
1136 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
1137 chooser.setAccessory(storageChooser);
1138 if (document.getFile() != null)
1139 chooser.setSelectedFile(document.getFile());
1141 int option = chooser.showSaveDialog(BasicFrame.this);
1142 if (option != JFileChooser.APPROVE_OPTION) {
1143 log.user("User decided not to save, option=" + option);
1147 file = chooser.getSelectedFile();
1149 log.user("User did not select a file");
1153 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
1154 storageChooser.storeOptions(document.getDefaultStorageOptions());
1156 if (file.getName().indexOf('.') < 0) {
1157 log.debug("File name does not contain extension, adding .ork");
1158 String name = file.getAbsolutePath();
1159 name = name + ".ork";
1160 file = new File(name);
1163 if (file.exists()) {
1164 log.info("File " + file + " exists, confirming overwrite from user");
1165 int result = JOptionPane.showConfirmDialog(this,
1166 "File '" + file.getName() + "' exists. Do you want to overwrite it?",
1167 "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
1168 if (result != JOptionPane.YES_OPTION) {
1169 log.user("User decided not to overwrite the file");
1174 return saveAs(file);
1177 private boolean saveAs(File file) {
1178 log.info("Saving document as " + file);
1179 boolean saved = false;
1181 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1182 // User cancelled the dialog
1183 log.user("User cancelled saving in storage options dialog");
1188 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1190 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1191 "Writing " + file.getName() + "...", worker)) {
1193 // User cancelled the save
1194 log.user("User cancelled the save, deleting the file");
1201 document.setFile(file);
1202 document.setSaved(true);
1205 } catch (ExecutionException e) {
1207 Throwable cause = e.getCause();
1209 if (cause instanceof IOException) {
1210 log.warn("An I/O error occurred while saving " + file, cause);
1211 JOptionPane.showMessageDialog(this, new String[] {
1212 "An I/O error occurred while saving:",
1213 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1216 Reflection.handleWrappedException(e);
1219 } catch (InterruptedException e) {
1220 throw new BugException("EDT was interrupted", e);
1227 private boolean closeAction() {
1228 if (!document.isSaved()) {
1229 log.info("Confirming whether to save the design");
1230 ComponentConfigDialog.hideDialog();
1231 int result = JOptionPane.showConfirmDialog(this,
1232 "Design '" + rocket.getName() + "' has not been saved. " +
1233 "Do you want to save it?",
1234 "Design not saved", JOptionPane.YES_NO_CANCEL_OPTION,
1235 JOptionPane.QUESTION_MESSAGE);
1236 if (result == JOptionPane.YES_OPTION) {
1238 log.user("User requested file save");
1239 if (!saveAction()) {
1240 log.info("File save was interrupted, not closing");
1243 } else if (result == JOptionPane.NO_OPTION) {
1244 // Don't save: No-op
1245 log.user("User requested to discard design");
1248 log.user("User cancelled closing, result=" + result);
1253 // Rocket has been saved or discarded
1254 log.debug("Disposing window");
1257 ComponentConfigDialog.hideDialog();
1258 ComponentAnalysisDialog.hideDialog();
1260 frames.remove(this);
1261 if (frames.isEmpty()) {
1262 log.info("Last frame closed, exiting");
1271 * Open a new design window with a basic rocket+stage.
1273 public static void newAction() {
1274 log.info("New action initiated");
1276 Rocket rocket = new Rocket();
1277 Stage stage = new Stage();
1278 stage.setName("Sustainer");
1279 rocket.addChild(stage);
1280 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1283 BasicFrame frame = new BasicFrame(doc);
1284 frame.replaceable = true;
1285 frame.setVisible(true);
1286 ComponentConfigDialog.showDialog(frame, doc, rocket);
1290 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1292 public static void quitAction() {
1293 log.info("Quit action initiated");
1294 for (int i = frames.size() - 1; i >= 0; i--) {
1295 log.debug("Closing frame " + frames.get(i));
1296 if (!frames.get(i).closeAction()) {
1298 log.info("Quit was cancelled");
1302 // Should not be reached, but just in case
1303 log.error("Should already have exited application");
1309 * Set the title of the frame, taking into account the name of the rocket, file it
1310 * has been saved to (if any) and saved status.
1312 private void setTitle() {
1313 File file = document.getFile();
1314 boolean saved = document.isSaved();
1317 title = rocket.getName();
1319 title = title + " (" + file.getName() + ")";
1322 title = "*" + title;
1330 * Find a currently open BasicFrame containing the specified rocket. This method
1331 * can be used to map a Rocket to a BasicFrame from GUI methods.
1333 * @param rocket the Rocket.
1334 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1336 public static BasicFrame findFrame(Rocket rocket) {
1337 for (BasicFrame f : frames) {
1338 if (f.rocket == rocket) {
1339 log.debug("Found frame " + f + " for rocket " + rocket);
1343 log.debug("Could not find frame for rocket " + rocket);
1348 * Find a currently open document by the rocket object. This method can be used
1349 * to map a Rocket to OpenRocketDocument from GUI methods.
1351 * @param rocket the Rocket.
1352 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1354 public static OpenRocketDocument findDocument(Rocket rocket) {
1355 BasicFrame frame = findFrame(rocket);
1356 if (frame != null) {
1357 return frame.document;