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;
22 import java.lang.reflect.InvocationTargetException;
24 import java.net.URISyntaxException;
26 import java.net.URLDecoder;
27 import java.util.ArrayList;
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.Timer;
51 import javax.swing.ToolTipManager;
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.communication.UpdateInfo;
63 import net.sf.openrocket.communication.UpdateInfoRetriever;
64 import net.sf.openrocket.database.Databases;
65 import net.sf.openrocket.document.OpenRocketDocument;
66 import net.sf.openrocket.file.GeneralRocketLoader;
67 import net.sf.openrocket.file.RocketLoadException;
68 import net.sf.openrocket.file.RocketLoader;
69 import net.sf.openrocket.file.RocketSaver;
70 import net.sf.openrocket.file.openrocket.OpenRocketSaver;
71 import net.sf.openrocket.gui.StorageOptionChooser;
72 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
73 import net.sf.openrocket.gui.dialogs.AboutDialog;
74 import net.sf.openrocket.gui.dialogs.BugReportDialog;
75 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
76 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
77 import net.sf.openrocket.gui.dialogs.LicenseDialog;
78 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
79 import net.sf.openrocket.gui.dialogs.UpdateInfoDialog;
80 import net.sf.openrocket.gui.dialogs.WarningDialog;
81 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
82 import net.sf.openrocket.gui.scalefigure.RocketPanel;
83 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
84 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
85 import net.sf.openrocket.rocketcomponent.Rocket;
86 import net.sf.openrocket.rocketcomponent.RocketComponent;
87 import net.sf.openrocket.rocketcomponent.Stage;
88 import net.sf.openrocket.util.BugException;
89 import net.sf.openrocket.util.GUIUtil;
90 import net.sf.openrocket.util.Icons;
91 import net.sf.openrocket.util.OpenFileWorker;
92 import net.sf.openrocket.util.Prefs;
93 import net.sf.openrocket.util.Reflection;
94 import net.sf.openrocket.util.SaveFileWorker;
95 import net.sf.openrocket.util.TestRockets;
97 public class BasicFrame extends JFrame {
98 private static final long serialVersionUID = 1L;
101 * The RocketLoader instance used for loading all rocket designs.
103 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
105 private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
108 // FileFilters for different types of rocket design files
109 private static final FileFilter ALL_DESIGNS_FILTER =
110 new SimpleFileFilter("All rocket designs (*.ork; *.rkt)",
111 ".ork", ".ork.gz", ".rkt", ".rkt.gz");
113 private static final FileFilter OPENROCKET_DESIGN_FILTER =
114 new SimpleFileFilter("OpenRocket designs (*.ork)", ".ork", ".ork.gz");
116 private static final FileFilter ROCKSIM_DESIGN_FILTER =
117 new SimpleFileFilter("RockSim designs (*.rkt)", ".rkt", ".rkt.gz");
122 public static final int COMPONENT_TAB = 0;
123 public static final int SIMULATION_TAB = 1;
127 * List of currently open frames. When the list goes empty
128 * it is time to exit the application.
130 private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
137 * Whether "New" and "Open" should replace this frame.
138 * Should be set to false on the first rocket modification.
140 private boolean replaceable = false;
144 private final OpenRocketDocument document;
145 private final Rocket rocket;
147 private JTabbedPane tabbedPane;
148 private RocketPanel rocketpanel;
149 private ComponentTree tree = null;
151 private final DocumentSelectionModel selectionModel;
152 private final TreeSelectionModel componentSelectionModel;
153 private final ListSelectionModel simulationSelectionModel;
155 /** Actions available for rocket modifications */
156 private final RocketActions actions;
161 * Sole constructor. Creates a new frame based on the supplied document
162 * and adds it to the current frames list.
164 * @param document the document to show.
166 public BasicFrame(OpenRocketDocument document) {
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 // The main vertical split pane
200 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
201 vertical.setResizeWeight(0.5);
205 // The top tabbed pane
206 tabbedPane = new JTabbedPane();
207 tabbedPane.addTab("Rocket design", null, designTab());
208 tabbedPane.addTab("Flight simulations", null, simulationPanel);
210 vertical.setTopComponent(tabbedPane);
214 // Bottom segment, rocket figure
216 rocketpanel = new RocketPanel(document);
217 vertical.setBottomComponent(rocketpanel);
219 rocketpanel.setSelectionModel(tree.getSelectionModel());
225 rocket.addComponentChangeListener(new ComponentChangeListener() {
226 public void componentChanged(ComponentChangeEvent e) {
234 Dimension size = Prefs.getWindowSize(this.getClass());
236 size = Toolkit.getDefaultToolkit().getScreenSize();
237 size.width = size.width*9/10;
238 size.height = size.height*9/10;
241 this.addComponentListener(new ComponentAdapter() {
243 public void componentResized(ComponentEvent e) {
244 Prefs.setWindowSize(BasicFrame.this.getClass(), BasicFrame.this.getSize());
247 this.setLocationByPlatform(true);
249 GUIUtil.setWindowIcons(this);
252 vertical.setDividerLocation(0.4);
253 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
254 addWindowListener(new WindowAdapter() {
256 public void windowClosing(WindowEvent e) {
265 * Construct the "Rocket design" tab. This contains a horizontal split pane
266 * with the left component the design tree and the right component buttons
267 * for adding components.
269 private JComponent designTab() {
270 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true);
271 horizontal.setResizeWeight(0.5);
274 // Upper-left segment, component tree
276 JPanel panel = new JPanel(new MigLayout("fill, flowy","","[grow]"));
278 tree = new ComponentTree(rocket);
279 tree.setSelectionModel(componentSelectionModel);
281 // Remove JTree key events that interfere with menu accelerators
282 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
283 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
284 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
285 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
286 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
287 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
288 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
289 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
293 // Double-click opens config dialog
294 MouseListener ml = new MouseAdapter() {
296 public void mousePressed(MouseEvent e) {
297 int selRow = tree.getRowForLocation(e.getX(), e.getY());
298 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
300 if((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
302 RocketComponent c = (RocketComponent)selPath.getLastPathComponent();
303 ComponentConfigDialog.showDialog(BasicFrame.this,
304 BasicFrame.this.document, c);
309 tree.addMouseListener(ml);
311 // Update dialog when selection is changed
312 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
313 public void valueChanged(TreeSelectionEvent e) {
314 // Scroll tree to the selected item
315 TreePath path = componentSelectionModel.getSelectionPath();
318 tree.scrollPathToVisible(path);
320 if (!ComponentConfigDialog.isDialogVisible())
322 RocketComponent c = (RocketComponent)path.getLastPathComponent();
323 ComponentConfigDialog.showDialog(BasicFrame.this,
324 BasicFrame.this.document, c);
328 // Place tree inside scroll pane
329 JScrollPane scroll = new JScrollPane(tree);
330 panel.add(scroll,"spany, grow, wrap");
334 JButton button = new JButton(actions.getMoveUpAction());
335 panel.add(button,"sizegroup buttons, aligny 65%");
337 button = new JButton(actions.getMoveDownAction());
338 panel.add(button,"sizegroup buttons, aligny 0%");
340 button = new JButton(actions.getEditAction());
341 panel.add(button, "sizegroup buttons");
343 button = new JButton(actions.getNewStageAction());
344 panel.add(button,"sizegroup buttons");
346 button = new JButton(actions.getDeleteAction());
347 button.setIcon(null);
348 button.setMnemonic(0);
349 panel.add(button,"sizegroup buttons");
351 horizontal.setLeftComponent(panel);
354 // Upper-right segment, component addition buttons
356 panel = new JPanel(new MigLayout("fill, insets 0","[0::]"));
358 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
359 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
360 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
361 scroll.getViewport()));
362 scroll.setBorder(null);
363 scroll.setViewportBorder(null);
365 TitledBorder border = new TitledBorder("Add new component");
366 border.setTitleFont(border.getTitleFont().deriveFont(Font.BOLD));
367 scroll.setBorder(border);
369 panel.add(scroll,"grow");
371 horizontal.setRightComponent(panel);
379 * Creates the menu for the window.
381 private void createMenu() {
382 JMenuBar menubar = new JMenuBar();
387 menu = new JMenu("File");
388 menu.setMnemonic(KeyEvent.VK_F);
389 menu.getAccessibleContext().setAccessibleDescription("File-handling related tasks");
392 item = new JMenuItem("New",KeyEvent.VK_N);
393 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
394 item.setMnemonic(KeyEvent.VK_N);
395 item.getAccessibleContext().setAccessibleDescription("Create a new rocket design");
396 item.setIcon(Icons.FILE_NEW);
397 item.addActionListener(new ActionListener() {
398 public void actionPerformed(ActionEvent e) {
406 item = new JMenuItem("Open...",KeyEvent.VK_O);
407 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
408 item.getAccessibleContext().setAccessibleDescription("Open a rocket design");
409 item.setIcon(Icons.FILE_OPEN);
410 item.addActionListener(new ActionListener() {
411 public void actionPerformed(ActionEvent e) {
417 item = new JMenuItem("Open example...");
418 item.getAccessibleContext().setAccessibleDescription("Open an example rocket design");
419 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
420 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
421 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
422 item.addActionListener(new ActionListener() {
423 public void actionPerformed(ActionEvent e) {
424 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
427 open(u, BasicFrame.this);
436 item = new JMenuItem("Save",KeyEvent.VK_S);
437 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
438 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design");
439 item.setIcon(Icons.FILE_SAVE);
440 item.addActionListener(new ActionListener() {
441 public void actionPerformed(ActionEvent e) {
447 item = new JMenuItem("Save as...",KeyEvent.VK_A);
448 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
449 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
450 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design "+
452 item.setIcon(Icons.FILE_SAVE_AS);
453 item.addActionListener(new ActionListener() {
454 public void actionPerformed(ActionEvent e) {
460 // menu.addSeparator();
461 menu.add(new JSeparator());
463 item = new JMenuItem("Close",KeyEvent.VK_C);
464 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
465 item.getAccessibleContext().setAccessibleDescription("Close the current rocket design");
466 item.setIcon(Icons.FILE_CLOSE);
467 item.addActionListener(new ActionListener() {
468 public void actionPerformed(ActionEvent e) {
476 item = new JMenuItem("Quit",KeyEvent.VK_Q);
477 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
478 item.getAccessibleContext().setAccessibleDescription("Quit the program");
479 item.setIcon(Icons.FILE_QUIT);
480 item.addActionListener(new ActionListener() {
481 public void actionPerformed(ActionEvent e) {
490 menu = new JMenu("Edit");
491 menu.setMnemonic(KeyEvent.VK_E);
492 menu.getAccessibleContext().setAccessibleDescription("Rocket editing");
496 Action action = document.getUndoAction();
497 item = new JMenuItem(action);
498 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
499 item.setMnemonic(KeyEvent.VK_U);
500 item.getAccessibleContext().setAccessibleDescription("Undo the previous operation");
504 action = document.getRedoAction();
505 item = new JMenuItem(action);
506 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
507 item.setMnemonic(KeyEvent.VK_R);
508 item.getAccessibleContext().setAccessibleDescription("Redo the previously undone " +
515 item = new JMenuItem(actions.getCutAction());
518 item = new JMenuItem(actions.getCopyAction());
521 item = new JMenuItem(actions.getPasteAction());
524 item = new JMenuItem(actions.getDeleteAction());
529 item = new JMenuItem("Preferences");
530 item.setIcon(Icons.PREFERENCES);
531 item.getAccessibleContext().setAccessibleDescription("Setup the application "+
533 item.addActionListener(new ActionListener() {
534 public void actionPerformed(ActionEvent e) {
535 PreferencesDialog.showPreferences();
544 menu = new JMenu("Analyze");
545 menu.setMnemonic(KeyEvent.VK_A);
546 menu.getAccessibleContext().setAccessibleDescription("Analyzing the rocket");
549 item = new JMenuItem("Component analysis",KeyEvent.VK_C);
550 item.getAccessibleContext().setAccessibleDescription("Analyze the rocket components " +
552 item.addActionListener(new ActionListener() {
553 public void actionPerformed(ActionEvent e) {
554 ComponentAnalysisDialog.showDialog(rocketpanel);
561 // (shown if openrocket.debug.menu is defined)
562 if (System.getProperty("openrocket.debug.menu") != null) {
563 menubar.add(makeDebugMenu());
570 menu = new JMenu("Help");
571 menu.setMnemonic(KeyEvent.VK_H);
572 menu.getAccessibleContext().setAccessibleDescription("Information about OpenRocket");
577 item = new JMenuItem("License",KeyEvent.VK_L);
578 item.getAccessibleContext().setAccessibleDescription("OpenRocket license information");
579 item.addActionListener(new ActionListener() {
580 public void actionPerformed(ActionEvent e) {
581 new LicenseDialog(BasicFrame.this).setVisible(true);
586 item = new JMenuItem("Bug report",KeyEvent.VK_B);
587 item.getAccessibleContext().setAccessibleDescription("Information about reporting " +
588 "bugs in OpenRocket");
589 item.addActionListener(new ActionListener() {
590 public void actionPerformed(ActionEvent e) {
591 // new BugDialog(BasicFrame.this).setVisible(true);
592 BugReportDialog.showBugReportDialog(BasicFrame.this);
597 item = new JMenuItem("About",KeyEvent.VK_A);
598 item.getAccessibleContext().setAccessibleDescription("About OpenRocket");
599 item.addActionListener(new ActionListener() {
600 public void actionPerformed(ActionEvent e) {
601 new AboutDialog(BasicFrame.this).setVisible(true);
607 this.setJMenuBar(menubar);
611 private JMenu makeDebugMenu() {
616 menu = new JMenu("Debug");
617 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
619 item = new JMenuItem("What is this menu?");
620 item.addActionListener(new ActionListener() {
621 public void actionPerformed(ActionEvent e) {
622 JOptionPane.showMessageDialog(BasicFrame.this,
624 "The 'Debug' menu includes actions for testing and debugging " +
626 "The menu is made visible by defining the system property " +
627 "'openrocket.debug.menu' when starting OpenRocket.",
628 "It should not be visible by default." },
629 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
636 item = new JMenuItem("Create test rocket");
637 item.addActionListener(new ActionListener() {
639 public void actionPerformed(ActionEvent e) {
640 JTextField field = new JTextField();
641 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
642 "Input text key to generate random rocket:",
644 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
645 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
651 r = new TestRockets(null).makeTestRocket();
652 } else if (sel == 1) {
653 r = new TestRockets(field.getText()).makeTestRocket();
658 OpenRocketDocument doc = new OpenRocketDocument(r);
660 BasicFrame frame = new BasicFrame(doc);
661 frame.setVisible(true);
668 item = new JMenuItem("Create 'Iso-Haisu'");
669 item.addActionListener(new ActionListener() {
671 public void actionPerformed(ActionEvent e) {
672 Rocket r = TestRockets.makeIsoHaisu();
673 OpenRocketDocument doc = new OpenRocketDocument(r);
675 BasicFrame frame = new BasicFrame(doc);
676 frame.setVisible(true);
682 item = new JMenuItem("Create 'Big Blue'");
683 item.addActionListener(new ActionListener() {
685 public void actionPerformed(ActionEvent e) {
686 Rocket r = TestRockets.makeBigBlue();
687 OpenRocketDocument doc = new OpenRocketDocument(r);
689 BasicFrame frame = new BasicFrame(doc);
690 frame.setVisible(true);
699 item = new JMenuItem("Exception here");
700 item.addActionListener(new ActionListener() {
701 public void actionPerformed(ActionEvent e) {
702 throw new RuntimeException("Testing exception from menu action listener");
707 item = new JMenuItem("Exception from EDT");
708 item.addActionListener(new ActionListener() {
709 public void actionPerformed(ActionEvent e) {
710 SwingUtilities.invokeLater(new Runnable() {
713 throw new RuntimeException("Testing exception from " +
714 "later invoked EDT thread");
721 item = new JMenuItem("Exception from other thread");
722 item.addActionListener(new ActionListener() {
723 public void actionPerformed(ActionEvent e) {
727 throw new RuntimeException("Testing exception from " +
728 "newly created thread");
743 * Select the tab on the main pane.
745 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
747 public void selectTab(int tab) {
748 tabbedPane.setSelectedIndex(tab);
753 private void openAction() {
754 JFileChooser chooser = new JFileChooser();
756 chooser.addChoosableFileFilter(ALL_DESIGNS_FILTER);
757 chooser.addChoosableFileFilter(OPENROCKET_DESIGN_FILTER);
758 chooser.addChoosableFileFilter(ROCKSIM_DESIGN_FILTER);
759 chooser.setFileFilter(ALL_DESIGNS_FILTER);
761 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
762 chooser.setMultiSelectionEnabled(true);
763 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
764 if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
767 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
769 File[] files = chooser.getSelectedFiles();
771 for (File file: files) {
772 System.out.println("Opening file: " + file);
773 if (open(file, this)) {
775 // Close previous window if replacing
776 if (replaceable && document.isSaved()) {
786 private static boolean open(URL url, BasicFrame parent) {
787 String filename = null;
789 // Try using URI.getPath();
791 URI uri = url.toURI();
792 filename = uri.getPath();
793 } catch (URISyntaxException ignore) { }
795 // Try URL-decoding the URL
796 if (filename == null) {
798 filename = URLDecoder.decode(url.toString(), "UTF-8");
799 } catch (UnsupportedEncodingException ignore) { }
803 if (filename == null) {
807 // Remove path from filename
808 if (filename.lastIndexOf('/') >= 0) {
809 filename = filename.substring(filename.lastIndexOf('/')+1);
813 InputStream is = url.openStream();
814 if (open(is, filename, parent)) {
815 // Close previous window if replacing
816 if (parent.replaceable && parent.document.isSaved()) {
817 parent.closeAction();
818 parent.replaceable = false;
821 } catch (IOException e) {
822 JOptionPane.showMessageDialog(parent,
823 "An error occurred while opening the file " + filename,
824 "Error loading file", JOptionPane.ERROR_MESSAGE);
832 * Open the specified file from an InputStream in a new design frame. If an error
833 * occurs, an error dialog is shown and <code>false</code> is returned.
835 * @param stream the stream to load from.
836 * @param filename the file name to display in dialogs (not set to the document).
837 * @param parent the parent component for which a progress dialog is opened.
838 * @return whether the file was successfully loaded and opened.
840 private static boolean open(InputStream stream, String filename, Window parent) {
841 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
842 return open(worker, filename, null, parent);
847 * Open the specified file in a new design frame. If an error occurs, an error
848 * dialog is shown and <code>false</code> is returned.
850 * @param file the file to open.
851 * @param parent the parent component for which a progress dialog is opened.
852 * @return whether the file was successfully loaded and opened.
854 public static boolean open(File file, Window parent) {
855 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
856 return open(worker, file.getName(), file, parent);
861 * Open the specified file using the provided worker.
863 * @param worker the OpenFileWorker that loads the file.
864 * @param filename the file name to display in dialogs.
865 * @param file the File to set the document to (may be null).
869 private static boolean open(OpenFileWorker worker, String filename, File file,
872 // Open the file in a Swing worker thread
873 if (!SwingWorkerDialog.runWorker(parent, "Opening file",
874 "Reading " + filename + "...", worker)) {
876 // User cancelled the operation
881 // Handle the document
882 OpenRocketDocument doc = null;
887 } catch (ExecutionException e) {
889 Throwable cause = e.getCause();
891 if (cause instanceof FileNotFoundException) {
893 JOptionPane.showMessageDialog(parent,
894 "File not found: " + filename,
895 "Error opening file", JOptionPane.ERROR_MESSAGE);
898 } else if (cause instanceof RocketLoadException) {
900 JOptionPane.showMessageDialog(parent,
901 "Unable to open file '" + filename +"': "
902 + cause.getMessage(),
903 "Error opening file", JOptionPane.ERROR_MESSAGE);
908 throw new BugException("Unknown error when opening file", e);
912 } catch (InterruptedException e) {
913 throw new BugException("EDT was interrupted", e);
917 throw new BugException("BUG: Document loader returned null");
922 WarningSet warnings = worker.getRocketLoader().getWarnings();
923 if (!warnings.isEmpty()) {
924 WarningDialog.showWarnings(parent,
926 "The following problems were encountered while opening " + filename + ".",
927 "Some design features may not have been loaded correctly."
929 "Warnings while opening file", warnings);
933 // Set document state
938 BasicFrame frame = new BasicFrame(doc);
939 frame.setVisible(true);
952 private boolean saveAction() {
953 File file = document.getFile();
955 return saveAsAction();
958 // Saving RockSim designs is not supported
959 if (ROCKSIM_DESIGN_FILTER.accept(file)) {
960 file = new File(file.getAbsolutePath().replaceAll(".[rR][kK][tT](.[gG][zZ])?$",
963 int option = JOptionPane.showConfirmDialog(this, new Object[] {
964 "Saving designs in RockSim format is not supported.",
965 "Save in OpenRocket format instead ("+file.getName()+")?"
966 }, "Save "+file.getName(), JOptionPane.YES_NO_OPTION,
967 JOptionPane.QUESTION_MESSAGE, null);
968 if (option != JOptionPane.YES_OPTION)
971 document.setFile(file);
977 private boolean saveAsAction() {
979 while (file == null) {
980 // TODO: HIGH: what if *.rkt chosen?
981 StorageOptionChooser storageChooser =
982 new StorageOptionChooser(document, document.getDefaultStorageOptions());
983 JFileChooser chooser = new JFileChooser();
984 chooser.setFileFilter(OPENROCKET_DESIGN_FILTER);
985 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
986 chooser.setAccessory(storageChooser);
987 if (document.getFile() != null)
988 chooser.setSelectedFile(document.getFile());
990 if (chooser.showSaveDialog(BasicFrame.this) != JFileChooser.APPROVE_OPTION)
993 file = chooser.getSelectedFile();
997 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
998 storageChooser.storeOptions(document.getDefaultStorageOptions());
1000 if (file.getName().indexOf('.') < 0) {
1001 String name = file.getAbsolutePath();
1002 name = name + ".ork";
1003 file = new File(name);
1006 if (file.exists()) {
1007 int result = JOptionPane.showConfirmDialog(this,
1008 "File '"+file.getName()+"' exists. Do you want to overwrite it?",
1009 "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
1010 if (result != JOptionPane.YES_OPTION)
1019 private boolean saveAs(File file) {
1020 System.out.println("Saving to file: " + file.getName());
1021 boolean saved = false;
1023 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1024 // User cancelled the dialog
1029 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1031 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1032 "Writing " + file.getName() + "...", worker)) {
1034 // User cancelled the save
1041 document.setFile(file);
1042 document.setSaved(true);
1045 } catch (ExecutionException e) {
1047 Throwable cause = e.getCause();
1049 if (cause instanceof IOException) {
1050 JOptionPane.showMessageDialog(this, new String[] {
1051 "An I/O error occurred while saving:",
1052 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1055 Reflection.handleWrappedException(e);
1058 } catch (InterruptedException e) {
1059 throw new BugException("EDT was interrupted", e);
1066 private boolean closeAction() {
1067 if (!document.isSaved()) {
1068 ComponentConfigDialog.hideDialog();
1069 int result = JOptionPane.showConfirmDialog(this,
1070 "Design '"+rocket.getName()+"' has not been saved. " +
1071 "Do you want to save it?",
1072 "Design not saved", JOptionPane.YES_NO_CANCEL_OPTION,
1073 JOptionPane.QUESTION_MESSAGE);
1074 if (result == JOptionPane.YES_OPTION) {
1077 return false; // If save was interrupted
1078 } else if (result == JOptionPane.NO_OPTION) {
1079 // Don't save: No-op
1086 // Rocket has been saved or discarded
1089 // TODO: LOW: Close only dialogs that have this frame as their parent
1090 ComponentConfigDialog.hideDialog();
1091 ComponentAnalysisDialog.hideDialog();
1093 frames.remove(this);
1094 if (frames.isEmpty())
1101 * Closes this frame if it is replaceable.
1103 public void closeIfReplaceable() {
1104 if (this.replaceable && document.isSaved()) {
1110 * Open a new design window with a basic rocket+stage.
1112 public static void newAction() {
1113 Rocket rocket = new Rocket();
1114 Stage stage = new Stage();
1115 stage.setName("Sustainer");
1116 rocket.addChild(stage);
1117 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1120 BasicFrame frame = new BasicFrame(doc);
1121 frame.replaceable = true;
1122 frame.setVisible(true);
1123 ComponentConfigDialog.showDialog(frame, doc, rocket);
1127 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1129 public static void quitAction() {
1130 for (int i=frames.size()-1; i>=0; i--) {
1131 if (!frames.get(i).closeAction()) {
1136 // Should not be reached, but just in case
1142 * Set the title of the frame, taking into account the name of the rocket, file it
1143 * has been saved to (if any) and saved status.
1145 private void setTitle() {
1146 File file = document.getFile();
1147 boolean saved = document.isSaved();
1150 title = rocket.getName();
1152 title = title + " ("+file.getName()+")";
1155 title = "*" + title;
1163 * Find a currently open BasicFrame containing the specified rocket. This method
1164 * can be used to map a Rocket to a BasicFrame from GUI methods.
1166 * @param rocket the Rocket.
1167 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1169 public static BasicFrame findFrame(Rocket rocket) {
1170 for (BasicFrame f: frames) {
1171 if (f.rocket == rocket)
1178 * Find a currently open document by the rocket object. This method can be used
1179 * to map a Rocket to OpenRocketDocument from GUI methods.
1181 * @param rocket the Rocket.
1182 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1184 public static OpenRocketDocument findDocument(Rocket rocket) {
1185 for (BasicFrame f: frames) {
1186 if (f.rocket == rocket)
1193 public static void main(final String[] args) {
1195 // Run the actual startup method in the EDT since it can use progress dialogs etc.
1197 SwingUtilities.invokeAndWait(new Runnable() {
1203 } catch (InterruptedException e) {
1204 e.printStackTrace();
1205 } catch (InvocationTargetException e) {
1206 e.printStackTrace();
1212 private static void runMain(String[] args) {
1214 // Initialize the splash screen with version info
1218 // Start update info fetching
1219 final UpdateInfoRetriever updateInfo;
1220 if (Prefs.getCheckUpdates()) {
1221 updateInfo = new UpdateInfoRetriever();
1228 // Set the best available look-and-feel
1229 GUIUtil.setBestLAF();
1231 // Set tooltip delay time. Tooltips are used in MotorChooserDialog extensively.
1232 ToolTipManager.sharedInstance().setDismissDelay(30000);
1235 // Setup the uncaught exception handler
1236 ExceptionHandler.registerExceptionHandler();
1240 Prefs.loadDefaultUnits();
1244 Databases.fakeMethod();
1246 // Starting action (load files or open new document)
1247 if (!handleCommandLine(args)) {
1252 // Check whether update info has been fetched or whether it needs more time
1253 checkUpdateStatus(updateInfo);
1257 private static void checkUpdateStatus(final UpdateInfoRetriever updateInfo) {
1258 if (updateInfo == null)
1262 if (!updateInfo.isRunning())
1265 final Timer timer = new Timer(delay, null);
1267 ActionListener listener = new ActionListener() {
1268 private int count = 5;
1270 public void actionPerformed(ActionEvent e) {
1271 if (!updateInfo.isRunning()) {
1274 String current = Prefs.getVersion();
1275 String last = Prefs.getString(Prefs.LAST_UPDATE, "");
1277 UpdateInfo info = updateInfo.getUpdateInfo();
1278 if (info != null && info.getLatestVersion() != null &&
1279 !current.equals(info.getLatestVersion()) &&
1280 !last.equals(info.getLatestVersion())) {
1282 UpdateInfoDialog infoDialog = new UpdateInfoDialog(info);
1283 infoDialog.setVisible(true);
1284 if (infoDialog.isReminderSelected()) {
1285 Prefs.putString(Prefs.LAST_UPDATE, "");
1287 Prefs.putString(Prefs.LAST_UPDATE, info.getLatestVersion());
1296 timer.addActionListener(listener);
1302 * Handles arguments passed from the command line. This may be used either
1303 * when starting the first instance of OpenRocket or later when OpenRocket is
1304 * executed again while running.
1306 * @param args the command-line arguments.
1307 * @return whether a new frame was opened or similar user desired action was
1308 * performed as a result.
1310 public static boolean handleCommandLine(String[] args) {
1312 // Check command-line for files
1313 boolean opened = false;
1314 for (String file: args) {
1315 if (open(new File(file), null)) {