updates for 0.9.4
[debian/openrocket] / src / net / sf / openrocket / gui / main / BasicFrame.java
1 package net.sf.openrocket.gui.main;
2
3 import java.awt.Dimension;
4 import java.awt.Font;
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;
17 import java.io.File;
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;
23 import java.net.URI;
24 import java.net.URISyntaxException;
25 import java.net.URL;
26 import java.net.URLDecoder;
27 import java.util.ArrayList;
28 import java.util.concurrent.ExecutionException;
29
30 import javax.swing.Action;
31 import javax.swing.InputMap;
32 import javax.swing.JButton;
33 import javax.swing.JComponent;
34 import javax.swing.JFileChooser;
35 import javax.swing.JFrame;
36 import javax.swing.JMenu;
37 import javax.swing.JMenuBar;
38 import javax.swing.JMenuItem;
39 import javax.swing.JOptionPane;
40 import javax.swing.JPanel;
41 import javax.swing.JScrollPane;
42 import javax.swing.JSeparator;
43 import javax.swing.JSplitPane;
44 import javax.swing.JTabbedPane;
45 import javax.swing.JTextField;
46 import javax.swing.KeyStroke;
47 import javax.swing.ListSelectionModel;
48 import javax.swing.LookAndFeel;
49 import javax.swing.ScrollPaneConstants;
50 import javax.swing.SwingUtilities;
51 import javax.swing.ToolTipManager;
52 import javax.swing.UIManager;
53 import javax.swing.border.TitledBorder;
54 import javax.swing.event.TreeSelectionEvent;
55 import javax.swing.event.TreeSelectionListener;
56 import javax.swing.filechooser.FileFilter;
57 import javax.swing.tree.DefaultTreeSelectionModel;
58 import javax.swing.tree.TreePath;
59 import javax.swing.tree.TreeSelectionModel;
60
61 import net.miginfocom.swing.MigLayout;
62 import net.sf.openrocket.aerodynamics.WarningSet;
63 import net.sf.openrocket.document.OpenRocketDocument;
64 import net.sf.openrocket.file.GeneralRocketLoader;
65 import net.sf.openrocket.file.OpenRocketSaver;
66 import net.sf.openrocket.file.RocketLoadException;
67 import net.sf.openrocket.file.RocketLoader;
68 import net.sf.openrocket.file.RocketSaver;
69 import net.sf.openrocket.gui.StorageOptionChooser;
70 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
71 import net.sf.openrocket.gui.dialogs.AboutDialog;
72 import net.sf.openrocket.gui.dialogs.BugReportDialog;
73 import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog;
74 import net.sf.openrocket.gui.dialogs.ExampleDesignDialog;
75 import net.sf.openrocket.gui.dialogs.LicenseDialog;
76 import net.sf.openrocket.gui.dialogs.SwingWorkerDialog;
77 import net.sf.openrocket.gui.dialogs.WarningDialog;
78 import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog;
79 import net.sf.openrocket.gui.scalefigure.RocketPanel;
80 import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
81 import net.sf.openrocket.rocketcomponent.ComponentChangeListener;
82 import net.sf.openrocket.rocketcomponent.Rocket;
83 import net.sf.openrocket.rocketcomponent.RocketComponent;
84 import net.sf.openrocket.rocketcomponent.Stage;
85 import net.sf.openrocket.util.GUIUtil;
86 import net.sf.openrocket.util.Icons;
87 import net.sf.openrocket.util.OpenFileWorker;
88 import net.sf.openrocket.util.Prefs;
89 import net.sf.openrocket.util.SaveFileWorker;
90 import net.sf.openrocket.util.TestRockets;
91
92 public class BasicFrame extends JFrame {
93         private static final long serialVersionUID = 1L;
94
95         /**
96          * The RocketLoader instance used for loading all rocket designs.
97          */
98         private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
99         
100         private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver();
101
102         
103         /**
104          * File filter for filtering only rocket designs.
105          */
106         private static final FileFilter ROCKET_DESIGN_FILTER = new FileFilter() {
107                 @Override
108                 public String getDescription() {
109                         return "OpenRocket designs (*.ork)";
110                 }
111                 @Override
112                 public boolean accept(File f) {
113                         if (f.isDirectory())
114                                 return true;
115                         String name = f.getName().toLowerCase();
116                         return name.endsWith(".ork") || name.endsWith(".ork.gz");
117                 }
118     };
119     
120     
121     
122     public static final int COMPONENT_TAB = 0;
123     public static final int SIMULATION_TAB = 1;
124     
125
126         /**
127          * List of currently open frames.  When the list goes empty
128          * it is time to exit the application.
129          */
130         private static final ArrayList<BasicFrame> frames = new ArrayList<BasicFrame>();
131         
132         
133         
134         
135         
136         /**
137          * Whether "New" and "Open" should replace this frame.
138          * Should be set to false on the first rocket modification.
139          */
140         private boolean replaceable = false;
141         
142         
143         
144         private final OpenRocketDocument document;
145         private final Rocket rocket;
146         
147         private JTabbedPane tabbedPane;
148         private RocketPanel rocketpanel;
149         private ComponentTree tree = null;
150         
151         private final DocumentSelectionModel selectionModel;
152         private final TreeSelectionModel componentSelectionModel;
153         private final ListSelectionModel simulationSelectionModel;
154         
155         /** Actions available for rocket modifications */
156         private final RocketActions actions;
157         
158         
159         
160         /**
161          * Sole constructor.  Creates a new frame based on the supplied document
162          * and adds it to the current frames list.
163          * 
164          * @param document      the document to show.
165          */
166         public BasicFrame(OpenRocketDocument document) {
167
168                 this.document = document;
169                 this.rocket = document.getRocket();
170                 this.rocket.getDefaultConfiguration().setAllStages();
171                 
172                 
173                 // Set replaceable flag to false at first modification
174                 rocket.addComponentChangeListener(new ComponentChangeListener() {
175                         public void componentChanged(ComponentChangeEvent e) {
176                                 replaceable = false;
177                                 BasicFrame.this.rocket.removeComponentChangeListener(this);
178                         }
179                 });
180                 
181                 
182                 // Create the component tree selection model that will be used
183                 componentSelectionModel = new DefaultTreeSelectionModel();
184                 componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
185                 
186                 // Obtain the simulation selection model that will be used
187                 SimulationPanel simulationPanel = new SimulationPanel(document);
188                 simulationSelectionModel = simulationPanel.getSimulationListSelectionModel();
189                 
190                 // Combine into a DocumentSelectionModel
191                 selectionModel = new DocumentSelectionModel(document);
192                 selectionModel.attachComponentTreeSelectionModel(componentSelectionModel);
193                 selectionModel.attachSimulationListSelectionModel(simulationSelectionModel);
194                 
195                 
196                 actions = new RocketActions(document, selectionModel, this);
197                 
198                 
199                 // The main vertical split pane         
200                 JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
201                 vertical.setResizeWeight(0.5);
202                 this.add(vertical);
203
204                 
205                 // The top tabbed pane
206                 tabbedPane = new JTabbedPane();
207                 tabbedPane.addTab("Rocket design", null, designTab());
208                 tabbedPane.addTab("Flight simulations", null, simulationPanel);
209                 
210                 vertical.setTopComponent(tabbedPane);
211                 
212
213
214                 //  Bottom segment, rocket figure
215                 
216                 rocketpanel = new RocketPanel(document);
217                 vertical.setBottomComponent(rocketpanel);
218
219                 rocketpanel.setSelectionModel(tree.getSelectionModel());
220
221                                         
222                 createMenu();
223                 
224                 
225                 rocket.addComponentChangeListener(new ComponentChangeListener() {
226                         public void componentChanged(ComponentChangeEvent e) {
227                                 setTitle();
228                         }
229                 });
230                 
231                 setTitle();
232                 this.pack();
233
234                 Dimension size = Prefs.getWindowSize(this.getClass());
235                 if (size == null) {
236                         size = Toolkit.getDefaultToolkit().getScreenSize();
237                         size.width = size.width*9/10;
238                         size.height = size.height*9/10;
239                 }
240                 this.setSize(size);
241                 this.addComponentListener(new ComponentAdapter() {
242                         @Override
243                         public void componentResized(ComponentEvent e) {
244                                 Prefs.setWindowSize(BasicFrame.this.getClass(), BasicFrame.this.getSize());
245                         }
246                 });
247                 this.setLocationByPlatform(true);
248
249                 GUIUtil.setWindowIcons(this);
250                 
251                 this.validate();
252                 vertical.setDividerLocation(0.4);
253                 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
254                 addWindowListener(new WindowAdapter() {
255                         @Override
256                         public void windowClosing(WindowEvent e) {
257                                 closeAction();
258                         }
259                 });
260                 frames.add(this);
261         }
262         
263         
264         /**
265          * Construct the "Rocket design" tab.  This contains a horizontal split pane
266          * with the left component the design tree and the right component buttons
267          * for adding components.
268          */
269         private JComponent designTab() {
270                 JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true);
271                 horizontal.setResizeWeight(0.5);
272
273
274                 //  Upper-left segment, component tree
275
276                 JPanel panel = new JPanel(new MigLayout("fill, flowy","","[grow]"));
277
278                 tree = new ComponentTree(rocket);
279                 tree.setSelectionModel(componentSelectionModel);
280
281                 // Remove JTree key events that interfere with menu accelerators
282                 InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED);
283                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null);
284                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null);
285                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null);
286                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null);
287                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null);
288                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null);
289                 im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null);
290
291
292                 
293                 // Double-click opens config dialog
294                 MouseListener ml = new MouseAdapter() {
295                         @Override
296                         public void mousePressed(MouseEvent e) {
297                                 int selRow = tree.getRowForLocation(e.getX(), e.getY());
298                                 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
299                                 if(selRow != -1) {
300                                         if((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) {
301                                                 // Double-click
302                                                 RocketComponent c = (RocketComponent)selPath.getLastPathComponent();
303                                                 ComponentConfigDialog.showDialog(BasicFrame.this, 
304                                                                 BasicFrame.this.document, c);
305                                         }
306                                 }
307                         }
308                 };
309                 tree.addMouseListener(ml);
310
311                 // Update dialog when selection is changed
312                 componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() {
313                         public void valueChanged(TreeSelectionEvent e) {
314                                 // Scroll tree to the selected item
315                                 TreePath path = componentSelectionModel.getSelectionPath();
316                                 if (path == null)
317                                         return;
318                                 tree.scrollPathToVisible(path);
319                                 
320                                 if (!ComponentConfigDialog.isDialogVisible())
321                                         return;
322                                 RocketComponent c = (RocketComponent)path.getLastPathComponent();
323                                 ComponentConfigDialog.showDialog(BasicFrame.this, 
324                                                 BasicFrame.this.document, c);
325                         }
326                 });
327
328                 // Place tree inside scroll pane
329                 JScrollPane scroll = new JScrollPane(tree);
330                 panel.add(scroll,"spany, grow, wrap");
331                 
332                 
333                 // Buttons
334                 JButton button = new JButton(actions.getMoveUpAction());
335                 panel.add(button,"sizegroup buttons, aligny 65%");
336                 
337                 button = new JButton(actions.getMoveDownAction());
338                 panel.add(button,"sizegroup buttons, aligny 0%");
339                 
340                 button = new JButton(actions.getEditAction());
341                 panel.add(button, "sizegroup buttons");
342                 
343                 button = new JButton(actions.getNewStageAction());
344                 panel.add(button,"sizegroup buttons");
345                 
346                 button = new JButton(actions.getDeleteAction());
347                 button.setIcon(null);
348                 button.setMnemonic(0);
349                 panel.add(button,"sizegroup buttons");
350
351                 horizontal.setLeftComponent(panel);
352
353
354                 //  Upper-right segment, component addition buttons
355
356                 panel = new JPanel(new MigLayout("fill, insets 0","[0::]"));
357
358                 scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
359                                 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
360                 scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel,
361                                 scroll.getViewport()));
362                 scroll.setBorder(null);
363                 scroll.setViewportBorder(null);
364
365                 TitledBorder border = new TitledBorder("Add new component");
366                 border.setTitleFont(border.getTitleFont().deriveFont(Font.BOLD));
367                 scroll.setBorder(border);
368
369                 panel.add(scroll,"grow");
370
371                 horizontal.setRightComponent(panel);
372
373                 return horizontal;
374         }
375         
376         
377         
378         /**
379          * Creates the menu for the window.
380          */
381         private void createMenu() {
382                 JMenuBar menubar = new JMenuBar();
383                 JMenu menu;
384                 JMenuItem item;
385                 
386                 ////  File
387                 menu = new JMenu("File");
388                 menu.setMnemonic(KeyEvent.VK_F);
389                 menu.getAccessibleContext().setAccessibleDescription("File-handling related tasks");
390                 menubar.add(menu);
391                 
392                 item = new JMenuItem("New",KeyEvent.VK_N);
393                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
394                 item.setMnemonic(KeyEvent.VK_N);
395                 item.getAccessibleContext().setAccessibleDescription("Create a new rocket design");
396                 item.setIcon(Icons.FILE_NEW);
397                 item.addActionListener(new ActionListener() {
398                         public void actionPerformed(ActionEvent e) {
399                                 newAction();
400                                 if (replaceable)
401                                         closeAction();
402                         }
403                 });
404                 menu.add(item);
405                 
406                 item = new JMenuItem("Open...",KeyEvent.VK_O);
407                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
408                 item.getAccessibleContext().setAccessibleDescription("Open a rocket design");
409                 item.setIcon(Icons.FILE_OPEN);
410                 item.addActionListener(new ActionListener() {
411                         public void actionPerformed(ActionEvent e) {
412                                 openAction();
413                         }
414                 });
415                 menu.add(item);
416                 
417                 item = new JMenuItem("Open example...");
418                 item.getAccessibleContext().setAccessibleDescription("Open an example rocket design");
419                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, 
420                                 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
421                 item.setIcon(Icons.FILE_OPEN_EXAMPLE);
422                 item.addActionListener(new ActionListener() {
423                         public void actionPerformed(ActionEvent e) {
424                                 URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this);
425                                 if (urls != null) {
426                                         for (URL u: urls) {
427                                                 open(u, BasicFrame.this);
428                                         }
429                                 }
430                         }
431                 });
432                 menu.add(item);
433                 
434                 menu.addSeparator();
435                 
436                 item = new JMenuItem("Save",KeyEvent.VK_S);
437                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
438                 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design");
439                 item.setIcon(Icons.FILE_SAVE);
440                 item.addActionListener(new ActionListener() {
441                         public void actionPerformed(ActionEvent e) {
442                                 saveAction();
443                         }
444                 });
445                 menu.add(item);
446                 
447                 item = new JMenuItem("Save as...",KeyEvent.VK_A);
448                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, 
449                                 ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
450                 item.getAccessibleContext().setAccessibleDescription("Save the current rocket design "+
451                                 "to a new file");
452                 item.setIcon(Icons.FILE_SAVE_AS);
453                 item.addActionListener(new ActionListener() {
454                         public void actionPerformed(ActionEvent e) {
455                                 saveAsAction();
456                         }
457                 });
458                 menu.add(item);
459                 
460 //              menu.addSeparator();
461                 menu.add(new JSeparator());
462                 
463                 item = new JMenuItem("Close",KeyEvent.VK_C);
464                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
465                 item.getAccessibleContext().setAccessibleDescription("Close the current rocket design");
466                 item.setIcon(Icons.FILE_CLOSE);
467                 item.addActionListener(new ActionListener() {
468                         public void actionPerformed(ActionEvent e) {
469                                 closeAction();
470                         }
471                 });
472                 menu.add(item);
473                 
474                 menu.addSeparator();
475
476                 item = new JMenuItem("Quit",KeyEvent.VK_Q);
477                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
478                 item.getAccessibleContext().setAccessibleDescription("Quit the program");
479                 item.setIcon(Icons.FILE_QUIT);
480                 item.addActionListener(new ActionListener() {
481                         public void actionPerformed(ActionEvent e) {
482                                 quitAction();
483                         }
484                 });
485                 menu.add(item);
486                 
487                 
488
489                 ////  Edit
490                 menu = new JMenu("Edit");
491                 menu.setMnemonic(KeyEvent.VK_E);
492                 menu.getAccessibleContext().setAccessibleDescription("Rocket editing");
493                 menubar.add(menu);
494                 
495                 
496                 Action action = document.getUndoAction();
497                 item = new JMenuItem(action);
498                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK));
499                 item.setMnemonic(KeyEvent.VK_U);
500                 item.getAccessibleContext().setAccessibleDescription("Undo the previous operation");
501
502                 menu.add(item);
503
504                 action = document.getRedoAction();
505                 item = new JMenuItem(action);
506                 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK));
507                 item.setMnemonic(KeyEvent.VK_R);
508                 item.getAccessibleContext().setAccessibleDescription("Redo the previously undone " +
509                                 "operation");
510                 menu.add(item);
511                 
512                 menu.addSeparator();
513                 
514                 
515                 item = new JMenuItem(actions.getCutAction());
516                 menu.add(item);
517         
518                 item = new JMenuItem(actions.getCopyAction());
519                 menu.add(item);
520         
521                 item = new JMenuItem(actions.getPasteAction());
522                 menu.add(item);
523                 
524                 item = new JMenuItem(actions.getDeleteAction());
525                 menu.add(item);
526                 
527                 menu.addSeparator();
528                 
529                 item = new JMenuItem("Preferences");
530                 item.setIcon(Icons.PREFERENCES);
531                 item.getAccessibleContext().setAccessibleDescription("Setup the application "+
532                                 "preferences");
533                 item.addActionListener(new ActionListener() {
534                         public void actionPerformed(ActionEvent e) {
535                                 PreferencesDialog.showPreferences();
536                         }
537                 });
538                 menu.add(item);
539         
540                 
541
542
543                 ////  Analyze
544                 menu = new JMenu("Analyze");
545                 menu.setMnemonic(KeyEvent.VK_A);
546                 menu.getAccessibleContext().setAccessibleDescription("Analyzing the rocket");
547                 menubar.add(menu);
548                 
549                 item = new JMenuItem("Component analysis",KeyEvent.VK_C);
550                 item.getAccessibleContext().setAccessibleDescription("Analyze the rocket components " +
551                                 "separately");
552                 item.addActionListener(new ActionListener() {
553                         public void actionPerformed(ActionEvent e) {
554                                 ComponentAnalysisDialog.showDialog(rocketpanel);
555                         }
556                 });
557                 menu.add(item);
558                 
559                 
560                 ////  Debug
561                 // (shown if openrocket.debug.menu is defined)
562                 if (System.getProperty("openrocket.debug.menu") != null) {
563                         menubar.add(makeDebugMenu());
564                 }
565
566                 
567                 
568                 ////  Help
569                 
570                 menu = new JMenu("Help");
571                 menu.setMnemonic(KeyEvent.VK_H);
572                 menu.getAccessibleContext().setAccessibleDescription("Information about OpenRocket");
573                 menubar.add(menu);
574                 
575                 
576                 
577                 item = new JMenuItem("License",KeyEvent.VK_L);
578                 item.getAccessibleContext().setAccessibleDescription("OpenRocket license information");
579                 item.addActionListener(new ActionListener() {
580                         public void actionPerformed(ActionEvent e) {
581                                 new LicenseDialog(BasicFrame.this).setVisible(true);
582                         }
583                 });
584                 menu.add(item);
585                 
586                 item = new JMenuItem("Bug report",KeyEvent.VK_B);
587                 item.getAccessibleContext().setAccessibleDescription("Information about reporting " +
588                                 "bugs in OpenRocket");
589                 item.addActionListener(new ActionListener() {
590                         public void actionPerformed(ActionEvent e) {
591 //                              new BugDialog(BasicFrame.this).setVisible(true);
592                                 BugReportDialog.showBugReportDialog(BasicFrame.this);
593                         }
594                 });
595                 menu.add(item);
596                 
597                 item = new JMenuItem("About",KeyEvent.VK_A);
598                 item.getAccessibleContext().setAccessibleDescription("About OpenRocket");
599                 item.addActionListener(new ActionListener() {
600                         public void actionPerformed(ActionEvent e) {
601                                 new AboutDialog(BasicFrame.this).setVisible(true);
602                         }
603                 });
604                 menu.add(item);
605                 
606                 
607                 this.setJMenuBar(menubar);
608         }
609         
610         
611         private JMenu makeDebugMenu() {
612                 JMenu menu;
613                 JMenuItem item;
614                 
615                 ////  Debug menu
616                 menu = new JMenu("Debug");
617                 menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks");
618                 
619                 item = new JMenuItem("What is this menu?");
620                 item.addActionListener(new ActionListener() {
621                         public void actionPerformed(ActionEvent e) {
622                                 JOptionPane.showMessageDialog(BasicFrame.this,
623                                                 new Object[] {
624                                                 "The 'Debug' menu includes actions for testing and debugging " +
625                                                 "OpenRocket.", " ",
626                                                 "The menu is made visible by defining the system property " +
627                                                 "'openrocket.debug.menu' when starting OpenRocket.",
628                                                 "It should not be visible by default." },
629                                                 "Debug menu", JOptionPane.INFORMATION_MESSAGE);
630                         }
631                 });
632                 menu.add(item);
633                 
634                 menu.addSeparator();
635                 
636                 item = new JMenuItem("Create test rocket");
637                 item.addActionListener(new ActionListener() {
638                         @Override
639                         public void actionPerformed(ActionEvent e) {
640                                 JTextField field = new JTextField();
641                                 int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] {
642                                                 "Input text key to generate random rocket:",
643                                                 field
644                                         }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION, 
645                                         JOptionPane.QUESTION_MESSAGE, null, new Object[] {
646                                                 "Random", "OK"
647                                 }, "OK");
648                                 
649                                 Rocket r;
650                                 if (sel == 0) {
651                                         r = new TestRockets(null).makeTestRocket();
652                                 } else if (sel == 1) {
653                                         r = new TestRockets(field.getText()).makeTestRocket();
654                                 } else {
655                                         return;
656                                 }
657                                 
658                                 OpenRocketDocument doc = new OpenRocketDocument(r);
659                                 doc.setSaved(true);
660                                 BasicFrame frame = new BasicFrame(doc);
661                                 frame.setVisible(true);
662                         }
663                 });
664                 menu.add(item);
665                 
666                 menu.addSeparator();
667                 
668                 item = new JMenuItem("Exception here");
669                 item.addActionListener(new ActionListener() {
670                         public void actionPerformed(ActionEvent e) {
671                                 throw new RuntimeException("Testing exception from menu action listener");
672                         }
673                 });
674                 menu.add(item);
675                 
676                 item = new JMenuItem("Exception from EDT");
677                 item.addActionListener(new ActionListener() {
678                         public void actionPerformed(ActionEvent e) {
679                                 SwingUtilities.invokeLater(new Runnable() {
680                                         @Override
681                                         public void run() {
682                                                 throw new RuntimeException("Testing exception from " +
683                                                                 "later invoked EDT thread");
684                                         }
685                                 });
686                         }
687                 });
688                 menu.add(item);
689                 
690                 item = new JMenuItem("Exception from other thread");
691                 item.addActionListener(new ActionListener() {
692                         public void actionPerformed(ActionEvent e) {
693                                 new Thread() {
694                                         @Override
695                                         public void run() {
696                                                 throw new RuntimeException("Testing exception from " +
697                                                                 "newly created thread");
698                                         }
699                                 }.start();
700                         }
701                 });
702                 menu.add(item);
703                 
704                 
705                 
706                 return menu;
707         }
708         
709         
710         
711         /**
712          * Select the tab on the main pane.
713          * 
714          * @param tab   one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
715          */
716         public void selectTab(int tab) {
717                 tabbedPane.setSelectedIndex(tab);
718         }
719
720         
721         
722         private void openAction() {
723             JFileChooser chooser = new JFileChooser();
724             chooser.setFileFilter(ROCKET_DESIGN_FILTER);
725             chooser.setMultiSelectionEnabled(true);
726             chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
727             if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
728                 return;
729             
730             Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
731
732             File[] files = chooser.getSelectedFiles();
733             
734             for (File file: files) {
735                 System.out.println("Opening file: " + file);
736                 if (open(file, this)) {
737                         
738                         // Close previous window if replacing
739                         if (replaceable && document.isSaved()) {
740                                 closeAction();
741                                 replaceable = false;
742                         }
743                 }
744             }
745         }
746         
747         
748         
749         
750         private static boolean open(URL url, Window parent) {
751                 String filename = null;
752                 
753                 // Try using URI.getPath();
754                 try {
755                         URI uri = url.toURI();
756                         filename = uri.getPath();
757                 } catch (URISyntaxException ignore) { }
758
759                 // Try URL-decoding the URL
760                 if (filename == null) {
761                         try {
762                                 filename = URLDecoder.decode(url.toString(), "UTF-8");
763                         } catch (UnsupportedEncodingException ignore) { }
764                 }
765                 
766                 // Last resort
767                 if (filename == null) {
768                         filename = "";
769                 }
770                 
771                 // Remove path from filename
772                 if (filename.lastIndexOf('/') >= 0) {
773                         filename = filename.substring(filename.lastIndexOf('/')+1);
774                 }
775                 
776                 try {
777                         InputStream is = url.openStream();
778                         open(is, filename, parent);
779                 } catch (IOException e) {
780                         JOptionPane.showMessageDialog(parent, 
781                                         "An error occurred while opening the file " + filename,
782                                         "Error loading file", JOptionPane.ERROR_MESSAGE);
783                 }
784                 
785                 return false;
786         }
787         
788         
789         /**
790          * Open the specified file from an InputStream in a new design frame.  If an error
791          * occurs, an error dialog is shown and <code>false</code> is returned.
792          * 
793          * @param stream        the stream to load from.
794          * @param filename      the file name to display in dialogs (not set to the document).
795          * @param parent        the parent component for which a progress dialog is opened.
796          * @return                      whether the file was successfully loaded and opened.
797          */
798         private static boolean open(InputStream stream, String filename, Window parent) {
799                 OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER);
800                 return open(worker, filename, null, parent);
801         }
802         
803
804         /**
805          * Open the specified file in a new design frame.  If an error occurs, an error
806          * dialog is shown and <code>false</code> is returned.
807          * 
808          * @param file          the file to open.
809          * @param parent        the parent component for which a progress dialog is opened.
810          * @return                      whether the file was successfully loaded and opened.
811          */
812         private static boolean open(File file, Window parent) {
813                 OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER);
814                 return open(worker, file.getName(), file, parent);
815         }
816         
817
818         /**
819          * Open the specified file using the provided worker.
820          * 
821          * @param worker        the OpenFileWorker that loads the file.
822          * @param filename      the file name to display in dialogs.
823          * @param file          the File to set the document to (may be null).
824          * @param parent
825          * @return
826          */
827         private static boolean open(OpenFileWorker worker, String filename, File file, 
828                         Window parent) {
829
830                 // Open the file in a Swing worker thread
831                 if (!SwingWorkerDialog.runWorker(parent, "Opening file", 
832                                 "Reading " + filename + "...", worker)) {
833
834                         // User cancelled the operation
835                         return false;
836                 }
837
838                 
839                 // Handle the document
840                 OpenRocketDocument doc = null;
841                 try {
842
843                         doc = worker.get();
844
845                 } catch (ExecutionException e) {
846
847                         Throwable cause = e.getCause();
848
849                         if (cause instanceof FileNotFoundException) {
850
851                                 JOptionPane.showMessageDialog(parent, 
852                                                 "File not found: " + filename,
853                                                 "Error opening file", JOptionPane.ERROR_MESSAGE);
854                                 return false;
855
856                         } else if (cause instanceof RocketLoadException) {
857
858                                 JOptionPane.showMessageDialog(parent, 
859                                                 "Unable to open file '" + filename +"': " 
860                                                 + cause.getMessage(),
861                                                 "Error opening file", JOptionPane.ERROR_MESSAGE);
862                                 return false;
863
864                         } else {
865
866                                 throw new RuntimeException("Unknown error when opening file", e);
867
868                         }
869
870                 } catch (InterruptedException e) {
871                         throw new RuntimeException("EDT was interrupted", e);
872                 }
873                 
874                 if (doc == null) {
875                         throw new RuntimeException("BUG: Document loader returned null");
876                 }
877                 
878                 
879             // Show warnings
880                 WarningSet warnings = worker.getRocketLoader().getWarnings();
881                 if (!warnings.isEmpty()) {
882                         WarningDialog.showWarnings(parent,
883                                         new Object[] {
884                                         "The following problems were encountered while opening " + filename + ".",
885                                         "Some design features may not have been loaded correctly."
886                                         },
887                                         "Warnings while opening file", warnings);
888                 }
889                 
890             
891             // Set document state
892             doc.setFile(file);
893             doc.setSaved(true);
894
895             // Open the frame
896             BasicFrame frame = new BasicFrame(doc);
897             frame.setVisible(true);
898
899             return true;
900         }
901         
902         
903         
904         
905         
906         
907         
908         
909         
910         private boolean saveAction() {
911                 File file = document.getFile();
912                 if (file==null) {
913                         return saveAsAction();
914                 } else {
915                         return saveAs(file);
916                 }
917         }
918         
919         
920         private boolean saveAsAction() {
921                 File file = null;
922                 while (file == null) {
923                         StorageOptionChooser storageChooser = 
924                                 new StorageOptionChooser(document, document.getDefaultStorageOptions());
925                         JFileChooser chooser = new JFileChooser();
926                         chooser.setFileFilter(ROCKET_DESIGN_FILTER);
927                         chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
928                         chooser.setAccessory(storageChooser);
929                         if (document.getFile() != null)
930                                 chooser.setSelectedFile(document.getFile());
931                         
932                         if (chooser.showSaveDialog(BasicFrame.this) != JFileChooser.APPROVE_OPTION)
933                                 return false;
934                         
935                         file = chooser.getSelectedFile();
936                         if (file == null)
937                                 return false;
938
939                         Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
940                         storageChooser.storeOptions(document.getDefaultStorageOptions());
941                         
942                         if (file.getName().indexOf('.') < 0) {
943                                 String name = file.getAbsolutePath();
944                                 name = name + ".ork";
945                                 file = new File(name);
946                         }
947                         
948                         if (file.exists()) {
949                                 int result = JOptionPane.showConfirmDialog(this, 
950                                                 "File '"+file.getName()+"' exists.  Do you want to overwrite it?", 
951                                                 "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
952                                 if (result != JOptionPane.YES_OPTION)
953                                         return false;
954                         }
955                 }
956             saveAs(file);
957             return true;
958         }
959         
960         
961         private boolean saveAs(File file) {
962             System.out.println("Saving to file: " + file.getName());
963             boolean saved = false;
964             
965             if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
966                 // User cancelled the dialog
967                 return false;
968             }
969
970
971             SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
972
973             if (!SwingWorkerDialog.runWorker(this, "Saving file", 
974                         "Writing " + file.getName() + "...", worker)) {
975                 
976                 // User cancelled the save
977                 file.delete();
978                 return false;
979             }
980             
981             try {
982                         worker.get();
983                         document.setFile(file);
984                         document.setSaved(true);
985                         saved = true;
986                     setTitle();
987                 } catch (ExecutionException e) {
988                         Throwable cause = e.getCause();
989                         
990                         if (cause instanceof IOException) {
991                         JOptionPane.showMessageDialog(this, new String[] { 
992                                         "An I/O error occurred while saving:",
993                                         e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
994                         return false;
995                         } else {
996                                 throw new RuntimeException("Unknown error when saving file", e);
997                         }
998                         
999                 } catch (InterruptedException e) {
1000                         throw new RuntimeException("EDT was interrupted", e);
1001                 }
1002             
1003             return saved;
1004         }
1005         
1006         
1007         private boolean closeAction() {
1008                 if (!document.isSaved()) {
1009                         ComponentConfigDialog.hideDialog();
1010                         int result = JOptionPane.showConfirmDialog(this, 
1011                                         "Design '"+rocket.getName()+"' has not been saved.  " +
1012                                                         "Do you want to save it?", 
1013                                         "Design not saved", JOptionPane.YES_NO_CANCEL_OPTION, 
1014                                         JOptionPane.QUESTION_MESSAGE);
1015                         if (result == JOptionPane.YES_OPTION) {
1016                                 // Save
1017                                 if (!saveAction())
1018                                         return false;  // If save was interrupted
1019                         } else if (result == JOptionPane.NO_OPTION) {
1020                                 // Don't save: No-op
1021                         } else {
1022                                 // Cancel or close
1023                                 return false;
1024                         }
1025                 }
1026                 
1027                 // Rocket has been saved or discarded
1028                 this.dispose();
1029
1030                 // TODO: LOW: Close only dialogs that have this frame as their parent
1031                 ComponentConfigDialog.hideDialog();
1032                 ComponentAnalysisDialog.hideDialog();
1033                 
1034                 frames.remove(this);
1035                 if (frames.isEmpty())
1036                         System.exit(0);
1037                 return true;
1038         }
1039         
1040         
1041         /**
1042          * Closes this frame if it is replaceable.
1043          */
1044         public void closeIfReplaceable() {
1045                 if (this.replaceable && document.isSaved()) {
1046                         closeAction();
1047                 }
1048         }
1049         
1050         /**
1051          * Open a new design window with a basic rocket+stage.
1052          */
1053         public static void newAction() {
1054                 Rocket rocket = new Rocket();
1055                 Stage stage = new Stage();
1056                 stage.setName("Sustainer");
1057                 rocket.addChild(stage);
1058                 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1059                 doc.setSaved(true);
1060                 
1061                 BasicFrame frame = new BasicFrame(doc);
1062                 frame.replaceable = true;
1063                 frame.setVisible(true);
1064                 ComponentConfigDialog.showDialog(frame, doc, rocket);
1065         }
1066         
1067         /**
1068          * Quit the application.  Confirms saving unsaved designs.  The action of File->Quit.
1069          */
1070         public static void quitAction() {
1071                 for (int i=frames.size()-1; i>=0; i--) {
1072                         if (!frames.get(i).closeAction()) {
1073                                 // Close canceled
1074                                 return;
1075                         }
1076                 }
1077                 // Should not be reached, but just in case
1078                 System.exit(0);
1079         }
1080         
1081         
1082         /**
1083          * Set the title of the frame, taking into account the name of the rocket, file it 
1084          * has been saved to (if any) and saved status.
1085          */
1086         private void setTitle() {
1087                 File file = document.getFile();
1088                 boolean saved = document.isSaved();
1089                 String title;
1090                 
1091                 title = rocket.getName();
1092                 if (file!=null) {
1093                         title = title + " ("+file.getName()+")";
1094                 }
1095                 if (!saved)
1096                         title = "*" + title;
1097                 
1098                 setTitle(title);
1099         }
1100         
1101         
1102         
1103         /**
1104          * Find a currently open BasicFrame containing the specified rocket.  This method
1105          * can be used to map a Rocket to a BasicFrame from GUI methods.
1106          * 
1107          * @param rocket the Rocket.
1108          * @return               the corresponding BasicFrame, or <code>null</code> if none found.
1109          */
1110         public static BasicFrame findFrame(Rocket rocket) {
1111                 for (BasicFrame f: frames) {
1112                         if (f.rocket == rocket)
1113                                 return f;
1114                 }
1115                 return null;
1116         }
1117         
1118         /**
1119          * Find a currently open document by the rocket object.  This method can be used
1120          * to map a Rocket to OpenRocketDocument from GUI methods.
1121          * 
1122          * @param rocket the Rocket.
1123          * @return               the corresponding OpenRocketDocument, or <code>null</code> if not found.
1124          */
1125         public static OpenRocketDocument findDocument(Rocket rocket) {
1126                 for (BasicFrame f: frames) {
1127                         if (f.rocket == rocket)
1128                                 return f.document;
1129                 }
1130                 return null;
1131         }
1132         
1133         
1134         public static void main(final String[] args) {
1135                 
1136                 // Run the actual startup method in the EDT since it can use progress dialogs etc.
1137                 try {
1138                         SwingUtilities.invokeAndWait(new Runnable() {
1139                                 @Override
1140                                 public void run() {
1141                                         runMain(args);
1142                                 }
1143                         });
1144                 } catch (InterruptedException e) {
1145                         e.printStackTrace();
1146                 } catch (InvocationTargetException e) {
1147                         e.printStackTrace();
1148                 }
1149                 
1150         }
1151         
1152         
1153         private static void runMain(String[] args) {
1154
1155                 /*
1156                  * Set the look-and-feel.  On Linux, Motif/Metal is sometimes incorrectly used 
1157                  * which is butt-ugly, so if the system l&f is Motif/Metal, we search for a few
1158                  * other alternatives.
1159                  */
1160                 try {
1161                         // Set system L&F
1162                         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
1163                         
1164                         // Check whether we have an ugly L&F
1165                         LookAndFeel laf = UIManager.getLookAndFeel();
1166                         if (laf == null ||
1167                                         laf.getName().matches(".*[mM][oO][tT][iI][fF].*") ||
1168                                         laf.getName().matches(".*[mM][eE][tT][aA][lL].*")) {
1169                                 
1170                                 // Search for better LAF
1171                                 UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();
1172                                 String lafNames[] = {
1173                                                 ".*[gG][tT][kK].*",
1174                                                 ".*[wW][iI][nN].*",
1175                                                 ".*[mM][aA][cC].*",
1176                                                 ".*[aA][qQ][uU][aA].*",
1177                                                 ".*[nN][iI][mM][bB].*"
1178                                 };
1179                                 
1180                                 lf: for (String lafName: lafNames) {
1181                                         for (UIManager.LookAndFeelInfo l: info) {
1182                                                 if (l.getName().matches(lafName)) {
1183                                                         UIManager.setLookAndFeel(l.getClassName());
1184                                                         break lf;
1185                                                 }
1186                                         }                                       
1187                                 }
1188                         }
1189                 } catch (Exception e) {
1190                         System.err.println("Error setting LAF: " + e);
1191                 }
1192
1193                 // Set tooltip delay time.  Tooltips are used in MotorChooserDialog extensively.
1194                 ToolTipManager.sharedInstance().setDismissDelay(30000);
1195                 
1196                 
1197                 // Setup the uncaught exception handler
1198                 ExceptionHandler.registerExceptionHandler();
1199                 
1200                 
1201                 // Load defaults
1202                 Prefs.loadDefaultUnits();
1203
1204                 
1205                 // Starting action
1206                 if (!handleCommandLine(args)) {
1207                         newAction();
1208                 }
1209         }
1210         
1211         
1212         /**
1213          * Handles arguments passed from the command line.  This may be used either
1214          * when starting the first instance of OpenRocket or later when OpenRocket is
1215          * executed again while running.
1216          * 
1217          * @param args  the command-line arguments.
1218          * @return              whether a new frame was opened or similar user desired action was
1219          *                              performed as a result.
1220          */
1221         public static boolean handleCommandLine(String[] args) {
1222                 
1223                 // Check command-line for files
1224                 boolean opened = false;
1225                 for (String file: args) {
1226                         if (open(new File(file), null)) {
1227                                 opened = true;
1228                         }
1229                 }
1230                 return opened;
1231         }
1232
1233 }