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