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();
109 * File filter for filtering only rocket designs.
111 private static final FileFilter ROCKET_DESIGN_FILTER = new FileFilter() {
113 public String getDescription() {
114 return "OpenRocket designs (*.ork)";
117 public boolean accept(File f) {
120 String name = f.getName().toLowerCase();
121 return name.endsWith(".ork") || name.endsWith(".ork.gz");
127 public static final int COMPONENT_TAB = 0;
128 public static final int SIMULATION_TAB = 1;
132 * List of currently open frames. When the list goes empty
133 * it is time to exit the application.
135 private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
142 * Whether "New" and "Open" should replace this frame.
143 * Should be set to false on the first rocket modification.
145 private boolean replaceable = false;
149 private final OpenRocketDocument document;
150 private final Rocket rocket;
152 private JTabbedPane tabbedPane;
153 private RocketPanel rocketpanel;
154 private ComponentTree tree = null;
156 private final DocumentSelectionModel selectionModel;
157 private final TreeSelectionModel componentSelectionModel;
158 private final ListSelectionModel simulationSelectionModel;
160 /** Actions available for rocket modifications */
161 private final RocketActions actions;
166 * Sole constructor. Creates a new frame based on the supplied document
167 * and adds it to the current frames list.
169 * @param document the document to show.
171 public BasicFrame(OpenRocketDocument document) {
173 this.document = document;
174 this.rocket = document.getRocket();
175 this.rocket.getDefaultConfiguration().setAllStages();
178 // Set replaceable flag to false at first modification
179 rocket.addComponentChangeListener(new ComponentChangeListener() {
180 public void componentChanged(ComponentChangeEvent e) {
182 BasicFrame.this.rocket.removeComponentChangeListener(this);
187 // Create the component tree selection model that will be used
188 componentSelectionModel = new DefaultTreeSelectionModel();
189 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
191 // Obtain the simulation selection model that will be used
192 SimulationPanel simulationPanel = new SimulationPanel(document);
193 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
195 // Combine into a DocumentSelectionModel
196 selectionModel = new DocumentSelectionModel(document);
197 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
198 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
201 actions = new RocketActions(document, selectionModel, this);
204 // The main vertical split pane
205 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
206 vertical.setResizeWeight(0.5);
210 // The top tabbed pane
211 tabbedPane = new JTabbedPane();
212 tabbedPane.addTab("Rocket design", null, designTab());
213 tabbedPane.addTab("Flight simulations", null, simulationPanel);
215 vertical.setTopComponent(tabbedPane);
219 // Bottom segment, rocket figure
221 rocketpanel = new RocketPanel(document);
222 vertical.setBottomComponent(rocketpanel);
224 rocketpanel.setSelectionModel(tree.getSelectionModel());
230 rocket.addComponentChangeListener(new ComponentChangeListener() {
231 public void componentChanged(ComponentChangeEvent e) {
239 Dimension size = Prefs.getWindowSize(this.getClass());
241 size = Toolkit.getDefaultToolkit().getScreenSize();
242 size.width = size.width*9/10;
243 size.height = size.height*9/10;
246 this.addComponentListener(new ComponentAdapter() {
248 public void componentResized(ComponentEvent e) {
249 Prefs.setWindowSize(BasicFrame.this.getClass(), BasicFrame.this.getSize());
252 this.setLocationByPlatform(true);
254 GUIUtil.setWindowIcons(this);
257 vertical.setDividerLocation(0.4);
258 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
259 addWindowListener(new WindowAdapter() {
261 public void windowClosing(WindowEvent e) {
270 * Construct the "Rocket design" tab. This contains a horizontal split pane
271 * with the left component the design tree and the right component buttons
272 * for adding components.
274 private JComponent designTab() {
275 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true);
276 horizontal.setResizeWeight(0.5);
279 // Upper-left segment, component tree
281 JPanel panel = new JPanel(new MigLayout("fill, flowy","","[grow]"));
283 tree = new ComponentTree(rocket);
284 tree.setSelectionModel(componentSelectionModel);
286 // Remove JTree key events that interfere with menu accelerators
287 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
288 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
289 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
290 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
291 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
292 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
293 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
294 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
298 // Double-click opens config dialog
299 MouseListener ml = new MouseAdapter() {
301 public void mousePressed(MouseEvent e) {
302 int selRow = tree.getRowForLocation(e.getX(), e.getY());
303 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
305 if((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
307 RocketComponent c = (RocketComponent)selPath.getLastPathComponent();
308 ComponentConfigDialog.showDialog(BasicFrame.this,
309 BasicFrame.this.document, c);
314 tree.addMouseListener(ml);
316 // Update dialog when selection is changed
317 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
318 public void valueChanged(TreeSelectionEvent e) {
319 // Scroll tree to the selected item
320 TreePath path = componentSelectionModel.getSelectionPath();
323 tree.scrollPathToVisible(path);
325 if (!ComponentConfigDialog.isDialogVisible())
327 RocketComponent c = (RocketComponent)path.getLastPathComponent();
328 ComponentConfigDialog.showDialog(BasicFrame.this,
329 BasicFrame.this.document, c);
333 // Place tree inside scroll pane
334 JScrollPane scroll = new JScrollPane(tree);
335 panel.add(scroll,"spany, grow, wrap");
339 JButton button = new JButton(actions.getMoveUpAction());
340 panel.add(button,"sizegroup buttons, aligny 65%");
342 button = new JButton(actions.getMoveDownAction());
343 panel.add(button,"sizegroup buttons, aligny 0%");
345 button = new JButton(actions.getEditAction());
346 panel.add(button, "sizegroup buttons");
348 button = new JButton(actions.getNewStageAction());
349 panel.add(button,"sizegroup buttons");
351 button = new JButton(actions.getDeleteAction());
352 button.setIcon(null);
353 button.setMnemonic(0);
354 panel.add(button,"sizegroup buttons");
356 horizontal.setLeftComponent(panel);
359 // Upper-right segment, component addition buttons
361 panel = new JPanel(new MigLayout("fill, insets 0","[0::]"));
363 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
364 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
365 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
366 scroll.getViewport()));
367 scroll.setBorder(null);
368 scroll.setViewportBorder(null);
370 TitledBorder border = new TitledBorder("Add new component");
371 border.setTitleFont(border.getTitleFont().deriveFont(Font.BOLD));
372 scroll.setBorder(border);
374 panel.add(scroll,"grow");
376 horizontal.setRightComponent(panel);
384 * Creates the menu for the window.
386 private void createMenu() {
387 JMenuBar menubar = new JMenuBar();
392 menu = new JMenu("File");
393 menu.setMnemonic(KeyEvent.VK_F);
394 menu.getAccessibleContext().setAccessibleDescription("File-handling related tasks");
397 item = new JMenuItem("New",KeyEvent.VK_N);
398 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
399 item.setMnemonic(KeyEvent.VK_N);
400 item.getAccessibleContext().setAccessibleDescription("Create a new rocket design");
401 item.setIcon(Icons.FILE_NEW);
402 item.addActionListener(new ActionListener() {
403 public void actionPerformed(ActionEvent e) {
411 item = new JMenuItem("Open...",KeyEvent.VK_O);
412 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
413 item.getAccessibleContext().setAccessibleDescription("Open a rocket design");
414 item.setIcon(Icons.FILE_OPEN);
415 item.addActionListener(new ActionListener() {
416 public void actionPerformed(ActionEvent e) {
422 item = new JMenuItem("Open example...");
423 item.getAccessibleContext().setAccessibleDescription("Open an example rocket design");
424 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
425 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
426 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
427 item.addActionListener(new ActionListener() {
428 public void actionPerformed(ActionEvent e) {
429 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
432 open(u, BasicFrame.this);
441 item = new JMenuItem("Save",KeyEvent.VK_S);
442 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
443 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design");
444 item.setIcon(Icons.FILE_SAVE);
445 item.addActionListener(new ActionListener() {
446 public void actionPerformed(ActionEvent e) {
452 item = new JMenuItem("Save as...",KeyEvent.VK_A);
453 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
454 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
455 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design "+
457 item.setIcon(Icons.FILE_SAVE_AS);
458 item.addActionListener(new ActionListener() {
459 public void actionPerformed(ActionEvent e) {
465 // menu.addSeparator();
466 menu.add(new JSeparator());
468 item = new JMenuItem("Close",KeyEvent.VK_C);
469 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
470 item.getAccessibleContext().setAccessibleDescription("Close the current rocket design");
471 item.setIcon(Icons.FILE_CLOSE);
472 item.addActionListener(new ActionListener() {
473 public void actionPerformed(ActionEvent e) {
481 item = new JMenuItem("Quit",KeyEvent.VK_Q);
482 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
483 item.getAccessibleContext().setAccessibleDescription("Quit the program");
484 item.setIcon(Icons.FILE_QUIT);
485 item.addActionListener(new ActionListener() {
486 public void actionPerformed(ActionEvent e) {
495 menu = new JMenu("Edit");
496 menu.setMnemonic(KeyEvent.VK_E);
497 menu.getAccessibleContext().setAccessibleDescription("Rocket editing");
501 Action action = document.getUndoAction();
502 item = new JMenuItem(action);
503 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
504 item.setMnemonic(KeyEvent.VK_U);
505 item.getAccessibleContext().setAccessibleDescription("Undo the previous operation");
509 action = document.getRedoAction();
510 item = new JMenuItem(action);
511 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
512 item.setMnemonic(KeyEvent.VK_R);
513 item.getAccessibleContext().setAccessibleDescription("Redo the previously undone " +
520 item = new JMenuItem(actions.getCutAction());
523 item = new JMenuItem(actions.getCopyAction());
526 item = new JMenuItem(actions.getPasteAction());
529 item = new JMenuItem(actions.getDeleteAction());
534 item = new JMenuItem("Preferences");
535 item.setIcon(Icons.PREFERENCES);
536 item.getAccessibleContext().setAccessibleDescription("Setup the application "+
538 item.addActionListener(new ActionListener() {
539 public void actionPerformed(ActionEvent e) {
540 PreferencesDialog.showPreferences();
549 menu = new JMenu("Analyze");
550 menu.setMnemonic(KeyEvent.VK_A);
551 menu.getAccessibleContext().setAccessibleDescription("Analyzing the rocket");
554 item = new JMenuItem("Component analysis",KeyEvent.VK_C);
555 item.getAccessibleContext().setAccessibleDescription("Analyze the rocket components " +
557 item.addActionListener(new ActionListener() {
558 public void actionPerformed(ActionEvent e) {
559 ComponentAnalysisDialog.showDialog(rocketpanel);
566 // (shown if openrocket.debug.menu is defined)
567 if (System.getProperty("openrocket.debug.menu") != null) {
568 menubar.add(makeDebugMenu());
575 menu = new JMenu("Help");
576 menu.setMnemonic(KeyEvent.VK_H);
577 menu.getAccessibleContext().setAccessibleDescription("Information about OpenRocket");
582 item = new JMenuItem("License",KeyEvent.VK_L);
583 item.getAccessibleContext().setAccessibleDescription("OpenRocket license information");
584 item.addActionListener(new ActionListener() {
585 public void actionPerformed(ActionEvent e) {
586 new LicenseDialog(BasicFrame.this).setVisible(true);
591 item = new JMenuItem("Bug report",KeyEvent.VK_B);
592 item.getAccessibleContext().setAccessibleDescription("Information about reporting " +
593 "bugs in OpenRocket");
594 item.addActionListener(new ActionListener() {
595 public void actionPerformed(ActionEvent e) {
596 // new BugDialog(BasicFrame.this).setVisible(true);
597 BugReportDialog.showBugReportDialog(BasicFrame.this);
602 item = new JMenuItem("About",KeyEvent.VK_A);
603 item.getAccessibleContext().setAccessibleDescription("About OpenRocket");
604 item.addActionListener(new ActionListener() {
605 public void actionPerformed(ActionEvent e) {
606 new AboutDialog(BasicFrame.this).setVisible(true);
612 this.setJMenuBar(menubar);
616 private JMenu makeDebugMenu() {
621 menu = new JMenu("Debug");
622 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
624 item = new JMenuItem("What is this menu?");
625 item.addActionListener(new ActionListener() {
626 public void actionPerformed(ActionEvent e) {
627 JOptionPane.showMessageDialog(BasicFrame.this,
629 "The 'Debug' menu includes actions for testing and debugging " +
631 "The menu is made visible by defining the system property " +
632 "'openrocket.debug.menu' when starting OpenRocket.",
633 "It should not be visible by default." },
634 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
641 item = new JMenuItem("Create test rocket");
642 item.addActionListener(new ActionListener() {
644 public void actionPerformed(ActionEvent e) {
645 JTextField field = new JTextField();
646 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
647 "Input text key to generate random rocket:",
649 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
650 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
656 r = new TestRockets(null).makeTestRocket();
657 } else if (sel == 1) {
658 r = new TestRockets(field.getText()).makeTestRocket();
663 OpenRocketDocument doc = new OpenRocketDocument(r);
665 BasicFrame frame = new BasicFrame(doc);
666 frame.setVisible(true);
673 item = new JMenuItem("Create 'Iso-Haisu'");
674 item.addActionListener(new ActionListener() {
676 public void actionPerformed(ActionEvent e) {
677 Rocket r = TestRockets.makeIsoHaisu();
678 OpenRocketDocument doc = new OpenRocketDocument(r);
680 BasicFrame frame = new BasicFrame(doc);
681 frame.setVisible(true);
687 item = new JMenuItem("Create 'Big Blue'");
688 item.addActionListener(new ActionListener() {
690 public void actionPerformed(ActionEvent e) {
691 Rocket r = TestRockets.makeBigBlue();
692 OpenRocketDocument doc = new OpenRocketDocument(r);
694 BasicFrame frame = new BasicFrame(doc);
695 frame.setVisible(true);
704 item = new JMenuItem("Exception here");
705 item.addActionListener(new ActionListener() {
706 public void actionPerformed(ActionEvent e) {
707 throw new RuntimeException("Testing exception from menu action listener");
712 item = new JMenuItem("Exception from EDT");
713 item.addActionListener(new ActionListener() {
714 public void actionPerformed(ActionEvent e) {
715 SwingUtilities.invokeLater(new Runnable() {
718 throw new RuntimeException("Testing exception from " +
719 "later invoked EDT thread");
726 item = new JMenuItem("Exception from other thread");
727 item.addActionListener(new ActionListener() {
728 public void actionPerformed(ActionEvent e) {
732 throw new RuntimeException("Testing exception from " +
733 "newly created thread");
748 * Select the tab on the main pane.
750 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
752 public void selectTab(int tab) {
753 tabbedPane.setSelectedIndex(tab);
758 private void openAction() {
759 JFileChooser chooser = new JFileChooser();
760 chooser.setFileFilter(ROCKET_DESIGN_FILTER);
761 chooser.setMultiSelectionEnabled(true);
762 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
763 if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
766 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
768 File[] files = chooser.getSelectedFiles();
770 for (File file: files) {
771 System.out.println("Opening file: " + file);
772 if (open(file, this)) {
774 // Close previous window if replacing
775 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 private 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();
962 private boolean saveAsAction() {
964 while (file == null) {
965 StorageOptionChooser storageChooser =
966 new StorageOptionChooser(document, document.getDefaultStorageOptions());
967 JFileChooser chooser = new JFileChooser();
968 chooser.setFileFilter(ROCKET_DESIGN_FILTER);
969 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
970 chooser.setAccessory(storageChooser);
971 if (document.getFile() != null)
972 chooser.setSelectedFile(document.getFile());
974 if (chooser.showSaveDialog(BasicFrame.this) != JFileChooser.APPROVE_OPTION)
977 file = chooser.getSelectedFile();
981 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
982 storageChooser.storeOptions(document.getDefaultStorageOptions());
984 if (file.getName().indexOf('.') < 0) {
985 String name = file.getAbsolutePath();
986 name = name + ".ork";
987 file = new File(name);
991 int result = JOptionPane.showConfirmDialog(this,
992 "File '"+file.getName()+"' exists. Do you want to overwrite it?",
993 "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
994 if (result != JOptionPane.YES_OPTION)
1003 private boolean saveAs(File file) {
1004 System.out.println("Saving to file: " + file.getName());
1005 boolean saved = false;
1007 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1008 // User cancelled the dialog
1013 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1015 if (!SwingWorkerDialog.runWorker(this, "Saving file",
1016 "Writing " + file.getName() + "...", worker)) {
1018 // User cancelled the save
1025 document.setFile(file);
1026 document.setSaved(true);
1029 } catch (ExecutionException e) {
1031 Throwable cause = e.getCause();
1033 if (cause instanceof IOException) {
1034 JOptionPane.showMessageDialog(this, new String[] {
1035 "An I/O error occurred while saving:",
1036 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1039 Reflection.handleWrappedException(e);
1042 } catch (InterruptedException e) {
1043 throw new BugException("EDT was interrupted", e);
1050 private boolean closeAction() {
1051 if (!document.isSaved()) {
1052 ComponentConfigDialog.hideDialog();
1053 int result = JOptionPane.showConfirmDialog(this,
1054 "Design '"+rocket.getName()+"' has not been saved. " +
1055 "Do you want to save it?",
1056 "Design not saved", JOptionPane.YES_NO_CANCEL_OPTION,
1057 JOptionPane.QUESTION_MESSAGE);
1058 if (result == JOptionPane.YES_OPTION) {
1061 return false; // If save was interrupted
1062 } else if (result == JOptionPane.NO_OPTION) {
1063 // Don't save: No-op
1070 // Rocket has been saved or discarded
1073 // TODO: LOW: Close only dialogs that have this frame as their parent
1074 ComponentConfigDialog.hideDialog();
1075 ComponentAnalysisDialog.hideDialog();
1077 frames.remove(this);
1078 if (frames.isEmpty())
1085 * Closes this frame if it is replaceable.
1087 public void closeIfReplaceable() {
1088 if (this.replaceable && document.isSaved()) {
1094 * Open a new design window with a basic rocket+stage.
1096 public static void newAction() {
1097 Rocket rocket = new Rocket();
1098 Stage stage = new Stage();
1099 stage.setName("Sustainer");
1100 rocket.addChild(stage);
1101 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1104 BasicFrame frame = new BasicFrame(doc);
1105 frame.replaceable = true;
1106 frame.setVisible(true);
1107 ComponentConfigDialog.showDialog(frame, doc, rocket);
1111 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1113 public static void quitAction() {
1114 for (int i=frames.size()-1; i>=0; i--) {
1115 if (!frames.get(i).closeAction()) {
1120 // Should not be reached, but just in case
1126 * Set the title of the frame, taking into account the name of the rocket, file it
1127 * has been saved to (if any) and saved status.
1129 private void setTitle() {
1130 File file = document.getFile();
1131 boolean saved = document.isSaved();
1134 title = rocket.getName();
1136 title = title + " ("+file.getName()+")";
1139 title = "*" + title;
1147 * Find a currently open BasicFrame containing the specified rocket. This method
1148 * can be used to map a Rocket to a BasicFrame from GUI methods.
1150 * @param rocket the Rocket.
1151 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1153 public static BasicFrame findFrame(Rocket rocket) {
1154 for (BasicFrame f: frames) {
1155 if (f.rocket == rocket)
1162 * Find a currently open document by the rocket object. This method can be used
1163 * to map a Rocket to OpenRocketDocument from GUI methods.
1165 * @param rocket the Rocket.
1166 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1168 public static OpenRocketDocument findDocument(Rocket rocket) {
1169 for (BasicFrame f: frames) {
1170 if (f.rocket == rocket)
1177 public static void main(final String[] args) {
1179 // Run the actual startup method in the EDT since it can use progress dialogs etc.
1181 SwingUtilities.invokeAndWait(new Runnable() {
1187 } catch (InterruptedException e) {
1188 e.printStackTrace();
1189 } catch (InvocationTargetException e) {
1190 e.printStackTrace();
1196 private static void runMain(String[] args) {
1198 // Start update info fetching
1199 final UpdateInfoRetriever updateInfo;
1200 if (Prefs.getCheckUpdates()) {
1201 updateInfo = new UpdateInfoRetriever();
1208 // Set the best available look-and-feel
1209 GUIUtil.setBestLAF();
1211 // Set tooltip delay time. Tooltips are used in MotorChooserDialog extensively.
1212 ToolTipManager.sharedInstance().setDismissDelay(30000);
1215 // Setup the uncaught exception handler
1216 ExceptionHandler.registerExceptionHandler();
1220 Prefs.loadDefaultUnits();
1224 Databases.fakeMethod();
1226 // Starting action (load files or open new document)
1227 if (!handleCommandLine(args)) {
1232 // Check whether update info has been fetched or whether it needs more time
1233 checkUpdateStatus(updateInfo);
1237 private static void checkUpdateStatus(final UpdateInfoRetriever updateInfo) {
1238 if (updateInfo == null)
1242 if (!updateInfo.isRunning())
1245 final Timer timer = new Timer(delay, null);
1247 ActionListener listener = new ActionListener() {
1248 private int count = 5;
1250 public void actionPerformed(ActionEvent e) {
1251 if (!updateInfo.isRunning()) {
1254 String current = Prefs.getVersion();
1255 String last = Prefs.getString(Prefs.LAST_UPDATE, "");
1257 UpdateInfo info = updateInfo.getUpdateInfo();
1258 if (info != null && info.getLatestVersion() != null &&
1259 !current.equals(info.getLatestVersion()) &&
1260 !last.equals(info.getLatestVersion())) {
1262 UpdateInfoDialog infoDialog = new UpdateInfoDialog(info);
1263 infoDialog.setVisible(true);
1264 if (infoDialog.isReminderSelected()) {
1265 Prefs.putString(Prefs.LAST_UPDATE, "");
1267 Prefs.putString(Prefs.LAST_UPDATE, info.getLatestVersion());
1276 timer.addActionListener(listener);
1282 * Handles arguments passed from the command line. This may be used either
1283 * when starting the first instance of OpenRocket or later when OpenRocket is
1284 * executed again while running.
1286 * @param args the command-line arguments.
1287 * @return whether a new frame was opened or similar user desired action was
1288 * performed as a result.
1290 public static boolean handleCommandLine(String[] args) {
1292 // Check command-line for files
1293 boolean opened = false;
1294 for (String file: args) {
1295 if (open(new File(file), null)) {