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