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.Iterator;
29 import java.util.concurrent.ExecutionException;
31 import javax.swing.Action;
32 import javax.swing.InputMap;
33 import javax.swing.JButton;
34 import javax.swing.JComponent;
35 import javax.swing.JFileChooser;
36 import javax.swing.JFrame;
37 import javax.swing.JMenu;
38 import javax.swing.JMenuBar;
39 import javax.swing.JMenuItem;
40 import javax.swing.JOptionPane;
41 import javax.swing.JPanel;
42 import javax.swing.JScrollPane;
43 import javax.swing.JSeparator;
44 import javax.swing.JSplitPane;
45 import javax.swing.JTabbedPane;
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.Warning;
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.BugDialog;
72 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
73 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
74 import net.sf.openrocket.gui.dialogs.LicenseDialog;
75 import net.sf.openrocket.gui.dialogs.PreferencesDialog;
76 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
77 import net.sf.openrocket.gui.scalefigure.RocketPanel;
78 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
79 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
80 import net.sf.openrocket.rocketcomponent.Rocket;
81 import net.sf.openrocket.rocketcomponent.RocketComponent;
82 import net.sf.openrocket.rocketcomponent.Stage;
83 import net.sf.openrocket.util.Icons;
84 import net.sf.openrocket.util.OpenFileWorker;
85 import net.sf.openrocket.util.Prefs;
86 import net.sf.openrocket.util.SaveFileWorker;
88 public class BasicFrame extends JFrame {
89 private static final long serialVersionUID = 1L;
92 * The RocketLoader instance used for loading all rocket designs.
94 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
96 private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
100 * File filter for filtering only rocket designs.
102 private static final FileFilter ROCKET_DESIGN_FILTER = new FileFilter() {
104 public String getDescription() {
105 return "OpenRocket designs (*.ork)";
108 public boolean accept(File f) {
111 String name = f.getName().toLowerCase();
112 return name.endsWith(".ork") || name.endsWith(".ork.gz");
118 public static final int COMPONENT_TAB = 0;
119 public static final int SIMULATION_TAB = 1;
123 * List of currently open frames. When the list goes empty
124 * it is time to exit the application.
126 private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
133 * Whether "New" and "Open" should replace this frame.
134 * Should be set to false on the first rocket modification.
136 private boolean replaceable = false;
140 private final OpenRocketDocument document;
141 private final Rocket rocket;
143 private JTabbedPane tabbedPane;
144 private RocketPanel rocketpanel;
145 private ComponentTree tree = null;
147 private final DocumentSelectionModel selectionModel;
148 private final TreeSelectionModel componentSelectionModel;
149 private final ListSelectionModel simulationSelectionModel;
151 /** Actions available for rocket modifications */
152 private final RocketActions actions;
157 * Sole constructor. Creates a new frame based on the supplied document
158 * and adds it to the current frames list.
160 * @param document the document to show.
162 public BasicFrame(OpenRocketDocument document) {
164 this.document = document;
165 this.rocket = document.getRocket();
166 this.rocket.getDefaultConfiguration().setAllStages();
169 // Set replaceable flag to false at first modification
170 rocket.addComponentChangeListener(new ComponentChangeListener() {
171 public void componentChanged(ComponentChangeEvent e) {
173 BasicFrame.this.rocket.removeComponentChangeListener(this);
178 // Create the component tree selection model that will be used
179 componentSelectionModel = new DefaultTreeSelectionModel();
180 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
182 // Obtain the simulation selection model that will be used
183 SimulationPanel simulationPanel = new SimulationPanel(document);
184 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
186 // Combine into a DocumentSelectionModel
187 selectionModel = new DocumentSelectionModel(document);
188 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
189 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
192 actions = new RocketActions(document, selectionModel, this);
195 // The main vertical split pane
196 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
197 vertical.setResizeWeight(0.5);
201 // The top tabbed pane
202 tabbedPane = new JTabbedPane();
203 tabbedPane.addTab("Rocket design", null, designTab());
204 tabbedPane.addTab("Flight simulations", null, simulationPanel);
206 vertical.setTopComponent(tabbedPane);
210 // Bottom segment, rocket figure
212 rocketpanel = new RocketPanel(document);
213 vertical.setBottomComponent(rocketpanel);
215 rocketpanel.setSelectionModel(tree.getSelectionModel());
221 rocket.addComponentChangeListener(new ComponentChangeListener() {
222 public void componentChanged(ComponentChangeEvent e) {
230 Dimension size = Prefs.getWindowSize(this.getClass());
232 size = Toolkit.getDefaultToolkit().getScreenSize();
233 size.width = size.width*9/10;
234 size.height = size.height*9/10;
237 this.addComponentListener(new ComponentAdapter() {
239 public void componentResized(ComponentEvent e) {
240 Prefs.setWindowSize(BasicFrame.this.getClass(), BasicFrame.this.getSize());
243 this.setLocationByPlatform(true);
246 vertical.setDividerLocation(0.4);
247 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
248 addWindowListener(new WindowAdapter() {
250 public void windowClosing(WindowEvent e) {
259 * Construct the "Rocket design" tab. This contains a horizontal split pane
260 * with the left component the design tree and the right component buttons
261 * for adding components.
263 private JComponent designTab() {
264 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true);
265 horizontal.setResizeWeight(0.5);
268 // Upper-left segment, component tree
270 JPanel panel = new JPanel(new MigLayout("fill, flowy","","[grow]"));
272 tree = new ComponentTree(rocket);
273 tree.setSelectionModel(componentSelectionModel);
275 // Remove JTree key events that interfere with menu accelerators
276 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
277 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
278 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
279 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
280 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
281 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
282 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
283 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
287 // Double-click opens config dialog
288 MouseListener ml = new MouseAdapter() {
290 public void mousePressed(MouseEvent e) {
291 int selRow = tree.getRowForLocation(e.getX(), e.getY());
292 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
294 if(e.getClickCount() == 2) {
296 RocketComponent c = (RocketComponent)selPath.getLastPathComponent();
297 ComponentConfigDialog.showDialog(BasicFrame.this,
298 BasicFrame.this.document, c);
303 tree.addMouseListener(ml);
305 // Update dialog when selection is changed
306 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
307 public void valueChanged(TreeSelectionEvent e) {
308 // Scroll tree to the selected item
309 TreePath path = componentSelectionModel.getSelectionPath();
312 tree.scrollPathToVisible(path);
314 if (!ComponentConfigDialog.isDialogVisible())
316 RocketComponent c = (RocketComponent)path.getLastPathComponent();
317 ComponentConfigDialog.showDialog(BasicFrame.this,
318 BasicFrame.this.document, c);
322 // Place tree inside scroll pane
323 JScrollPane scroll = new JScrollPane(tree);
324 panel.add(scroll,"spany, grow, wrap");
328 JButton button = new JButton(actions.getMoveUpAction());
329 panel.add(button,"sizegroup buttons, aligny 65%");
331 button = new JButton(actions.getMoveDownAction());
332 panel.add(button,"sizegroup buttons, aligny 0%");
334 button = new JButton(actions.getEditAction());
335 panel.add(button, "sizegroup buttons");
337 button = new JButton(actions.getNewStageAction());
338 panel.add(button,"sizegroup buttons");
340 button = new JButton(actions.getDeleteAction());
341 button.setIcon(null);
342 button.setMnemonic(0);
343 panel.add(button,"sizegroup buttons");
345 horizontal.setLeftComponent(panel);
348 // Upper-right segment, component addition buttons
350 panel = new JPanel(new MigLayout("fill, insets 0","[0::]"));
352 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
353 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
354 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
355 scroll.getViewport()));
356 scroll.setBorder(null);
357 scroll.setViewportBorder(null);
359 TitledBorder border = new TitledBorder("Add new component");
360 border.setTitleFont(border.getTitleFont().deriveFont(Font.BOLD));
361 scroll.setBorder(border);
363 panel.add(scroll,"grow");
365 horizontal.setRightComponent(panel);
373 * Creates the menu for the window.
375 private void createMenu() {
376 JMenuBar menubar = new JMenuBar();
381 menu = new JMenu("File");
382 menu.setMnemonic(KeyEvent.VK_F);
383 menu.getAccessibleContext().setAccessibleDescription("File-handling related tasks");
386 item = new JMenuItem("New",KeyEvent.VK_N);
387 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
388 item.setMnemonic(KeyEvent.VK_N);
389 item.getAccessibleContext().setAccessibleDescription("Create a new rocket design");
390 item.setIcon(Icons.FILE_NEW);
391 item.addActionListener(new ActionListener() {
392 public void actionPerformed(ActionEvent e) {
400 item = new JMenuItem("Open...",KeyEvent.VK_O);
401 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
402 item.getAccessibleContext().setAccessibleDescription("Open a rocket design");
403 item.setIcon(Icons.FILE_OPEN);
404 item.addActionListener(new ActionListener() {
405 public void actionPerformed(ActionEvent e) {
411 item = new JMenuItem("Open example...");
412 item.getAccessibleContext().setAccessibleDescription("Open an example rocket design");
413 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
414 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
415 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
416 item.addActionListener(new ActionListener() {
417 public void actionPerformed(ActionEvent e) {
418 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
421 open(u, BasicFrame.this);
430 item = new JMenuItem("Save",KeyEvent.VK_S);
431 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
432 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design");
433 item.setIcon(Icons.FILE_SAVE);
434 item.addActionListener(new ActionListener() {
435 public void actionPerformed(ActionEvent e) {
441 item = new JMenuItem("Save as...",KeyEvent.VK_A);
442 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
443 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
444 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design "+
446 item.setIcon(Icons.FILE_SAVE_AS);
447 item.addActionListener(new ActionListener() {
448 public void actionPerformed(ActionEvent e) {
454 // menu.addSeparator();
455 menu.add(new JSeparator());
457 item = new JMenuItem("Close",KeyEvent.VK_C);
458 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
459 item.getAccessibleContext().setAccessibleDescription("Close the current rocket design");
460 item.setIcon(Icons.FILE_CLOSE);
461 item.addActionListener(new ActionListener() {
462 public void actionPerformed(ActionEvent e) {
470 item = new JMenuItem("Quit",KeyEvent.VK_Q);
471 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
472 item.getAccessibleContext().setAccessibleDescription("Quit the program");
473 item.setIcon(Icons.FILE_QUIT);
474 item.addActionListener(new ActionListener() {
475 public void actionPerformed(ActionEvent e) {
484 menu = new JMenu("Edit");
485 menu.setMnemonic(KeyEvent.VK_E);
486 menu.getAccessibleContext().setAccessibleDescription("Rocket editing");
490 Action action = document.getUndoAction();
491 item = new JMenuItem(action);
492 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
493 item.setMnemonic(KeyEvent.VK_U);
494 item.getAccessibleContext().setAccessibleDescription("Undo the previous operation");
498 action = document.getRedoAction();
499 item = new JMenuItem(action);
500 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
501 item.setMnemonic(KeyEvent.VK_R);
502 item.getAccessibleContext().setAccessibleDescription("Redo the previously undone " +
509 item = new JMenuItem(actions.getCutAction());
512 item = new JMenuItem(actions.getCopyAction());
515 item = new JMenuItem(actions.getPasteAction());
518 item = new JMenuItem(actions.getDeleteAction());
523 item = new JMenuItem("Preferences");
524 item.setIcon(Icons.PREFERENCES);
525 item.getAccessibleContext().setAccessibleDescription("Setup the application "+
527 item.addActionListener(new ActionListener() {
528 public void actionPerformed(ActionEvent e) {
529 PreferencesDialog.showPreferences();
538 menu = new JMenu("Analyze");
539 menu.setMnemonic(KeyEvent.VK_A);
540 menu.getAccessibleContext().setAccessibleDescription("Analyzing the rocket");
543 item = new JMenuItem("Component analysis",KeyEvent.VK_C);
544 item.getAccessibleContext().setAccessibleDescription("Analyze the rocket components " +
546 item.addActionListener(new ActionListener() {
547 public void actionPerformed(ActionEvent e) {
548 ComponentAnalysisDialog.showDialog(rocketpanel);
557 menu = new JMenu("Help");
558 menu.setMnemonic(KeyEvent.VK_H);
559 menu.getAccessibleContext().setAccessibleDescription("Information about OpenRocket");
564 item = new JMenuItem("License",KeyEvent.VK_L);
565 item.getAccessibleContext().setAccessibleDescription("OpenRocket license information");
566 item.addActionListener(new ActionListener() {
567 public void actionPerformed(ActionEvent e) {
568 new LicenseDialog(BasicFrame.this).setVisible(true);
573 item = new JMenuItem("Bug report",KeyEvent.VK_B);
574 item.getAccessibleContext().setAccessibleDescription("Information about reporting " +
575 "bugs in OpenRocket");
576 item.addActionListener(new ActionListener() {
577 public void actionPerformed(ActionEvent e) {
578 new BugDialog(BasicFrame.this).setVisible(true);
583 item = new JMenuItem("About",KeyEvent.VK_A);
584 item.getAccessibleContext().setAccessibleDescription("About OpenRocket");
585 item.addActionListener(new ActionListener() {
586 public void actionPerformed(ActionEvent e) {
587 new AboutDialog(BasicFrame.this).setVisible(true);
593 this.setJMenuBar(menubar);
599 * Select the tab on the main pane.
601 * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
603 public void selectTab(int tab) {
604 tabbedPane.setSelectedIndex(tab);
609 private void openAction() {
610 JFileChooser chooser = new JFileChooser();
611 chooser.setFileFilter(ROCKET_DESIGN_FILTER);
612 chooser.setMultiSelectionEnabled(true);
613 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
614 if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
617 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
619 File[] files = chooser.getSelectedFiles();
621 for (File file: files) {
622 System.out.println("Opening file: " + file);
623 if (open(file, this)) {
625 // Close previous window if replacing
626 if (replaceable && document.isSaved()) {
637 private static boolean open(URL url, Window parent) {
638 String filename = null;
640 // Try using URI.getPath();
642 URI uri = url.toURI();
643 filename = uri.getPath();
644 } catch (URISyntaxException ignore) { }
646 // Try URL-decoding the URL
647 if (filename == null) {
649 filename = URLDecoder.decode(url.toString(), "UTF-8");
650 } catch (UnsupportedEncodingException ignore) { }
654 if (filename == null) {
658 // Remove path from filename
659 if (filename.lastIndexOf('/') >= 0) {
660 filename = filename.substring(filename.lastIndexOf('/')+1);
664 InputStream is = url.openStream();
665 open(is, filename, parent);
666 } catch (IOException e) {
667 JOptionPane.showMessageDialog(parent,
668 "An error occurred while opening the file " + filename,
669 "Error loading file", JOptionPane.ERROR_MESSAGE);
677 * Open the specified file from an InputStream in a new design frame. If an error
678 * occurs, an error dialog is shown and <code>false</code> is returned.
680 * @param stream the stream to load from.
681 * @param filename the file name to display in dialogs (not set to the document).
682 * @param parent the parent component for which a progress dialog is opened.
683 * @return whether the file was successfully loaded and opened.
685 private static boolean open(InputStream stream, String filename, Window parent) {
686 OpenFileWorker worker = new OpenFileWorker(stream);
687 return open(worker, filename, null, parent);
692 * Open the specified file in a new design frame. If an error occurs, an error
693 * dialog is shown and <code>false</code> is returned.
695 * @param file the file to open.
696 * @param parent the parent component for which a progress dialog is opened.
697 * @return whether the file was successfully loaded and opened.
699 private static boolean open(File file, Window parent) {
700 OpenFileWorker worker = new OpenFileWorker(file);
701 return open(worker, file.getName(), file, parent);
706 * Open the specified file using the provided worker.
708 * @param worker the OpenFileWorker that loads the file.
709 * @param filename the file name to display in dialogs.
710 * @param file the File to set the document to (may be null).
714 private static boolean open(OpenFileWorker worker, String filename, File file,
717 // Open the file in a Swing worker thread
718 if (!SwingWorkerDialog.runWorker(parent, "Opening file",
719 "Reading " + filename + "...", worker)) {
721 // User cancelled the operation
726 // Handle the document
727 OpenRocketDocument doc = null;
732 } catch (ExecutionException e) {
734 Throwable cause = e.getCause();
736 if (cause instanceof FileNotFoundException) {
738 JOptionPane.showMessageDialog(parent,
739 "File not found: " + filename,
740 "Error opening file", JOptionPane.ERROR_MESSAGE);
743 } else if (cause instanceof RocketLoadException) {
745 JOptionPane.showMessageDialog(parent,
746 "Unable to open file '" + filename +"': "
747 + cause.getMessage(),
748 "Error opening file", JOptionPane.ERROR_MESSAGE);
753 throw new RuntimeException("Unknown error when opening file", e);
757 } catch (InterruptedException e) {
758 throw new RuntimeException("EDT was interrupted", e);
762 throw new RuntimeException("BUG: Document loader returned null");
767 Iterator<Warning> warns = ROCKET_LOADER.getWarnings().iterator();
768 System.out.println("Warnings:");
769 while (warns.hasNext()) {
770 System.out.println(" "+warns.next());
771 // TODO: HIGH: dialog
774 // Set document state
779 BasicFrame frame = new BasicFrame(doc);
780 frame.setVisible(true);
793 private boolean saveAction() {
794 File file = document.getFile();
796 return saveAsAction();
803 private boolean saveAsAction() {
805 while (file == null) {
806 StorageOptionChooser storageChooser =
807 new StorageOptionChooser(document, document.getDefaultStorageOptions());
808 JFileChooser chooser = new JFileChooser();
809 chooser.setFileFilter(ROCKET_DESIGN_FILTER);
810 chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
811 chooser.setAccessory(storageChooser);
812 if (document.getFile() != null)
813 chooser.setSelectedFile(document.getFile());
815 if (chooser.showSaveDialog(BasicFrame.this) != JFileChooser.APPROVE_OPTION)
818 file = chooser.getSelectedFile();
822 Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
823 storageChooser.storeOptions(document.getDefaultStorageOptions());
825 if (file.getName().indexOf('.') < 0) {
826 String name = file.getAbsolutePath();
827 name = name + ".ork";
828 file = new File(name);
832 int result = JOptionPane.showConfirmDialog(this,
833 "File '"+file.getName()+"' exists. Do you want to overwrite it?",
834 "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
835 if (result != JOptionPane.YES_OPTION)
844 private boolean saveAs(File file) {
845 System.out.println("Saving to file: " + file.getName());
846 boolean saved = false;
848 if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
849 // User cancelled the dialog
854 SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
856 if (!SwingWorkerDialog.runWorker(this, "Saving file",
857 "Writing " + file.getName() + "...", worker)) {
859 // User cancelled the save
866 document.setFile(file);
867 document.setSaved(true);
870 } catch (ExecutionException e) {
871 Throwable cause = e.getCause();
873 if (cause instanceof IOException) {
874 JOptionPane.showMessageDialog(this, new String[] {
875 "An I/O error occurred while saving:",
876 e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
879 throw new RuntimeException("Unknown error when saving file", e);
882 } catch (InterruptedException e) {
883 throw new RuntimeException("EDT was interrupted", e);
890 private boolean closeAction() {
891 if (!document.isSaved()) {
892 ComponentConfigDialog.hideDialog();
893 int result = JOptionPane.showConfirmDialog(this,
894 "Design '"+rocket.getName()+"' has not been saved. " +
895 "Do you want to save it?",
896 "Design not saved", JOptionPane.YES_NO_CANCEL_OPTION,
897 JOptionPane.QUESTION_MESSAGE);
898 if (result == JOptionPane.YES_OPTION) {
901 return false; // If save was interrupted
902 } else if (result == JOptionPane.NO_OPTION) {
910 // Rocket has been saved or discarded
913 // TODO: LOW: Close only dialogs that have this frame as their parent
914 ComponentConfigDialog.hideDialog();
915 ComponentAnalysisDialog.hideDialog();
918 if (frames.isEmpty())
925 * Closes this frame if it is replaceable.
927 public void closeIfReplaceable() {
928 if (this.replaceable && document.isSaved()) {
934 * Open a new design window with a basic rocket+stage.
936 public static void newAction() {
937 Rocket rocket = new Rocket();
938 Stage stage = new Stage();
939 stage.setName("Sustainer");
940 rocket.addChild(stage);
941 OpenRocketDocument doc = new OpenRocketDocument(rocket);
944 BasicFrame frame = new BasicFrame(doc);
945 frame.replaceable = true;
946 frame.setVisible(true);
947 ComponentConfigDialog.showDialog(frame, doc, rocket);
951 * Quit the application. Confirms saving unsaved designs. The action of File->Quit.
953 public static void quitAction() {
954 for (int i=frames.size()-1; i>=0; i--) {
955 if (!frames.get(i).closeAction()) {
960 // Should not be reached, but just in case
966 * Set the title of the frame, taking into account the name of the rocket, file it
967 * has been saved to (if any) and saved status.
969 private void setTitle() {
970 File file = document.getFile();
971 boolean saved = document.isSaved();
974 title = rocket.getName();
976 title = title + " ("+file.getName()+")";
987 * Find a currently open BasicFrame containing the specified rocket. This method
988 * can be used to map a Rocket to a BasicFrame from GUI methods.
990 * @param rocket the Rocket.
991 * @return the corresponding BasicFrame, or <code>null</code> if none found.
993 public static BasicFrame findFrame(Rocket rocket) {
994 for (BasicFrame f: frames) {
995 if (f.rocket == rocket)
1002 * Find a currently open document by the rocket object. This method can be used
1003 * to map a Rocket to OpenRocketDocument from GUI methods.
1005 * @param rocket the Rocket.
1006 * @return the corresponding OpenRocketDocument, or <code>null</code> if not found.
1008 public static OpenRocketDocument findDocument(Rocket rocket) {
1009 for (BasicFrame f: frames) {
1010 if (f.rocket == rocket)
1017 public static void main(final String[] args) {
1019 // Run the actual startup method in the EDT since it can use dialogs etc.
1021 SwingUtilities.invokeAndWait(new Runnable() {
1027 } catch (InterruptedException e) {
1028 e.printStackTrace();
1029 } catch (InvocationTargetException e) {
1030 e.printStackTrace();
1036 private static void runMain(String[] args) {
1039 * Set the look-and-feel. On Linux, Motif/Metal is sometimes incorrectly used
1040 * which is butt-ugly, so if the system l&f is Motif/Metal, we search for a few
1041 * other alternatives.
1045 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
1047 // Check whether we have an ugly L&F
1048 LookAndFeel laf = UIManager.getLookAndFeel();
1050 laf.getName().matches(".*[mM][oO][tT][iI][fF].*") ||
1051 laf.getName().matches(".*[mM][eE][tT][aA][lL].*")) {
1053 // Search for better LAF
1054 UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();
1055 String lafNames[] = {
1059 ".*[aA][qQ][uU][aA].*",
1060 ".*[nN][iI][mM][bB].*"
1063 lf: for (String lafName: lafNames) {
1064 for (UIManager.LookAndFeelInfo l: info) {
1065 if (l.getName().matches(lafName)) {
1066 UIManager.setLookAndFeel(l.getClassName());
1072 } catch (Exception e) {
1073 System.err.println("Error setting LAF: " + e);
1076 // Set tooltip delay time. Tooltips are used in MotorChooserDialog extensively.
1077 ToolTipManager.sharedInstance().setDismissDelay(30000);
1081 Prefs.loadDefaultUnits();
1084 // Check command-line for files
1085 boolean opened = false;
1086 for (String file: args) {
1087 if (open(new File(file), null)) {