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