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.KeyStroke;
46 import javax.swing.ListSelectionModel;
47 import javax.swing.LookAndFeel;
48 import javax.swing.ScrollPaneConstants;
49 import javax.swing.SwingUtilities;
50 import javax.swing.ToolTipManager;
51 import javax.swing.UIManager;
52 import javax.swing.border.TitledBorder;
53 import javax.swing.event.TreeSelectionEvent;
54 import javax.swing.event.TreeSelectionListener;
55 import javax.swing.filechooser.FileFilter;
56 import javax.swing.tree.DefaultTreeSelectionModel;
57 import javax.swing.tree.TreePath;
58 import javax.swing.tree.TreeSelectionModel;
60 import net.miginfocom.swing.MigLayout;
61 import net.sf.openrocket.aerodynamics.WarningSet;
62 import net.sf.openrocket.document.OpenRocketDocument;
63 import net.sf.openrocket.file.GeneralRocketLoader;
64 import net.sf.openrocket.file.OpenRocketSaver;
65 import net.sf.openrocket.file.RocketLoadException;
66 import net.sf.openrocket.file.RocketLoader;
67 import net.sf.openrocket.file.RocketSaver;
68 import net.sf.openrocket.gui.StorageOptionChooser;
69 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
70 import net.sf.openrocket.gui.dialogs.AboutDialog;
71 import net.sf.openrocket.gui.dialogs.BugReportDialog;
72 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
73 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
74 import net.sf.openrocket.gui.dialogs.LicenseDialog;
75 import net.sf.openrocket.gui.dialogs.PreferencesDialog;
76 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
77 import net.sf.openrocket.gui.dialogs.WarningDialog;
78 import net.sf.openrocket.gui.scalefigure.RocketPanel;
79 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
80 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
81 import net.sf.openrocket.rocketcomponent.Rocket;
82 import net.sf.openrocket.rocketcomponent.RocketComponent;
83 import net.sf.openrocket.rocketcomponent.Stage;
84 import net.sf.openrocket.util.GUIUtil;
85 import net.sf.openrocket.util.Icons;
86 import net.sf.openrocket.util.OpenFileWorker;
87 import net.sf.openrocket.util.Prefs;
88 import net.sf.openrocket.util.SaveFileWorker;
90 public class BasicFrame extends JFrame {
91 private static final long serialVersionUID = 1L;
94 * The RocketLoader instance used for loading all rocket designs.
96 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
98 private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
102 * File filter for filtering only rocket designs.
104 private static final FileFilter ROCKET_DESIGN_FILTER = new FileFilter() {
106 public String getDescription() {
107 return "OpenRocket designs (*.ork)";
110 public boolean accept(File f) {
113 String name = f.getName().toLowerCase();
114 return name.endsWith(".ork") || name.endsWith(".ork.gz");
120 public static final int COMPONENT_TAB = 0;
121 public static final int SIMULATION_TAB = 1;
125 * List of currently open frames. When the list goes empty
126 * it is time to exit the application.
128 private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
135 * Whether "New" and "Open" should replace this frame.
136 * Should be set to false on the first rocket modification.
138 private boolean replaceable = false;
142 private final OpenRocketDocument document;
143 private final Rocket rocket;
145 private JTabbedPane tabbedPane;
146 private RocketPanel rocketpanel;
147 private ComponentTree tree = null;
149 private final DocumentSelectionModel selectionModel;
150 private final TreeSelectionModel componentSelectionModel;
151 private final ListSelectionModel simulationSelectionModel;
153 /** Actions available for rocket modifications */
154 private final RocketActions actions;
159 * Sole constructor. Creates a new frame based on the supplied document
160 * and adds it to the current frames list.
162 * @param document the document to show.
164 public BasicFrame(OpenRocketDocument document) {
166 this.document = document;
167 this.rocket = document.getRocket();
168 this.rocket.getDefaultConfiguration().setAllStages();
171 // Set replaceable flag to false at first modification
172 rocket.addComponentChangeListener(new ComponentChangeListener() {
173 public void componentChanged(ComponentChangeEvent e) {
175 BasicFrame.this.rocket.removeComponentChangeListener(this);
180 // Create the component tree selection model that will be used
181 componentSelectionModel = new DefaultTreeSelectionModel();
182 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
184 // Obtain the simulation selection model that will be used
185 SimulationPanel simulationPanel = new SimulationPanel(document);
186 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
188 // Combine into a DocumentSelectionModel
189 selectionModel = new DocumentSelectionModel(document);
190 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
191 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
194 actions = new RocketActions(document, selectionModel, this);
197 // The main vertical split pane
198 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
199 vertical.setResizeWeight(0.5);
203 // The top tabbed pane
204 tabbedPane = new JTabbedPane();
205 tabbedPane.addTab("Rocket design", null, designTab());
206 tabbedPane.addTab("Flight simulations", null, simulationPanel);
208 vertical.setTopComponent(tabbedPane);
212 // Bottom segment, rocket figure
214 rocketpanel = new RocketPanel(document);
215 vertical.setBottomComponent(rocketpanel);
217 rocketpanel.setSelectionModel(tree.getSelectionModel());
223 rocket.addComponentChangeListener(new ComponentChangeListener() {
224 public void componentChanged(ComponentChangeEvent e) {
232 Dimension size = Prefs.getWindowSize(this.getClass());
234 size = Toolkit.getDefaultToolkit().getScreenSize();
235 size.width = size.width*9/10;
236 size.height = size.height*9/10;
239 this.addComponentListener(new ComponentAdapter() {
241 public void componentResized(ComponentEvent e) {
242 Prefs.setWindowSize(BasicFrame.this.getClass(), BasicFrame.this.getSize());
245 this.setLocationByPlatform(true);
247 GUIUtil.setWindowIcons(this);
250 vertical.setDividerLocation(0.4);
251 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
252 addWindowListener(new WindowAdapter() {
254 public void windowClosing(WindowEvent e) {
263 * Construct the "Rocket design" tab. This contains a horizontal split pane
264 * with the left component the design tree and the right component buttons
265 * for adding components.
267 private JComponent designTab() {
268 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true);
269 horizontal.setResizeWeight(0.5);
272 // Upper-left segment, component tree
274 JPanel panel = new JPanel(new MigLayout("fill, flowy","","[grow]"));
276 tree = new ComponentTree(rocket);
277 tree.setSelectionModel(componentSelectionModel);
279 // Remove JTree key events that interfere with menu accelerators
280 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
281 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
282 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
283 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
284 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
285 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
286 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
287 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
291 // Double-click opens config dialog
292 MouseListener ml = new MouseAdapter() {
294 public void mousePressed(MouseEvent e) {
295 int selRow = tree.getRowForLocation(e.getX(), e.getY());
296 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
298 if(e.getClickCount() == 2) {
300 RocketComponent c = (RocketComponent)selPath.getLastPathComponent();
301 ComponentConfigDialog.showDialog(BasicFrame.this,
302 BasicFrame.this.document, c);
307 tree.addMouseListener(ml);
309 // Update dialog when selection is changed
310 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
311 public void valueChanged(TreeSelectionEvent e) {
312 // Scroll tree to the selected item
313 TreePath path = componentSelectionModel.getSelectionPath();
316 tree.scrollPathToVisible(path);
318 if (!ComponentConfigDialog.isDialogVisible())
320 RocketComponent c = (RocketComponent)path.getLastPathComponent();
321 ComponentConfigDialog.showDialog(BasicFrame.this,
322 BasicFrame.this.document, c);
326 // Place tree inside scroll pane
327 JScrollPane scroll = new JScrollPane(tree);
328 panel.add(scroll,"spany, grow, wrap");
332 JButton button = new JButton(actions.getMoveUpAction());
333 panel.add(button,"sizegroup buttons, aligny 65%");
335 button = new JButton(actions.getMoveDownAction());
336 panel.add(button,"sizegroup buttons, aligny 0%");
338 button = new JButton(actions.getEditAction());
339 panel.add(button, "sizegroup buttons");
341 button = new JButton(actions.getNewStageAction());
342 panel.add(button,"sizegroup buttons");
344 button = new JButton(actions.getDeleteAction());
345 button.setIcon(null);
346 button.setMnemonic(0);
347 panel.add(button,"sizegroup buttons");
349 horizontal.setLeftComponent(panel);
352 // Upper-right segment, component addition buttons
354 panel = new JPanel(new MigLayout("fill, insets 0","[0::]"));
356 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
357 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
358 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
359 scroll.getViewport()));
360 scroll.setBorder(null);
361 scroll.setViewportBorder(null);
363 TitledBorder border = new TitledBorder("Add new component");
364 border.setTitleFont(border.getTitleFont().deriveFont(Font.BOLD));
365 scroll.setBorder(border);
367 panel.add(scroll,"grow");
369 horizontal.setRightComponent(panel);
377 * Creates the menu for the window.
379 private void createMenu() {
380 JMenuBar menubar = new JMenuBar();
385 menu = new JMenu("File");
386 menu.setMnemonic(KeyEvent.VK_F);
387 menu.getAccessibleContext().setAccessibleDescription("File-handling related tasks");
390 item = new JMenuItem("New",KeyEvent.VK_N);
391 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
392 item.setMnemonic(KeyEvent.VK_N);
393 item.getAccessibleContext().setAccessibleDescription("Create a new rocket design");
394 item.setIcon(Icons.FILE_NEW);
395 item.addActionListener(new ActionListener() {
396 public void actionPerformed(ActionEvent e) {
404 item = new JMenuItem("Open...",KeyEvent.VK_O);
405 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
406 item.getAccessibleContext().setAccessibleDescription("Open a rocket design");
407 item.setIcon(Icons.FILE_OPEN);
408 item.addActionListener(new ActionListener() {
409 public void actionPerformed(ActionEvent e) {
415 item = new JMenuItem("Open example...");
416 item.getAccessibleContext().setAccessibleDescription("Open an example rocket design");
417 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
418 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
419 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
420 item.addActionListener(new ActionListener() {
421 public void actionPerformed(ActionEvent e) {
422 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
425 open(u, BasicFrame.this);
434 item = new JMenuItem("Save",KeyEvent.VK_S);
435 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
436 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design");
437 item.setIcon(Icons.FILE_SAVE);
438 item.addActionListener(new ActionListener() {
439 public void actionPerformed(ActionEvent e) {
445 item = new JMenuItem("Save as...",KeyEvent.VK_A);
446 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
447 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
448 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design "+
450 item.setIcon(Icons.FILE_SAVE_AS);
451 item.addActionListener(new ActionListener() {
452 public void actionPerformed(ActionEvent e) {
458 // menu.addSeparator();
459 menu.add(new JSeparator());
461 item = new JMenuItem("Close",KeyEvent.VK_C);
462 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
463 item.getAccessibleContext().setAccessibleDescription("Close the current rocket design");
464 item.setIcon(Icons.FILE_CLOSE);
465 item.addActionListener(new ActionListener() {
466 public void actionPerformed(ActionEvent e) {
474 item = new JMenuItem("Quit",KeyEvent.VK_Q);
475 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
476 item.getAccessibleContext().setAccessibleDescription("Quit the program");
477 item.setIcon(Icons.FILE_QUIT);
478 item.addActionListener(new ActionListener() {
479 public void actionPerformed(ActionEvent e) {
488 menu = new JMenu("Edit");
489 menu.setMnemonic(KeyEvent.VK_E);
490 menu.getAccessibleContext().setAccessibleDescription("Rocket editing");
494 Action action = document.getUndoAction();
495 item = new JMenuItem(action);
496 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
497 item.setMnemonic(KeyEvent.VK_U);
498 item.getAccessibleContext().setAccessibleDescription("Undo the previous operation");
502 action = document.getRedoAction();
503 item = new JMenuItem(action);
504 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
505 item.setMnemonic(KeyEvent.VK_R);
506 item.getAccessibleContext().setAccessibleDescription("Redo the previously undone " +
513 item = new JMenuItem(actions.getCutAction());
516 item = new JMenuItem(actions.getCopyAction());
519 item = new JMenuItem(actions.getPasteAction());
522 item = new JMenuItem(actions.getDeleteAction());
527 item = new JMenuItem("Preferences");
528 item.setIcon(Icons.PREFERENCES);
529 item.getAccessibleContext().setAccessibleDescription("Setup the application "+
531 item.addActionListener(new ActionListener() {
532 public void actionPerformed(ActionEvent e) {
533 PreferencesDialog.showPreferences();
542 menu = new JMenu("Analyze");
543 menu.setMnemonic(KeyEvent.VK_A);
544 menu.getAccessibleContext().setAccessibleDescription("Analyzing the rocket");
547 item = new JMenuItem("Component analysis",KeyEvent.VK_C);
548 item.getAccessibleContext().setAccessibleDescription("Analyze the rocket components " +
550 item.addActionListener(new ActionListener() {
551 public void actionPerformed(ActionEvent e) {
552 ComponentAnalysisDialog.showDialog(rocketpanel);
559 // (shown if openrocket.debug.menu is defined)
560 if (System.getProperty("openrocket.debug.menu") != null) {
561 menubar.add(makeDebugMenu());
568 menu = new JMenu("Help");
569 menu.setMnemonic(KeyEvent.VK_H);
570 menu.getAccessibleContext().setAccessibleDescription("Information about OpenRocket");
575 item = new JMenuItem("License",KeyEvent.VK_L);
576 item.getAccessibleContext().setAccessibleDescription("OpenRocket license information");
577 item.addActionListener(new ActionListener() {
578 public void actionPerformed(ActionEvent e) {
579 new LicenseDialog(BasicFrame.this).setVisible(true);
584 item = new JMenuItem("Bug report",KeyEvent.VK_B);
585 item.getAccessibleContext().setAccessibleDescription("Information about reporting " +
586 "bugs in OpenRocket");
587 item.addActionListener(new ActionListener() {
588 public void actionPerformed(ActionEvent e) {
589 // new BugDialog(BasicFrame.this).setVisible(true);
590 BugReportDialog.showBugReportDialog(BasicFrame.this);
595 item = new JMenuItem("About",KeyEvent.VK_A);
596 item.getAccessibleContext().setAccessibleDescription("About OpenRocket");
597 item.addActionListener(new ActionListener() {
598 public void actionPerformed(ActionEvent e) {
599 new AboutDialog(BasicFrame.this).setVisible(true);
605 this.setJMenuBar(menubar);
609 private JMenu makeDebugMenu() {
614 menu = new JMenu("Debug");
615 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
617 item = new JMenuItem("What is this menu?");
618 item.addActionListener(new ActionListener() {
619 public void actionPerformed(ActionEvent e) {
620 JOptionPane.showMessageDialog(BasicFrame.this,
622 "The 'Debug' menu includes actions for testing and debugging " +
624 "The menu is made visible by defining the system property " +
625 "'openrocket.debug.menu' when starting OpenRocket.",
626 "It should not be visible by default." },
627 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
634 item = new JMenuItem("Exception here");
635 item.addActionListener(new ActionListener() {
636 public void actionPerformed(ActionEvent e) {
637 throw new RuntimeException("Testing exception from menu action listener");
642 item = new JMenuItem("Exception from EDT");
643 item.addActionListener(new ActionListener() {
644 public void actionPerformed(ActionEvent e) {
645 SwingUtilities.invokeLater(new Runnable() {
648 throw new RuntimeException("Testing exception from " +
649 "later invoked EDT thread");
656 item = new JMenuItem("Exception from other thread");
657 item.addActionListener(new ActionListener() {
658 public void actionPerformed(ActionEvent e) {
662 throw new RuntimeException("Testing exception from " +
663 "newly created thread");
678 * Select the tab on the main pane.
680 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
682 public void selectTab(int tab) {
683 tabbedPane.setSelectedIndex(tab);
688 private void openAction() {
689 JFileChooser chooser = new JFileChooser();
690 chooser.setFileFilter(ROCKET_DESIGN_FILTER);
691 chooser.setMultiSelectionEnabled(true);
692 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
693 if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
696 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
698 File[] files = chooser.getSelectedFiles();
700 for (File file: files) {
701 System.out.println("Opening file: " + file);
702 if (open(file, this)) {
704 // Close previous window if replacing
705 if (replaceable && document.isSaved()) {
716 private static boolean open(URL url, Window parent) {
717 String filename = null;
719 // Try using URI.getPath();
721 URI uri = url.toURI();
722 filename = uri.getPath();
723 } catch (URISyntaxException ignore) { }
725 // Try URL-decoding the URL
726 if (filename == null) {
728 filename = URLDecoder.decode(url.toString(), "UTF-8");
729 } catch (UnsupportedEncodingException ignore) { }
733 if (filename == null) {
737 // Remove path from filename
738 if (filename.lastIndexOf('/') >= 0) {
739 filename = filename.substring(filename.lastIndexOf('/')+1);
743 InputStream is = url.openStream();
744 open(is, filename, parent);
745 } catch (IOException e) {
746 JOptionPane.showMessageDialog(parent,
747 "An error occurred while opening the file " + filename,
748 "Error loading file", JOptionPane.ERROR_MESSAGE);
756 * Open the specified file from an InputStream in a new design frame. If an error
757 * occurs, an error dialog is shown and <code>false</code> is returned.
759 * @param stream the stream to load from.
760 * @param filename the file name to display in dialogs (not set to the document).
761 * @param parent the parent component for which a progress dialog is opened.
762 * @return whether the file was successfully loaded and opened.
764 private static boolean open(InputStream stream, String filename, Window parent) {
765 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
766 return open(worker, filename, null, parent);
771 * Open the specified file in a new design frame. If an error occurs, an error
772 * dialog is shown and <code>false</code> is returned.
774 * @param file the file to open.
775 * @param parent the parent component for which a progress dialog is opened.
776 * @return whether the file was successfully loaded and opened.
778 private static boolean open(File file, Window parent) {
779 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
780 return open(worker, file.getName(), file, parent);
785 * Open the specified file using the provided worker.
787 * @param worker the OpenFileWorker that loads the file.
788 * @param filename the file name to display in dialogs.
789 * @param file the File to set the document to (may be null).
793 private static boolean open(OpenFileWorker worker, String filename, File file,
796 // Open the file in a Swing worker thread
797 if (!SwingWorkerDialog.runWorker(parent, "Opening file",
798 "Reading " + filename + "...", worker)) {
800 // User cancelled the operation
805 // Handle the document
806 OpenRocketDocument doc = null;
811 } catch (ExecutionException e) {
813 Throwable cause = e.getCause();
815 if (cause instanceof FileNotFoundException) {
817 JOptionPane.showMessageDialog(parent,
818 "File not found: " + filename,
819 "Error opening file", JOptionPane.ERROR_MESSAGE);
822 } else if (cause instanceof RocketLoadException) {
824 JOptionPane.showMessageDialog(parent,
825 "Unable to open file '" + filename +"': "
826 + cause.getMessage(),
827 "Error opening file", JOptionPane.ERROR_MESSAGE);
832 throw new RuntimeException("Unknown error when opening file", e);
836 } catch (InterruptedException e) {
837 throw new RuntimeException("EDT was interrupted", e);
841 throw new RuntimeException("BUG: Document loader returned null");
846 WarningSet warnings = worker.getRocketLoader().getWarnings();
847 if (!warnings.isEmpty()) {
848 WarningDialog.showWarnings(parent,
850 "The following problems were encountered while opening " + filename + ".",
851 "Some design features may not have been loaded correctly."
853 "Warnings while opening file", warnings);
857 // Set document state
862 BasicFrame frame = new BasicFrame(doc);
863 frame.setVisible(true);
876 private boolean saveAction() {
877 File file = document.getFile();
879 return saveAsAction();
886 private boolean saveAsAction() {
888 while (file == null) {
889 StorageOptionChooser storageChooser =
890 new StorageOptionChooser(document, document.getDefaultStorageOptions());
891 JFileChooser chooser = new JFileChooser();
892 chooser.setFileFilter(ROCKET_DESIGN_FILTER);
893 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
894 chooser.setAccessory(storageChooser);
895 if (document.getFile() != null)
896 chooser.setSelectedFile(document.getFile());
898 if (chooser.showSaveDialog(BasicFrame.this) != JFileChooser.APPROVE_OPTION)
901 file = chooser.getSelectedFile();
905 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
906 storageChooser.storeOptions(document.getDefaultStorageOptions());
908 if (file.getName().indexOf('.') < 0) {
909 String name = file.getAbsolutePath();
910 name = name + ".ork";
911 file = new File(name);
915 int result = JOptionPane.showConfirmDialog(this,
916 "File '"+file.getName()+"' exists. Do you want to overwrite it?",
917 "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
918 if (result != JOptionPane.YES_OPTION)
927 private boolean saveAs(File file) {
928 System.out.println("Saving to file: " + file.getName());
929 boolean saved = false;
931 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
932 // User cancelled the dialog
937 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
939 if (!SwingWorkerDialog.runWorker(this, "Saving file",
940 "Writing " + file.getName() + "...", worker)) {
942 // User cancelled the save
949 document.setFile(file);
950 document.setSaved(true);
953 } catch (ExecutionException e) {
954 Throwable cause = e.getCause();
956 if (cause instanceof IOException) {
957 JOptionPane.showMessageDialog(this, new String[] {
958 "An I/O error occurred while saving:",
959 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
962 throw new RuntimeException("Unknown error when saving file", e);
965 } catch (InterruptedException e) {
966 throw new RuntimeException("EDT was interrupted", e);
973 private boolean closeAction() {
974 if (!document.isSaved()) {
975 ComponentConfigDialog.hideDialog();
976 int result = JOptionPane.showConfirmDialog(this,
977 "Design '"+rocket.getName()+"' has not been saved. " +
978 "Do you want to save it?",
979 "Design not saved", JOptionPane.YES_NO_CANCEL_OPTION,
980 JOptionPane.QUESTION_MESSAGE);
981 if (result == JOptionPane.YES_OPTION) {
984 return false; // If save was interrupted
985 } else if (result == JOptionPane.NO_OPTION) {
993 // Rocket has been saved or discarded
996 // TODO: LOW: Close only dialogs that have this frame as their parent
997 ComponentConfigDialog.hideDialog();
998 ComponentAnalysisDialog.hideDialog();
1000 frames.remove(this);
1001 if (frames.isEmpty())
1008 * Closes this frame if it is replaceable.
1010 public void closeIfReplaceable() {
1011 if (this.replaceable && document.isSaved()) {
1017 * Open a new design window with a basic rocket+stage.
1019 public static void newAction() {
1020 Rocket rocket = new Rocket();
1021 Stage stage = new Stage();
1022 stage.setName("Sustainer");
1023 rocket.addChild(stage);
1024 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1027 BasicFrame frame = new BasicFrame(doc);
1028 frame.replaceable = true;
1029 frame.setVisible(true);
1030 ComponentConfigDialog.showDialog(frame, doc, rocket);
1034 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1036 public static void quitAction() {
1037 for (int i=frames.size()-1; i>=0; i--) {
1038 if (!frames.get(i).closeAction()) {
1043 // Should not be reached, but just in case
1049 * Set the title of the frame, taking into account the name of the rocket, file it
1050 * has been saved to (if any) and saved status.
1052 private void setTitle() {
1053 File file = document.getFile();
1054 boolean saved = document.isSaved();
1057 title = rocket.getName();
1059 title = title + " ("+file.getName()+")";
1062 title = "*" + title;
1070 * Find a currently open BasicFrame containing the specified rocket. This method
1071 * can be used to map a Rocket to a BasicFrame from GUI methods.
1073 * @param rocket the Rocket.
1074 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1076 public static BasicFrame findFrame(Rocket rocket) {
1077 for (BasicFrame f: frames) {
1078 if (f.rocket == rocket)
1085 * Find a currently open document by the rocket object. This method can be used
1086 * to map a Rocket to OpenRocketDocument from GUI methods.
1088 * @param rocket the Rocket.
1089 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1091 public static OpenRocketDocument findDocument(Rocket rocket) {
1092 for (BasicFrame f: frames) {
1093 if (f.rocket == rocket)
1100 public static void main(final String[] args) {
1102 // Run the actual startup method in the EDT since it can use progress dialogs etc.
1104 SwingUtilities.invokeAndWait(new Runnable() {
1110 } catch (InterruptedException e) {
1111 e.printStackTrace();
1112 } catch (InvocationTargetException e) {
1113 e.printStackTrace();
1119 private static void runMain(String[] args) {
1122 * Set the look-and-feel. On Linux, Motif/Metal is sometimes incorrectly used
1123 * which is butt-ugly, so if the system l&f is Motif/Metal, we search for a few
1124 * other alternatives.
1128 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
1130 // Check whether we have an ugly L&F
1131 LookAndFeel laf = UIManager.getLookAndFeel();
1133 laf.getName().matches(".*[mM][oO][tT][iI][fF].*") ||
1134 laf.getName().matches(".*[mM][eE][tT][aA][lL].*")) {
1136 // Search for better LAF
1137 UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();
1138 String lafNames[] = {
1142 ".*[aA][qQ][uU][aA].*",
1143 ".*[nN][iI][mM][bB].*"
1146 lf: for (String lafName: lafNames) {
1147 for (UIManager.LookAndFeelInfo l: info) {
1148 if (l.getName().matches(lafName)) {
1149 UIManager.setLookAndFeel(l.getClassName());
1155 } catch (Exception e) {
1156 System.err.println("Error setting LAF: " + e);
1159 // Set tooltip delay time. Tooltips are used in MotorChooserDialog extensively.
1160 ToolTipManager.sharedInstance().setDismissDelay(30000);
1163 // Setup the uncaught exception handler
1164 ExceptionHandler.registerExceptionHandler();
1168 Prefs.loadDefaultUnits();
1172 if (!handleCommandLine(args)) {
1179 * Handles arguments passed from the command line. This may be used either
1180 * when starting the first instance of OpenRocket or later when OpenRocket is
1181 * executed again while running.
1183 * @param args the command-line arguments.
1184 * @return whether a new frame was opened or similar user desired action was
1185 * performed as a result.
1187 public static boolean handleCommandLine(String[] args) {
1189 // Check command-line for files
1190 boolean opened = false;
1191 for (String file: args) {
1192 if (open(new File(file), null)) {