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.GUIUtil;
91 import net.sf.openrocket.util.Icons;
92 import net.sf.openrocket.util.OpenFileWorker;
93 import net.sf.openrocket.util.Prefs;
94 import net.sf.openrocket.util.SaveFileWorker;
95 import net.sf.openrocket.util.TestRockets;
97 public class BasicFrame extends JFrame {
98 private static final long serialVersionUID = 1L;
101 * The RocketLoader instance used for loading all rocket designs.
103 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
105 private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
109 * File filter for filtering only rocket designs.
111 private static final FileFilter ROCKET_DESIGN_FILTER = new FileFilter() {
113 public String getDescription() {
114 return "OpenRocket designs (*.ork)";
117 public boolean accept(File f) {
120 String name = f.getName().toLowerCase();
121 return name.endsWith(".ork") || name.endsWith(".ork.gz");
127 public static final int COMPONENT_TAB = 0;
128 public static final int SIMULATION_TAB = 1;
132 * List of currently open frames. When the list goes empty
133 * it is time to exit the application.
135 private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
142 * Whether "New" and "Open" should replace this frame.
143 * Should be set to false on the first rocket modification.
145 private boolean replaceable = false;
149 private final OpenRocketDocument document;
150 private final Rocket rocket;
152 private JTabbedPane tabbedPane;
153 private RocketPanel rocketpanel;
154 private ComponentTree tree = null;
156 private final DocumentSelectionModel selectionModel;
157 private final TreeSelectionModel componentSelectionModel;
158 private final ListSelectionModel simulationSelectionModel;
160 /** Actions available for rocket modifications */
161 private final RocketActions actions;
166 * Sole constructor. Creates a new frame based on the supplied document
167 * and adds it to the current frames list.
169 * @param document the document to show.
171 public BasicFrame(OpenRocketDocument document) {
173 this.document = document;
174 this.rocket = document.getRocket();
175 this.rocket.getDefaultConfiguration().setAllStages();
178 // Set replaceable flag to false at first modification
179 rocket.addComponentChangeListener(new ComponentChangeListener() {
180 public void componentChanged(ComponentChangeEvent e) {
182 BasicFrame.this.rocket.removeComponentChangeListener(this);
187 // Create the component tree selection model that will be used
188 componentSelectionModel = new DefaultTreeSelectionModel();
189 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
191 // Obtain the simulation selection model that will be used
192 SimulationPanel simulationPanel = new SimulationPanel(document);
193 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
195 // Combine into a DocumentSelectionModel
196 selectionModel = new DocumentSelectionModel(document);
197 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
198 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
201 actions = new RocketActions(document, selectionModel, this);
204 // The main vertical split pane
205 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
206 vertical.setResizeWeight(0.5);
210 // The top tabbed pane
211 tabbedPane = new JTabbedPane();
212 tabbedPane.addTab("Rocket design", null, designTab());
213 tabbedPane.addTab("Flight simulations", null, simulationPanel);
215 vertical.setTopComponent(tabbedPane);
219 // Bottom segment, rocket figure
221 rocketpanel = new RocketPanel(document);
222 vertical.setBottomComponent(rocketpanel);
224 rocketpanel.setSelectionModel(tree.getSelectionModel());
230 rocket.addComponentChangeListener(new ComponentChangeListener() {
231 public void componentChanged(ComponentChangeEvent e) {
239 Dimension size = Prefs.getWindowSize(this.getClass());
241 size = Toolkit.getDefaultToolkit().getScreenSize();
242 size.width = size.width*9/10;
243 size.height = size.height*9/10;
246 this.addComponentListener(new ComponentAdapter() {
248 public void componentResized(ComponentEvent e) {
249 Prefs.setWindowSize(BasicFrame.this.getClass(), BasicFrame.this.getSize());
252 this.setLocationByPlatform(true);
254 GUIUtil.setWindowIcons(this);
257 vertical.setDividerLocation(0.4);
258 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
259 addWindowListener(new WindowAdapter() {
261 public void windowClosing(WindowEvent e) {
270 * Construct the "Rocket design" tab. This contains a horizontal split pane
271 * with the left component the design tree and the right component buttons
272 * for adding components.
274 private JComponent designTab() {
275 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true);
276 horizontal.setResizeWeight(0.5);
279 // Upper-left segment, component tree
281 JPanel panel = new JPanel(new MigLayout("fill, flowy","","[grow]"));
283 tree = new ComponentTree(rocket);
284 tree.setSelectionModel(componentSelectionModel);
286 // Remove JTree key events that interfere with menu accelerators
287 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
288 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
289 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
290 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
291 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
292 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
293 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
294 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
298 // Double-click opens config dialog
299 MouseListener ml = new MouseAdapter() {
301 public void mousePressed(MouseEvent e) {
302 int selRow = tree.getRowForLocation(e.getX(), e.getY());
303 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
305 if((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
307 RocketComponent c = (RocketComponent)selPath.getLastPathComponent();
308 ComponentConfigDialog.showDialog(BasicFrame.this,
309 BasicFrame.this.document, c);
314 tree.addMouseListener(ml);
316 // Update dialog when selection is changed
317 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
318 public void valueChanged(TreeSelectionEvent e) {
319 // Scroll tree to the selected item
320 TreePath path = componentSelectionModel.getSelectionPath();
323 tree.scrollPathToVisible(path);
325 if (!ComponentConfigDialog.isDialogVisible())
327 RocketComponent c = (RocketComponent)path.getLastPathComponent();
328 ComponentConfigDialog.showDialog(BasicFrame.this,
329 BasicFrame.this.document, c);
333 // Place tree inside scroll pane
334 JScrollPane scroll = new JScrollPane(tree);
335 panel.add(scroll,"spany, grow, wrap");
339 JButton button = new JButton(actions.getMoveUpAction());
340 panel.add(button,"sizegroup buttons, aligny 65%");
342 button = new JButton(actions.getMoveDownAction());
343 panel.add(button,"sizegroup buttons, aligny 0%");
345 button = new JButton(actions.getEditAction());
346 panel.add(button, "sizegroup buttons");
348 button = new JButton(actions.getNewStageAction());
349 panel.add(button,"sizegroup buttons");
351 button = new JButton(actions.getDeleteAction());
352 button.setIcon(null);
353 button.setMnemonic(0);
354 panel.add(button,"sizegroup buttons");
356 horizontal.setLeftComponent(panel);
359 // Upper-right segment, component addition buttons
361 panel = new JPanel(new MigLayout("fill, insets 0","[0::]"));
363 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
364 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
365 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
366 scroll.getViewport()));
367 scroll.setBorder(null);
368 scroll.setViewportBorder(null);
370 TitledBorder border = new TitledBorder("Add new component");
371 border.setTitleFont(border.getTitleFont().deriveFont(Font.BOLD));
372 scroll.setBorder(border);
374 panel.add(scroll,"grow");
376 horizontal.setRightComponent(panel);
384 * Creates the menu for the window.
386 private void createMenu() {
387 JMenuBar menubar = new JMenuBar();
392 menu = new JMenu("File");
393 menu.setMnemonic(KeyEvent.VK_F);
394 menu.getAccessibleContext().setAccessibleDescription("File-handling related tasks");
397 item = new JMenuItem("New",KeyEvent.VK_N);
398 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
399 item.setMnemonic(KeyEvent.VK_N);
400 item.getAccessibleContext().setAccessibleDescription("Create a new rocket design");
401 item.setIcon(Icons.FILE_NEW);
402 item.addActionListener(new ActionListener() {
403 public void actionPerformed(ActionEvent e) {
411 item = new JMenuItem("Open...",KeyEvent.VK_O);
412 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
413 item.getAccessibleContext().setAccessibleDescription("Open a rocket design");
414 item.setIcon(Icons.FILE_OPEN);
415 item.addActionListener(new ActionListener() {
416 public void actionPerformed(ActionEvent e) {
422 item = new JMenuItem("Open example...");
423 item.getAccessibleContext().setAccessibleDescription("Open an example rocket design");
424 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
425 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
426 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
427 item.addActionListener(new ActionListener() {
428 public void actionPerformed(ActionEvent e) {
429 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
432 open(u, BasicFrame.this);
441 item = new JMenuItem("Save",KeyEvent.VK_S);
442 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
443 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design");
444 item.setIcon(Icons.FILE_SAVE);
445 item.addActionListener(new ActionListener() {
446 public void actionPerformed(ActionEvent e) {
452 item = new JMenuItem("Save as...",KeyEvent.VK_A);
453 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
454 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
455 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design "+
457 item.setIcon(Icons.FILE_SAVE_AS);
458 item.addActionListener(new ActionListener() {
459 public void actionPerformed(ActionEvent e) {
465 // menu.addSeparator();
466 menu.add(new JSeparator());
468 item = new JMenuItem("Close",KeyEvent.VK_C);
469 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
470 item.getAccessibleContext().setAccessibleDescription("Close the current rocket design");
471 item.setIcon(Icons.FILE_CLOSE);
472 item.addActionListener(new ActionListener() {
473 public void actionPerformed(ActionEvent e) {
481 item = new JMenuItem("Quit",KeyEvent.VK_Q);
482 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
483 item.getAccessibleContext().setAccessibleDescription("Quit the program");
484 item.setIcon(Icons.FILE_QUIT);
485 item.addActionListener(new ActionListener() {
486 public void actionPerformed(ActionEvent e) {
495 menu = new JMenu("Edit");
496 menu.setMnemonic(KeyEvent.VK_E);
497 menu.getAccessibleContext().setAccessibleDescription("Rocket editing");
501 Action action = document.getUndoAction();
502 item = new JMenuItem(action);
503 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
504 item.setMnemonic(KeyEvent.VK_U);
505 item.getAccessibleContext().setAccessibleDescription("Undo the previous operation");
509 action = document.getRedoAction();
510 item = new JMenuItem(action);
511 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
512 item.setMnemonic(KeyEvent.VK_R);
513 item.getAccessibleContext().setAccessibleDescription("Redo the previously undone " +
520 item = new JMenuItem(actions.getCutAction());
523 item = new JMenuItem(actions.getCopyAction());
526 item = new JMenuItem(actions.getPasteAction());
529 item = new JMenuItem(actions.getDeleteAction());
534 item = new JMenuItem("Preferences");
535 item.setIcon(Icons.PREFERENCES);
536 item.getAccessibleContext().setAccessibleDescription("Setup the application "+
538 item.addActionListener(new ActionListener() {
539 public void actionPerformed(ActionEvent e) {
540 PreferencesDialog.showPreferences();
549 menu = new JMenu("Analyze");
550 menu.setMnemonic(KeyEvent.VK_A);
551 menu.getAccessibleContext().setAccessibleDescription("Analyzing the rocket");
554 item = new JMenuItem("Component analysis",KeyEvent.VK_C);
555 item.getAccessibleContext().setAccessibleDescription("Analyze the rocket components " +
557 item.addActionListener(new ActionListener() {
558 public void actionPerformed(ActionEvent e) {
559 ComponentAnalysisDialog.showDialog(rocketpanel);
566 // (shown if openrocket.debug.menu is defined)
567 if (System.getProperty("openrocket.debug.menu") != null) {
568 menubar.add(makeDebugMenu());
575 menu = new JMenu("Help");
576 menu.setMnemonic(KeyEvent.VK_H);
577 menu.getAccessibleContext().setAccessibleDescription("Information about OpenRocket");
582 item = new JMenuItem("License",KeyEvent.VK_L);
583 item.getAccessibleContext().setAccessibleDescription("OpenRocket license information");
584 item.addActionListener(new ActionListener() {
585 public void actionPerformed(ActionEvent e) {
586 new LicenseDialog(BasicFrame.this).setVisible(true);
591 item = new JMenuItem("Bug report",KeyEvent.VK_B);
592 item.getAccessibleContext().setAccessibleDescription("Information about reporting " +
593 "bugs in OpenRocket");
594 item.addActionListener(new ActionListener() {
595 public void actionPerformed(ActionEvent e) {
596 // new BugDialog(BasicFrame.this).setVisible(true);
597 BugReportDialog.showBugReportDialog(BasicFrame.this);
602 item = new JMenuItem("About",KeyEvent.VK_A);
603 item.getAccessibleContext().setAccessibleDescription("About OpenRocket");
604 item.addActionListener(new ActionListener() {
605 public void actionPerformed(ActionEvent e) {
606 new AboutDialog(BasicFrame.this).setVisible(true);
612 this.setJMenuBar(menubar);
616 private JMenu makeDebugMenu() {
621 menu = new JMenu("Debug");
622 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
624 item = new JMenuItem("What is this menu?");
625 item.addActionListener(new ActionListener() {
626 public void actionPerformed(ActionEvent e) {
627 JOptionPane.showMessageDialog(BasicFrame.this,
629 "The 'Debug' menu includes actions for testing and debugging " +
631 "The menu is made visible by defining the system property " +
632 "'openrocket.debug.menu' when starting OpenRocket.",
633 "It should not be visible by default." },
634 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
641 item = new JMenuItem("Create test rocket");
642 item.addActionListener(new ActionListener() {
644 public void actionPerformed(ActionEvent e) {
645 JTextField field = new JTextField();
646 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
647 "Input text key to generate random rocket:",
649 }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION,
650 JOptionPane.QUESTION_MESSAGE, null, new Object[] {
656 r = new TestRockets(null).makeTestRocket();
657 } else if (sel == 1) {
658 r = new TestRockets(field.getText()).makeTestRocket();
663 OpenRocketDocument doc = new OpenRocketDocument(r);
665 BasicFrame frame = new BasicFrame(doc);
666 frame.setVisible(true);
673 item = new JMenuItem("Exception here");
674 item.addActionListener(new ActionListener() {
675 public void actionPerformed(ActionEvent e) {
676 throw new RuntimeException("Testing exception from menu action listener");
681 item = new JMenuItem("Exception from EDT");
682 item.addActionListener(new ActionListener() {
683 public void actionPerformed(ActionEvent e) {
684 SwingUtilities.invokeLater(new Runnable() {
687 throw new RuntimeException("Testing exception from " +
688 "later invoked EDT thread");
695 item = new JMenuItem("Exception from other thread");
696 item.addActionListener(new ActionListener() {
697 public void actionPerformed(ActionEvent e) {
701 throw new RuntimeException("Testing exception from " +
702 "newly created thread");
717 * Select the tab on the main pane.
719 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
721 public void selectTab(int tab) {
722 tabbedPane.setSelectedIndex(tab);
727 private void openAction() {
728 JFileChooser chooser = new JFileChooser();
729 chooser.setFileFilter(ROCKET_DESIGN_FILTER);
730 chooser.setMultiSelectionEnabled(true);
731 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
732 if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
735 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
737 File[] files = chooser.getSelectedFiles();
739 for (File file: files) {
740 System.out.println("Opening file: " + file);
741 if (open(file, this)) {
743 // Close previous window if replacing
744 if (replaceable && document.isSaved()) {
755 private static boolean open(URL url, BasicFrame parent) {
756 String filename = null;
758 // Try using URI.getPath();
760 URI uri = url.toURI();
761 filename = uri.getPath();
762 } catch (URISyntaxException ignore) { }
764 // Try URL-decoding the URL
765 if (filename == null) {
767 filename = URLDecoder.decode(url.toString(), "UTF-8");
768 } catch (UnsupportedEncodingException ignore) { }
772 if (filename == null) {
776 // Remove path from filename
777 if (filename.lastIndexOf('/') >= 0) {
778 filename = filename.substring(filename.lastIndexOf('/')+1);
782 InputStream is = url.openStream();
783 if (open(is, filename, parent)) {
784 // Close previous window if replacing
785 if (parent.replaceable && parent.document.isSaved()) {
786 parent.closeAction();
787 parent.replaceable = false;
790 } catch (IOException e) {
791 JOptionPane.showMessageDialog(parent,
792 "An error occurred while opening the file " + filename,
793 "Error loading file", JOptionPane.ERROR_MESSAGE);
801 * Open the specified file from an InputStream in a new design frame. If an error
802 * occurs, an error dialog is shown and <code>false</code> is returned.
804 * @param stream the stream to load from.
805 * @param filename the file name to display in dialogs (not set to the document).
806 * @param parent the parent component for which a progress dialog is opened.
807 * @return whether the file was successfully loaded and opened.
809 private static boolean open(InputStream stream, String filename, Window parent) {
810 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
811 return open(worker, filename, null, parent);
816 * Open the specified file in a new design frame. If an error occurs, an error
817 * dialog is shown and <code>false</code> is returned.
819 * @param file the file to open.
820 * @param parent the parent component for which a progress dialog is opened.
821 * @return whether the file was successfully loaded and opened.
823 private static boolean open(File file, Window parent) {
824 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
825 return open(worker, file.getName(), file, parent);
830 * Open the specified file using the provided worker.
832 * @param worker the OpenFileWorker that loads the file.
833 * @param filename the file name to display in dialogs.
834 * @param file the File to set the document to (may be null).
838 private static boolean open(OpenFileWorker worker, String filename, File file,
841 // Open the file in a Swing worker thread
842 if (!SwingWorkerDialog.runWorker(parent, "Opening file",
843 "Reading " + filename + "...", worker)) {
845 // User cancelled the operation
850 // Handle the document
851 OpenRocketDocument doc = null;
856 } catch (ExecutionException e) {
858 Throwable cause = e.getCause();
860 if (cause instanceof FileNotFoundException) {
862 JOptionPane.showMessageDialog(parent,
863 "File not found: " + filename,
864 "Error opening file", JOptionPane.ERROR_MESSAGE);
867 } else if (cause instanceof RocketLoadException) {
869 JOptionPane.showMessageDialog(parent,
870 "Unable to open file '" + filename +"': "
871 + cause.getMessage(),
872 "Error opening file", JOptionPane.ERROR_MESSAGE);
877 throw new RuntimeException("Unknown error when opening file", e);
881 } catch (InterruptedException e) {
882 throw new RuntimeException("EDT was interrupted", e);
886 throw new RuntimeException("BUG: Document loader returned null");
891 WarningSet warnings = worker.getRocketLoader().getWarnings();
892 if (!warnings.isEmpty()) {
893 WarningDialog.showWarnings(parent,
895 "The following problems were encountered while opening " + filename + ".",
896 "Some design features may not have been loaded correctly."
898 "Warnings while opening file", warnings);
902 // Set document state
907 BasicFrame frame = new BasicFrame(doc);
908 frame.setVisible(true);
921 private boolean saveAction() {
922 File file = document.getFile();
924 return saveAsAction();
931 private boolean saveAsAction() {
933 while (file == null) {
934 StorageOptionChooser storageChooser =
935 new StorageOptionChooser(document, document.getDefaultStorageOptions());
936 JFileChooser chooser = new JFileChooser();
937 chooser.setFileFilter(ROCKET_DESIGN_FILTER);
938 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
939 chooser.setAccessory(storageChooser);
940 if (document.getFile() != null)
941 chooser.setSelectedFile(document.getFile());
943 if (chooser.showSaveDialog(BasicFrame.this) != JFileChooser.APPROVE_OPTION)
946 file = chooser.getSelectedFile();
950 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
951 storageChooser.storeOptions(document.getDefaultStorageOptions());
953 if (file.getName().indexOf('.') < 0) {
954 String name = file.getAbsolutePath();
955 name = name + ".ork";
956 file = new File(name);
960 int result = JOptionPane.showConfirmDialog(this,
961 "File '"+file.getName()+"' exists. Do you want to overwrite it?",
962 "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
963 if (result != JOptionPane.YES_OPTION)
972 private boolean saveAs(File file) {
973 System.out.println("Saving to file: " + file.getName());
974 boolean saved = false;
976 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
977 // User cancelled the dialog
982 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
984 if (!SwingWorkerDialog.runWorker(this, "Saving file",
985 "Writing " + file.getName() + "...", worker)) {
987 // User cancelled the save
994 document.setFile(file);
995 document.setSaved(true);
998 } catch (ExecutionException e) {
999 Throwable cause = e.getCause();
1001 if (cause instanceof IOException) {
1002 JOptionPane.showMessageDialog(this, new String[] {
1003 "An I/O error occurred while saving:",
1004 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1007 throw new RuntimeException("Unknown error when saving file", e);
1010 } catch (InterruptedException e) {
1011 throw new RuntimeException("EDT was interrupted", e);
1018 private boolean closeAction() {
1019 if (!document.isSaved()) {
1020 ComponentConfigDialog.hideDialog();
1021 int result = JOptionPane.showConfirmDialog(this,
1022 "Design '"+rocket.getName()+"' has not been saved. " +
1023 "Do you want to save it?",
1024 "Design not saved", JOptionPane.YES_NO_CANCEL_OPTION,
1025 JOptionPane.QUESTION_MESSAGE);
1026 if (result == JOptionPane.YES_OPTION) {
1029 return false; // If save was interrupted
1030 } else if (result == JOptionPane.NO_OPTION) {
1031 // Don't save: No-op
1038 // Rocket has been saved or discarded
1041 // TODO: LOW: Close only dialogs that have this frame as their parent
1042 ComponentConfigDialog.hideDialog();
1043 ComponentAnalysisDialog.hideDialog();
1045 frames.remove(this);
1046 if (frames.isEmpty())
1053 * Closes this frame if it is replaceable.
1055 public void closeIfReplaceable() {
1056 if (this.replaceable && document.isSaved()) {
1062 * Open a new design window with a basic rocket+stage.
1064 public static void newAction() {
1065 Rocket rocket = new Rocket();
1066 Stage stage = new Stage();
1067 stage.setName("Sustainer");
1068 rocket.addChild(stage);
1069 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1072 BasicFrame frame = new BasicFrame(doc);
1073 frame.replaceable = true;
1074 frame.setVisible(true);
1075 ComponentConfigDialog.showDialog(frame, doc, rocket);
1079 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
1081 public static void quitAction() {
1082 for (int i=frames.size()-1; i>=0; i--) {
1083 if (!frames.get(i).closeAction()) {
1088 // Should not be reached, but just in case
1094 * Set the title of the frame, taking into account the name of the rocket, file it
1095 * has been saved to (if any) and saved status.
1097 private void setTitle() {
1098 File file = document.getFile();
1099 boolean saved = document.isSaved();
1102 title = rocket.getName();
1104 title = title + " ("+file.getName()+")";
1107 title = "*" + title;
1115 * Find a currently open BasicFrame containing the specified rocket. This method
1116 * can be used to map a Rocket to a BasicFrame from GUI methods.
1118 * @param rocket the Rocket.
1119 * @return the corresponding BasicFrame, or <code>null</code> if none found.
1121 public static BasicFrame findFrame(Rocket rocket) {
1122 for (BasicFrame f: frames) {
1123 if (f.rocket == rocket)
1130 * Find a currently open document by the rocket object. This method can be used
1131 * to map a Rocket to OpenRocketDocument from GUI methods.
1133 * @param rocket the Rocket.
1134 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1136 public static OpenRocketDocument findDocument(Rocket rocket) {
1137 for (BasicFrame f: frames) {
1138 if (f.rocket == rocket)
1145 public static void main(final String[] args) {
1147 // Run the actual startup method in the EDT since it can use progress dialogs etc.
1149 SwingUtilities.invokeAndWait(new Runnable() {
1155 } catch (InterruptedException e) {
1156 e.printStackTrace();
1157 } catch (InvocationTargetException e) {
1158 e.printStackTrace();
1164 private static void runMain(String[] args) {
1166 // Start update info fetching
1167 final UpdateInfoRetriever updateInfo;
1168 if (Prefs.getCheckUpdates()) {
1169 updateInfo = new UpdateInfoRetriever();
1178 * Set the look-and-feel. On Linux, Motif/Metal is sometimes incorrectly used
1179 * which is butt-ugly, so if the system l&f is Motif/Metal, we search for a few
1180 * other alternatives.
1184 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
1186 // Check whether we have an ugly L&F
1187 LookAndFeel laf = UIManager.getLookAndFeel();
1189 laf.getName().matches(".*[mM][oO][tT][iI][fF].*") ||
1190 laf.getName().matches(".*[mM][eE][tT][aA][lL].*")) {
1192 // Search for better LAF
1193 UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();
1194 String lafNames[] = {
1198 ".*[aA][qQ][uU][aA].*",
1199 ".*[nN][iI][mM][bB].*"
1202 lf: for (String lafName: lafNames) {
1203 for (UIManager.LookAndFeelInfo l: info) {
1204 if (l.getName().matches(lafName)) {
1205 UIManager.setLookAndFeel(l.getClassName());
1211 } catch (Exception e) {
1212 System.err.println("Error setting LAF: " + e);
1215 // Set tooltip delay time. Tooltips are used in MotorChooserDialog extensively.
1216 ToolTipManager.sharedInstance().setDismissDelay(30000);
1219 // Setup the uncaught exception handler
1220 ExceptionHandler.registerExceptionHandler();
1224 Prefs.loadDefaultUnits();
1228 Databases.fakeMethod();
1230 // Starting action (load files or open new document)
1231 if (!handleCommandLine(args)) {
1236 // Check whether update info has been fetched or whether it needs more time
1237 checkUpdateStatus(updateInfo);
1241 private static void checkUpdateStatus(final UpdateInfoRetriever updateInfo) {
1242 if (updateInfo == null)
1246 if (!updateInfo.isRunning())
1249 final Timer timer = new Timer(delay, null);
1251 ActionListener listener = new ActionListener() {
1252 private int count = 5;
1254 public void actionPerformed(ActionEvent e) {
1255 if (!updateInfo.isRunning()) {
1258 String current = Prefs.getVersion();
1259 String last = Prefs.getString(Prefs.LAST_UPDATE, "");
1261 UpdateInfo info = updateInfo.getUpdateInfo();
1262 if (info != null && info.getLatestVersion() != null &&
1263 !current.equals(info.getLatestVersion()) &&
1264 !last.equals(info.getLatestVersion())) {
1265 Prefs.putString(Prefs.LAST_UPDATE, info.getLatestVersion());
1266 new UpdateInfoDialog(info).setVisible(true);
1274 timer.addActionListener(listener);
1280 * Handles arguments passed from the command line. This may be used either
1281 * when starting the first instance of OpenRocket or later when OpenRocket is
1282 * executed again while running.
1284 * @param args the command-line arguments.
1285 * @return whether a new frame was opened or similar user desired action was
1286 * performed as a result.
1288 public static boolean handleCommandLine(String[] args) {
1290 // Check command-line for files
1291 boolean opened = false;
1292 for (String file: args) {
1293 if (open(new File(file), null)) {