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.concurrent.ExecutionException;
30 import javax.swing.Action;
31 import javax.swing.InputMap;
32 import javax.swing.JButton;
33 import javax.swing.JComponent;
34 import javax.swing.JFileChooser;
35 import javax.swing.JFrame;
36 import javax.swing.JMenu;
37 import javax.swing.JMenuBar;
38 import javax.swing.JMenuItem;
39 import javax.swing.JOptionPane;
40 import javax.swing.JPanel;
41 import javax.swing.JScrollPane;
42 import javax.swing.JSeparator;
43 import javax.swing.JSplitPane;
44 import javax.swing.JTabbedPane;
45 import javax.swing.JTextField;
46 import javax.swing.KeyStroke;
47 import javax.swing.ListSelectionModel;
48 import javax.swing.ScrollPaneConstants;
49 import javax.swing.SwingUtilities;
50 import javax.swing.border.TitledBorder;
51 import javax.swing.event.TreeSelectionEvent;
52 import javax.swing.event.TreeSelectionListener;
53 import javax.swing.filechooser.FileFilter;
54 import javax.swing.tree.DefaultTreeSelectionModel;
55 import javax.swing.tree.TreePath;
56 import javax.swing.tree.TreeSelectionModel;
58 import net.miginfocom.swing.MigLayout;
59 import net.sf.openrocket.aerodynamics.WarningSet;
60 import net.sf.openrocket.document.OpenRocketDocument;
61 import net.sf.openrocket.file.GeneralRocketLoader;
62 import net.sf.openrocket.file.RocketLoadException;
63 import net.sf.openrocket.file.RocketLoader;
64 import net.sf.openrocket.file.RocketSaver;
65 import net.sf.openrocket.file.openrocket.OpenRocketSaver;
66 import net.sf.openrocket.gui.StorageOptionChooser;
67 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
68 import net.sf.openrocket.gui.dialogs.AboutDialog;
69 import net.sf.openrocket.gui.dialogs.BugReportDialog;
70 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
71 import net.sf.openrocket.gui.dialogs.DebugLogDialog;
72 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
73 import net.sf.openrocket.gui.dialogs.LicenseDialog;
74 import net.sf.openrocket.gui.dialogs.MotorDatabaseLoadingDialog;
75 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
76 import net.sf.openrocket.gui.dialogs.WarningDialog;
77 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
78 import net.sf.openrocket.gui.main.componenttree.ComponentTree;
79 import net.sf.openrocket.gui.scalefigure.RocketPanel;
80 import net.sf.openrocket.logging.LogHelper;
81 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
82 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
83 import net.sf.openrocket.rocketcomponent.Rocket;
84 import net.sf.openrocket.rocketcomponent.RocketComponent;
85 import net.sf.openrocket.rocketcomponent.Stage;
86 import net.sf.openrocket.startup.Application;
87 import net.sf.openrocket.util.BugException;
88 import net.sf.openrocket.util.GUIUtil;
89 import net.sf.openrocket.util.Icons;
90 import net.sf.openrocket.util.OpenFileWorker;
91 import net.sf.openrocket.util.Prefs;
92 import net.sf.openrocket.util.Reflection;
93 import net.sf.openrocket.util.SaveFileWorker;
94 import net.sf.openrocket.util.TestRockets;
96 public class BasicFrame extends JFrame {
97 private static final LogHelper log = Application.getLogger();
100 * The RocketLoader instance used for loading all rocket designs.
102 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
104 private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
107 // FileFilters for different types of rocket design files
108 private static final FileFilter ALL_DESIGNS_FILTER =
109 new SimpleFileFilter("All rocket designs (*.ork; *.rkt)",
110 ".ork", ".ork.gz", ".rkt", ".rkt.gz");
112 private static final FileFilter OPENROCKET_DESIGN_FILTER =
113 new SimpleFileFilter("OpenRocket designs (*.ork)", ".ork", ".ork.gz");
115 private static final FileFilter ROCKSIM_DESIGN_FILTER =
116 new SimpleFileFilter("RockSim designs (*.rkt)", ".rkt", ".rkt.gz");
121 public static final int COMPONENT_TAB = 0;
122 public static final int SIMULATION_TAB = 1;
126 * List of currently open frames. When the list goes empty
127 * it is time to exit the application.
129 private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
136 * Whether "New" and "Open" should replace this frame.
137 * Should be set to false on the first rocket modification.
139 private boolean replaceable = false;
143 private final OpenRocketDocument document;
144 private final Rocket rocket;
146 private JTabbedPane tabbedPane;
147 private RocketPanel rocketpanel;
148 private ComponentTree tree = null;
150 private final DocumentSelectionModel selectionModel;
151 private final TreeSelectionModel componentSelectionModel;
152 private final ListSelectionModel simulationSelectionModel;
154 /** Actions available for rocket modifications */
155 private final RocketActions actions;
160 * Sole constructor. Creates a new frame based on the supplied document
161 * and adds it to the current frames list.
163 * @param document the document to show.
165 public BasicFrame(OpenRocketDocument document) {
166 log.debug("Instantiating new BasicFrame");
168 this.document = document;
169 this.rocket = document.getRocket();
170 this.rocket.getDefaultConfiguration().setAllStages();
173 // Set replaceable flag to false at first modification
174 rocket.addComponentChangeListener(new ComponentChangeListener() {
175 public void componentChanged(ComponentChangeEvent e) {
177 BasicFrame.this.rocket.removeComponentChangeListener(this);
182 // Create the component tree selection model that will be used
183 componentSelectionModel = new DefaultTreeSelectionModel();
184 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
186 // Obtain the simulation selection model that will be used
187 SimulationPanel simulationPanel = new SimulationPanel(document);
188 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
190 // Combine into a DocumentSelectionModel
191 selectionModel = new DocumentSelectionModel(document);
192 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
193 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
196 actions = new RocketActions(document, selectionModel, this);
199 log.debug("Constructing the BasicFrame UI");
201 // The main vertical split pane
202 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
203 vertical.setResizeWeight(0.5);
207 // The top tabbed pane
208 tabbedPane = new JTabbedPane();
209 tabbedPane.addTab("Rocket design", null, designTab());
210 tabbedPane.addTab("Flight simulations", null, simulationPanel);
212 vertical.setTopComponent(tabbedPane);
216 // Bottom segment, rocket figure
218 rocketpanel = new RocketPanel(document);
219 vertical.setBottomComponent(rocketpanel);
221 rocketpanel.setSelectionModel(tree.getSelectionModel());
227 rocket.addComponentChangeListener(new ComponentChangeListener() {
228 public void componentChanged(ComponentChangeEvent e) {
236 Dimension size = Prefs.getWindowSize(this.getClass());
238 size = Toolkit.getDefaultToolkit().getScreenSize();
239 size.width = size.width * 9 / 10;
240 size.height = size.height * 9 / 10;
243 this.addComponentListener(new ComponentAdapter() {
245 public void componentResized(ComponentEvent e) {
246 Prefs.setWindowSize(BasicFrame.this.getClass(), BasicFrame.this.getSize());
249 this.setLocationByPlatform(true);
251 GUIUtil.setWindowIcons(this);
254 vertical.setDividerLocation(0.4);
255 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
256 addWindowListener(new WindowAdapter() {
258 public void windowClosing(WindowEvent e) {
264 log.debug("BasicFrame instantiation complete");
269 * Construct the "Rocket design" tab. This contains a horizontal split pane
270 * with the left component the design tree and the right component buttons
271 * for adding components.
273 private JComponent designTab() {
274 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
275 horizontal.setResizeWeight(0.5);
278 // Upper-left segment, component tree
280 JPanel panel = new JPanel(new MigLayout("fill, flowy", "", "[grow]"));
282 tree = new ComponentTree(document);
283 tree.setSelectionModel(componentSelectionModel);
285 // Remove JTree key events that interfere with menu accelerators
286 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
287 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
288 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
289 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
290 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
291 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
292 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
293 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
297 // Double-click opens config dialog
298 MouseListener ml = new MouseAdapter() {
300 public void mousePressed(MouseEvent e) {
301 int selRow = tree.getRowForLocation(e.getX(), e.getY());
302 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
304 if ((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
306 RocketComponent c = (RocketComponent) selPath.getLastPathComponent();
307 ComponentConfigDialog.showDialog(BasicFrame.this,
308 BasicFrame.this.document, c);
313 tree.addMouseListener(ml);
315 // Update dialog when selection is changed
316 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
317 public void valueChanged(TreeSelectionEvent e) {
318 // Scroll tree to the selected item
319 TreePath path = componentSelectionModel.getSelectionPath();
322 tree.scrollPathToVisible(path);
324 if (!ComponentConfigDialog.isDialogVisible())
326 RocketComponent c = (RocketComponent) path.getLastPathComponent();
327 ComponentConfigDialog.showDialog(BasicFrame.this,
328 BasicFrame.this.document, c);
332 // Place tree inside scroll pane
333 JScrollPane scroll = new JScrollPane(tree);
334 panel.add(scroll, "spany, grow, wrap");
338 JButton button = new JButton(actions.getMoveUpAction());
339 panel.add(button, "sizegroup buttons, aligny 65%");
341 button = new JButton(actions.getMoveDownAction());
342 panel.add(button, "sizegroup buttons, aligny 0%");
344 button = new JButton(actions.getEditAction());
345 panel.add(button, "sizegroup buttons");
347 button = new JButton(actions.getNewStageAction());
348 panel.add(button, "sizegroup buttons");
350 button = new JButton(actions.getDeleteAction());
351 button.setIcon(null);
352 button.setMnemonic(0);
353 panel.add(button, "sizegroup buttons");
355 horizontal.setLeftComponent(panel);
358 // Upper-right segment, component addition buttons
360 panel = new JPanel(new MigLayout("fill, insets 0", "[0::]"));
362 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
363 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
364 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
365 scroll.getViewport()));
366 scroll.setBorder(null);
367 scroll.setViewportBorder(null);
369 TitledBorder border = new TitledBorder("Add new component");
370 border.setTitleFont(border.getTitleFont().deriveFont(Font.BOLD));
371 scroll.setBorder(border);
373 panel.add(scroll, "grow");
375 horizontal.setRightComponent(panel);
383 * Creates the menu for the window.
385 private void createMenu() {
386 JMenuBar menubar = new JMenuBar();
391 menu = new JMenu("File");
392 menu.setMnemonic(KeyEvent.VK_F);
393 menu.getAccessibleContext().setAccessibleDescription("File-handling related tasks");
396 item = new JMenuItem("New", KeyEvent.VK_N);
397 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
398 item.setMnemonic(KeyEvent.VK_N);
399 item.getAccessibleContext().setAccessibleDescription("Create a new rocket design");
400 item.setIcon(Icons.FILE_NEW);
401 item.addActionListener(new ActionListener() {
402 public void actionPerformed(ActionEvent e) {
403 log.user("New... selected");
406 log.info("Closing previous window");
413 item = new JMenuItem("Open...", KeyEvent.VK_O);
414 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
415 item.getAccessibleContext().setAccessibleDescription("Open a rocket design");
416 item.setIcon(Icons.FILE_OPEN);
417 item.addActionListener(new ActionListener() {
418 public void actionPerformed(ActionEvent e) {
419 log.user("Open... selected");
425 item = new JMenuItem("Open example...");
426 item.getAccessibleContext().setAccessibleDescription("Open an example rocket design");
427 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
428 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
429 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
430 item.addActionListener(new ActionListener() {
431 public void actionPerformed(ActionEvent e) {
432 log.user("Open example... selected");
433 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
436 log.user("Opening example " + u);
437 open(u, BasicFrame.this);
446 item = new JMenuItem("Save", KeyEvent.VK_S);
447 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
448 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design");
449 item.setIcon(Icons.FILE_SAVE);
450 item.addActionListener(new ActionListener() {
451 public void actionPerformed(ActionEvent e) {
452 log.user("Save selected");
458 item = new JMenuItem("Save as...", KeyEvent.VK_A);
459 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
460 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
461 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design " +
463 item.setIcon(Icons.FILE_SAVE_AS);
464 item.addActionListener(new ActionListener() {
465 public void actionPerformed(ActionEvent e) {
466 log.user("Save as... selected");
472 // menu.addSeparator();
473 menu.add(new JSeparator());
475 item = new JMenuItem("Close", KeyEvent.VK_C);
476 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
477 item.getAccessibleContext().setAccessibleDescription("Close the current rocket design");
478 item.setIcon(Icons.FILE_CLOSE);
479 item.addActionListener(new ActionListener() {
480 public void actionPerformed(ActionEvent e) {
481 log.user("Close selected");
489 item = new JMenuItem("Quit", KeyEvent.VK_Q);
490 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
491 item.getAccessibleContext().setAccessibleDescription("Quit the program");
492 item.setIcon(Icons.FILE_QUIT);
493 item.addActionListener(new ActionListener() {
494 public void actionPerformed(ActionEvent e) {
495 log.user("Quit selected");
504 menu = new JMenu("Edit");
505 menu.setMnemonic(KeyEvent.VK_E);
506 menu.getAccessibleContext().setAccessibleDescription("Rocket editing");
510 Action action = document.getUndoAction();
511 item = new JMenuItem(action);
512 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
513 item.setMnemonic(KeyEvent.VK_U);
514 item.getAccessibleContext().setAccessibleDescription("Undo the previous operation");
518 action = document.getRedoAction();
519 item = new JMenuItem(action);
520 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
521 item.setMnemonic(KeyEvent.VK_R);
522 item.getAccessibleContext().setAccessibleDescription("Redo the previously undone " +
529 item = new JMenuItem(actions.getCutAction());
532 item = new JMenuItem(actions.getCopyAction());
535 item = new JMenuItem(actions.getPasteAction());
538 item = new JMenuItem(actions.getDeleteAction());
543 item = new JMenuItem("Preferences");
544 item.setIcon(Icons.PREFERENCES);
545 item.getAccessibleContext().setAccessibleDescription("Setup the application " +
547 item.addActionListener(new ActionListener() {
548 public void actionPerformed(ActionEvent e) {
549 log.user("Preferences selected");
550 PreferencesDialog.showPreferences();
559 menu = new JMenu("Analyze");
560 menu.setMnemonic(KeyEvent.VK_A);
561 menu.getAccessibleContext().setAccessibleDescription("Analyzing the rocket");
564 item = new JMenuItem("Component analysis", KeyEvent.VK_C);
565 item.getAccessibleContext().setAccessibleDescription("Analyze the rocket components " +
567 item.addActionListener(new ActionListener() {
568 public void actionPerformed(ActionEvent e) {
569 log.user("Component analysis selected");
570 ComponentAnalysisDialog.showDialog(rocketpanel);
577 // (shown if openrocket.debug.menu is defined)
578 if (System.getProperty("openrocket.debug.menu") != null) {
579 menubar.add(makeDebugMenu());
586 menu = new JMenu("Help");
587 menu.setMnemonic(KeyEvent.VK_H);
588 menu.getAccessibleContext().setAccessibleDescription("Information about OpenRocket");
593 item = new JMenuItem("License", KeyEvent.VK_L);
594 item.getAccessibleContext().setAccessibleDescription("OpenRocket license information");
595 item.addActionListener(new ActionListener() {
596 public void actionPerformed(ActionEvent e) {
597 log.user("License selected");
598 new LicenseDialog(BasicFrame.this).setVisible(true);
605 item = new JMenuItem("Bug report", KeyEvent.VK_B);
606 item.getAccessibleContext().setAccessibleDescription("Information about reporting " +
607 "bugs in OpenRocket");
608 item.addActionListener(new ActionListener() {
609 public void actionPerformed(ActionEvent e) {
610 log.user("Bug report selected");
611 BugReportDialog.showBugReportDialog(BasicFrame.this);
616 item = new JMenuItem("Debug log");
617 item.getAccessibleContext().setAccessibleDescription("View the OpenRocket debug log");
618 item.addActionListener(new ActionListener() {
619 public void actionPerformed(ActionEvent e) {
620 log.user("Debug log selected");
621 new DebugLogDialog(BasicFrame.this).setVisible(true);
628 item = new JMenuItem("About", KeyEvent.VK_A);
629 item.getAccessibleContext().setAccessibleDescription("About OpenRocket");
630 item.addActionListener(new ActionListener() {
631 public void actionPerformed(ActionEvent e) {
632 log.user("About selected");
633 new AboutDialog(BasicFrame.this).setVisible(true);
639 this.setJMenuBar(menubar);
643 private JMenu makeDebugMenu() {
648 menu = new JMenu("Debug");
649 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
651 item = new JMenuItem("What is this menu?");
652 item.addActionListener(new ActionListener() {
653 public void actionPerformed(ActionEvent e) {
654 log.user("What is this menu? selected");
655 JOptionPane.showMessageDialog(BasicFrame.this,
657 "The 'Debug' menu includes actions for testing and debugging " +
659 "The menu is made visible by defining the system property " +
660 "'openrocket.debug.menu' when starting OpenRocket.",
661 "It should not be visible by default." },
662 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
669 item = new JMenuItem("Create test rocket");
670 item.addActionListener(new ActionListener() {
672 public void actionPerformed(ActionEvent e) {
673 log.user("Create test rocket selected");
674 JTextField field = new JTextField();
675 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
676 "Input text key to generate random rocket:",
678 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
679 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
685 r = new TestRockets(null).makeTestRocket();
686 } else if (sel == 1) {
687 r = new TestRockets(field.getText()).makeTestRocket();
692 OpenRocketDocument doc = new OpenRocketDocument(r);
694 BasicFrame frame = new BasicFrame(doc);
695 frame.setVisible(true);
702 item = new JMenuItem("Create 'Iso-Haisu'");
703 item.addActionListener(new ActionListener() {
705 public void actionPerformed(ActionEvent e) {
706 log.user("Create Iso-Haisu selected");
707 Rocket r = TestRockets.makeIsoHaisu();
708 OpenRocketDocument doc = new OpenRocketDocument(r);
710 BasicFrame frame = new BasicFrame(doc);
711 frame.setVisible(true);
717 item = new JMenuItem("Create 'Big Blue'");
718 item.addActionListener(new ActionListener() {
720 public void actionPerformed(ActionEvent e) {
721 log.user("Create Big Blue selected");
722 Rocket r = TestRockets.makeBigBlue();
723 OpenRocketDocument doc = new OpenRocketDocument(r);
725 BasicFrame frame = new BasicFrame(doc);
726 frame.setVisible(true);
733 item = new JMenuItem("Exception here");
734 item.addActionListener(new ActionListener() {
735 public void actionPerformed(ActionEvent e) {
736 log.user("Exception here selected");
737 throw new RuntimeException("Testing exception from menu action listener");
742 item = new JMenuItem("Exception from EDT");
743 item.addActionListener(new ActionListener() {
744 public void actionPerformed(ActionEvent e) {
745 log.user("Exception from EDT selected");
746 SwingUtilities.invokeLater(new Runnable() {
749 throw new RuntimeException("Testing exception from " +
750 "later invoked EDT thread");
757 item = new JMenuItem("Exception from other thread");
758 item.addActionListener(new ActionListener() {
759 public void actionPerformed(ActionEvent e) {
760 log.user("Exception from other thread selected");
764 throw new RuntimeException("Testing exception from " +
765 "newly created thread");
780 * Select the tab on the main pane.
782 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
784 public void selectTab(int tab) {
785 tabbedPane.setSelectedIndex(tab);
790 private void openAction() {
791 JFileChooser chooser = new JFileChooser();
793 chooser.addChoosableFileFilter(ALL_DESIGNS_FILTER);
794 chooser.addChoosableFileFilter(OPENROCKET_DESIGN_FILTER);
795 chooser.addChoosableFileFilter(ROCKSIM_DESIGN_FILTER);
796 chooser.setFileFilter(ALL_DESIGNS_FILTER);
798 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
799 chooser.setMultiSelectionEnabled(true);
800 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
801 int option = chooser.showOpenDialog(this);
802 if (option != JFileChooser.APPROVE_OPTION) {
803 log.user("Decided not to open files, option=" + option);
807 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
809 File[] files = chooser.getSelectedFiles();
810 log.user("Opening files " + Arrays.toString(files));
812 for (File file : files) {
813 log.info("Opening file: " + file);
814 if (open(file, this)) {
816 // Close previous window if replacing
817 if (replaceable && document.isSaved()) {
818 log.info("Closing window because it is replaceable");
828 * Open a file based on a URL.
829 * @param url the file to open.
830 * @param parent the parent window for dialogs.
831 * @return <code>true</code> if opened successfully.
833 private static boolean open(URL url, BasicFrame parent) {
834 String filename = null;
836 // First figure out the file name from the URL
838 // Try using URI.getPath();
840 URI uri = url.toURI();
841 filename = uri.getPath();
842 } catch (URISyntaxException ignore) {
845 // Try URL-decoding the URL
846 if (filename == null) {
848 filename = URLDecoder.decode(url.toString(), "UTF-8");
849 } catch (UnsupportedEncodingException ignore) {
854 if (filename == null) {
858 // Remove path from filename
859 if (filename.lastIndexOf('/') >= 0) {
860 filename = filename.substring(filename.lastIndexOf('/') + 1);
865 log.info("Opening file from url=" + url + " filename=" + filename);
867 InputStream is = url.openStream();
868 if (open(is, filename, parent)) {
869 // Close previous window if replacing
870 if (parent.replaceable && parent.document.isSaved()) {
871 parent.closeAction();
872 parent.replaceable = false;
875 } catch (IOException e) {
876 log.warn("Error opening file" + e);
877 JOptionPane.showMessageDialog(parent,
878 "An error occurred while opening the file " + filename,
879 "Error loading file", JOptionPane.ERROR_MESSAGE);
887 * Open the specified file from an InputStream in a new design frame. If an error
888 * occurs, an error dialog is shown and <code>false</code> is returned.
890 * @param stream the stream to load from.
891 * @param filename the file name to display in dialogs (not set to the document).
892 * @param parent the parent component for which a progress dialog is opened.
893 * @return whether the file was successfully loaded and opened.
895 private static boolean open(InputStream stream, String filename, Window parent) {
896 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
897 return open(worker, filename, null, parent);
902 * Open the specified file in a new design frame. If an error occurs, an error
903 * dialog is shown and <code>false</code> is returned.
905 * @param file the file to open.
906 * @param parent the parent component for which a progress dialog is opened.
907 * @return whether the file was successfully loaded and opened.
909 public static boolean open(File file, Window parent) {
910 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
911 return open(worker, file.getName(), file, parent);
916 * Open the specified file using the provided worker.
918 * @param worker the OpenFileWorker that loads the file.
919 * @param filename the file name to display in dialogs.
920 * @param file the File to set the document to (may be null).
924 private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) {
926 MotorDatabaseLoadingDialog.check(parent);
928 // Open the file in a Swing worker thread
929 log.info("Starting OpenFileWorker");
930 if (!SwingWorkerDialog.runWorker(parent, "Opening file", "Reading " + filename + "...", worker)) {
931 // User cancelled the operation
932 log.info("User cancelled the OpenFileWorker");
937 // Handle the document
938 OpenRocketDocument doc = null;
943 } catch (ExecutionException e) {
945 Throwable cause = e.getCause();
947 if (cause instanceof FileNotFoundException) {
949 log.warn("File not found", cause);
950 JOptionPane.showMessageDialog(parent,
951 "File not found: " + filename,
952 "Error opening file", JOptionPane.ERROR_MESSAGE);
955 } else if (cause instanceof RocketLoadException) {
957 log.warn("Error loading the file", cause);
958 JOptionPane.showMessageDialog(parent,
959 "Unable to open file '" + filename + "': "
960 + cause.getMessage(),
961 "Error opening file", JOptionPane.ERROR_MESSAGE);
966 throw new BugException("Unknown error when opening file", e);
970 } catch (InterruptedException e) {
971 throw new BugException("EDT was interrupted", e);
975 throw new BugException("Document loader returned null");
980 WarningSet warnings = worker.getRocketLoader().getWarnings();
981 if (!warnings.isEmpty()) {
982 log.info("Warnings while reading file: " + warnings);
983 WarningDialog.showWarnings(parent,
985 "The following problems were encountered while opening " + filename + ".",
986 "Some design features may not have been loaded correctly."
988 "Warnings while opening file", warnings);
992 // Set document state
997 log.debug("Opening new frame with the document");
998 BasicFrame frame = new BasicFrame(doc);
999 frame.setVisible(true);
1008 private boolean saveAction() {
1009 File file = document.getFile();
1011 log.info("Document does not contain file, opening save as dialog instead");
1012 return saveAsAction();
1014 log.info("Saving document to " + file);
1016 // Saving RockSim designs is not supported
1017 if (ROCKSIM_DESIGN_FILTER.accept(file)) {
1018 file = new File(file.getAbsolutePath().replaceAll(".[rR][kK][tT](.[gG][zZ])?$",
1021 log.info("Attempting to save in RockSim format, renaming to " + file);
1022 int option = JOptionPane.showConfirmDialog(this, new Object[] {
1023 "Saving designs in RockSim format is not supported.",
1024 "Save in OpenRocket format instead (" + file.getName() + ")?"
1025 }, "Save " + file.getName(), JOptionPane.YES_NO_OPTION,
1026 JOptionPane.QUESTION_MESSAGE, null);
1027 if (option != JOptionPane.YES_OPTION) {
1028 log.user("User chose not to save");
1032 document.setFile(file);
1034 return saveAs(file);
1038 private boolean saveAsAction() {
1041 // TODO: HIGH: what if *.rkt chosen?
1042 StorageOptionChooser storageChooser =
1043 new StorageOptionChooser(document, document.getDefaultStorageOptions());
1044 JFileChooser chooser = new JFileChooser();
1045 chooser.setFileFilter(OPENROCKET_DESIGN_FILTER);
1046 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
1047 chooser.setAccessory(storageChooser);
1048 if (document.getFile() != null)
1049 chooser.setSelectedFile(document.getFile());
1051 int option = chooser.showSaveDialog(BasicFrame.this);
1052 if (option != JFileChooser.APPROVE_OPTION) {
1053 log.user("User decided not to save, option=" + option);
1057 file = chooser.getSelectedFile();
1059 log.user("User did not select a file");
1063 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
1064 storageChooser.storeOptions(document.getDefaultStorageOptions());
1066 if (file.getName().indexOf('.') < 0) {
1067 log.debug("File name does not contain extension, adding .ork");
1068 String name = file.getAbsolutePath();
1069 name = name + ".ork";
1070 file = new File(name);
1073 if (file.exists()) {
1074 log.info("File " + file + " exists, confirming overwrite from user");
1075 int result = JOptionPane.showConfirmDialog(this,
1076 "File '" + file.getName() + "' exists. Do you want to overwrite it?",
1077 "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
1078 if (result != JOptionPane.YES_OPTION) {
1079 log.user("User decided not to overwrite the file");
1084 return saveAs(file);
1087 private boolean saveAs(File file) {
1088 log.info("Saving document as " + file);
1089 boolean saved = false;
1091 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1092 // User cancelled the dialog
1093 log.user("User cancelled saving in storage options dialog");
1098 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1100 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1101 "Writing " + file.getName() + "...", worker)) {
1103 // User cancelled the save
1104 log.user("User cancelled the save, deleting the file");
1111 document.setFile(file);
1112 document.setSaved(true);
1115 } catch (ExecutionException e) {
1117 Throwable cause = e.getCause();
1119 if (cause instanceof IOException) {
1120 log.warn("An I/O error occurred while saving " + file, cause);
1121 JOptionPane.showMessageDialog(this, new String[] {
1122 "An I/O error occurred while saving:",
1123 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1126 Reflection.handleWrappedException(e);
1129 } catch (InterruptedException e) {
1130 throw new BugException("EDT was interrupted", e);
1137 private boolean closeAction() {
1138 if (!document.isSaved()) {
1139 log.info("Confirming whether to save the design");
1140 ComponentConfigDialog.hideDialog();
1141 int result = JOptionPane.showConfirmDialog(this,
1142 "Design '" + rocket.getName() + "' has not been saved. " +
1143 "Do you want to save it?",
1144 "Design not saved", JOptionPane.YES_NO_CANCEL_OPTION,
1145 JOptionPane.QUESTION_MESSAGE);
1146 if (result == JOptionPane.YES_OPTION) {
1148 log.user("User requested file save");
1149 if (!saveAction()) {
1150 log.info("File save was interrupted, not closing");
1153 } else if (result == JOptionPane.NO_OPTION) {
1154 // Don't save: No-op
1155 log.user("User requested to discard design");
1158 log.user("User cancelled closing, result=" + result);
1163 // Rocket has been saved or discarded
1164 log.debug("Disposing window");
1167 ComponentConfigDialog.hideDialog();
1168 ComponentAnalysisDialog.hideDialog();
1170 frames.remove(this);
1171 if (frames.isEmpty()) {
1172 log.info("Last frame closed, exiting");
1181 * Open a new design window with a basic rocket+stage.
1183 public static void newAction() {
1184 log.info("New action initiated");
1186 Rocket rocket = new Rocket();
1187 Stage stage = new Stage();
1188 stage.setName("Sustainer");
1189 rocket.addChild(stage);
1190 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1193 BasicFrame frame = new BasicFrame(doc);
1194 frame.replaceable = true;
1195 frame.setVisible(true);
1196 ComponentConfigDialog.showDialog(frame, doc, rocket);
1200 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1202 public static void quitAction() {
1203 log.info("Quit action initiated");
1204 for (int i = frames.size() - 1; i >= 0; i--) {
1205 log.debug("Closing frame " + frames.get(i));
1206 if (!frames.get(i).closeAction()) {
1208 log.info("Quit was cancelled");
1212 // Should not be reached, but just in case
1213 log.error("Should already have exited application");
1219 * Set the title of the frame, taking into account the name of the rocket, file it
1220 * has been saved to (if any) and saved status.
1222 private void setTitle() {
1223 File file = document.getFile();
1224 boolean saved = document.isSaved();
1227 title = rocket.getName();
1229 title = title + " (" + file.getName() + ")";
1232 title = "*" + title;
1240 * Find a currently open BasicFrame containing the specified rocket. This method
1241 * can be used to map a Rocket to a BasicFrame from GUI methods.
1243 * @param rocket the Rocket.
1244 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1246 public static BasicFrame findFrame(Rocket rocket) {
1247 for (BasicFrame f : frames) {
1248 if (f.rocket == rocket) {
1249 log.debug("Found frame " + f + " for rocket " + rocket);
1253 log.debug("Could not find frame for rocket " + rocket);
1258 * Find a currently open document by the rocket object. This method can be used
1259 * to map a Rocket to OpenRocketDocument from GUI methods.
1261 * @param rocket the Rocket.
1262 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1264 public static OpenRocketDocument findDocument(Rocket rocket) {
1265 BasicFrame frame = findFrame(rocket);
1266 if (frame != null) {
1267 return frame.document;