release 0.9.6
[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         /**
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                 
672
673                 item = new JMenuItem("Create 'Iso-Haisu'");
674                 item.addActionListener(new ActionListener() {
675                         @Override
676                         public void actionPerformed(ActionEvent e) {
677                                 Rocket r = TestRockets.makeIsoHaisu();
678                                 OpenRocketDocument doc = new OpenRocketDocument(r);
679                                 doc.setSaved(true);
680                                 BasicFrame frame = new BasicFrame(doc);
681                                 frame.setVisible(true);
682                         }
683                 });
684                 menu.add(item);
685                 
686
687                 item = new JMenuItem("Create 'Big Blue'");
688                 item.addActionListener(new ActionListener() {
689                         @Override
690                         public void actionPerformed(ActionEvent e) {
691                                 Rocket r = TestRockets.makeBigBlue();
692                                 OpenRocketDocument doc = new OpenRocketDocument(r);
693                                 doc.setSaved(true);
694                                 BasicFrame frame = new BasicFrame(doc);
695                                 frame.setVisible(true);
696                         }
697                 });
698                 menu.add(item);
699                 
700                 
701                 
702                 menu.addSeparator();
703                 
704                 item = new JMenuItem("Exception here");
705                 item.addActionListener(new ActionListener() {
706                         public void actionPerformed(ActionEvent e) {
707                                 throw new RuntimeException("Testing exception from menu action listener");
708                         }
709                 });
710                 menu.add(item);
711                 
712                 item = new JMenuItem("Exception from EDT");
713                 item.addActionListener(new ActionListener() {
714                         public void actionPerformed(ActionEvent e) {
715                                 SwingUtilities.invokeLater(new Runnable() {
716                                         @Override
717                                         public void run() {
718                                                 throw new RuntimeException("Testing exception from " +
719                                                                 "later invoked EDT thread");
720                                         }
721                                 });
722                         }
723                 });
724                 menu.add(item);
725                 
726                 item = new JMenuItem("Exception from other thread");
727                 item.addActionListener(new ActionListener() {
728                         public void actionPerformed(ActionEvent e) {
729                                 new Thread() {
730                                         @Override
731                                         public void run() {
732                                                 throw new RuntimeException("Testing exception from " +
733                                                                 "newly created thread");
734                                         }
735                                 }.start();
736                         }
737                 });
738                 menu.add(item);
739                 
740                 
741                 
742                 return menu;
743         }
744         
745         
746         
747         /**
748          * Select the tab on the main pane.
749          * 
750          * @param tab   one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}.
751          */
752         public void selectTab(int tab) {
753                 tabbedPane.setSelectedIndex(tab);
754         }
755
756         
757         
758         private void openAction() {
759             JFileChooser chooser = new JFileChooser();
760             chooser.setFileFilter(ROCKET_DESIGN_FILTER);
761             chooser.setMultiSelectionEnabled(true);
762             chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
763             if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
764                 return;
765             
766             Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
767
768             File[] files = chooser.getSelectedFiles();
769             
770             for (File file: files) {
771                 System.out.println("Opening file: " + file);
772                 if (open(file, this)) {
773                         
774                         // Close previous window if replacing
775                         if (replaceable && document.isSaved()) {
776                                 closeAction();
777                                 replaceable = false;
778                         }
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                 } else {
957                         return saveAs(file);
958                 }
959         }
960         
961         
962         private boolean saveAsAction() {
963                 File file = null;
964                 while (file == null) {
965                         StorageOptionChooser storageChooser = 
966                                 new StorageOptionChooser(document, document.getDefaultStorageOptions());
967                         JFileChooser chooser = new JFileChooser();
968                         chooser.setFileFilter(ROCKET_DESIGN_FILTER);
969                         chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
970                         chooser.setAccessory(storageChooser);
971                         if (document.getFile() != null)
972                                 chooser.setSelectedFile(document.getFile());
973                         
974                         if (chooser.showSaveDialog(BasicFrame.this) != JFileChooser.APPROVE_OPTION)
975                                 return false;
976                         
977                         file = chooser.getSelectedFile();
978                         if (file == null)
979                                 return false;
980
981                         Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
982                         storageChooser.storeOptions(document.getDefaultStorageOptions());
983                         
984                         if (file.getName().indexOf('.') < 0) {
985                                 String name = file.getAbsolutePath();
986                                 name = name + ".ork";
987                                 file = new File(name);
988                         }
989                         
990                         if (file.exists()) {
991                                 int result = JOptionPane.showConfirmDialog(this, 
992                                                 "File '"+file.getName()+"' exists.  Do you want to overwrite it?", 
993                                                 "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
994                                 if (result != JOptionPane.YES_OPTION)
995                                         return false;
996                         }
997                 }
998             saveAs(file);
999             return true;
1000         }
1001         
1002         
1003         private boolean saveAs(File file) {
1004             System.out.println("Saving to file: " + file.getName());
1005             boolean saved = false;
1006             
1007             if (!StorageOptionChooser.verifyStorageOptions(document, this)) {
1008                 // User cancelled the dialog
1009                 return false;
1010             }
1011
1012
1013             SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER);
1014
1015             if (!SwingWorkerDialog.runWorker(this, "Saving file", 
1016                         "Writing " + file.getName() + "...", worker)) {
1017                 
1018                 // User cancelled the save
1019                 file.delete();
1020                 return false;
1021             }
1022             
1023             try {
1024                         worker.get();
1025                         document.setFile(file);
1026                         document.setSaved(true);
1027                         saved = true;
1028                     setTitle();
1029                 } catch (ExecutionException e) {
1030
1031                         Throwable cause = e.getCause();
1032                         
1033                         if (cause instanceof IOException) {
1034                         JOptionPane.showMessageDialog(this, new String[] { 
1035                                         "An I/O error occurred while saving:",
1036                                         e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE);
1037                         return false;
1038                         } else {
1039                                 Reflection.handleWrappedException(e);
1040                         }
1041                         
1042                 } catch (InterruptedException e) {
1043                         throw new BugException("EDT was interrupted", e);
1044                 }
1045             
1046             return saved;
1047         }
1048         
1049         
1050         private boolean closeAction() {
1051                 if (!document.isSaved()) {
1052                         ComponentConfigDialog.hideDialog();
1053                         int result = JOptionPane.showConfirmDialog(this, 
1054                                         "Design '"+rocket.getName()+"' has not been saved.  " +
1055                                                         "Do you want to save it?", 
1056                                         "Design not saved", JOptionPane.YES_NO_CANCEL_OPTION, 
1057                                         JOptionPane.QUESTION_MESSAGE);
1058                         if (result == JOptionPane.YES_OPTION) {
1059                                 // Save
1060                                 if (!saveAction())
1061                                         return false;  // If save was interrupted
1062                         } else if (result == JOptionPane.NO_OPTION) {
1063                                 // Don't save: No-op
1064                         } else {
1065                                 // Cancel or close
1066                                 return false;
1067                         }
1068                 }
1069                 
1070                 // Rocket has been saved or discarded
1071                 this.dispose();
1072
1073                 // TODO: LOW: Close only dialogs that have this frame as their parent
1074                 ComponentConfigDialog.hideDialog();
1075                 ComponentAnalysisDialog.hideDialog();
1076                 
1077                 frames.remove(this);
1078                 if (frames.isEmpty())
1079                         System.exit(0);
1080                 return true;
1081         }
1082         
1083         
1084         /**
1085          * Closes this frame if it is replaceable.
1086          */
1087         public void closeIfReplaceable() {
1088                 if (this.replaceable && document.isSaved()) {
1089                         closeAction();
1090                 }
1091         }
1092         
1093         /**
1094          * Open a new design window with a basic rocket+stage.
1095          */
1096         public static void newAction() {
1097                 Rocket rocket = new Rocket();
1098                 Stage stage = new Stage();
1099                 stage.setName("Sustainer");
1100                 rocket.addChild(stage);
1101                 OpenRocketDocument doc = new OpenRocketDocument(rocket);
1102                 doc.setSaved(true);
1103                 
1104                 BasicFrame frame = new BasicFrame(doc);
1105                 frame.replaceable = true;
1106                 frame.setVisible(true);
1107                 ComponentConfigDialog.showDialog(frame, doc, rocket);
1108         }
1109         
1110         /**
1111          * Quit the application.  Confirms saving unsaved designs.  The action of File->Quit.
1112          */
1113         public static void quitAction() {
1114                 for (int i=frames.size()-1; i>=0; i--) {
1115                         if (!frames.get(i).closeAction()) {
1116                                 // Close canceled
1117                                 return;
1118                         }
1119                 }
1120                 // Should not be reached, but just in case
1121                 System.exit(0);
1122         }
1123         
1124         
1125         /**
1126          * Set the title of the frame, taking into account the name of the rocket, file it 
1127          * has been saved to (if any) and saved status.
1128          */
1129         private void setTitle() {
1130                 File file = document.getFile();
1131                 boolean saved = document.isSaved();
1132                 String title;
1133                 
1134                 title = rocket.getName();
1135                 if (file!=null) {
1136                         title = title + " ("+file.getName()+")";
1137                 }
1138                 if (!saved)
1139                         title = "*" + title;
1140                 
1141                 setTitle(title);
1142         }
1143         
1144         
1145         
1146         /**
1147          * Find a currently open BasicFrame containing the specified rocket.  This method
1148          * can be used to map a Rocket to a BasicFrame from GUI methods.
1149          * 
1150          * @param rocket the Rocket.
1151          * @return               the corresponding BasicFrame, or <code>null</code> if none found.
1152          */
1153         public static BasicFrame findFrame(Rocket rocket) {
1154                 for (BasicFrame f: frames) {
1155                         if (f.rocket == rocket)
1156                                 return f;
1157                 }
1158                 return null;
1159         }
1160         
1161         /**
1162          * Find a currently open document by the rocket object.  This method can be used
1163          * to map a Rocket to OpenRocketDocument from GUI methods.
1164          * 
1165          * @param rocket the Rocket.
1166          * @return               the corresponding OpenRocketDocument, or <code>null</code> if not found.
1167          */
1168         public static OpenRocketDocument findDocument(Rocket rocket) {
1169                 for (BasicFrame f: frames) {
1170                         if (f.rocket == rocket)
1171                                 return f.document;
1172                 }
1173                 return null;
1174         }
1175         
1176         
1177         public static void main(final String[] args) {
1178                 
1179                 // Run the actual startup method in the EDT since it can use progress dialogs etc.
1180                 try {
1181                         SwingUtilities.invokeAndWait(new Runnable() {
1182                                 @Override
1183                                 public void run() {
1184                                         runMain(args);
1185                                 }
1186                         });
1187                 } catch (InterruptedException e) {
1188                         e.printStackTrace();
1189                 } catch (InvocationTargetException e) {
1190                         e.printStackTrace();
1191                 }
1192                 
1193         }
1194         
1195         
1196         private static void runMain(String[] args) {
1197                 
1198                 // Start update info fetching
1199                 final UpdateInfoRetriever updateInfo;
1200                 if (Prefs.getCheckUpdates()) {
1201                         updateInfo = new UpdateInfoRetriever();
1202                         updateInfo.start();
1203                 } else {
1204                         updateInfo = null;
1205                 }
1206                 
1207                 
1208                 // Set the best available look-and-feel
1209                 GUIUtil.setBestLAF();
1210
1211                 // Set tooltip delay time.  Tooltips are used in MotorChooserDialog extensively.
1212                 ToolTipManager.sharedInstance().setDismissDelay(30000);
1213                 
1214                 
1215                 // Setup the uncaught exception handler
1216                 ExceptionHandler.registerExceptionHandler();
1217                 
1218                 
1219                 // Load defaults
1220                 Prefs.loadDefaultUnits();
1221                 
1222
1223                 // Load motors etc.
1224                 Databases.fakeMethod();
1225                 
1226                 // Starting action (load files or open new document)
1227                 if (!handleCommandLine(args)) {
1228                         newAction();
1229                 }
1230                 
1231                 
1232                 // Check whether update info has been fetched or whether it needs more time
1233                 checkUpdateStatus(updateInfo);
1234         }
1235         
1236         
1237         private static void checkUpdateStatus(final UpdateInfoRetriever updateInfo) {
1238                 if (updateInfo == null)
1239                         return;
1240
1241                 int delay = 1000;
1242                 if (!updateInfo.isRunning())
1243                         delay = 100;
1244
1245                 final Timer timer = new Timer(delay, null);
1246
1247                 ActionListener listener = new ActionListener() {
1248                         private int count = 5;
1249                         @Override
1250                         public void actionPerformed(ActionEvent e) {
1251                                 if (!updateInfo.isRunning()) {
1252                                         timer.stop();
1253                                         
1254                                         String current = Prefs.getVersion();
1255                                         String last = Prefs.getString(Prefs.LAST_UPDATE, "");
1256
1257                                         UpdateInfo info = updateInfo.getUpdateInfo();
1258                                         if (info != null && info.getLatestVersion() != null &&
1259                                                         !current.equals(info.getLatestVersion()) &&
1260                                                         !last.equals(info.getLatestVersion())) {
1261                                                 
1262                                                 UpdateInfoDialog infoDialog = new UpdateInfoDialog(info);
1263                                                 infoDialog.setVisible(true);
1264                                                 if (infoDialog.isReminderSelected()) {
1265                                                         Prefs.putString(Prefs.LAST_UPDATE, "");
1266                                                 } else {
1267                                                         Prefs.putString(Prefs.LAST_UPDATE, info.getLatestVersion());
1268                                                 }
1269                                         }
1270                                 }
1271                                 count--;
1272                                 if (count <= 0)
1273                                         timer.stop();
1274                         }
1275                 };
1276                 timer.addActionListener(listener);
1277                 timer.start();
1278         }
1279         
1280         
1281         /**
1282          * Handles arguments passed from the command line.  This may be used either
1283          * when starting the first instance of OpenRocket or later when OpenRocket is
1284          * executed again while running.
1285          * 
1286          * @param args  the command-line arguments.
1287          * @return              whether a new frame was opened or similar user desired action was
1288          *                              performed as a result.
1289          */
1290         public static boolean handleCommandLine(String[] args) {
1291                 
1292                 // Check command-line for files
1293                 boolean opened = false;
1294                 for (String file: args) {
1295                         if (open(new File(file), null)) {
1296                                 opened = true;
1297                         }
1298                 }
1299                 return opened;
1300         }
1301
1302 }