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.Timer;
52 import javax.swing.ToolTipManager;
53 import javax.swing.UIManager;
54 import javax.swing.border.TitledBorder;
55 import javax.swing.event.TreeSelectionEvent;
56 import javax.swing.event.TreeSelectionListener;
57 import javax.swing.filechooser.FileFilter;
58 import javax.swing.tree.DefaultTreeSelectionModel;
59 import javax.swing.tree.TreePath;
60 import javax.swing.tree.TreeSelectionModel;
62 import net.miginfocom.swing.MigLayout;
63 import net.sf.openrocket.aerodynamics.WarningSet;
64 import net.sf.openrocket.communication.UpdateInfo;
65 import net.sf.openrocket.communication.UpdateInfoRetriever;
66 import net.sf.openrocket.database.Databases;
67 import net.sf.openrocket.document.OpenRocketDocument;
68 import net.sf.openrocket.file.GeneralRocketLoader;
69 import net.sf.openrocket.file.RocketLoadException;
70 import net.sf.openrocket.file.RocketLoader;
71 import net.sf.openrocket.file.RocketSaver;
72 import net.sf.openrocket.file.openrocket.OpenRocketSaver;
73 import net.sf.openrocket.gui.StorageOptionChooser;
74 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
75 import net.sf.openrocket.gui.dialogs.AboutDialog;
76 import net.sf.openrocket.gui.dialogs.BugReportDialog;
77 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
78 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
79 import net.sf.openrocket.gui.dialogs.LicenseDialog;
80 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
81 import net.sf.openrocket.gui.dialogs.UpdateInfoDialog;
82 import net.sf.openrocket.gui.dialogs.WarningDialog;
83 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
84 import net.sf.openrocket.gui.scalefigure.RocketPanel;
85 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
86 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
87 import net.sf.openrocket.rocketcomponent.Rocket;
88 import net.sf.openrocket.rocketcomponent.RocketComponent;
89 import net.sf.openrocket.rocketcomponent.Stage;
90 import net.sf.openrocket.util.BugException;
91 import net.sf.openrocket.util.GUIUtil;
92 import net.sf.openrocket.util.Icons;
93 import net.sf.openrocket.util.OpenFileWorker;
94 import net.sf.openrocket.util.Prefs;
95 import net.sf.openrocket.util.SaveFileWorker;
96 import net.sf.openrocket.util.TestRockets;
98 public class BasicFrame extends JFrame {
99 private static final long serialVersionUID = 1L;
102 * The RocketLoader instance used for loading all rocket designs.
104 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
106 private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
110 * File filter for filtering only rocket designs.
112 private static final FileFilter ROCKET_DESIGN_FILTER = new FileFilter() {
114 public String getDescription() {
115 return "OpenRocket designs (*.ork)";
118 public boolean accept(File f) {
121 String name = f.getName().toLowerCase();
122 return name.endsWith(".ork") || name.endsWith(".ork.gz");
128 public static final int COMPONENT_TAB = 0;
129 public static final int SIMULATION_TAB = 1;
133 * List of currently open frames. When the list goes empty
134 * it is time to exit the application.
136 private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
143 * Whether "New" and "Open" should replace this frame.
144 * Should be set to false on the first rocket modification.
146 private boolean replaceable = false;
150 private final OpenRocketDocument document;
151 private final Rocket rocket;
153 private JTabbedPane tabbedPane;
154 private RocketPanel rocketpanel;
155 private ComponentTree tree = null;
157 private final DocumentSelectionModel selectionModel;
158 private final TreeSelectionModel componentSelectionModel;
159 private final ListSelectionModel simulationSelectionModel;
161 /** Actions available for rocket modifications */
162 private final RocketActions actions;
167 * Sole constructor. Creates a new frame based on the supplied document
168 * and adds it to the current frames list.
170 * @param document the document to show.
172 public BasicFrame(OpenRocketDocument document) {
174 this.document = document;
175 this.rocket = document.getRocket();
176 this.rocket.getDefaultConfiguration().setAllStages();
179 // Set replaceable flag to false at first modification
180 rocket.addComponentChangeListener(new ComponentChangeListener() {
181 public void componentChanged(ComponentChangeEvent e) {
183 BasicFrame.this.rocket.removeComponentChangeListener(this);
188 // Create the component tree selection model that will be used
189 componentSelectionModel = new DefaultTreeSelectionModel();
190 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
192 // Obtain the simulation selection model that will be used
193 SimulationPanel simulationPanel = new SimulationPanel(document);
194 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
196 // Combine into a DocumentSelectionModel
197 selectionModel = new DocumentSelectionModel(document);
198 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
199 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
202 actions = new RocketActions(document, selectionModel, this);
205 // The main vertical split pane
206 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
207 vertical.setResizeWeight(0.5);
211 // The top tabbed pane
212 tabbedPane = new JTabbedPane();
213 tabbedPane.addTab("Rocket design", null, designTab());
214 tabbedPane.addTab("Flight simulations", null, simulationPanel);
216 vertical.setTopComponent(tabbedPane);
220 // Bottom segment, rocket figure
222 rocketpanel = new RocketPanel(document);
223 vertical.setBottomComponent(rocketpanel);
225 rocketpanel.setSelectionModel(tree.getSelectionModel());
231 rocket.addComponentChangeListener(new ComponentChangeListener() {
232 public void componentChanged(ComponentChangeEvent e) {
240 Dimension size = Prefs.getWindowSize(this.getClass());
242 size = Toolkit.getDefaultToolkit().getScreenSize();
243 size.width = size.width*9/10;
244 size.height = size.height*9/10;
247 this.addComponentListener(new ComponentAdapter() {
249 public void componentResized(ComponentEvent e) {
250 Prefs.setWindowSize(BasicFrame.this.getClass(), BasicFrame.this.getSize());
253 this.setLocationByPlatform(true);
255 GUIUtil.setWindowIcons(this);
258 vertical.setDividerLocation(0.4);
259 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
260 addWindowListener(new WindowAdapter() {
262 public void windowClosing(WindowEvent e) {
271 * Construct the "Rocket design" tab. This contains a horizontal split pane
272 * with the left component the design tree and the right component buttons
273 * for adding components.
275 private JComponent designTab() {
276 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true);
277 horizontal.setResizeWeight(0.5);
280 // Upper-left segment, component tree
282 JPanel panel = new JPanel(new MigLayout("fill, flowy","","[grow]"));
284 tree = new ComponentTree(rocket);
285 tree.setSelectionModel(componentSelectionModel);
287 // Remove JTree key events that interfere with menu accelerators
288 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
289 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
290 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
291 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
292 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
293 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
294 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
295 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
299 // Double-click opens config dialog
300 MouseListener ml = new MouseAdapter() {
302 public void mousePressed(MouseEvent e) {
303 int selRow = tree.getRowForLocation(e.getX(), e.getY());
304 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
306 if((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
308 RocketComponent c = (RocketComponent)selPath.getLastPathComponent();
309 ComponentConfigDialog.showDialog(BasicFrame.this,
310 BasicFrame.this.document, c);
315 tree.addMouseListener(ml);
317 // Update dialog when selection is changed
318 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
319 public void valueChanged(TreeSelectionEvent e) {
320 // Scroll tree to the selected item
321 TreePath path = componentSelectionModel.getSelectionPath();
324 tree.scrollPathToVisible(path);
326 if (!ComponentConfigDialog.isDialogVisible())
328 RocketComponent c = (RocketComponent)path.getLastPathComponent();
329 ComponentConfigDialog.showDialog(BasicFrame.this,
330 BasicFrame.this.document, c);
334 // Place tree inside scroll pane
335 JScrollPane scroll = new JScrollPane(tree);
336 panel.add(scroll,"spany, grow, wrap");
340 JButton button = new JButton(actions.getMoveUpAction());
341 panel.add(button,"sizegroup buttons, aligny 65%");
343 button = new JButton(actions.getMoveDownAction());
344 panel.add(button,"sizegroup buttons, aligny 0%");
346 button = new JButton(actions.getEditAction());
347 panel.add(button, "sizegroup buttons");
349 button = new JButton(actions.getNewStageAction());
350 panel.add(button,"sizegroup buttons");
352 button = new JButton(actions.getDeleteAction());
353 button.setIcon(null);
354 button.setMnemonic(0);
355 panel.add(button,"sizegroup buttons");
357 horizontal.setLeftComponent(panel);
360 // Upper-right segment, component addition buttons
362 panel = new JPanel(new MigLayout("fill, insets 0","[0::]"));
364 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
365 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
366 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
367 scroll.getViewport()));
368 scroll.setBorder(null);
369 scroll.setViewportBorder(null);
371 TitledBorder border = new TitledBorder("Add new component");
372 border.setTitleFont(border.getTitleFont().deriveFont(Font.BOLD));
373 scroll.setBorder(border);
375 panel.add(scroll,"grow");
377 horizontal.setRightComponent(panel);
385 * Creates the menu for the window.
387 private void createMenu() {
388 JMenuBar menubar = new JMenuBar();
393 menu = new JMenu("File");
394 menu.setMnemonic(KeyEvent.VK_F);
395 menu.getAccessibleContext().setAccessibleDescription("File-handling related tasks");
398 item = new JMenuItem("New",KeyEvent.VK_N);
399 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
400 item.setMnemonic(KeyEvent.VK_N);
401 item.getAccessibleContext().setAccessibleDescription("Create a new rocket design");
402 item.setIcon(Icons.FILE_NEW);
403 item.addActionListener(new ActionListener() {
404 public void actionPerformed(ActionEvent e) {
412 item = new JMenuItem("Open...",KeyEvent.VK_O);
413 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
414 item.getAccessibleContext().setAccessibleDescription("Open a rocket design");
415 item.setIcon(Icons.FILE_OPEN);
416 item.addActionListener(new ActionListener() {
417 public void actionPerformed(ActionEvent e) {
423 item = new JMenuItem("Open example...");
424 item.getAccessibleContext().setAccessibleDescription("Open an example rocket design");
425 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
426 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
427 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
428 item.addActionListener(new ActionListener() {
429 public void actionPerformed(ActionEvent e) {
430 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
433 open(u, BasicFrame.this);
442 item = new JMenuItem("Save",KeyEvent.VK_S);
443 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
444 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design");
445 item.setIcon(Icons.FILE_SAVE);
446 item.addActionListener(new ActionListener() {
447 public void actionPerformed(ActionEvent e) {
453 item = new JMenuItem("Save as...",KeyEvent.VK_A);
454 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
455 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
456 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design "+
458 item.setIcon(Icons.FILE_SAVE_AS);
459 item.addActionListener(new ActionListener() {
460 public void actionPerformed(ActionEvent e) {
466 // menu.addSeparator();
467 menu.add(new JSeparator());
469 item = new JMenuItem("Close",KeyEvent.VK_C);
470 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
471 item.getAccessibleContext().setAccessibleDescription("Close the current rocket design");
472 item.setIcon(Icons.FILE_CLOSE);
473 item.addActionListener(new ActionListener() {
474 public void actionPerformed(ActionEvent e) {
482 item = new JMenuItem("Quit",KeyEvent.VK_Q);
483 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
484 item.getAccessibleContext().setAccessibleDescription("Quit the program");
485 item.setIcon(Icons.FILE_QUIT);
486 item.addActionListener(new ActionListener() {
487 public void actionPerformed(ActionEvent e) {
496 menu = new JMenu("Edit");
497 menu.setMnemonic(KeyEvent.VK_E);
498 menu.getAccessibleContext().setAccessibleDescription("Rocket editing");
502 Action action = document.getUndoAction();
503 item = new JMenuItem(action);
504 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
505 item.setMnemonic(KeyEvent.VK_U);
506 item.getAccessibleContext().setAccessibleDescription("Undo the previous operation");
510 action = document.getRedoAction();
511 item = new JMenuItem(action);
512 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
513 item.setMnemonic(KeyEvent.VK_R);
514 item.getAccessibleContext().setAccessibleDescription("Redo the previously undone " +
521 item = new JMenuItem(actions.getCutAction());
524 item = new JMenuItem(actions.getCopyAction());
527 item = new JMenuItem(actions.getPasteAction());
530 item = new JMenuItem(actions.getDeleteAction());
535 item = new JMenuItem("Preferences");
536 item.setIcon(Icons.PREFERENCES);
537 item.getAccessibleContext().setAccessibleDescription("Setup the application "+
539 item.addActionListener(new ActionListener() {
540 public void actionPerformed(ActionEvent e) {
541 PreferencesDialog.showPreferences();
550 menu = new JMenu("Analyze");
551 menu.setMnemonic(KeyEvent.VK_A);
552 menu.getAccessibleContext().setAccessibleDescription("Analyzing the rocket");
555 item = new JMenuItem("Component analysis",KeyEvent.VK_C);
556 item.getAccessibleContext().setAccessibleDescription("Analyze the rocket components " +
558 item.addActionListener(new ActionListener() {
559 public void actionPerformed(ActionEvent e) {
560 ComponentAnalysisDialog.showDialog(rocketpanel);
567 // (shown if openrocket.debug.menu is defined)
568 if (System.getProperty("openrocket.debug.menu") != null) {
569 menubar.add(makeDebugMenu());
576 menu = new JMenu("Help");
577 menu.setMnemonic(KeyEvent.VK_H);
578 menu.getAccessibleContext().setAccessibleDescription("Information about OpenRocket");
583 item = new JMenuItem("License",KeyEvent.VK_L);
584 item.getAccessibleContext().setAccessibleDescription("OpenRocket license information");
585 item.addActionListener(new ActionListener() {
586 public void actionPerformed(ActionEvent e) {
587 new LicenseDialog(BasicFrame.this).setVisible(true);
592 item = new JMenuItem("Bug report",KeyEvent.VK_B);
593 item.getAccessibleContext().setAccessibleDescription("Information about reporting " +
594 "bugs in OpenRocket");
595 item.addActionListener(new ActionListener() {
596 public void actionPerformed(ActionEvent e) {
597 // new BugDialog(BasicFrame.this).setVisible(true);
598 BugReportDialog.showBugReportDialog(BasicFrame.this);
603 item = new JMenuItem("About",KeyEvent.VK_A);
604 item.getAccessibleContext().setAccessibleDescription("About OpenRocket");
605 item.addActionListener(new ActionListener() {
606 public void actionPerformed(ActionEvent e) {
607 new AboutDialog(BasicFrame.this).setVisible(true);
613 this.setJMenuBar(menubar);
617 private JMenu makeDebugMenu() {
622 menu = new JMenu("Debug");
623 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
625 item = new JMenuItem("What is this menu?");
626 item.addActionListener(new ActionListener() {
627 public void actionPerformed(ActionEvent e) {
628 JOptionPane.showMessageDialog(BasicFrame.this,
630 "The 'Debug' menu includes actions for testing and debugging " +
632 "The menu is made visible by defining the system property " +
633 "'openrocket.debug.menu' when starting OpenRocket.",
634 "It should not be visible by default." },
635 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
642 item = new JMenuItem("Create test rocket");
643 item.addActionListener(new ActionListener() {
645 public void actionPerformed(ActionEvent e) {
646 JTextField field = new JTextField();
647 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
648 "Input text key to generate random rocket:",
650 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
651 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
657 r = new TestRockets(null).makeTestRocket();
658 } else if (sel == 1) {
659 r = new TestRockets(field.getText()).makeTestRocket();
664 OpenRocketDocument doc = new OpenRocketDocument(r);
666 BasicFrame frame = new BasicFrame(doc);
667 frame.setVisible(true);
674 item = new JMenuItem("Exception here");
675 item.addActionListener(new ActionListener() {
676 public void actionPerformed(ActionEvent e) {
677 throw new RuntimeException("Testing exception from menu action listener");
682 item = new JMenuItem("Exception from EDT");
683 item.addActionListener(new ActionListener() {
684 public void actionPerformed(ActionEvent e) {
685 SwingUtilities.invokeLater(new Runnable() {
688 throw new RuntimeException("Testing exception from " +
689 "later invoked EDT thread");
696 item = new JMenuItem("Exception from other thread");
697 item.addActionListener(new ActionListener() {
698 public void actionPerformed(ActionEvent e) {
702 throw new RuntimeException("Testing exception from " +
703 "newly created thread");
718 * Select the tab on the main pane.
720 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
722 public void selectTab(int tab) {
723 tabbedPane.setSelectedIndex(tab);
728 private void openAction() {
729 JFileChooser chooser = new JFileChooser();
730 chooser.setFileFilter(ROCKET_DESIGN_FILTER);
731 chooser.setMultiSelectionEnabled(true);
732 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
733 if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
736 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
738 File[] files = chooser.getSelectedFiles();
740 for (File file: files) {
741 System.out.println("Opening file: " + file);
742 if (open(file, this)) {
744 // Close previous window if replacing
745 if (replaceable && document.isSaved()) {
756 private static boolean open(URL url, BasicFrame parent) {
757 String filename = null;
759 // Try using URI.getPath();
761 URI uri = url.toURI();
762 filename = uri.getPath();
763 } catch (URISyntaxException ignore) { }
765 // Try URL-decoding the URL
766 if (filename == null) {
768 filename = URLDecoder.decode(url.toString(), "UTF-8");
769 } catch (UnsupportedEncodingException ignore) { }
773 if (filename == null) {
777 // Remove path from filename
778 if (filename.lastIndexOf('/') >= 0) {
779 filename = filename.substring(filename.lastIndexOf('/')+1);
783 InputStream is = url.openStream();
784 if (open(is, filename, parent)) {
785 // Close previous window if replacing
786 if (parent.replaceable && parent.document.isSaved()) {
787 parent.closeAction();
788 parent.replaceable = false;
791 } catch (IOException e) {
792 JOptionPane.showMessageDialog(parent,
793 "An error occurred while opening the file " + filename,
794 "Error loading file", JOptionPane.ERROR_MESSAGE);
802 * Open the specified file from an InputStream in a new design frame. If an error
803 * occurs, an error dialog is shown and <code>false</code> is returned.
805 * @param stream the stream to load from.
806 * @param filename the file name to display in dialogs (not set to the document).
807 * @param parent the parent component for which a progress dialog is opened.
808 * @return whether the file was successfully loaded and opened.
810 private static boolean open(InputStream stream, String filename, Window parent) {
811 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
812 return open(worker, filename, null, parent);
817 * Open the specified file in a new design frame. If an error occurs, an error
818 * dialog is shown and <code>false</code> is returned.
820 * @param file the file to open.
821 * @param parent the parent component for which a progress dialog is opened.
822 * @return whether the file was successfully loaded and opened.
824 private static boolean open(File file, Window parent) {
825 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
826 return open(worker, file.getName(), file, parent);
831 * Open the specified file using the provided worker.
833 * @param worker the OpenFileWorker that loads the file.
834 * @param filename the file name to display in dialogs.
835 * @param file the File to set the document to (may be null).
839 private static boolean open(OpenFileWorker worker, String filename, File file,
842 // Open the file in a Swing worker thread
843 if (!SwingWorkerDialog.runWorker(parent, "Opening file",
844 "Reading " + filename + "...", worker)) {
846 // User cancelled the operation
851 // Handle the document
852 OpenRocketDocument doc = null;
857 } catch (ExecutionException e) {
859 Throwable cause = e.getCause();
861 if (cause instanceof FileNotFoundException) {
863 JOptionPane.showMessageDialog(parent,
864 "File not found: " + filename,
865 "Error opening file", JOptionPane.ERROR_MESSAGE);
868 } else if (cause instanceof RocketLoadException) {
870 JOptionPane.showMessageDialog(parent,
871 "Unable to open file '" + filename +"': "
872 + cause.getMessage(),
873 "Error opening file", JOptionPane.ERROR_MESSAGE);
878 throw new BugException("Unknown error when opening file", e);
882 } catch (InterruptedException e) {
883 throw new BugException("EDT was interrupted", e);
887 throw new BugException("BUG: Document loader returned null");
892 WarningSet warnings = worker.getRocketLoader().getWarnings();
893 if (!warnings.isEmpty()) {
894 WarningDialog.showWarnings(parent,
896 "The following problems were encountered while opening " + filename + ".",
897 "Some design features may not have been loaded correctly."
899 "Warnings while opening file", warnings);
903 // Set document state
908 BasicFrame frame = new BasicFrame(doc);
909 frame.setVisible(true);
922 private boolean saveAction() {
923 File file = document.getFile();
925 return saveAsAction();
932 private boolean saveAsAction() {
934 while (file == null) {
935 StorageOptionChooser storageChooser =
936 new StorageOptionChooser(document, document.getDefaultStorageOptions());
937 JFileChooser chooser = new JFileChooser();
938 chooser.setFileFilter(ROCKET_DESIGN_FILTER);
939 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
940 chooser.setAccessory(storageChooser);
941 if (document.getFile() != null)
942 chooser.setSelectedFile(document.getFile());
944 if (chooser.showSaveDialog(BasicFrame.this) != JFileChooser.APPROVE_OPTION)
947 file = chooser.getSelectedFile();
951 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
952 storageChooser.storeOptions(document.getDefaultStorageOptions());
954 if (file.getName().indexOf('.') < 0) {
955 String name = file.getAbsolutePath();
956 name = name + ".ork";
957 file = new File(name);
961 int result = JOptionPane.showConfirmDialog(this,
962 "File '"+file.getName()+"' exists. Do you want to overwrite it?",
963 "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
964 if (result != JOptionPane.YES_OPTION)
973 private boolean saveAs(File file) {
974 System.out.println("Saving to file: " + file.getName());
975 boolean saved = false;
977 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
978 // User cancelled the dialog
983 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
985 if (!SwingWorkerDialog.runWorker(this, "Saving file",
986 "Writing " + file.getName() + "...", worker)) {
988 // User cancelled the save
995 document.setFile(file);
996 document.setSaved(true);
999 } catch (ExecutionException e) {
1000 Throwable cause = e.getCause();
1002 if (cause instanceof IOException) {
1003 JOptionPane.showMessageDialog(this, new String[] {
1004 "An I/O error occurred while saving:",
1005 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1008 throw new BugException("Unknown error when saving file", e);
1011 } catch (InterruptedException e) {
1012 throw new BugException("EDT was interrupted", e);
1019 private boolean closeAction() {
1020 if (!document.isSaved()) {
1021 ComponentConfigDialog.hideDialog();
1022 int result = JOptionPane.showConfirmDialog(this,
1023 "Design '"+rocket.getName()+"' has not been saved. " +
1024 "Do you want to save it?",
1025 "Design not saved", JOptionPane.YES_NO_CANCEL_OPTION,
1026 JOptionPane.QUESTION_MESSAGE);
1027 if (result == JOptionPane.YES_OPTION) {
1030 return false; // If save was interrupted
1031 } else if (result == JOptionPane.NO_OPTION) {
1032 // Don't save: No-op
1039 // Rocket has been saved or discarded
1042 // TODO: LOW: Close only dialogs that have this frame as their parent
1043 ComponentConfigDialog.hideDialog();
1044 ComponentAnalysisDialog.hideDialog();
1046 frames.remove(this);
1047 if (frames.isEmpty())
1054 * Closes this frame if it is replaceable.
1056 public void closeIfReplaceable() {
1057 if (this.replaceable && document.isSaved()) {
1063 * Open a new design window with a basic rocket+stage.
1065 public static void newAction() {
1066 Rocket rocket = new Rocket();
1067 Stage stage = new Stage();
1068 stage.setName("Sustainer");
1069 rocket.addChild(stage);
1070 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1073 BasicFrame frame = new BasicFrame(doc);
1074 frame.replaceable = true;
1075 frame.setVisible(true);
1076 ComponentConfigDialog.showDialog(frame, doc, rocket);
1080 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1082 public static void quitAction() {
1083 for (int i=frames.size()-1; i>=0; i--) {
1084 if (!frames.get(i).closeAction()) {
1089 // Should not be reached, but just in case
1095 * Set the title of the frame, taking into account the name of the rocket, file it
1096 * has been saved to (if any) and saved status.
1098 private void setTitle() {
1099 File file = document.getFile();
1100 boolean saved = document.isSaved();
1103 title = rocket.getName();
1105 title = title + " ("+file.getName()+")";
1108 title = "*" + title;
1116 * Find a currently open BasicFrame containing the specified rocket. This method
1117 * can be used to map a Rocket to a BasicFrame from GUI methods.
1119 * @param rocket the Rocket.
1120 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1122 public static BasicFrame findFrame(Rocket rocket) {
1123 for (BasicFrame f: frames) {
1124 if (f.rocket == rocket)
1131 * Find a currently open document by the rocket object. This method can be used
1132 * to map a Rocket to OpenRocketDocument from GUI methods.
1134 * @param rocket the Rocket.
1135 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1137 public static OpenRocketDocument findDocument(Rocket rocket) {
1138 for (BasicFrame f: frames) {
1139 if (f.rocket == rocket)
1146 public static void main(final String[] args) {
1148 // Run the actual startup method in the EDT since it can use progress dialogs etc.
1150 SwingUtilities.invokeAndWait(new Runnable() {
1156 } catch (InterruptedException e) {
1157 e.printStackTrace();
1158 } catch (InvocationTargetException e) {
1159 e.printStackTrace();
1165 private static void runMain(String[] args) {
1167 // Start update info fetching
1168 final UpdateInfoRetriever updateInfo;
1169 if (Prefs.getCheckUpdates()) {
1170 updateInfo = new UpdateInfoRetriever();
1179 * Set the look-and-feel. On Linux, Motif/Metal is sometimes incorrectly used
1180 * which is butt-ugly, so if the system l&f is Motif/Metal, we search for a few
1181 * other alternatives.
1185 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
1187 // Check whether we have an ugly L&F
1188 LookAndFeel laf = UIManager.getLookAndFeel();
1190 laf.getName().matches(".*[mM][oO][tT][iI][fF].*") ||
1191 laf.getName().matches(".*[mM][eE][tT][aA][lL].*")) {
1193 // Search for better LAF
1194 UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();
1195 String lafNames[] = {
1199 ".*[aA][qQ][uU][aA].*",
1200 ".*[nN][iI][mM][bB].*"
1203 lf: for (String lafName: lafNames) {
1204 for (UIManager.LookAndFeelInfo l: info) {
1205 if (l.getName().matches(lafName)) {
1206 UIManager.setLookAndFeel(l.getClassName());
1212 } catch (Exception e) {
1213 System.err.println("Error setting LAF: " + e);
1216 // Set tooltip delay time. Tooltips are used in MotorChooserDialog extensively.
1217 ToolTipManager.sharedInstance().setDismissDelay(30000);
1220 // Setup the uncaught exception handler
1221 ExceptionHandler.registerExceptionHandler();
1225 Prefs.loadDefaultUnits();
1229 Databases.fakeMethod();
1231 // Starting action (load files or open new document)
1232 if (!handleCommandLine(args)) {
1237 // Check whether update info has been fetched or whether it needs more time
1238 checkUpdateStatus(updateInfo);
1242 private static void checkUpdateStatus(final UpdateInfoRetriever updateInfo) {
1243 if (updateInfo == null)
1247 if (!updateInfo.isRunning())
1250 final Timer timer = new Timer(delay, null);
1252 ActionListener listener = new ActionListener() {
1253 private int count = 5;
1255 public void actionPerformed(ActionEvent e) {
1256 if (!updateInfo.isRunning()) {
1259 String current = Prefs.getVersion();
1260 String last = Prefs.getString(Prefs.LAST_UPDATE, "");
1262 UpdateInfo info = updateInfo.getUpdateInfo();
1263 if (info != null && info.getLatestVersion() != null &&
1264 !current.equals(info.getLatestVersion()) &&
1265 !last.equals(info.getLatestVersion())) {
1267 UpdateInfoDialog infoDialog = new UpdateInfoDialog(info);
1268 infoDialog.setVisible(true);
1269 if (infoDialog.isReminderSelected()) {
1270 Prefs.putString(Prefs.LAST_UPDATE, "");
1272 Prefs.putString(Prefs.LAST_UPDATE, info.getLatestVersion());
1281 timer.addActionListener(listener);
1287 * Handles arguments passed from the command line. This may be used either
1288 * when starting the first instance of OpenRocket or later when OpenRocket is
1289 * executed again while running.
1291 * @param args the command-line arguments.
1292 * @return whether a new frame was opened or similar user desired action was
1293 * performed as a result.
1295 public static boolean handleCommandLine(String[] args) {
1297 // Check command-line for files
1298 boolean opened = false;
1299 for (String file: args) {
1300 if (open(new File(file), null)) {