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