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