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.l10n.Translator;
85 import net.sf.openrocket.logging.LogHelper;
86 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
87 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
88 import net.sf.openrocket.rocketcomponent.Rocket;
89 import net.sf.openrocket.rocketcomponent.RocketComponent;
90 import net.sf.openrocket.rocketcomponent.Stage;
91 import net.sf.openrocket.startup.Application;
92 import net.sf.openrocket.util.BugException;
93 import net.sf.openrocket.util.GUIUtil;
94 import net.sf.openrocket.util.Icons;
95 import net.sf.openrocket.util.MemoryManagement;
96 import net.sf.openrocket.util.MemoryManagement.MemoryData;
97 import net.sf.openrocket.util.OpenFileWorker;
98 import net.sf.openrocket.util.Prefs;
99 import net.sf.openrocket.util.Reflection;
100 import net.sf.openrocket.util.SaveFileWorker;
101 import net.sf.openrocket.util.TestRockets;
103 public class BasicFrame extends JFrame {
104 private static final LogHelper log = Application.getLogger();
107 * The RocketLoader instance used for loading all rocket designs.
109 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
111 private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
113 private static final Translator trans = Application.getTranslator();
115 // FileFilters for different types of rocket design files
116 private static final FileFilter ALL_DESIGNS_FILTER =
117 //// All rocket designs (*.ork; *.rkt)
118 new SimpleFileFilter(trans.get("BasicFrame.SimpleFileFilter1"),
119 ".ork", ".ork.gz", ".rkt", ".rkt.gz");
121 private static final FileFilter OPENROCKET_DESIGN_FILTER =
122 //// OpenRocket designs (*.ork)
123 new SimpleFileFilter(trans.get("BasicFrame.SimpleFileFilter2"), ".ork", ".ork.gz");
125 private static final FileFilter ROCKSIM_DESIGN_FILTER =
126 //// RockSim designs (*.rkt)
127 new SimpleFileFilter(trans.get("BasicFrame.SimpleFileFilter3"), ".rkt", ".rkt.gz");
132 public static final int COMPONENT_TAB = 0;
133 public static final int SIMULATION_TAB = 1;
137 * List of currently open frames. When the list goes empty
138 * it is time to exit the application.
140 private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
147 * Whether "New" and "Open" should replace this frame.
148 * Should be set to false on the first rocket modification.
150 private boolean replaceable = false;
154 private final OpenRocketDocument document;
155 private final Rocket rocket;
157 private JTabbedPane tabbedPane;
158 private RocketPanel rocketpanel;
159 private ComponentTree tree = null;
161 private final DocumentSelectionModel selectionModel;
162 private final TreeSelectionModel componentSelectionModel;
163 private final ListSelectionModel simulationSelectionModel;
165 /** Actions available for rocket modifications */
166 private final RocketActions actions;
171 * Sole constructor. Creates a new frame based on the supplied document
172 * and adds it to the current frames list.
174 * @param document the document to show.
176 public BasicFrame(OpenRocketDocument document) {
177 log.debug("Instantiating new BasicFrame");
179 this.document = document;
180 this.rocket = document.getRocket();
181 this.rocket.getDefaultConfiguration().setAllStages();
184 // Set replaceable flag to false at first modification
185 rocket.addComponentChangeListener(new ComponentChangeListener() {
187 public void componentChanged(ComponentChangeEvent e) {
189 BasicFrame.this.rocket.removeComponentChangeListener(this);
194 // Create the component tree selection model that will be used
195 componentSelectionModel = new DefaultTreeSelectionModel();
196 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
198 // Obtain the simulation selection model that will be used
199 SimulationPanel simulationPanel = new SimulationPanel(document);
200 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
202 // Combine into a DocumentSelectionModel
203 selectionModel = new DocumentSelectionModel(document);
204 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
205 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
208 actions = new RocketActions(document, selectionModel, this);
211 log.debug("Constructing the BasicFrame UI");
213 // The main vertical split pane
214 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
215 vertical.setResizeWeight(0.5);
219 // The top tabbed pane
220 tabbedPane = new JTabbedPane();
222 tabbedPane.addTab(trans.get("BasicFrame.tab.Rocketdesign"), null, designTab());
223 //// Flight simulations
224 tabbedPane.addTab(trans.get("BasicFrame.tab.Flightsim"), null, simulationPanel);
226 vertical.setTopComponent(tabbedPane);
230 // Bottom segment, rocket figure
232 rocketpanel = new RocketPanel(document);
233 vertical.setBottomComponent(rocketpanel);
235 rocketpanel.setSelectionModel(tree.getSelectionModel());
241 rocket.addComponentChangeListener(new ComponentChangeListener() {
243 public void componentChanged(ComponentChangeEvent e) {
251 Dimension size = Prefs.getWindowSize(this.getClass());
253 size = Toolkit.getDefaultToolkit().getScreenSize();
254 size.width = size.width * 9 / 10;
255 size.height = size.height * 9 / 10;
258 this.addComponentListener(new ComponentAdapter() {
260 public void componentResized(ComponentEvent e) {
261 Prefs.setWindowSize(BasicFrame.this.getClass(), BasicFrame.this.getSize());
264 this.setLocationByPlatform(true);
266 GUIUtil.setWindowIcons(this);
269 vertical.setDividerLocation(0.4);
270 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
271 addWindowListener(new WindowAdapter() {
273 public void windowClosing(WindowEvent e) {
279 log.debug("BasicFrame instantiation complete");
284 * Construct the "Rocket design" tab. This contains a horizontal split pane
285 * with the left component the design tree and the right component buttons
286 * for adding components.
288 private JComponent designTab() {
289 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
290 horizontal.setResizeWeight(0.5);
293 // Upper-left segment, component tree
295 JPanel panel = new JPanel(new MigLayout("fill, flowy", "", "[grow]"));
297 tree = new ComponentTree(document);
298 tree.setSelectionModel(componentSelectionModel);
300 // Remove JTree key events that interfere with menu accelerators
301 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
302 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
303 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
304 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
305 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
306 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
307 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
308 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
312 // Double-click opens config dialog
313 MouseListener ml = new MouseAdapter() {
315 public void mousePressed(MouseEvent e) {
316 int selRow = tree.getRowForLocation(e.getX(), e.getY());
317 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
319 if ((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
321 RocketComponent c = (RocketComponent) selPath.getLastPathComponent();
322 ComponentConfigDialog.showDialog(BasicFrame.this,
323 BasicFrame.this.document, c);
328 tree.addMouseListener(ml);
330 // Update dialog when selection is changed
331 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
333 public void valueChanged(TreeSelectionEvent e) {
334 // Scroll tree to the selected item
335 TreePath path = componentSelectionModel.getSelectionPath();
338 tree.scrollPathToVisible(path);
340 if (!ComponentConfigDialog.isDialogVisible())
342 RocketComponent c = (RocketComponent) path.getLastPathComponent();
343 ComponentConfigDialog.showDialog(BasicFrame.this,
344 BasicFrame.this.document, c);
348 // Place tree inside scroll pane
349 JScrollPane scroll = new JScrollPane(tree);
350 panel.add(scroll, "spany, grow, wrap");
354 JButton button = new JButton(actions.getMoveUpAction());
355 panel.add(button, "sizegroup buttons, aligny 65%");
357 button = new JButton(actions.getMoveDownAction());
358 panel.add(button, "sizegroup buttons, aligny 0%");
360 button = new JButton(actions.getEditAction());
361 panel.add(button, "sizegroup buttons");
363 button = new JButton(actions.getNewStageAction());
364 panel.add(button, "sizegroup buttons");
366 button = new JButton(actions.getDeleteAction());
367 button.setIcon(null);
368 button.setMnemonic(0);
369 panel.add(button, "sizegroup buttons");
371 horizontal.setLeftComponent(panel);
374 // Upper-right segment, component addition buttons
376 panel = new JPanel(new MigLayout("fill, insets 0", "[0::]"));
378 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
379 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
380 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
381 scroll.getViewport()));
382 scroll.setBorder(null);
383 scroll.setViewportBorder(null);
385 TitledBorder border = new TitledBorder(trans.get("BasicFrame.title.Addnewcomp"));
386 border.setTitleFont(border.getTitleFont().deriveFont(Font.BOLD));
387 scroll.setBorder(border);
389 panel.add(scroll, "grow");
391 horizontal.setRightComponent(panel);
399 * Creates the menu for the window.
401 private void createMenu() {
402 JMenuBar menubar = new JMenuBar();
407 menu = new JMenu(trans.get("main.menu.file"));
408 menu.setMnemonic(KeyEvent.VK_F);
409 //// File-handling related tasks
410 menu.getAccessibleContext().setAccessibleDescription("File-handling related tasks");
414 item = new JMenuItem(trans.get("main.menu.file.new"), KeyEvent.VK_N);
415 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
416 item.setMnemonic(KeyEvent.VK_N);
417 //// Create a new rocket design
418 item.getAccessibleContext().setAccessibleDescription("Create a new rocket design");
419 item.setIcon(Icons.FILE_NEW);
420 item.addActionListener(new ActionListener() {
422 public void actionPerformed(ActionEvent e) {
423 log.user("New... selected");
426 log.info("Closing previous window");
434 item = new JMenuItem(trans.get("main.menu.file.open"), KeyEvent.VK_O);
435 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
436 //// Open a rocket design
437 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openrocketdesign"));
438 item.setIcon(Icons.FILE_OPEN);
439 item.addActionListener(new ActionListener() {
441 public void actionPerformed(ActionEvent e) {
442 log.user("Open... selected");
449 item = new JMenuItem(trans.get("main.menu.file.openExample"));
450 //// Open an example rocket design
451 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openexamplerocketdesign"));
452 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
453 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
454 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
455 item.addActionListener(new ActionListener() {
457 public void actionPerformed(ActionEvent e) {
458 log.user("Open example... selected");
459 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
462 log.user("Opening example " + u);
463 open(u, BasicFrame.this);
473 item = new JMenuItem(trans.get("main.menu.file.save"), KeyEvent.VK_S);
474 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
475 //// Save the current rocket design
476 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesign"));
477 item.setIcon(Icons.FILE_SAVE);
478 item.addActionListener(new ActionListener() {
480 public void actionPerformed(ActionEvent e) {
481 log.user("Save selected");
488 item = new JMenuItem(trans.get("main.menu.file.saveAs"), KeyEvent.VK_A);
489 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
490 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
491 //// Save the current rocket design to a new file
492 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesnewfile"));
493 item.setIcon(Icons.FILE_SAVE_AS);
494 item.addActionListener(new ActionListener() {
496 public void actionPerformed(ActionEvent e) {
497 log.user("Save as... selected");
504 item = new JMenuItem(trans.get("main.menu.file.print"), KeyEvent.VK_P);
505 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
506 //// Print parts list and fin template
507 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Printpart"));
508 item.setIcon(Icons.FILE_PRINT);
509 item.addActionListener(new ActionListener() {
511 public void actionPerformed(ActionEvent e) {
521 item = new JMenuItem(trans.get("main.menu.file.close"), KeyEvent.VK_C);
522 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
523 //// Close the current rocket design
524 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Closedesign"));
525 item.setIcon(Icons.FILE_CLOSE);
526 item.addActionListener(new ActionListener() {
528 public void actionPerformed(ActionEvent e) {
529 log.user("Close selected");
538 item = new JMenuItem(trans.get("main.menu.file.quit"), KeyEvent.VK_Q);
539 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
540 //// Quit the program
541 item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Quitprogram"));
542 item.setIcon(Icons.FILE_QUIT);
543 item.addActionListener(new ActionListener() {
545 public void actionPerformed(ActionEvent e) {
546 log.user("Quit selected");
555 menu = new JMenu(trans.get("main.menu.edit"));
556 menu.setMnemonic(KeyEvent.VK_E);
558 menu.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.menu.Rocketedt"));
562 Action action = document.getUndoAction();
563 item = new JMenuItem(action);
564 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
565 item.setMnemonic(KeyEvent.VK_U);
566 //// Undo the previous operation
567 item.getAccessibleContext().setAccessibleDescription("Undo the previous operation");
571 action = document.getRedoAction();
572 item = new JMenuItem(action);
573 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
574 item.setMnemonic(KeyEvent.VK_R);
575 //// Redo the previously undone operation
576 item.getAccessibleContext().setAccessibleDescription("Redo the previously undone " +
583 item = new JMenuItem(actions.getCutAction());
586 item = new JMenuItem(actions.getCopyAction());
589 item = new JMenuItem(actions.getPasteAction());
592 item = new JMenuItem(actions.getDeleteAction());
598 item = new JMenuItem(trans.get("main.menu.edit.preferences"));
599 item.setIcon(Icons.PREFERENCES);
600 //// Setup the application preferences
601 item.getAccessibleContext().setAccessibleDescription("Setup the application " +
603 item.addActionListener(new ActionListener() {
605 public void actionPerformed(ActionEvent e) {
606 log.user("Preferences selected");
607 PreferencesDialog.showPreferences();
616 menu = new JMenu(trans.get("main.menu.analyze"));
617 menu.setMnemonic(KeyEvent.VK_A);
618 //// Analyzing the rocket
619 menu.getAccessibleContext().setAccessibleDescription("Analyzing the rocket");
622 //// Component analysis
623 item = new JMenuItem(trans.get("main.menu.analyze.componentAnalysis"), KeyEvent.VK_C);
624 //// Analyze the rocket components separately
625 item.getAccessibleContext().setAccessibleDescription("Analyze the rocket components " +
627 item.addActionListener(new ActionListener() {
629 public void actionPerformed(ActionEvent e) {
630 log.user("Component analysis selected");
631 ComponentAnalysisDialog.showDialog(rocketpanel);
638 // (shown if openrocket.debug.menu is defined)
639 if (System.getProperty("openrocket.debug.menu") != null) {
640 menubar.add(makeDebugMenu());
647 menu = new JMenu(trans.get("main.menu.help"));
648 menu.setMnemonic(KeyEvent.VK_H);
649 //// Information about OpenRocket
650 menu.getAccessibleContext().setAccessibleDescription("Information about OpenRocket");
655 item = new JMenuItem(trans.get("main.menu.help.license"), KeyEvent.VK_L);
656 //// OpenRocket license information
657 item.getAccessibleContext().setAccessibleDescription("OpenRocket license information");
658 item.addActionListener(new ActionListener() {
660 public void actionPerformed(ActionEvent e) {
661 log.user("License selected");
662 new LicenseDialog(BasicFrame.this).setVisible(true);
670 item = new JMenuItem(trans.get("main.menu.help.bugReport"), KeyEvent.VK_B);
671 //// Information about reporting bugs in OpenRocket
672 item.getAccessibleContext().setAccessibleDescription("Information about reporting " +
673 "bugs in OpenRocket");
674 item.addActionListener(new ActionListener() {
676 public void actionPerformed(ActionEvent e) {
677 log.user("Bug report selected");
678 BugReportDialog.showBugReportDialog(BasicFrame.this);
684 item = new JMenuItem(trans.get("main.menu.help.debugLog"));
685 //// View the OpenRocket debug log
686 item.getAccessibleContext().setAccessibleDescription("View the OpenRocket debug log");
687 item.addActionListener(new ActionListener() {
689 public void actionPerformed(ActionEvent e) {
690 log.user("Debug log selected");
691 new DebugLogDialog(BasicFrame.this).setVisible(true);
699 item = new JMenuItem(trans.get("main.menu.help.about"), KeyEvent.VK_A);
700 //// About OpenRocket
701 item.getAccessibleContext().setAccessibleDescription("About OpenRocket");
702 item.addActionListener(new ActionListener() {
704 public void actionPerformed(ActionEvent e) {
705 log.user("About selected");
706 new AboutDialog(BasicFrame.this).setVisible(true);
712 this.setJMenuBar(menubar);
716 private JMenu makeDebugMenu() {
721 menu = new JMenu("Debug");
722 //// OpenRocket debugging tasks
723 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
725 //// What is this menu?
726 item = new JMenuItem("What is this menu?");
727 item.addActionListener(new ActionListener() {
729 public void actionPerformed(ActionEvent e) {
730 log.user("What is this menu? selected");
731 JOptionPane.showMessageDialog(BasicFrame.this,
733 "The 'Debug' menu includes actions for testing and debugging " +
735 "The menu is made visible by defining the system property " +
736 "'openrocket.debug.menu' when starting OpenRocket.",
737 "It should not be visible by default." },
738 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
745 //// Create test rocket
746 item = new JMenuItem("Create test rocket");
747 item.addActionListener(new ActionListener() {
749 public void actionPerformed(ActionEvent e) {
750 log.user("Create test rocket selected");
751 JTextField field = new JTextField();
752 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
753 "Input text key to generate random rocket:",
755 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
756 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
762 r = new TestRockets(null).makeTestRocket();
763 } else if (sel == 1) {
764 r = new TestRockets(field.getText()).makeTestRocket();
769 OpenRocketDocument doc = new OpenRocketDocument(r);
771 BasicFrame frame = new BasicFrame(doc);
772 frame.setVisible(true);
779 item = new JMenuItem("Create 'Iso-Haisu'");
780 item.addActionListener(new ActionListener() {
782 public void actionPerformed(ActionEvent e) {
783 log.user("Create Iso-Haisu selected");
784 Rocket r = TestRockets.makeIsoHaisu();
785 OpenRocketDocument doc = new OpenRocketDocument(r);
787 BasicFrame frame = new BasicFrame(doc);
788 frame.setVisible(true);
794 item = new JMenuItem("Create 'Big Blue'");
795 item.addActionListener(new ActionListener() {
797 public void actionPerformed(ActionEvent e) {
798 log.user("Create Big Blue selected");
799 Rocket r = TestRockets.makeBigBlue();
800 OpenRocketDocument doc = new OpenRocketDocument(r);
802 BasicFrame frame = new BasicFrame(doc);
803 frame.setVisible(true);
811 item = new JMenuItem("Memory statistics");
812 item.addActionListener(new ActionListener() {
814 public void actionPerformed(ActionEvent e) {
815 log.user("Memory statistics selected");
817 // Get discarded but remaining objects (this also runs System.gc multiple times)
818 List<MemoryData> objects = MemoryManagement.getRemainingCollectableObjects();
819 StringBuilder sb = new StringBuilder();
820 sb.append("Objects that should have been garbage-collected but have not been:\n");
822 for (MemoryData data : objects) {
823 Object o = data.getReference().get();
826 sb.append("Age ").append(System.currentTimeMillis() - data.getRegistrationTime())
827 .append(" ms: ").append(o).append('\n');
829 // Explicitly null the strong reference to avoid possibility of invisible references
832 sb.append("Total: " + count);
834 // Get basic memory stats
836 long max = Runtime.getRuntime().maxMemory();
837 long free = Runtime.getRuntime().freeMemory();
838 long used = max - free;
839 String[] stats = new String[4];
840 stats[0] = "Memory usage:";
841 stats[1] = String.format(" Max memory: %.1f MB", max / 1024.0 / 1024.0);
842 stats[2] = String.format(" Used memory: %.1f MB (%.0f%%)", used / 1024.0 / 1024.0, 100.0 * used / max);
843 stats[3] = String.format(" Free memory: %.1f MB (%.0f%%)", free / 1024.0 / 1024.0, 100.0 * free / max);
846 DetailDialog.showDetailedMessageDialog(BasicFrame.this, stats, sb.toString(),
847 "Memory statistics", JOptionPane.INFORMATION_MESSAGE);
853 item = new JMenuItem("Exhaust memory");
854 item.addActionListener(new ActionListener() {
856 public void actionPerformed(ActionEvent e) {
857 log.user("Exhaust memory selected");
858 LinkedList<byte[]> data = new LinkedList<byte[]>();
860 final int bytesPerArray = 10240;
863 byte[] array = new byte[bytesPerArray];
864 for (int i = 0; i < bytesPerArray; i++) {
870 } catch (OutOfMemoryError error) {
872 long size = bytesPerArray * (long) count;
873 String s = String.format("OutOfMemory occurred after %d iterations (approx. %.1f MB consumed)",
874 count, size / 1024.0 / 1024.0);
876 JOptionPane.showMessageDialog(BasicFrame.this, s);
886 item = new JMenuItem("Exception here");
887 item.addActionListener(new ActionListener() {
889 public void actionPerformed(ActionEvent e) {
890 log.user("Exception here selected");
891 throw new RuntimeException("Testing exception from menu action listener");
896 item = new JMenuItem("Exception from EDT");
897 item.addActionListener(new ActionListener() {
899 public void actionPerformed(ActionEvent e) {
900 log.user("Exception from EDT selected");
901 SwingUtilities.invokeLater(new Runnable() {
904 throw new RuntimeException("Testing exception from " +
905 "later invoked EDT thread");
912 item = new JMenuItem("Exception from other thread");
913 item.addActionListener(new ActionListener() {
915 public void actionPerformed(ActionEvent e) {
916 log.user("Exception from other thread selected");
920 throw new RuntimeException("Testing exception from newly created thread");
927 item = new JMenuItem("OutOfMemoryError here");
928 item.addActionListener(new ActionListener() {
930 public void actionPerformed(ActionEvent e) {
931 log.user("OutOfMemoryError here selected");
932 throw new OutOfMemoryError("Testing OutOfMemoryError from menu action listener");
944 * Select the tab on the main pane.
946 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
948 public void selectTab(int tab) {
949 tabbedPane.setSelectedIndex(tab);
954 private void openAction() {
955 JFileChooser chooser = new JFileChooser();
957 chooser.addChoosableFileFilter(ALL_DESIGNS_FILTER);
958 chooser.addChoosableFileFilter(OPENROCKET_DESIGN_FILTER);
959 chooser.addChoosableFileFilter(ROCKSIM_DESIGN_FILTER);
960 chooser.setFileFilter(ALL_DESIGNS_FILTER);
962 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
963 chooser.setMultiSelectionEnabled(true);
964 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
965 int option = chooser.showOpenDialog(this);
966 if (option != JFileChooser.APPROVE_OPTION) {
967 log.user("Decided not to open files, option=" + option);
971 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
973 File[] files = chooser.getSelectedFiles();
974 log.user("Opening files " + Arrays.toString(files));
976 for (File file : files) {
977 log.info("Opening file: " + file);
978 if (open(file, this)) {
980 // Close previous window if replacing
981 if (replaceable && document.isSaved()) {
982 log.info("Closing window because it is replaceable");
992 * Open a file based on a URL.
993 * @param url the file to open.
994 * @param parent the parent window for dialogs.
995 * @return <code>true</code> if opened successfully.
997 private static boolean open(URL url, BasicFrame parent) {
998 String filename = null;
1000 // First figure out the file name from the URL
1002 // Try using URI.getPath();
1004 URI uri = url.toURI();
1005 filename = uri.getPath();
1006 } catch (URISyntaxException ignore) {
1009 // Try URL-decoding the URL
1010 if (filename == null) {
1012 filename = URLDecoder.decode(url.toString(), "UTF-8");
1013 } catch (UnsupportedEncodingException ignore) {
1018 if (filename == null) {
1022 // Remove path from filename
1023 if (filename.lastIndexOf('/') >= 0) {
1024 filename = filename.substring(filename.lastIndexOf('/') + 1);
1029 log.info("Opening file from url=" + url + " filename=" + filename);
1031 InputStream is = url.openStream();
1032 if (open(is, filename, parent)) {
1033 // Close previous window if replacing
1034 if (parent.replaceable && parent.document.isSaved()) {
1035 parent.closeAction();
1036 parent.replaceable = false;
1039 } catch (IOException e) {
1040 log.warn("Error opening file" + e);
1041 JOptionPane.showMessageDialog(parent,
1042 "An error occurred while opening the file " + filename,
1043 "Error loading file", JOptionPane.ERROR_MESSAGE);
1051 * Open the specified file from an InputStream in a new design frame. If an error
1052 * occurs, an error dialog is shown and <code>false</code> is returned.
1054 * @param stream the stream to load from.
1055 * @param filename the file name to display in dialogs (not set to the document).
1056 * @param parent the parent component for which a progress dialog is opened.
1057 * @return whether the file was successfully loaded and opened.
1059 private static boolean open(InputStream stream, String filename, Window parent) {
1060 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
1061 return open(worker, filename, null, parent);
1066 * Open the specified file in a new design frame. If an error occurs, an error
1067 * dialog is shown and <code>false</code> is returned.
1069 * @param file the file to open.
1070 * @param parent the parent component for which a progress dialog is opened.
1071 * @return whether the file was successfully loaded and opened.
1073 public static boolean open(File file, Window parent) {
1074 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
1075 return open(worker, file.getName(), file, parent);
1080 * Open the specified file using the provided worker.
1082 * @param worker the OpenFileWorker that loads the file.
1083 * @param filename the file name to display in dialogs.
1084 * @param file the File to set the document to (may be null).
1088 private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) {
1090 MotorDatabaseLoadingDialog.check(parent);
1092 // Open the file in a Swing worker thread
1093 log.info("Starting OpenFileWorker");
1094 if (!SwingWorkerDialog.runWorker(parent, "Opening file", "Reading " + filename + "...", worker)) {
1095 // User cancelled the operation
1096 log.info("User cancelled the OpenFileWorker");
1101 // Handle the document
1102 OpenRocketDocument doc = null;
1107 } catch (ExecutionException e) {
1109 Throwable cause = e.getCause();
1111 if (cause instanceof FileNotFoundException) {
1113 log.warn("File not found", cause);
1114 JOptionPane.showMessageDialog(parent,
1115 "File not found: " + filename,
1116 "Error opening file", JOptionPane.ERROR_MESSAGE);
1119 } else if (cause instanceof RocketLoadException) {
1121 log.warn("Error loading the file", cause);
1122 JOptionPane.showMessageDialog(parent,
1123 "Unable to open file '" + filename + "': "
1124 + cause.getMessage(),
1125 "Error opening file", JOptionPane.ERROR_MESSAGE);
1130 throw new BugException("Unknown error when opening file", e);
1134 } catch (InterruptedException e) {
1135 throw new BugException("EDT was interrupted", e);
1139 throw new BugException("Document loader returned null");
1144 WarningSet warnings = worker.getRocketLoader().getWarnings();
1145 if (!warnings.isEmpty()) {
1146 log.info("Warnings while reading file: " + warnings);
1147 WarningDialog.showWarnings(parent,
1149 "The following problems were encountered while opening " + filename + ".",
1150 "Some design features may not have been loaded correctly."
1152 "Warnings while opening file", warnings);
1156 // Set document state
1161 log.debug("Opening new frame with the document");
1162 BasicFrame frame = new BasicFrame(doc);
1163 frame.setVisible(true);
1172 private boolean saveAction() {
1173 File file = document.getFile();
1175 log.info("Document does not contain file, opening save as dialog instead");
1176 return saveAsAction();
1178 log.info("Saving document to " + file);
1180 // Saving RockSim designs is not supported
1181 if (ROCKSIM_DESIGN_FILTER.accept(file)) {
1182 file = new File(file.getAbsolutePath().replaceAll(".[rR][kK][tT](.[gG][zZ])?$",
1185 log.info("Attempting to save in RockSim format, renaming to " + file);
1186 int option = JOptionPane.showConfirmDialog(this, new Object[] {
1187 "Saving designs in RockSim format is not supported.",
1188 "Save in OpenRocket format instead (" + file.getName() + ")?"
1189 }, "Save " + file.getName(), JOptionPane.YES_NO_OPTION,
1190 JOptionPane.QUESTION_MESSAGE, null);
1191 if (option != JOptionPane.YES_OPTION) {
1192 log.user("User chose not to save");
1196 document.setFile(file);
1198 return saveAs(file);
1202 private boolean saveAsAction() {
1205 // TODO: HIGH: what if *.rkt chosen?
1206 StorageOptionChooser storageChooser =
1207 new StorageOptionChooser(document, document.getDefaultStorageOptions());
1208 JFileChooser chooser = new JFileChooser();
1209 chooser.setFileFilter(OPENROCKET_DESIGN_FILTER);
1210 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
1211 chooser.setAccessory(storageChooser);
1212 if (document.getFile() != null)
1213 chooser.setSelectedFile(document.getFile());
1215 int option = chooser.showSaveDialog(BasicFrame.this);
1216 if (option != JFileChooser.APPROVE_OPTION) {
1217 log.user("User decided not to save, option=" + option);
1221 file = chooser.getSelectedFile();
1223 log.user("User did not select a file");
1227 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
1228 storageChooser.storeOptions(document.getDefaultStorageOptions());
1230 if (file.getName().indexOf('.') < 0) {
1231 log.debug("File name does not contain extension, adding .ork");
1232 String name = file.getAbsolutePath();
1233 name = name + ".ork";
1234 file = new File(name);
1237 if (file.exists()) {
1238 log.info("File " + file + " exists, confirming overwrite from user");
1239 int result = JOptionPane.showConfirmDialog(this,
1240 "File '" + file.getName() + "' exists. Do you want to overwrite it?",
1241 "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
1242 if (result != JOptionPane.YES_OPTION) {
1243 log.user("User decided not to overwrite the file");
1248 return saveAs(file);
1251 private boolean saveAs(File file) {
1252 log.info("Saving document as " + file);
1253 boolean saved = false;
1255 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1256 // User cancelled the dialog
1257 log.user("User cancelled saving in storage options dialog");
1262 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1264 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1265 "Writing " + file.getName() + "...", worker)) {
1267 // User cancelled the save
1268 log.user("User cancelled the save, deleting the file");
1275 document.setFile(file);
1276 document.setSaved(true);
1279 } catch (ExecutionException e) {
1281 Throwable cause = e.getCause();
1283 if (cause instanceof IOException) {
1284 log.warn("An I/O error occurred while saving " + file, cause);
1285 JOptionPane.showMessageDialog(this, new String[] {
1286 "An I/O error occurred while saving:",
1287 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1290 Reflection.handleWrappedException(e);
1293 } catch (InterruptedException e) {
1294 throw new BugException("EDT was interrupted", e);
1301 private boolean closeAction() {
1302 if (!document.isSaved()) {
1303 log.info("Confirming whether to save the design");
1304 ComponentConfigDialog.hideDialog();
1305 int result = JOptionPane.showConfirmDialog(this,
1306 trans.get("BasicFrame.dlg.lbl1") + rocket.getName() +
1307 trans.get("BasicFrame.dlg.lbl2")+ " " +
1308 trans.get("BasicFrame.dlg.lbl3"),
1309 trans.get("BasicFrame.dlg.title"), JOptionPane.YES_NO_CANCEL_OPTION,
1310 JOptionPane.QUESTION_MESSAGE);
1311 if (result == JOptionPane.YES_OPTION) {
1313 log.user("User requested file save");
1314 if (!saveAction()) {
1315 log.info("File save was interrupted, not closing");
1318 } else if (result == JOptionPane.NO_OPTION) {
1319 // Don't save: No-op
1320 log.user("User requested to discard design");
1323 log.user("User cancelled closing, result=" + result);
1328 // Rocket has been saved or discarded
1329 log.debug("Disposing window");
1332 ComponentConfigDialog.hideDialog();
1333 ComponentAnalysisDialog.hideDialog();
1335 frames.remove(this);
1336 if (frames.isEmpty()) {
1337 log.info("Last frame closed, exiting");
1348 public void printAction() {
1349 new PrintDialog(document);
1353 * Open a new design window with a basic rocket+stage.
1355 public static void newAction() {
1356 log.info("New action initiated");
1358 Rocket rocket = new Rocket();
1359 Stage stage = new Stage();
1360 stage.setName("Sustainer");
1361 rocket.addChild(stage);
1362 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1365 BasicFrame frame = new BasicFrame(doc);
1366 frame.replaceable = true;
1367 frame.setVisible(true);
1368 ComponentConfigDialog.showDialog(frame, doc, rocket);
1372 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1374 public static void quitAction() {
1375 log.info("Quit action initiated");
1376 for (int i = frames.size() - 1; i >= 0; i--) {
1377 log.debug("Closing frame " + frames.get(i));
1378 if (!frames.get(i).closeAction()) {
1380 log.info("Quit was cancelled");
1384 // Should not be reached, but just in case
1385 log.error("Should already have exited application");
1391 * Set the title of the frame, taking into account the name of the rocket, file it
1392 * has been saved to (if any) and saved status.
1394 private void setTitle() {
1395 File file = document.getFile();
1396 boolean saved = document.isSaved();
1399 title = rocket.getName();
1401 title = title + " (" + file.getName() + ")";
1404 title = "*" + title;
1412 * Find a currently open BasicFrame containing the specified rocket. This method
1413 * can be used to map a Rocket to a BasicFrame from GUI methods.
1415 * @param rocket the Rocket.
1416 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1418 public static BasicFrame findFrame(Rocket rocket) {
1419 for (BasicFrame f : frames) {
1420 if (f.rocket == rocket) {
1421 log.debug("Found frame " + f + " for rocket " + rocket);
1425 log.debug("Could not find frame for rocket " + rocket);
1430 * Find a currently open document by the rocket object. This method can be used
1431 * to map a Rocket to OpenRocketDocument from GUI methods.
1433 * @param rocket the Rocket.
1434 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1436 public static OpenRocketDocument findDocument(Rocket rocket) {
1437 BasicFrame frame = findFrame(rocket);
1438 if (frame != null) {
1439 return frame.document;