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.LookAndFeel;
49 import javax.swing.ScrollPaneConstants;
50 import javax.swing.SwingUtilities;
51 import javax.swing.ToolTipManager;
52 import javax.swing.UIManager;
53 import javax.swing.border.TitledBorder;
54 import javax.swing.event.TreeSelectionEvent;
55 import javax.swing.event.TreeSelectionListener;
56 import javax.swing.filechooser.FileFilter;
57 import javax.swing.tree.DefaultTreeSelectionModel;
58 import javax.swing.tree.TreePath;
59 import javax.swing.tree.TreeSelectionModel;
61 import net.miginfocom.swing.MigLayout;
62 import net.sf.openrocket.aerodynamics.WarningSet;
63 import net.sf.openrocket.document.OpenRocketDocument;
64 import net.sf.openrocket.file.GeneralRocketLoader;
65 import net.sf.openrocket.file.OpenRocketSaver;
66 import net.sf.openrocket.file.RocketLoadException;
67 import net.sf.openrocket.file.RocketLoader;
68 import net.sf.openrocket.file.RocketSaver;
69 import net.sf.openrocket.gui.StorageOptionChooser;
70 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
71 import net.sf.openrocket.gui.dialogs.AboutDialog;
72 import net.sf.openrocket.gui.dialogs.BugReportDialog;
73 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
74 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
75 import net.sf.openrocket.gui.dialogs.LicenseDialog;
76 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
77 import net.sf.openrocket.gui.dialogs.WarningDialog;
78 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
79 import net.sf.openrocket.gui.scalefigure.RocketPanel;
80 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
81 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
82 import net.sf.openrocket.rocketcomponent.Rocket;
83 import net.sf.openrocket.rocketcomponent.RocketComponent;
84 import net.sf.openrocket.rocketcomponent.Stage;
85 import net.sf.openrocket.util.GUIUtil;
86 import net.sf.openrocket.util.Icons;
87 import net.sf.openrocket.util.OpenFileWorker;
88 import net.sf.openrocket.util.Prefs;
89 import net.sf.openrocket.util.SaveFileWorker;
90 import net.sf.openrocket.util.TestRockets;
92 public class BasicFrame extends JFrame {
93 private static final long serialVersionUID = 1L;
96 * The RocketLoader instance used for loading all rocket designs.
98 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
100 private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
104 * File filter for filtering only rocket designs.
106 private static final FileFilter ROCKET_DESIGN_FILTER = new FileFilter() {
108 public String getDescription() {
109 return "OpenRocket designs (*.ork)";
112 public boolean accept(File f) {
115 String name = f.getName().toLowerCase();
116 return name.endsWith(".ork") || name.endsWith(".ork.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("Exception here");
669 item.addActionListener(new ActionListener() {
670 public void actionPerformed(ActionEvent e) {
671 throw new RuntimeException("Testing exception from menu action listener");
676 item = new JMenuItem("Exception from EDT");
677 item.addActionListener(new ActionListener() {
678 public void actionPerformed(ActionEvent e) {
679 SwingUtilities.invokeLater(new Runnable() {
682 throw new RuntimeException("Testing exception from " +
683 "later invoked EDT thread");
690 item = new JMenuItem("Exception from other thread");
691 item.addActionListener(new ActionListener() {
692 public void actionPerformed(ActionEvent e) {
696 throw new RuntimeException("Testing exception from " +
697 "newly created thread");
712 * Select the tab on the main pane.
714 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
716 public void selectTab(int tab) {
717 tabbedPane.setSelectedIndex(tab);
722 private void openAction() {
723 JFileChooser chooser = new JFileChooser();
724 chooser.setFileFilter(ROCKET_DESIGN_FILTER);
725 chooser.setMultiSelectionEnabled(true);
726 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
727 if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
730 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
732 File[] files = chooser.getSelectedFiles();
734 for (File file: files) {
735 System.out.println("Opening file: " + file);
736 if (open(file, this)) {
738 // Close previous window if replacing
739 if (replaceable && document.isSaved()) {
750 private static boolean open(URL url, Window parent) {
751 String filename = null;
753 // Try using URI.getPath();
755 URI uri = url.toURI();
756 filename = uri.getPath();
757 } catch (URISyntaxException ignore) { }
759 // Try URL-decoding the URL
760 if (filename == null) {
762 filename = URLDecoder.decode(url.toString(), "UTF-8");
763 } catch (UnsupportedEncodingException ignore) { }
767 if (filename == null) {
771 // Remove path from filename
772 if (filename.lastIndexOf('/') >= 0) {
773 filename = filename.substring(filename.lastIndexOf('/')+1);
777 InputStream is = url.openStream();
778 open(is, filename, parent);
779 } catch (IOException e) {
780 JOptionPane.showMessageDialog(parent,
781 "An error occurred while opening the file " + filename,
782 "Error loading file", JOptionPane.ERROR_MESSAGE);
790 * Open the specified file from an InputStream in a new design frame. If an error
791 * occurs, an error dialog is shown and <code>false</code> is returned.
793 * @param stream the stream to load from.
794 * @param filename the file name to display in dialogs (not set to the document).
795 * @param parent the parent component for which a progress dialog is opened.
796 * @return whether the file was successfully loaded and opened.
798 private static boolean open(InputStream stream, String filename, Window parent) {
799 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
800 return open(worker, filename, null, parent);
805 * Open the specified file in a new design frame. If an error occurs, an error
806 * dialog is shown and <code>false</code> is returned.
808 * @param file the file to open.
809 * @param parent the parent component for which a progress dialog is opened.
810 * @return whether the file was successfully loaded and opened.
812 private static boolean open(File file, Window parent) {
813 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
814 return open(worker, file.getName(), file, parent);
819 * Open the specified file using the provided worker.
821 * @param worker the OpenFileWorker that loads the file.
822 * @param filename the file name to display in dialogs.
823 * @param file the File to set the document to (may be null).
827 private static boolean open(OpenFileWorker worker, String filename, File file,
830 // Open the file in a Swing worker thread
831 if (!SwingWorkerDialog.runWorker(parent, "Opening file",
832 "Reading " + filename + "...", worker)) {
834 // User cancelled the operation
839 // Handle the document
840 OpenRocketDocument doc = null;
845 } catch (ExecutionException e) {
847 Throwable cause = e.getCause();
849 if (cause instanceof FileNotFoundException) {
851 JOptionPane.showMessageDialog(parent,
852 "File not found: " + filename,
853 "Error opening file", JOptionPane.ERROR_MESSAGE);
856 } else if (cause instanceof RocketLoadException) {
858 JOptionPane.showMessageDialog(parent,
859 "Unable to open file '" + filename +"': "
860 + cause.getMessage(),
861 "Error opening file", JOptionPane.ERROR_MESSAGE);
866 throw new RuntimeException("Unknown error when opening file", e);
870 } catch (InterruptedException e) {
871 throw new RuntimeException("EDT was interrupted", e);
875 throw new RuntimeException("BUG: Document loader returned null");
880 WarningSet warnings = worker.getRocketLoader().getWarnings();
881 if (!warnings.isEmpty()) {
882 WarningDialog.showWarnings(parent,
884 "The following problems were encountered while opening " + filename + ".",
885 "Some design features may not have been loaded correctly."
887 "Warnings while opening file", warnings);
891 // Set document state
896 BasicFrame frame = new BasicFrame(doc);
897 frame.setVisible(true);
910 private boolean saveAction() {
911 File file = document.getFile();
913 return saveAsAction();
920 private boolean saveAsAction() {
922 while (file == null) {
923 StorageOptionChooser storageChooser =
924 new StorageOptionChooser(document, document.getDefaultStorageOptions());
925 JFileChooser chooser = new JFileChooser();
926 chooser.setFileFilter(ROCKET_DESIGN_FILTER);
927 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
928 chooser.setAccessory(storageChooser);
929 if (document.getFile() != null)
930 chooser.setSelectedFile(document.getFile());
932 if (chooser.showSaveDialog(BasicFrame.this) != JFileChooser.APPROVE_OPTION)
935 file = chooser.getSelectedFile();
939 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
940 storageChooser.storeOptions(document.getDefaultStorageOptions());
942 if (file.getName().indexOf('.') < 0) {
943 String name = file.getAbsolutePath();
944 name = name + ".ork";
945 file = new File(name);
949 int result = JOptionPane.showConfirmDialog(this,
950 "File '"+file.getName()+"' exists. Do you want to overwrite it?",
951 "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
952 if (result != JOptionPane.YES_OPTION)
961 private boolean saveAs(File file) {
962 System.out.println("Saving to file: " + file.getName());
963 boolean saved = false;
965 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
966 // User cancelled the dialog
971 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
973 if (!SwingWorkerDialog.runWorker(this, "Saving file",
974 "Writing " + file.getName() + "...", worker)) {
976 // User cancelled the save
983 document.setFile(file);
984 document.setSaved(true);
987 } catch (ExecutionException e) {
988 Throwable cause = e.getCause();
990 if (cause instanceof IOException) {
991 JOptionPane.showMessageDialog(this, new String[] {
992 "An I/O error occurred while saving:",
993 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
996 throw new RuntimeException("Unknown error when saving file", e);
999 } catch (InterruptedException e) {
1000 throw new RuntimeException("EDT was interrupted", e);
1007 private boolean closeAction() {
1008 if (!document.isSaved()) {
1009 ComponentConfigDialog.hideDialog();
1010 int result = JOptionPane.showConfirmDialog(this,
1011 "Design '"+rocket.getName()+"' has not been saved. " +
1012 "Do you want to save it?",
1013 "Design not saved", JOptionPane.YES_NO_CANCEL_OPTION,
1014 JOptionPane.QUESTION_MESSAGE);
1015 if (result == JOptionPane.YES_OPTION) {
1018 return false; // If save was interrupted
1019 } else if (result == JOptionPane.NO_OPTION) {
1020 // Don't save: No-op
1027 // Rocket has been saved or discarded
1030 // TODO: LOW: Close only dialogs that have this frame as their parent
1031 ComponentConfigDialog.hideDialog();
1032 ComponentAnalysisDialog.hideDialog();
1034 frames.remove(this);
1035 if (frames.isEmpty())
1042 * Closes this frame if it is replaceable.
1044 public void closeIfReplaceable() {
1045 if (this.replaceable && document.isSaved()) {
1051 * Open a new design window with a basic rocket+stage.
1053 public static void newAction() {
1054 Rocket rocket = new Rocket();
1055 Stage stage = new Stage();
1056 stage.setName("Sustainer");
1057 rocket.addChild(stage);
1058 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1061 BasicFrame frame = new BasicFrame(doc);
1062 frame.replaceable = true;
1063 frame.setVisible(true);
1064 ComponentConfigDialog.showDialog(frame, doc, rocket);
1068 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1070 public static void quitAction() {
1071 for (int i=frames.size()-1; i>=0; i--) {
1072 if (!frames.get(i).closeAction()) {
1077 // Should not be reached, but just in case
1083 * Set the title of the frame, taking into account the name of the rocket, file it
1084 * has been saved to (if any) and saved status.
1086 private void setTitle() {
1087 File file = document.getFile();
1088 boolean saved = document.isSaved();
1091 title = rocket.getName();
1093 title = title + " ("+file.getName()+")";
1096 title = "*" + title;
1104 * Find a currently open BasicFrame containing the specified rocket. This method
1105 * can be used to map a Rocket to a BasicFrame from GUI methods.
1107 * @param rocket the Rocket.
1108 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1110 public static BasicFrame findFrame(Rocket rocket) {
1111 for (BasicFrame f: frames) {
1112 if (f.rocket == rocket)
1119 * Find a currently open document by the rocket object. This method can be used
1120 * to map a Rocket to OpenRocketDocument from GUI methods.
1122 * @param rocket the Rocket.
1123 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1125 public static OpenRocketDocument findDocument(Rocket rocket) {
1126 for (BasicFrame f: frames) {
1127 if (f.rocket == rocket)
1134 public static void main(final String[] args) {
1136 // Run the actual startup method in the EDT since it can use progress dialogs etc.
1138 SwingUtilities.invokeAndWait(new Runnable() {
1144 } catch (InterruptedException e) {
1145 e.printStackTrace();
1146 } catch (InvocationTargetException e) {
1147 e.printStackTrace();
1153 private static void runMain(String[] args) {
1156 * Set the look-and-feel. On Linux, Motif/Metal is sometimes incorrectly used
1157 * which is butt-ugly, so if the system l&f is Motif/Metal, we search for a few
1158 * other alternatives.
1162 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
1164 // Check whether we have an ugly L&F
1165 LookAndFeel laf = UIManager.getLookAndFeel();
1167 laf.getName().matches(".*[mM][oO][tT][iI][fF].*") ||
1168 laf.getName().matches(".*[mM][eE][tT][aA][lL].*")) {
1170 // Search for better LAF
1171 UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();
1172 String lafNames[] = {
1176 ".*[aA][qQ][uU][aA].*",
1177 ".*[nN][iI][mM][bB].*"
1180 lf: for (String lafName: lafNames) {
1181 for (UIManager.LookAndFeelInfo l: info) {
1182 if (l.getName().matches(lafName)) {
1183 UIManager.setLookAndFeel(l.getClassName());
1189 } catch (Exception e) {
1190 System.err.println("Error setting LAF: " + e);
1193 // Set tooltip delay time. Tooltips are used in MotorChooserDialog extensively.
1194 ToolTipManager.sharedInstance().setDismissDelay(30000);
1197 // Setup the uncaught exception handler
1198 ExceptionHandler.registerExceptionHandler();
1202 Prefs.loadDefaultUnits();
1206 if (!handleCommandLine(args)) {
1213 * Handles arguments passed from the command line. This may be used either
1214 * when starting the first instance of OpenRocket or later when OpenRocket is
1215 * executed again while running.
1217 * @param args the command-line arguments.
1218 * @return whether a new frame was opened or similar user desired action was
1219 * performed as a result.
1221 public static boolean handleCommandLine(String[] args) {
1223 // Check command-line for files
1224 boolean opened = false;
1225 for (String file: args) {
1226 if (open(new File(file), null)) {