error things
[jalview.git] / forester / java / src / org / forester / archaeopteryx / MainFrameApplication.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
7 // Copyright (C) 2003-2007 Ethalinda K.S. Cannon
8 // All rights reserved
9 //
10 // This library is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU Lesser General Public
12 // License as published by the Free Software Foundation; either
13 // version 2.1 of the License, or (at your option) any later version.
14 //
15 // This library is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // Lesser General Public License for more details.
19 //
20 // You should have received a copy of the GNU Lesser General Public
21 // License along with this library; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 //
24 // Contact: phylosoft @ gmail . com
25 // WWW: www.phylosoft.org/forester
26
27 package org.forester.archaeopteryx;
28
29 import java.awt.BorderLayout;
30 import java.awt.Font;
31 import java.awt.event.ActionEvent;
32 import java.awt.event.ComponentAdapter;
33 import java.awt.event.ComponentEvent;
34 import java.awt.event.WindowAdapter;
35 import java.awt.event.WindowEvent;
36 import java.io.File;
37 import java.io.FileInputStream;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.net.MalformedURLException;
41 import java.net.URL;
42 import java.util.ArrayList;
43 import java.util.HashSet;
44 import java.util.List;
45 import java.util.Set;
46
47 import javax.swing.ButtonGroup;
48 import javax.swing.JCheckBoxMenuItem;
49 import javax.swing.JFileChooser;
50 import javax.swing.JMenu;
51 import javax.swing.JMenuBar;
52 import javax.swing.JMenuItem;
53 import javax.swing.JOptionPane;
54 import javax.swing.JRadioButtonMenuItem;
55 import javax.swing.UIManager;
56 import javax.swing.UnsupportedLookAndFeelException;
57 import javax.swing.WindowConstants;
58 import javax.swing.event.ChangeEvent;
59 import javax.swing.event.ChangeListener;
60 import javax.swing.filechooser.FileFilter;
61 import javax.swing.plaf.synth.SynthLookAndFeel;
62
63 import org.forester.analysis.TaxonomyDataManager;
64 import org.forester.archaeopteryx.AptxUtil.GraphicsExportType;
65 import org.forester.archaeopteryx.Options.CLADOGRAM_TYPE;
66 import org.forester.archaeopteryx.Options.NODE_LABEL_DIRECTION;
67 import org.forester.archaeopteryx.Options.PHYLOGENY_GRAPHICS_TYPE;
68 import org.forester.archaeopteryx.tools.AncestralTaxonomyInferrer;
69 import org.forester.archaeopteryx.tools.GoAnnotation;
70 import org.forester.archaeopteryx.tools.InferenceManager;
71 import org.forester.archaeopteryx.tools.PhyloInferenceDialog;
72 import org.forester.archaeopteryx.tools.PhylogeneticInferenceOptions;
73 import org.forester.archaeopteryx.tools.PhylogeneticInferrer;
74 import org.forester.archaeopteryx.tools.SequenceDataRetriver;
75 import org.forester.archaeopteryx.webservices.PhylogeniesWebserviceClient;
76 import org.forester.archaeopteryx.webservices.WebservicesManager;
77 import org.forester.io.parsers.FastaParser;
78 import org.forester.io.parsers.GeneralMsaParser;
79 import org.forester.io.parsers.PhylogenyParser;
80 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
81 import org.forester.io.parsers.nhx.NHXParser;
82 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
83 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
84 import org.forester.io.parsers.phyloxml.PhyloXmlParser;
85 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
86 import org.forester.io.parsers.tol.TolParser;
87 import org.forester.io.parsers.util.ParserUtils;
88 import org.forester.io.writers.PhylogenyWriter;
89 import org.forester.io.writers.SequenceWriter;
90 import org.forester.msa.Msa;
91 import org.forester.msa.MsaFormatException;
92 import org.forester.phylogeny.Phylogeny;
93 import org.forester.phylogeny.PhylogenyMethods;
94 import org.forester.phylogeny.PhylogenyNode;
95 import org.forester.phylogeny.PhylogenyNode.NH_CONVERSION_SUPPORT_VALUE_STYLE;
96 import org.forester.phylogeny.data.Confidence;
97 import org.forester.phylogeny.data.Taxonomy;
98 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
99 import org.forester.phylogeny.factories.PhylogenyFactory;
100 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
101 import org.forester.sdi.GSDI;
102 import org.forester.sdi.GSDIR;
103 import org.forester.sdi.SDIException;
104 import org.forester.sdi.SDIR;
105 import org.forester.sequence.Sequence;
106 import org.forester.util.BasicDescriptiveStatistics;
107 import org.forester.util.BasicTable;
108 import org.forester.util.BasicTableParser;
109 import org.forester.util.DescriptiveStatistics;
110 import org.forester.util.ForesterUtil;
111 import org.forester.util.WindowsUtils;
112
113 public final class MainFrameApplication extends MainFrame {
114
115     static final String                      INFER_ANCESTOR_TAXONOMIES             = "Infer Ancestor Taxonomies";
116     static final String                      OBTAIN_DETAILED_TAXONOMIC_INFORMATION = "Obtain Detailed Taxonomic Information";
117     private final static int                 FRAME_X_SIZE                          = 800;
118     private final static int                 FRAME_Y_SIZE                          = 800;
119     // Filters for the file-open dialog (classes defined in this file)
120     private final static NHFilter            nhfilter                              = new NHFilter();
121     private final static NHXFilter           nhxfilter                             = new NHXFilter();
122     private final static XMLFilter           xmlfilter                             = new XMLFilter();
123     private final static TolFilter           tolfilter                             = new TolFilter();
124     private final static NexusFilter         nexusfilter                           = new NexusFilter();
125     private final static PdfFilter           pdffilter                             = new PdfFilter();
126     private final static GraphicsFileFilter  graphicsfilefilter                    = new GraphicsFileFilter();
127     private final static MsaFileFilter       msafilter                             = new MsaFileFilter();
128     private final static SequencesFileFilter seqsfilter                            = new SequencesFileFilter();
129     private final static DefaultFilter       defaultfilter                         = new DefaultFilter();
130     private static final long                serialVersionUID                      = -799735726778865234L;
131     private final JFileChooser               _values_filechooser;
132     private final JFileChooser               _open_filechooser;
133     private final JFileChooser               _msa_filechooser;
134     private final JFileChooser               _seqs_filechooser;
135     private final JFileChooser               _open_filechooser_for_species_tree;
136     private final JFileChooser               _save_filechooser;
137     private final JFileChooser               _writetopdf_filechooser;
138     private final JFileChooser               _writetographics_filechooser;
139     // Analysis menu
140     private JMenu                            _analysis_menu;
141     private JMenuItem                        _load_species_tree_item;
142     private JMenuItem                        _gsdi_item;
143     private JMenuItem                        _gsdir_item;
144     private JMenuItem                        _root_min_dups_item;
145     private JMenuItem                        _root_min_cost_l_item;
146     private JMenuItem                        _lineage_inference;
147     private JMenuItem                        _function_analysis;
148     // Application-only print menu items
149     private JMenuItem                        _print_item;
150     private JMenuItem                        _write_to_pdf_item;
151     private JMenuItem                        _write_to_jpg_item;
152     private JMenuItem                        _write_to_gif_item;
153     private JMenuItem                        _write_to_tif_item;
154     private JMenuItem                        _write_to_png_item;
155     private JMenuItem                        _write_to_bmp_item;
156     private Phylogeny                        _species_tree;
157     private File                             _current_dir;
158     private ButtonGroup                      _radio_group_1;
159     private ButtonGroup                      _radio_group_2;
160     // Others:
161     double                                   _min_not_collapse                     = Constants.MIN_NOT_COLLAPSE_DEFAULT;
162     // Phylogeny Inference menu
163     private JMenu                            _inference_menu;
164     private JMenuItem                        _inference_from_msa_item;
165     private JMenuItem                        _inference_from_seqs_item;
166     // Phylogeny Inference
167     private PhylogeneticInferenceOptions     _phylogenetic_inference_options       = null;
168     private Msa                              _msa                                  = null;
169     private File                             _msa_file                             = null;
170     private List<Sequence>                   _seqs                                 = null;
171     private File                             _seqs_file                            = null;
172     // expression values menu:
173     JMenuItem                                _read_values_jmi;
174
175     private MainFrameApplication( final Phylogeny[] phys, final Configuration config ) {
176         _configuration = config;
177         if ( _configuration == null ) {
178             throw new IllegalArgumentException( "configuration is null" );
179         }
180         setVisible( false );
181         setOptions( Options.createInstance( _configuration ) );
182         _mainpanel = new MainPanel( _configuration, this );
183         _open_filechooser = null;
184         _open_filechooser_for_species_tree = null;
185         _save_filechooser = null;
186         _writetopdf_filechooser = null;
187         _writetographics_filechooser = null;
188         _msa_filechooser = null;
189         _seqs_filechooser = null;
190         _values_filechooser = null;
191         _jmenubar = new JMenuBar();
192         buildFileMenu();
193         buildTypeMenu();
194         _contentpane = getContentPane();
195         _contentpane.setLayout( new BorderLayout() );
196         _contentpane.add( _mainpanel, BorderLayout.CENTER );
197         // App is this big
198         setSize( MainFrameApplication.FRAME_X_SIZE, MainFrameApplication.FRAME_Y_SIZE );
199         // The window listener
200         setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE );
201         addWindowListener( new WindowAdapter() {
202
203             @Override
204             public void windowClosing( final WindowEvent e ) {
205                 exit();
206             }
207         } );
208         //   setVisible( true );
209         if ( ( phys != null ) && ( phys.length > 0 ) ) {
210             AptxUtil.addPhylogeniesToTabs( phys, "", null, _configuration, _mainpanel );
211             validate();
212             getMainPanel().getControlPanel().showWholeAll();
213             getMainPanel().getControlPanel().showWhole();
214         }
215         //activateSaveAllIfNeeded();
216         // ...and its children
217         _contentpane.repaint();
218     }
219
220     private MainFrameApplication( final Phylogeny[] phys, final Configuration config, final String title ) {
221         this( phys, config, title, null );
222     }
223
224     private MainFrameApplication( final Phylogeny[] phys,
225                                   final Configuration config,
226                                   final String title,
227                                   final File current_dir ) {
228         super();
229         _configuration = config;
230         if ( _configuration == null ) {
231             throw new IllegalArgumentException( "configuration is null" );
232         }
233         try {
234             boolean synth_exception = false;
235             if ( Constants.__SYNTH_LF ) {
236                 try {
237                     final SynthLookAndFeel synth = new SynthLookAndFeel();
238                     synth.load( MainFrameApplication.class.getResourceAsStream( "/resources/synth_look_and_feel_1.xml" ),
239                                 MainFrameApplication.class );
240                     UIManager.setLookAndFeel( synth );
241                 }
242                 catch ( final Exception ex ) {
243                     synth_exception = true;
244                     ForesterUtil.printWarningMessage( Constants.PRG_NAME,
245                                                       "could not create synth look and feel: "
246                                                               + ex.getLocalizedMessage() );
247                 }
248             }
249             if ( !Constants.__SYNTH_LF || synth_exception ) {
250                 if ( _configuration.isUseNativeUI() ) {
251                     UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
252                 }
253                 else {
254                     UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
255                 }
256             }
257             //UIManager.setLookAndFeel( "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel" );
258         }
259         catch ( final UnsupportedLookAndFeelException e ) {
260             AptxUtil.dieWithSystemError( "unsupported look and feel: " + e.toString() );
261         }
262         catch ( final ClassNotFoundException e ) {
263             AptxUtil.dieWithSystemError( "class not found exception: " + e.toString() );
264         }
265         catch ( final InstantiationException e ) {
266             AptxUtil.dieWithSystemError( "instantiation exception: " + e.toString() );
267         }
268         catch ( final IllegalAccessException e ) {
269             AptxUtil.dieWithSystemError( "illegal access exception: " + e.toString() );
270         }
271       
272         if ( ( current_dir != null ) && current_dir.canRead() && current_dir.isDirectory() ) {
273             setCurrentDir( current_dir );
274         }
275         // hide until everything is ready
276         setVisible( false );
277         setOptions( Options.createInstance( _configuration ) );
278         setInferenceManager( InferenceManager.createInstance( _configuration ) );
279         setPhylogeneticInferenceOptions( PhylogeneticInferenceOptions.createInstance( _configuration ) );
280         //     _textframe = null; #~~~~
281         _species_tree = null;
282         // set title
283         setTitle( Constants.PRG_NAME + " " + Constants.VERSION + " (" + Constants.PRG_DATE + ")" );
284         _mainpanel = new MainPanel( _configuration, this );
285         // The file dialogs
286         _open_filechooser = new JFileChooser();
287         _open_filechooser.setCurrentDirectory( new File( "." ) );
288         _open_filechooser.setMultiSelectionEnabled( false );
289         _open_filechooser.addChoosableFileFilter( MainFrameApplication.xmlfilter );
290         _open_filechooser.addChoosableFileFilter( MainFrameApplication.nhxfilter );
291         _open_filechooser.addChoosableFileFilter( MainFrameApplication.nhfilter );
292         _open_filechooser.addChoosableFileFilter( MainFrameApplication.nexusfilter );
293         _open_filechooser.addChoosableFileFilter( MainFrameApplication.tolfilter );
294         _open_filechooser.addChoosableFileFilter( _open_filechooser.getAcceptAllFileFilter() );
295         _open_filechooser.setFileFilter( MainFrameApplication.defaultfilter );
296         _open_filechooser_for_species_tree = new JFileChooser();
297         _open_filechooser_for_species_tree.setCurrentDirectory( new File( "." ) );
298         _open_filechooser_for_species_tree.setMultiSelectionEnabled( false );
299         _open_filechooser_for_species_tree.addChoosableFileFilter( MainFrameApplication.xmlfilter );
300         _open_filechooser_for_species_tree.addChoosableFileFilter( MainFrameApplication.tolfilter );
301         _open_filechooser_for_species_tree.setFileFilter( MainFrameApplication.xmlfilter );
302         _save_filechooser = new JFileChooser();
303         _save_filechooser.setCurrentDirectory( new File( "." ) );
304         _save_filechooser.setMultiSelectionEnabled( false );
305         _save_filechooser.setFileFilter( MainFrameApplication.xmlfilter );
306         _save_filechooser.addChoosableFileFilter( MainFrameApplication.nhxfilter );
307         _save_filechooser.addChoosableFileFilter( MainFrameApplication.nhfilter );
308         _save_filechooser.addChoosableFileFilter( MainFrameApplication.nexusfilter );
309         _save_filechooser.addChoosableFileFilter( _save_filechooser.getAcceptAllFileFilter() );
310         _writetopdf_filechooser = new JFileChooser();
311         _writetopdf_filechooser.addChoosableFileFilter( MainFrameApplication.pdffilter );
312         _writetographics_filechooser = new JFileChooser();
313         _writetographics_filechooser.addChoosableFileFilter( MainFrameApplication.graphicsfilefilter );
314         // Msa:
315         _msa_filechooser = new JFileChooser();
316         _msa_filechooser.setName( "Read Multiple Sequence Alignment File" );
317         _msa_filechooser.setCurrentDirectory( new File( "." ) );
318         _msa_filechooser.setMultiSelectionEnabled( false );
319         _msa_filechooser.addChoosableFileFilter( _msa_filechooser.getAcceptAllFileFilter() );
320         _msa_filechooser.addChoosableFileFilter( MainFrameApplication.msafilter );
321         // Seqs:
322         _seqs_filechooser = new JFileChooser();
323         _seqs_filechooser.setName( "Read Sequences File" );
324         _seqs_filechooser.setCurrentDirectory( new File( "." ) );
325         _seqs_filechooser.setMultiSelectionEnabled( false );
326         _seqs_filechooser.addChoosableFileFilter( _seqs_filechooser.getAcceptAllFileFilter() );
327         _seqs_filechooser.addChoosableFileFilter( MainFrameApplication.seqsfilter );
328         // Expression
329         _values_filechooser = new JFileChooser();
330         _values_filechooser.setCurrentDirectory( new File( "." ) );
331         _values_filechooser.setMultiSelectionEnabled( false );
332         // build the menu bar
333         _jmenubar = new JMenuBar();
334         if ( !_configuration.isUseNativeUI() ) {
335             _jmenubar.setBackground( getConfiguration().getGuiMenuBackgroundColor() );
336         }
337         buildFileMenu();
338         if ( Constants.__ALLOW_PHYLOGENETIC_INFERENCE ) {
339             buildPhylogeneticInferenceMenu();
340         }
341         buildAnalysisMenu();
342         buildToolsMenu();
343         buildViewMenu();
344         buildFontSizeMenu();
345         buildOptionsMenu();
346         buildTypeMenu();
347         buildHelpMenu();
348         setJMenuBar( _jmenubar );
349         _jmenubar.add( _help_jmenu );
350         _contentpane = getContentPane();
351         _contentpane.setLayout( new BorderLayout() );
352         _contentpane.add( _mainpanel, BorderLayout.CENTER );
353         // App is this big
354         setSize( MainFrameApplication.FRAME_X_SIZE, MainFrameApplication.FRAME_Y_SIZE );
355         //        addWindowFocusListener( new WindowAdapter() {
356         //
357         //            @Override
358         //            public void windowGainedFocus( WindowEvent e ) {
359         //                requestFocusInWindow();
360         //            }
361         //        } );
362         // The window listener
363         setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE );
364         addWindowListener( new WindowAdapter() {
365
366             @Override
367             public void windowClosing( final WindowEvent e ) {
368                 if ( isUnsavedDataPresent() ) {
369                     final int r = JOptionPane.showConfirmDialog( null,
370                                                                  "Exit despite potentially unsaved changes?",
371                                                                  "Exit?",
372                                                                  JOptionPane.YES_NO_OPTION );
373                     if ( r != JOptionPane.YES_OPTION ) {
374                         return;
375                     }
376                 }
377                 else {
378                     final int r = JOptionPane.showConfirmDialog( null,
379                                                                  "Exit Archaeopteryx?",
380                                                                  "Exit?",
381                                                                  JOptionPane.YES_NO_OPTION );
382                     if ( r != JOptionPane.YES_OPTION ) {
383                         return;
384                     }
385                 }
386                 exit();
387             }
388         } );
389         // The component listener
390         addComponentListener( new ComponentAdapter() {
391
392             @Override
393             public void componentResized( final ComponentEvent e ) {
394                 if ( _mainpanel.getCurrentTreePanel() != null ) {
395                     _mainpanel.getCurrentTreePanel().setParametersForPainting( _mainpanel.getCurrentTreePanel()
396                                                                                        .getWidth(),
397                                                                                _mainpanel.getCurrentTreePanel()
398                                                                                        .getHeight(),
399                                                                                false );
400                 }
401             }
402         } );
403         requestFocusInWindow();
404         // addKeyListener( this );
405         setVisible( true );
406         if ( ( phys != null ) && ( phys.length > 0 ) ) {
407             AptxUtil.addPhylogeniesToTabs( phys, title, null, _configuration, _mainpanel );
408             validate();
409             getMainPanel().getControlPanel().showWholeAll();
410             getMainPanel().getControlPanel().showWhole();
411         }
412         activateSaveAllIfNeeded();
413         // ...and its children
414         _contentpane.repaint();
415         System.gc();
416     }
417
418     private MainFrameApplication( final Phylogeny[] phys, final String config_file, final String title ) {
419         // Reads the config file (false, false => not url, not applet):
420         this( phys, new Configuration( config_file, false, false, true ), title );
421     }
422
423     @Override
424     public void actionPerformed( final ActionEvent e ) {
425         try {
426             super.actionPerformed( e );
427             final Object o = e.getSource();
428             // Handle app-specific actions here:
429             if ( o == _open_item ) {
430                 readPhylogeniesFromFile();
431             }
432             else if ( o == _save_item ) {
433                 writeToFile( _mainpanel.getCurrentPhylogeny() );
434                 // If subtree currently displayed, save it, instead of complete
435                 // tree.
436             }
437             else if ( o == _new_item ) {
438                 newTree();
439             }
440             else if ( o == _save_all_item ) {
441                 writeAllToFile();
442             }
443             else if ( o == _close_item ) {
444                 closeCurrentPane();
445             }
446             else if ( o == _write_to_pdf_item ) {
447                 writeToPdf( _mainpanel.getCurrentPhylogeny() );
448             }
449             else if ( o == _write_to_jpg_item ) {
450                 writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.JPG );
451             }
452             else if ( o == _write_to_png_item ) {
453                 writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.PNG );
454             }
455             else if ( o == _write_to_gif_item ) {
456                 writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.GIF );
457             }
458             else if ( o == _write_to_tif_item ) {
459                 writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.TIFF );
460             }
461             else if ( o == _write_to_bmp_item ) {
462                 writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.BMP );
463             }
464             else if ( o == _print_item ) {
465                 print();
466             }
467             else if ( o == _load_species_tree_item ) {
468                 readSpeciesTreeFromFile();
469             }
470             else if ( o == _lineage_inference ) {
471                 if ( isSubtreeDisplayed() ) {
472                     JOptionPane.showMessageDialog( this,
473                                                    "Subtree is shown.",
474                                                    "Cannot infer ancestral taxonomies",
475                                                    JOptionPane.ERROR_MESSAGE );
476                     return;
477                 }
478                 executeLineageInference();
479             }
480             else if ( o == _function_analysis ) {
481                 executeFunctionAnalysis();
482             }
483             else if ( o == _obtain_detailed_taxonomic_information_jmi ) {
484                 if ( isSubtreeDisplayed() ) {
485                     return;
486                 }
487                 obtainDetailedTaxonomicInformation();
488             }
489             else if ( o == _obtain_detailed_taxonomic_information_deleting_jmi ) {
490                 if ( isSubtreeDisplayed() ) {
491                     return;
492                 }
493                 obtainDetailedTaxonomicInformationDelete();
494             }
495             else if ( o == _obtain_seq_information_jmi ) {
496                 obtainSequenceInformation();
497             }
498             else if ( o == _read_values_jmi ) {
499                 if ( isSubtreeDisplayed() ) {
500                     return;
501                 }
502                 addExpressionValuesFromFile();
503             }
504             else if ( o == _move_node_names_to_tax_sn_jmi ) {
505                 moveNodeNamesToTaxSn();
506             }
507             else if ( o == _move_node_names_to_seq_names_jmi ) {
508                 moveNodeNamesToSeqNames();
509             }
510             else if ( o == _extract_tax_code_from_node_names_jmi ) {
511                 extractTaxCodeFromNodeNames();
512             }
513             else if ( o == _gsdi_item ) {
514                 if ( isSubtreeDisplayed() ) {
515                     return;
516                 }
517                 executeGSDI();
518             }
519             else if ( o == _gsdir_item ) {
520                 if ( isSubtreeDisplayed() ) {
521                     return;
522                 }
523                 executeGSDIR();
524             }
525             else if ( o == _root_min_dups_item ) {
526                 if ( isSubtreeDisplayed() ) {
527                     return;
528                 }
529                 executeSDIR( false );
530             }
531             else if ( o == _root_min_cost_l_item ) {
532                 if ( isSubtreeDisplayed() ) {
533                     return;
534                 }
535                 executeSDIR( true );
536             }
537             else if ( o == _graphics_export_visible_only_cbmi ) {
538                 updateOptions( getOptions() );
539             }
540             else if ( o == _antialias_print_cbmi ) {
541                 updateOptions( getOptions() );
542             }
543             else if ( o == _print_black_and_white_cbmi ) {
544                 updateOptions( getOptions() );
545             }
546             else if ( o == _print_using_actual_size_cbmi ) {
547                 updateOptions( getOptions() );
548             }
549             else if ( o == _graphics_export_using_actual_size_cbmi ) {
550                 updateOptions( getOptions() );
551             }
552             else if ( o == _print_size_mi ) {
553                 choosePrintSize();
554             }
555             else if ( o == _choose_pdf_width_mi ) {
556                 choosePdfWidth();
557             }
558             else if ( o == _internal_number_are_confidence_for_nh_parsing_cbmi ) {
559                 updateOptions( getOptions() );
560             }
561             else if ( o == _replace_underscores_cbmi ) {
562                 if ( ( _extract_taxonomy_no_rbmi != null ) && !_extract_taxonomy_no_rbmi.isSelected() ) {
563                     _extract_taxonomy_no_rbmi.setSelected( true );
564                 }
565                 updateOptions( getOptions() );
566             }
567             else if ( o == _collapse_below_threshold ) {
568                 if ( isSubtreeDisplayed() ) {
569                     return;
570                 }
571                 collapseBelowThreshold();
572             }
573             else if ( ( o == _extract_taxonomy_pfam_rbmi ) || ( o == _extract_taxonomy_yes_rbmi ) ) {
574                 if ( _replace_underscores_cbmi != null ) {
575                     _replace_underscores_cbmi.setSelected( false );
576                 }
577                 updateOptions( getOptions() );
578             }
579             else if ( o == _inference_from_msa_item ) {
580                 executePhyleneticInference( false );
581             }
582             else if ( o == _inference_from_seqs_item ) {
583                 executePhyleneticInference( true );
584             }
585             _contentpane.repaint();
586         }
587         catch ( final Exception ex ) {
588             AptxUtil.unexpectedException( ex );
589         }
590         catch ( final Error err ) {
591             AptxUtil.unexpectedError( err );
592         }
593     }
594
595     public void end() {
596         _mainpanel.terminate();
597         _contentpane.removeAll();
598         setVisible( false );
599         dispose();
600     }
601
602     @Override
603     public MainPanel getMainPanel() {
604         return _mainpanel;
605     }
606
607     public Msa getMsa() {
608         return _msa;
609     }
610
611     public File getMsaFile() {
612         return _msa_file;
613     }
614
615     public List<Sequence> getSeqs() {
616         return _seqs;
617     }
618
619     public File getSeqsFile() {
620         return _seqs_file;
621     }
622
623     public void readMsaFromFile() {
624         // Set an initial directory if none set yet
625         final File my_dir = getCurrentDir();
626         _msa_filechooser.setMultiSelectionEnabled( false );
627         // Open file-open dialog and set current directory
628         if ( my_dir != null ) {
629             _msa_filechooser.setCurrentDirectory( my_dir );
630         }
631         final int result = _msa_filechooser.showOpenDialog( _contentpane );
632         // All done: get the msa
633         final File file = _msa_filechooser.getSelectedFile();
634         setCurrentDir( _msa_filechooser.getCurrentDirectory() );
635         if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) {
636             setMsaFile( null );
637             setMsa( null );
638             Msa msa = null;
639             try {
640                 final InputStream is = new FileInputStream( file );
641                 if ( FastaParser.isLikelyFasta( file ) ) {
642                     msa = FastaParser.parseMsa( is );
643                 }
644                 else {
645                     msa = GeneralMsaParser.parse( is );
646                 }
647             }
648             catch ( final MsaFormatException e ) {
649                 try {
650                     _mainpanel.getCurrentTreePanel().setArrowCursor();
651                 }
652                 catch ( final Exception ex ) {
653                     // Do nothing.
654                 }
655                 JOptionPane.showMessageDialog( this,
656                                                e.getLocalizedMessage(),
657                                                "Multiple sequence alignment format error",
658                                                JOptionPane.ERROR_MESSAGE );
659                 return;
660             }
661             catch ( final IOException e ) {
662                 try {
663                     _mainpanel.getCurrentTreePanel().setArrowCursor();
664                 }
665                 catch ( final Exception ex ) {
666                     // Do nothing.
667                 }
668                 JOptionPane.showMessageDialog( this,
669                                                e.getLocalizedMessage(),
670                                                "Failed to read multiple sequence alignment",
671                                                JOptionPane.ERROR_MESSAGE );
672                 return;
673             }
674             catch ( final IllegalArgumentException e ) {
675                 try {
676                     _mainpanel.getCurrentTreePanel().setArrowCursor();
677                 }
678                 catch ( final Exception ex ) {
679                     // Do nothing.
680                 }
681                 JOptionPane.showMessageDialog( this,
682                                                e.getLocalizedMessage(),
683                                                "Unexpected error during reading of multiple sequence alignment",
684                                                JOptionPane.ERROR_MESSAGE );
685                 return;
686             }
687             catch ( final Exception e ) {
688                 try {
689                     _mainpanel.getCurrentTreePanel().setArrowCursor();
690                 }
691                 catch ( final Exception ex ) {
692                     // Do nothing.
693                 }
694                 e.printStackTrace();
695                 JOptionPane.showMessageDialog( this,
696                                                e.getLocalizedMessage(),
697                                                "Unexpected error during reading of multiple sequence alignment",
698                                                JOptionPane.ERROR_MESSAGE );
699                 return;
700             }
701             if ( ( msa == null ) || ( msa.getNumberOfSequences() < 1 ) ) {
702                 JOptionPane.showMessageDialog( this,
703                                                "Multiple sequence alignment is empty",
704                                                "Illegal Multiple Sequence Alignment",
705                                                JOptionPane.ERROR_MESSAGE );
706                 return;
707             }
708             if ( msa.getNumberOfSequences() < 4 ) {
709                 JOptionPane.showMessageDialog( this,
710                                                "Multiple sequence alignment needs to contain at least 3 sequences",
711                                                "Illegal multiple sequence alignment",
712                                                JOptionPane.ERROR_MESSAGE );
713                 return;
714             }
715             if ( msa.getLength() < 2 ) {
716                 JOptionPane.showMessageDialog( this,
717                                                "Multiple sequence alignment needs to contain at least 2 residues",
718                                                "Illegal multiple sequence alignment",
719                                                JOptionPane.ERROR_MESSAGE );
720                 return;
721             }
722             System.gc();
723             setMsaFile( _msa_filechooser.getSelectedFile() );
724             setMsa( msa );
725         }
726     }
727
728     public void readSeqsFromFile() {
729         // Set an initial directory if none set yet
730         final File my_dir = getCurrentDir();
731         _seqs_filechooser.setMultiSelectionEnabled( false );
732         // Open file-open dialog and set current directory
733         if ( my_dir != null ) {
734             _seqs_filechooser.setCurrentDirectory( my_dir );
735         }
736         final int result = _seqs_filechooser.showOpenDialog( _contentpane );
737         // All done: get the seqs
738         final File file = _seqs_filechooser.getSelectedFile();
739         setCurrentDir( _seqs_filechooser.getCurrentDirectory() );
740         if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) {
741             setSeqsFile( null );
742             setSeqs( null );
743             List<Sequence> seqs = null;
744             try {
745                 if ( FastaParser.isLikelyFasta( new FileInputStream( file ) ) ) {
746                     seqs = FastaParser.parse( new FileInputStream( file ) );
747                     for( final Sequence seq : seqs ) {
748                         System.out.println( SequenceWriter.toFasta( seq, 60 ) );
749                     }
750                 }
751                 else {
752                     //TODO error
753                 }
754             }
755             catch ( final MsaFormatException e ) {
756                 try {
757                     _mainpanel.getCurrentTreePanel().setArrowCursor();
758                 }
759                 catch ( final Exception ex ) {
760                     // Do nothing.
761                 }
762                 JOptionPane.showMessageDialog( this,
763                                                e.getLocalizedMessage(),
764                                                "Multiple sequence file format error",
765                                                JOptionPane.ERROR_MESSAGE );
766                 return;
767             }
768             catch ( final IOException e ) {
769                 try {
770                     _mainpanel.getCurrentTreePanel().setArrowCursor();
771                 }
772                 catch ( final Exception ex ) {
773                     // Do nothing.
774                 }
775                 JOptionPane.showMessageDialog( this,
776                                                e.getLocalizedMessage(),
777                                                "Failed to read multiple sequence file",
778                                                JOptionPane.ERROR_MESSAGE );
779                 return;
780             }
781             catch ( final IllegalArgumentException e ) {
782                 try {
783                     _mainpanel.getCurrentTreePanel().setArrowCursor();
784                 }
785                 catch ( final Exception ex ) {
786                     // Do nothing.
787                 }
788                 JOptionPane.showMessageDialog( this,
789                                                e.getLocalizedMessage(),
790                                                "Unexpected error during reading of multiple sequence file",
791                                                JOptionPane.ERROR_MESSAGE );
792                 return;
793             }
794             catch ( final Exception e ) {
795                 try {
796                     _mainpanel.getCurrentTreePanel().setArrowCursor();
797                 }
798                 catch ( final Exception ex ) {
799                     // Do nothing.
800                 }
801                 e.printStackTrace();
802                 JOptionPane.showMessageDialog( this,
803                                                e.getLocalizedMessage(),
804                                                "Unexpected error during reading of multiple sequence file",
805                                                JOptionPane.ERROR_MESSAGE );
806                 return;
807             }
808             if ( ( seqs == null ) || ( seqs.size() < 1 ) ) {
809                 JOptionPane.showMessageDialog( this,
810                                                "Multiple sequence file is empty",
811                                                "Illegal multiple sequence file",
812                                                JOptionPane.ERROR_MESSAGE );
813                 return;
814             }
815             if ( seqs.size() < 4 ) {
816                 JOptionPane.showMessageDialog( this,
817                                                "Multiple sequence file needs to contain at least 3 sequences",
818                                                "Illegal multiple sequence file",
819                                                JOptionPane.ERROR_MESSAGE );
820                 return;
821             }
822             //  if ( msa.getLength() < 2 ) {
823             //       JOptionPane.showMessageDialog( this,
824             //                                      "Multiple sequence alignment needs to contain at least 2 residues",
825             //                                      "Illegal multiple sequence file",
826             //                                      JOptionPane.ERROR_MESSAGE );
827             //       return;
828             //   }
829             System.gc();
830             setSeqsFile( _seqs_filechooser.getSelectedFile() );
831             setSeqs( seqs );
832         }
833     }
834
835     void buildAnalysisMenu() {
836         _analysis_menu = MainFrame.createMenu( "Analysis", getConfiguration() );
837         _analysis_menu.add( _gsdi_item = new JMenuItem( "GSDI (Generalized Speciation Duplication Inference)" ) );
838         _analysis_menu.add( _gsdir_item = new JMenuItem( "GSDIR (re-rooting)" ) );
839         _analysis_menu.addSeparator();
840         _analysis_menu.add( _root_min_dups_item = new JMenuItem( "Root by Minimizing Duplications | Height (SDI)" ) );
841         _analysis_menu.add( _root_min_cost_l_item = new JMenuItem( "Root by Minimizing Cost L | Height (SDI)" ) );
842         _analysis_menu.addSeparator();
843         _analysis_menu.add( _load_species_tree_item = new JMenuItem( "Load Species Tree..." ) );
844         customizeJMenuItem( _gsdi_item );
845         customizeJMenuItem( _gsdir_item );
846         customizeJMenuItem( _root_min_dups_item );
847         customizeJMenuItem( _root_min_cost_l_item );
848         customizeJMenuItem( _load_species_tree_item );
849         _analysis_menu.addSeparator();
850         _analysis_menu.add( _lineage_inference = new JMenuItem( INFER_ANCESTOR_TAXONOMIES ) );
851         customizeJMenuItem( _lineage_inference );
852         _lineage_inference.setToolTipText( "Inference of ancestor taxonomies/lineages" );
853         _jmenubar.add( _analysis_menu );
854     }
855
856     @Override
857     void buildFileMenu() {
858         _file_jmenu = MainFrame.createMenu( "File", getConfiguration() );
859         _file_jmenu.add( _open_item = new JMenuItem( "Read Tree from File..." ) );
860         _file_jmenu.addSeparator();
861         _file_jmenu.add( _open_url_item = new JMenuItem( "Read Tree from URL/Webservice..." ) );
862         _file_jmenu.addSeparator();
863         final WebservicesManager webservices_manager = WebservicesManager.getInstance();
864         _load_phylogeny_from_webservice_menu_items = new JMenuItem[ webservices_manager
865                 .getAvailablePhylogeniesWebserviceClients().size() ];
866         for( int i = 0; i < webservices_manager.getAvailablePhylogeniesWebserviceClients().size(); ++i ) {
867             final PhylogeniesWebserviceClient client = webservices_manager.getAvailablePhylogeniesWebserviceClient( i );
868             _load_phylogeny_from_webservice_menu_items[ i ] = new JMenuItem( client.getMenuName() );
869             _file_jmenu.add( _load_phylogeny_from_webservice_menu_items[ i ] );
870         }
871         if ( getConfiguration().isEditable() ) {
872             _file_jmenu.addSeparator();
873             _file_jmenu.add( _new_item = new JMenuItem( "New" ) );
874             _new_item.setToolTipText( "to create a new tree with one node, as source for manual tree construction" );
875         }
876         _file_jmenu.addSeparator();
877         _file_jmenu.add( _save_item = new JMenuItem( "Save Tree As..." ) );
878         _file_jmenu.add( _save_all_item = new JMenuItem( "Save All Trees As..." ) );
879         _save_all_item.setToolTipText( "Write all phylogenies to one file." );
880         _save_all_item.setEnabled( false );
881         _file_jmenu.addSeparator();
882         _file_jmenu.add( _write_to_pdf_item = new JMenuItem( "Export to PDF file ..." ) );
883         if ( AptxUtil.canWriteFormat( "tif" ) || AptxUtil.canWriteFormat( "tiff" ) || AptxUtil.canWriteFormat( "TIF" ) ) {
884             _file_jmenu.add( _write_to_tif_item = new JMenuItem( "Export to TIFF file..." ) );
885         }
886         _file_jmenu.add( _write_to_png_item = new JMenuItem( "Export to PNG file..." ) );
887         _file_jmenu.add( _write_to_jpg_item = new JMenuItem( "Export to JPG file..." ) );
888         if ( AptxUtil.canWriteFormat( "gif" ) ) {
889             _file_jmenu.add( _write_to_gif_item = new JMenuItem( "Export to GIF file..." ) );
890         }
891         if ( AptxUtil.canWriteFormat( "bmp" ) ) {
892             _file_jmenu.add( _write_to_bmp_item = new JMenuItem( "Export to BMP file..." ) );
893         }
894         _file_jmenu.addSeparator();
895         _file_jmenu.add( _print_item = new JMenuItem( "Print..." ) );
896         _file_jmenu.addSeparator();
897         _file_jmenu.add( _close_item = new JMenuItem( "Close Tab" ) );
898         _close_item.setToolTipText( "To close the current pane." );
899         _close_item.setEnabled( true );
900         _file_jmenu.addSeparator();
901         _file_jmenu.add( _exit_item = new JMenuItem( "Exit" ) );
902         // For print in color option item
903         customizeJMenuItem( _open_item );
904         _open_item
905                 .setFont( new Font( _open_item.getFont().getFontName(), Font.BOLD, _open_item.getFont().getSize() + 4 ) );
906         customizeJMenuItem( _open_url_item );
907         for( int i = 0; i < webservices_manager.getAvailablePhylogeniesWebserviceClients().size(); ++i ) {
908             customizeJMenuItem( _load_phylogeny_from_webservice_menu_items[ i ] );
909         }
910         customizeJMenuItem( _save_item );
911         if ( getConfiguration().isEditable() ) {
912             customizeJMenuItem( _new_item );
913         }
914         customizeJMenuItem( _close_item );
915         customizeJMenuItem( _save_all_item );
916         customizeJMenuItem( _write_to_pdf_item );
917         customizeJMenuItem( _write_to_png_item );
918         customizeJMenuItem( _write_to_jpg_item );
919         customizeJMenuItem( _write_to_gif_item );
920         customizeJMenuItem( _write_to_tif_item );
921         customizeJMenuItem( _write_to_bmp_item );
922         customizeJMenuItem( _print_item );
923         customizeJMenuItem( _exit_item );
924         _jmenubar.add( _file_jmenu );
925     }
926
927     void buildOptionsMenu() {
928         _options_jmenu = MainFrame.createMenu( OPTIONS_HEADER, getConfiguration() );
929         _options_jmenu.addChangeListener( new ChangeListener() {
930
931             @Override
932             public void stateChanged( final ChangeEvent e ) {
933                 MainFrame.setOvPlacementColorChooseMenuItem( _overview_placment_mi, getOptions() );
934                 MainFrame.setTextColorChooseMenuItem( _switch_colors_mi, getCurrentTreePanel() );
935                 MainFrame
936                         .setTextMinSupportMenuItem( _choose_minimal_confidence_mi, getOptions(), getCurrentTreePanel() );
937                 MainFrame.setTextForFontChooserMenuItem( _choose_font_mi, MainFrame
938                         .createCurrentFontDesc( getMainPanel().getTreeFontSet() ) );
939                 setTextForGraphicsSizeChooserMenuItem( _print_size_mi, getOptions() );
940                 setTextForPdfLineWidthChooserMenuItem( _choose_pdf_width_mi, getOptions() );
941                 MainFrame.updateOptionsMenuDependingOnPhylogenyType( getMainPanel(),
942                                                                      _show_scale_cbmi,
943                                                                      _show_branch_length_values_cbmi,
944                                                                      _non_lined_up_cladograms_rbmi,
945                                                                      _uniform_cladograms_rbmi,
946                                                                      _ext_node_dependent_cladogram_rbmi,
947                                                                      _label_direction_cbmi );
948                 MainFrame.setCycleNodeFillMenuItem( _cycle_node_fill_mi, getOptions() );
949                 MainFrame.setCycleNodeShapeMenuItem( _cycle_node_shape_mi, getOptions() );
950                 MainFrame.setTextNodeSizeMenuItem( _choose_node_size_mi, getOptions() );
951             }
952         } );
953         _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( DISPLAY_SUBHEADER ), getConfiguration() ) );
954         _options_jmenu
955                 .add( _ext_node_dependent_cladogram_rbmi = new JRadioButtonMenuItem( MainFrame.NONUNIFORM_CLADOGRAMS_LABEL ) );
956         _options_jmenu.add( _uniform_cladograms_rbmi = new JRadioButtonMenuItem( MainFrame.UNIFORM_CLADOGRAMS_LABEL ) );
957         _options_jmenu.add( _non_lined_up_cladograms_rbmi = new JRadioButtonMenuItem( NON_LINED_UP_CLADOGRAMS_LABEL ) );
958         _radio_group_1 = new ButtonGroup();
959         _radio_group_1.add( _ext_node_dependent_cladogram_rbmi );
960         _radio_group_1.add( _uniform_cladograms_rbmi );
961         _radio_group_1.add( _non_lined_up_cladograms_rbmi );
962         _options_jmenu.add( _show_overview_cbmi = new JCheckBoxMenuItem( SHOW_OVERVIEW_LABEL ) );
963         _options_jmenu.add( _show_scale_cbmi = new JCheckBoxMenuItem( DISPLAY_SCALE_LABEL ) );
964         _options_jmenu
965                 .add( _show_branch_length_values_cbmi = new JCheckBoxMenuItem( DISPLAY_BRANCH_LENGTH_VALUES_LABEL ) );
966         _options_jmenu.add( _show_confidence_stddev_cbmi = new JCheckBoxMenuItem( SHOW_CONF_STDDEV_LABEL ) );
967         _options_jmenu.add( _show_default_node_shapes_cbmi = new JCheckBoxMenuItem( DISPLAY_NODE_BOXES_LABEL ) );
968         _options_jmenu
969                 .add( _taxonomy_colorize_node_shapes_cbmi = new JCheckBoxMenuItem( MainFrame.TAXONOMY_COLORIZE_NODE_SHAPES_LABEL ) );
970         _options_jmenu.add( _cycle_node_shape_mi = new JMenuItem( MainFrame.CYCLE_NODE_SHAPE_LABEL ) );
971         _options_jmenu.add( _cycle_node_fill_mi = new JMenuItem( MainFrame.CYCLE_NODE_FILL_LABEL ) );
972         _options_jmenu.add( _choose_node_size_mi = new JMenuItem( MainFrame.CHOOSE_NODE_SIZE_LABEL ) );
973         _options_jmenu.add( _label_direction_cbmi = new JCheckBoxMenuItem( LABEL_DIRECTION_LABEL ) );
974         _label_direction_cbmi.setToolTipText( LABEL_DIRECTION_TIP );
975         _options_jmenu.add( _color_labels_same_as_parent_branch = new JCheckBoxMenuItem( COLOR_LABELS_LABEL ) );
976         _color_labels_same_as_parent_branch.setToolTipText( MainFrame.COLOR_LABELS_TIP );
977         _options_jmenu.add( _abbreviate_scientific_names = new JCheckBoxMenuItem( ABBREV_SN_LABEL ) );
978         _options_jmenu.add( _screen_antialias_cbmi = new JCheckBoxMenuItem( SCREEN_ANTIALIAS_LABEL ) );
979         _options_jmenu.add( _background_gradient_cbmi = new JCheckBoxMenuItem( BG_GRAD_LABEL ) );
980         if ( getConfiguration().doDisplayOption( Configuration.show_domain_architectures ) ) {
981             _options_jmenu.add( _show_domain_labels = new JCheckBoxMenuItem( SHOW_DOMAIN_LABELS_LABEL ) );
982         }
983         _options_jmenu.add( _choose_minimal_confidence_mi = new JMenuItem( "" ) );
984         _options_jmenu.add( _overview_placment_mi = new JMenuItem( "" ) );
985         _options_jmenu.add( _switch_colors_mi = new JMenuItem( "" ) );
986         _options_jmenu.add( _choose_font_mi = new JMenuItem( "" ) );
987         _options_jmenu.addSeparator();
988         _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( SEARCH_SUBHEADER ), getConfiguration() ) );
989         _options_jmenu.add( _search_case_senstive_cbmi = new JCheckBoxMenuItem( SEARCH_CASE_SENSITIVE_LABEL ) );
990         _options_jmenu.add( _search_whole_words_only_cbmi = new JCheckBoxMenuItem( SEARCH_TERMS_ONLY_LABEL ) );
991         _options_jmenu.add( _inverse_search_result_cbmi = new JCheckBoxMenuItem( INVERSE_SEARCH_RESULT_LABEL ) );
992         _options_jmenu.addSeparator();
993         _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( "Graphics Export & Printing:" ),
994                                                       getConfiguration() ) );
995         _options_jmenu.add( _antialias_print_cbmi = new JCheckBoxMenuItem( "Antialias" ) );
996         _options_jmenu.add( _print_black_and_white_cbmi = new JCheckBoxMenuItem( "Export in Black and White" ) );
997         _options_jmenu
998                 .add( _print_using_actual_size_cbmi = new JCheckBoxMenuItem( "Use Current Image Size for PDF export and Printing" ) );
999         _options_jmenu
1000                 .add( _graphics_export_using_actual_size_cbmi = new JCheckBoxMenuItem( "Use Current Image Size for PNG, JPG, and GIF export" ) );
1001         _options_jmenu
1002                 .add( _graphics_export_visible_only_cbmi = new JCheckBoxMenuItem( "Limit to Visible ('Screenshot') for PNG, JPG, and GIF export" ) );
1003         _options_jmenu.add( _print_size_mi = new JMenuItem( "" ) );
1004         _options_jmenu.add( _choose_pdf_width_mi = new JMenuItem( "" ) );
1005         _options_jmenu.addSeparator();
1006         _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( "Newick/NHX/Nexus Input:" ), getConfiguration() ) );
1007         _options_jmenu
1008                 .add( _internal_number_are_confidence_for_nh_parsing_cbmi = new JCheckBoxMenuItem( "Internal Node Names are Confidence Values" ) );
1009         _options_jmenu.add( _replace_underscores_cbmi = new JCheckBoxMenuItem( "Replace Underscores with Spaces" ) );
1010         //
1011         _options_jmenu.add( _extract_taxonomy_no_rbmi = new JRadioButtonMenuItem( "No Taxonomy Extraction" ) );
1012         _options_jmenu
1013                 .add( _extract_taxonomy_pfam_rbmi = new JRadioButtonMenuItem( "Extract Taxonomy Codes from Pfam-style Node Names" ) );
1014         _extract_taxonomy_pfam_rbmi
1015                 .setToolTipText( "To extract 5-letter taxonomy codes from node names in the form of \"BCL2_MOUSE/134-298\"" );
1016         _options_jmenu
1017                 .add( _extract_taxonomy_yes_rbmi = new JRadioButtonMenuItem( "Extract Taxonomy Codes from Node Names" ) );
1018         _extract_taxonomy_yes_rbmi
1019                 .setToolTipText( "To extract 5-letter taxonomy codes from node names in the form of \"BCL2_MOUSE\" or \"BCL2_MOUSE B-cell lymphoma 2...\"" );
1020         _radio_group_2 = new ButtonGroup();
1021         _radio_group_2.add( _extract_taxonomy_no_rbmi );
1022         _radio_group_2.add( _extract_taxonomy_pfam_rbmi );
1023         _radio_group_2.add( _extract_taxonomy_yes_rbmi );
1024         // 
1025         _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( "Newick/Nexus Output:" ), getConfiguration() ) );
1026         _options_jmenu
1027                 .add( _use_brackets_for_conf_in_nh_export_cbmi = new JCheckBoxMenuItem( USE_BRACKETS_FOR_CONF_IN_NH_LABEL ) );
1028         _use_brackets_for_conf_in_nh_export_cbmi
1029                 .setToolTipText( "e.g. \"0.1[90]\" for a branch with support 90 and a length of 0.1" );
1030         _options_jmenu
1031                 .add( _use_internal_names_for_conf_in_nh_export_cbmi = new JCheckBoxMenuItem( USE_INTERNAL_NAMES_FOR_CONF_IN_NH_LABEL ) );
1032         customizeJMenuItem( _choose_font_mi );
1033         customizeJMenuItem( _choose_minimal_confidence_mi );
1034         customizeJMenuItem( _switch_colors_mi );
1035         customizeJMenuItem( _print_size_mi );
1036         customizeJMenuItem( _choose_pdf_width_mi );
1037         customizeJMenuItem( _overview_placment_mi );
1038         customizeCheckBoxMenuItem( _show_default_node_shapes_cbmi, getOptions().isShowDefaultNodeShapes() );
1039         customizeCheckBoxMenuItem( _taxonomy_colorize_node_shapes_cbmi, getOptions().isTaxonomyColorizeNodeShapes() );
1040         customizeJMenuItem( _cycle_node_shape_mi );
1041         customizeJMenuItem( _cycle_node_fill_mi );
1042         customizeJMenuItem( _choose_node_size_mi );
1043         customizeCheckBoxMenuItem( _color_labels_same_as_parent_branch, getOptions().isColorLabelsSameAsParentBranch() );
1044         customizeCheckBoxMenuItem( _screen_antialias_cbmi, getOptions().isAntialiasScreen() );
1045         customizeCheckBoxMenuItem( _background_gradient_cbmi, getOptions().isBackgroundColorGradient() );
1046         customizeCheckBoxMenuItem( _show_domain_labels, getOptions().isShowDomainLabels() );
1047         customizeCheckBoxMenuItem( _abbreviate_scientific_names, getOptions().isAbbreviateScientificTaxonNames() );
1048         customizeCheckBoxMenuItem( _search_case_senstive_cbmi, getOptions().isSearchCaseSensitive() );
1049         customizeCheckBoxMenuItem( _show_scale_cbmi, getOptions().isShowScale() );
1050         customizeRadioButtonMenuItem( _non_lined_up_cladograms_rbmi,
1051                                       getOptions().getCladogramType() == CLADOGRAM_TYPE.NON_LINED_UP );
1052         customizeRadioButtonMenuItem( _uniform_cladograms_rbmi,
1053                                       getOptions().getCladogramType() == CLADOGRAM_TYPE.TOTAL_NODE_SUM_DEP );
1054         customizeRadioButtonMenuItem( _ext_node_dependent_cladogram_rbmi,
1055                                       getOptions().getCladogramType() == CLADOGRAM_TYPE.EXT_NODE_SUM_DEP );
1056         customizeCheckBoxMenuItem( _show_branch_length_values_cbmi, getOptions().isShowBranchLengthValues() );
1057         customizeCheckBoxMenuItem( _show_overview_cbmi, getOptions().isShowOverview() );
1058         customizeCheckBoxMenuItem( _label_direction_cbmi,
1059                                    getOptions().getNodeLabelDirection() == NODE_LABEL_DIRECTION.RADIAL );
1060         customizeCheckBoxMenuItem( _antialias_print_cbmi, getOptions().isAntialiasPrint() );
1061         customizeCheckBoxMenuItem( _print_black_and_white_cbmi, getOptions().isPrintBlackAndWhite() );
1062         customizeCheckBoxMenuItem( _internal_number_are_confidence_for_nh_parsing_cbmi, getOptions()
1063                 .isInternalNumberAreConfidenceForNhParsing() );
1064         customizeRadioButtonMenuItem( _extract_taxonomy_no_rbmi,
1065                                       getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.NO );
1066         customizeRadioButtonMenuItem( _extract_taxonomy_yes_rbmi,
1067                                       getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.YES );
1068         customizeRadioButtonMenuItem( _extract_taxonomy_pfam_rbmi,
1069                                       getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.PFAM_STYLE_ONLY );
1070         customizeCheckBoxMenuItem( _replace_underscores_cbmi, getOptions().isReplaceUnderscoresInNhParsing() );
1071         customizeCheckBoxMenuItem( _search_whole_words_only_cbmi, getOptions().isMatchWholeTermsOnly() );
1072         customizeCheckBoxMenuItem( _inverse_search_result_cbmi, getOptions().isInverseSearchResult() );
1073         customizeCheckBoxMenuItem( _graphics_export_visible_only_cbmi, getOptions().isGraphicsExportVisibleOnly() );
1074         customizeCheckBoxMenuItem( _print_using_actual_size_cbmi, getOptions().isPrintUsingActualSize() );
1075         customizeCheckBoxMenuItem( _graphics_export_using_actual_size_cbmi, getOptions()
1076                 .isGraphicsExportUsingActualSize() );
1077         customizeCheckBoxMenuItem( _show_confidence_stddev_cbmi, getOptions().isShowConfidenceStddev() );
1078         customizeCheckBoxMenuItem( _use_brackets_for_conf_in_nh_export_cbmi, getOptions()
1079                 .getNhConversionSupportValueStyle() == NH_CONVERSION_SUPPORT_VALUE_STYLE.IN_SQUARE_BRACKETS );
1080         customizeCheckBoxMenuItem( _use_internal_names_for_conf_in_nh_export_cbmi, getOptions()
1081                 .getNhConversionSupportValueStyle() == NH_CONVERSION_SUPPORT_VALUE_STYLE.AS_INTERNAL_NODE_NAMES );
1082         _jmenubar.add( _options_jmenu );
1083     }
1084
1085     void buildPhylogeneticInferenceMenu() {
1086         final InferenceManager im = getInferenceManager();
1087         _inference_menu = MainFrame.createMenu( "Inference", getConfiguration() );
1088         _inference_menu.add( _inference_from_msa_item = new JMenuItem( "From Multiple Sequence Alignment..." ) );
1089         customizeJMenuItem( _inference_from_msa_item );
1090         _inference_from_msa_item.setToolTipText( "Basic phylogenetic inference from MSA" );
1091         if ( im.canDoMsa() ) {
1092             _inference_menu.add( _inference_from_seqs_item = new JMenuItem( "From Unaligned Sequences..." ) );
1093             customizeJMenuItem( _inference_from_seqs_item );
1094             _inference_from_seqs_item
1095                     .setToolTipText( "Basic phylogenetic inference including multiple sequence alignment" );
1096         }
1097         else {
1098             _inference_menu
1099                     .add( _inference_from_seqs_item = new JMenuItem( "From Unaligned Sequences (no program found)" ) );
1100             customizeJMenuItem( _inference_from_seqs_item );
1101             _inference_from_seqs_item.setEnabled( false );
1102         }
1103         _jmenubar.add( _inference_menu );
1104     }
1105
1106     void buildToolsMenu() {
1107         _tools_menu = createMenu( "Tools", getConfiguration() );
1108         _tools_menu.add( _confcolor_item = new JMenuItem( "Colorize Branches Depending on Confidence" ) );
1109         customizeJMenuItem( _confcolor_item );
1110         _tools_menu.add( _color_rank_jmi = new JMenuItem( "Colorize Subtrees via Taxonomic Rank" ) );
1111         customizeJMenuItem( _color_rank_jmi );
1112         _color_rank_jmi.setToolTipText( "for example, at \"Class\" level, colorize mammal specific subtree red" );
1113         _tools_menu.add( _taxcolor_item = new JMenuItem( "Taxonomy Colorize Branches" ) );
1114         customizeJMenuItem( _taxcolor_item );
1115         _tools_menu.add( _remove_branch_color_item = new JMenuItem( "Delete Branch Colors" ) );
1116         _remove_branch_color_item.setToolTipText( "To delete branch color values from the current phylogeny" );
1117         customizeJMenuItem( _remove_branch_color_item );
1118         _tools_menu.addSeparator();
1119         _tools_menu.add( _annotate_item = new JMenuItem( "Annotate Sequences of Selected Nodes" ) );
1120         customizeJMenuItem( _annotate_item );
1121         _tools_menu.addSeparator();
1122         _tools_menu.add( _midpoint_root_item = new JMenuItem( "Midpoint-Root" ) );
1123         customizeJMenuItem( _midpoint_root_item );
1124         _tools_menu.addSeparator();
1125         _tools_menu.add( _collapse_species_specific_subtrees = new JMenuItem( "Collapse Species-Specific Subtrees" ) );
1126         customizeJMenuItem( _collapse_species_specific_subtrees );
1127         _tools_menu
1128                 .add( _collapse_below_threshold = new JMenuItem( "Collapse Branches with Confidence Below Threshold into Multifurcations" ) );
1129         customizeJMenuItem( _collapse_below_threshold );
1130         _collapse_below_threshold
1131                 .setToolTipText( "To collapse branches with confidence values below a threshold into multifurcations (in the case of multiple confidences per branch: without at least one confidence value above a threshold)" );
1132         _tools_menu.addSeparator();
1133         _tools_menu
1134                 .add( _move_node_names_to_tax_sn_jmi = new JMenuItem( "Transfer Node Names to Taxonomic Scientific Names" ) );
1135         customizeJMenuItem( _move_node_names_to_tax_sn_jmi );
1136         _move_node_names_to_tax_sn_jmi.setToolTipText( "To interpret node names as taxonomic scientific names" );
1137         _tools_menu.add( _move_node_names_to_seq_names_jmi = new JMenuItem( "Transfer Node Names to Sequence Names" ) );
1138         customizeJMenuItem( _move_node_names_to_seq_names_jmi );
1139         _move_node_names_to_seq_names_jmi.setToolTipText( "To interpret node names as sequence (protein, gene) names" );
1140         _tools_menu
1141                 .add( _extract_tax_code_from_node_names_jmi = new JMenuItem( "Extract Taxonomic Codes from Node Names" ) );
1142         customizeJMenuItem( _extract_tax_code_from_node_names_jmi );
1143         _extract_tax_code_from_node_names_jmi
1144                 .setToolTipText( "To extract taxonomic codes (mnemonics) from nodes names in the form of 'xyz_ECOLI'" );
1145         _tools_menu.addSeparator();
1146         _tools_menu
1147                 .add( _obtain_detailed_taxonomic_information_jmi = new JMenuItem( OBTAIN_DETAILED_TAXONOMIC_INFORMATION ) );
1148         customizeJMenuItem( _obtain_detailed_taxonomic_information_jmi );
1149         _obtain_detailed_taxonomic_information_jmi
1150                 .setToolTipText( "To add additional taxonomic information (from UniProt Taxonomy)" );
1151         _tools_menu
1152                 .add( _obtain_detailed_taxonomic_information_deleting_jmi = new JMenuItem( "Obtain Detailed Taxonomic Information (deletes nodes!)" ) );
1153         customizeJMenuItem( _obtain_detailed_taxonomic_information_deleting_jmi );
1154         _obtain_detailed_taxonomic_information_deleting_jmi
1155                 .setToolTipText( "To add additional taxonomic information, deletes nodes for which taxonomy cannot found (from UniProt Taxonomy)" );
1156         _tools_menu.add( _obtain_seq_information_jmi = new JMenuItem( "Obtain Sequence Information" ) );
1157         customizeJMenuItem( _obtain_seq_information_jmi );
1158         _obtain_seq_information_jmi.setToolTipText( "To add additional sequence information" );
1159         _tools_menu.addSeparator();
1160         if ( !Constants.__RELEASE ) {
1161             _tools_menu.add( _function_analysis = new JMenuItem( "Add UniProtKB Annotations" ) );
1162             customizeJMenuItem( _function_analysis );
1163             _function_analysis
1164                     .setToolTipText( "To add UniProtKB annotations for sequences with appropriate identifiers" );
1165             _tools_menu.addSeparator();
1166         }
1167         _tools_menu.add( _read_values_jmi = new JMenuItem( "Read Vector/Expression Values" ) );
1168         customizeJMenuItem( _read_values_jmi );
1169         _read_values_jmi.setToolTipText( "To add vector (e.g. gene expression) values (beta)" );
1170         _jmenubar.add( _tools_menu );
1171     }
1172
1173     @Override
1174     void close() {
1175         if ( isUnsavedDataPresent() ) {
1176             final int r = JOptionPane.showConfirmDialog( this,
1177                                                          "Exit despite potentially unsaved changes?",
1178                                                          "Exit?",
1179                                                          JOptionPane.YES_NO_OPTION );
1180             if ( r != JOptionPane.YES_OPTION ) {
1181                 return;
1182             }
1183         }
1184         exit();
1185     }
1186
1187     void executeFunctionAnalysis() {
1188         if ( ( _mainpanel.getCurrentPhylogeny() == null ) || ( _mainpanel.getCurrentPhylogeny().isEmpty() ) ) {
1189             return;
1190         }
1191         final GoAnnotation a = new GoAnnotation( this,
1192                                                  _mainpanel.getCurrentTreePanel(),
1193                                                  _mainpanel.getCurrentPhylogeny() );
1194         new Thread( a ).start();
1195     }
1196
1197     void executeGSDI() {
1198         if ( !isOKforSDI( false, true ) ) {
1199             return;
1200         }
1201         if ( !_mainpanel.getCurrentPhylogeny().isRooted() ) {
1202             JOptionPane.showMessageDialog( this,
1203                                            "Gene tree is not rooted.",
1204                                            "Cannot execute GSDI",
1205                                            JOptionPane.ERROR_MESSAGE );
1206             return;
1207         }
1208         final Phylogeny gene_tree = _mainpanel.getCurrentPhylogeny().copy();
1209         gene_tree.setAllNodesToNotCollapse();
1210         gene_tree.recalculateNumberOfExternalDescendants( false );
1211         GSDI gsdi = null;
1212         final Phylogeny species_tree = _species_tree.copy();
1213         try {
1214             gsdi = new GSDI( gene_tree, species_tree, false, true, true );
1215         }
1216         catch ( final SDIException e ) {
1217             JOptionPane.showMessageDialog( this,
1218                                            e.getLocalizedMessage(),
1219                                            "Error during GSDI",
1220                                            JOptionPane.ERROR_MESSAGE );
1221             return;
1222         }
1223         catch ( final Exception e ) {
1224             AptxUtil.unexpectedException( e );
1225             return;
1226         }
1227         gene_tree.setRerootable( false );
1228         _mainpanel.getCurrentTreePanel().setTree( gene_tree );
1229         _mainpanel.getCurrentPhylogeny().clearHashIdToNodeMap();
1230         _mainpanel.getCurrentPhylogeny().recalculateNumberOfExternalDescendants( true );
1231         _mainpanel.getCurrentTreePanel().resetNodeIdToDistToLeafMap();
1232         _mainpanel.getCurrentTreePanel().setEdited( true );
1233         getControlPanel().setShowEvents( true );
1234         showWhole();
1235         final int selected = _mainpanel.getTabbedPane().getSelectedIndex();
1236         _mainpanel.addPhylogenyInNewTab( species_tree, getConfiguration(), "species tree", null );
1237         showWhole();
1238         _mainpanel.getTabbedPane().setSelectedIndex( selected );
1239         showWhole();
1240         _mainpanel.getCurrentTreePanel().setEdited( true );
1241         JOptionPane.showMessageDialog( this, "Duplications: " + gsdi.getDuplicationsSum() + "\n"
1242                 + "Potential duplications: " + gsdi.getSpeciationOrDuplicationEventsSum() + "\n" + "Speciations: "
1243                 + gsdi.getSpeciationsSum(), "GSDI successfully completed", JOptionPane.INFORMATION_MESSAGE );
1244     }
1245
1246     void executeGSDIR() {
1247         if ( !isOKforSDI( false, true ) ) {
1248             return;
1249         }
1250         final Phylogeny gene_tree = _mainpanel.getCurrentPhylogeny().copy();
1251         gene_tree.setAllNodesToNotCollapse();
1252         gene_tree.recalculateNumberOfExternalDescendants( false );
1253         GSDIR gsdir = null;
1254         final Phylogeny species_tree = _species_tree.copy();
1255         try {
1256             gsdir = new GSDIR( gene_tree, species_tree, true, true );
1257         }
1258         catch ( final SDIException e ) {
1259             JOptionPane.showMessageDialog( this,
1260                                            e.getLocalizedMessage(),
1261                                            "Error during GSDIR",
1262                                            JOptionPane.ERROR_MESSAGE );
1263             return;
1264         }
1265         catch ( final Exception e ) {
1266             AptxUtil.unexpectedException( e );
1267             return;
1268         }
1269         final List<Phylogeny> assigned_trees = gsdir.getMinDuplicationsSumGeneTrees();
1270         final List<Integer> shortests = GSDIR.getIndexesOfShortestTree( assigned_trees );
1271         final Phylogeny result_gene_tree = assigned_trees.get( shortests.get( 0 ) );
1272         result_gene_tree.setRerootable( false );
1273         result_gene_tree.clearHashIdToNodeMap();
1274         result_gene_tree.recalculateNumberOfExternalDescendants( true );
1275         _mainpanel.addPhylogenyInNewTab( result_gene_tree, getConfiguration(), "gene tree", null );
1276         getControlPanel().setShowEvents( true );
1277         showWhole();
1278         final int selected = _mainpanel.getTabbedPane().getSelectedIndex();
1279         _mainpanel.addPhylogenyInNewTab( species_tree, getConfiguration(), "species tree", null );
1280         showWhole();
1281         _mainpanel.getTabbedPane().setSelectedIndex( selected );
1282         showWhole();
1283         _mainpanel.getCurrentTreePanel().setEdited( true );
1284         JOptionPane.showMessageDialog( this,
1285                                        "Duplications (min): " + gsdir.getMinDuplicationsSum() + "\n" + "Speciations: "
1286                                                + gsdir.getSpeciationsSum() + "\n"
1287                                                + "Number of root positions minimizing duplications sum: "
1288                                                + gsdir.getMinDuplicationsSumGeneTrees().size() + "\n"
1289                                                + "Number of shortest trees: " + shortests.size(),
1290                                        "GSDIR successfully completed",
1291                                        JOptionPane.INFORMATION_MESSAGE );
1292     }
1293
1294     void executeLineageInference() {
1295         if ( ( _mainpanel.getCurrentPhylogeny() == null ) || ( _mainpanel.getCurrentPhylogeny().isEmpty() ) ) {
1296             return;
1297         }
1298         if ( !_mainpanel.getCurrentPhylogeny().isRooted() ) {
1299             JOptionPane.showMessageDialog( this,
1300                                            "Phylogeny is not rooted.",
1301                                            "Cannot infer ancestral taxonomies",
1302                                            JOptionPane.ERROR_MESSAGE );
1303             return;
1304         }
1305         final AncestralTaxonomyInferrer inferrer = new AncestralTaxonomyInferrer( this,
1306                                                                                   _mainpanel.getCurrentTreePanel(),
1307                                                                                   _mainpanel.getCurrentPhylogeny()
1308                                                                                           .copy() );
1309         new Thread( inferrer ).start();
1310     }
1311
1312     void executeSDIR( final boolean minimize_cost ) {
1313         if ( !isOKforSDI( true, true ) ) {
1314             return;
1315         }
1316         Phylogeny gene_tree = _mainpanel.getCurrentPhylogeny().copy();
1317         final SDIR sdiunrooted = new SDIR();
1318         gene_tree.setAllNodesToNotCollapse();
1319         gene_tree.recalculateNumberOfExternalDescendants( false );
1320         try {
1321             gene_tree = sdiunrooted.infer( gene_tree, _species_tree, minimize_cost, // minimize cost
1322                                            !minimize_cost, // minimize sum of dups
1323                                            true, // minimize height
1324                                            true, // return tree(s)
1325                                            1 )[ 0 ]; // # of trees to return
1326         }
1327         catch ( final Exception e ) {
1328             JOptionPane.showMessageDialog( this, e.toString(), "Error during SDIR", JOptionPane.ERROR_MESSAGE );
1329             return;
1330         }
1331         final int duplications = sdiunrooted.getMinimalDuplications();
1332         gene_tree.setRerootable( false );
1333         _mainpanel.getCurrentTreePanel().setTree( gene_tree );
1334         getControlPanel().setShowEvents( true );
1335         showWhole();
1336         _mainpanel.getCurrentTreePanel().setEdited( true );
1337         JOptionPane.showMessageDialog( this,
1338                                        "Number of duplications: " + duplications,
1339                                        "SDIR successfully completed",
1340                                        JOptionPane.INFORMATION_MESSAGE );
1341     }
1342
1343     void exit() {
1344         removeAllTextFrames();
1345         _mainpanel.terminate();
1346         _contentpane.removeAll();
1347         setVisible( false );
1348         dispose();
1349         System.exit( 0 );
1350     }
1351
1352     boolean isOKforSDI( final boolean species_tree_has_to_binary, final boolean gene_tree_has_to_binary ) {
1353         if ( ( _mainpanel.getCurrentPhylogeny() == null ) || _mainpanel.getCurrentPhylogeny().isEmpty() ) {
1354             return false;
1355         }
1356         else if ( ( _species_tree == null ) || _species_tree.isEmpty() ) {
1357             JOptionPane.showMessageDialog( this,
1358                                            "No species tree loaded",
1359                                            "Cannot execute SDI",
1360                                            JOptionPane.ERROR_MESSAGE );
1361             return false;
1362         }
1363         else if ( species_tree_has_to_binary && !_species_tree.isCompletelyBinary() ) {
1364             JOptionPane.showMessageDialog( this,
1365                                            "Species tree is not completely binary",
1366                                            "Cannot execute SDI",
1367                                            JOptionPane.ERROR_MESSAGE );
1368             return false;
1369         }
1370         else if ( gene_tree_has_to_binary && !_mainpanel.getCurrentPhylogeny().isCompletelyBinary() ) {
1371             JOptionPane.showMessageDialog( this,
1372                                            "Gene tree is not completely binary",
1373                                            "Cannot execute SDI",
1374                                            JOptionPane.ERROR_MESSAGE );
1375             return false;
1376         }
1377         else {
1378             return true;
1379         }
1380     }
1381
1382     @Override
1383     void readPhylogeniesFromURL() {
1384         URL url = null;
1385         Phylogeny[] phys = null;
1386         final String message = "Please enter a complete URL, for example \"http://www.phyloxml.org/examples/apaf.xml\"";
1387         final String url_string = JOptionPane.showInputDialog( this,
1388                                                                message,
1389                                                                "Use URL/webservice to obtain a phylogeny",
1390                                                                JOptionPane.QUESTION_MESSAGE );
1391         boolean nhx_or_nexus = false;
1392         if ( ( url_string != null ) && ( url_string.length() > 0 ) ) {
1393             try {
1394                 url = new URL( url_string );
1395                 PhylogenyParser parser = null;
1396                 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
1397                     parser = new TolParser();
1398                 }
1399                 else {
1400                     parser = ParserUtils.createParserDependingOnUrlContents( url, getConfiguration()
1401                             .isValidatePhyloXmlAgainstSchema() );
1402                 }
1403                 if ( parser instanceof NexusPhylogeniesParser ) {
1404                     nhx_or_nexus = true;
1405                 }
1406                 else if ( parser instanceof NHXParser ) {
1407                     nhx_or_nexus = true;
1408                 }
1409                 if ( _mainpanel.getCurrentTreePanel() != null ) {
1410                     _mainpanel.getCurrentTreePanel().setWaitCursor();
1411                 }
1412                 else {
1413                     _mainpanel.setWaitCursor();
1414                 }
1415                 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
1416                 phys = factory.create( url.openStream(), parser );
1417             }
1418             catch ( final MalformedURLException e ) {
1419                 JOptionPane.showMessageDialog( this,
1420                                                "Malformed URL: " + url + "\n" + e.getLocalizedMessage(),
1421                                                "Malformed URL",
1422                                                JOptionPane.ERROR_MESSAGE );
1423             }
1424             catch ( final IOException e ) {
1425                 JOptionPane.showMessageDialog( this,
1426                                                "Could not read from " + url + "\n"
1427                                                        + ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ),
1428                                                "Failed to read URL",
1429                                                JOptionPane.ERROR_MESSAGE );
1430             }
1431             catch ( final Exception e ) {
1432                 JOptionPane.showMessageDialog( this,
1433                                                ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ),
1434                                                "Unexpected Exception",
1435                                                JOptionPane.ERROR_MESSAGE );
1436             }
1437             finally {
1438                 if ( _mainpanel.getCurrentTreePanel() != null ) {
1439                     _mainpanel.getCurrentTreePanel().setArrowCursor();
1440                 }
1441                 else {
1442                     _mainpanel.setArrowCursor();
1443                 }
1444             }
1445             if ( ( phys != null ) && ( phys.length > 0 ) ) {
1446                 if ( nhx_or_nexus && getOptions().isInternalNumberAreConfidenceForNhParsing() ) {
1447                     for( final Phylogeny phy : phys ) {
1448                         PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
1449                     }
1450                 }
1451                 AptxUtil.addPhylogeniesToTabs( phys,
1452                                                new File( url.getFile() ).getName(),
1453                                                new File( url.getFile() ).toString(),
1454                                                getConfiguration(),
1455                                                getMainPanel() );
1456                 _mainpanel.getControlPanel().showWhole();
1457             }
1458         }
1459         activateSaveAllIfNeeded();
1460         System.gc();
1461     }
1462
1463     void setMsa( final Msa msa ) {
1464         _msa = msa;
1465     }
1466
1467     void setMsaFile( final File msa_file ) {
1468         _msa_file = msa_file;
1469     }
1470
1471     void setSeqs( final List<Sequence> seqs ) {
1472         _seqs = seqs;
1473     }
1474
1475     void setSeqsFile( final File seqs_file ) {
1476         _seqs_file = seqs_file;
1477     }
1478
1479     void writePhylogenyToGraphicsFile( final String file_name, final GraphicsExportType type ) {
1480         _mainpanel.getCurrentTreePanel().setParametersForPainting( _mainpanel.getCurrentTreePanel().getWidth(),
1481                                                                    _mainpanel.getCurrentTreePanel().getHeight(),
1482                                                                    true );
1483         String file_written_to = "";
1484         boolean error = false;
1485         try {
1486             file_written_to = AptxUtil.writePhylogenyToGraphicsFile( file_name,
1487                                                                      _mainpanel.getCurrentTreePanel().getWidth(),
1488                                                                      _mainpanel.getCurrentTreePanel().getHeight(),
1489                                                                      _mainpanel.getCurrentTreePanel(),
1490                                                                      _mainpanel.getControlPanel(),
1491                                                                      type,
1492                                                                      getOptions() );
1493         }
1494         catch ( final IOException e ) {
1495             error = true;
1496             JOptionPane.showMessageDialog( this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE );
1497         }
1498         if ( !error ) {
1499             if ( ( file_written_to != null ) && ( file_written_to.length() > 0 ) ) {
1500                 JOptionPane.showMessageDialog( this,
1501                                                "Wrote image to: " + file_written_to,
1502                                                "Graphics Export",
1503                                                JOptionPane.INFORMATION_MESSAGE );
1504             }
1505             else {
1506                 JOptionPane.showMessageDialog( this,
1507                                                "There was an unknown problem when attempting to write to an image file: \""
1508                                                        + file_name + "\"",
1509                                                "Error",
1510                                                JOptionPane.ERROR_MESSAGE );
1511             }
1512         }
1513         _contentpane.repaint();
1514     }
1515
1516     private void addExpressionValuesFromFile() {
1517         if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) ) {
1518             JOptionPane.showMessageDialog( this,
1519                                            "Need to load evolutionary tree first",
1520                                            "Can Not Read Expression Values",
1521                                            JOptionPane.WARNING_MESSAGE );
1522             return;
1523         }
1524         final File my_dir = getCurrentDir();
1525         if ( my_dir != null ) {
1526             _values_filechooser.setCurrentDirectory( my_dir );
1527         }
1528         final int result = _values_filechooser.showOpenDialog( _contentpane );
1529         final File file = _values_filechooser.getSelectedFile();
1530         if ( ( file != null ) && ( file.length() > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
1531             BasicTable<String> t = null;
1532             try {
1533                 t = BasicTableParser.parse( file, "\t" );
1534                 if ( t.getNumberOfColumns() < 2 ) {
1535                     t = BasicTableParser.parse( file, "," );
1536                 }
1537                 if ( t.getNumberOfColumns() < 2 ) {
1538                     t = BasicTableParser.parse( file, " " );
1539                 }
1540             }
1541             catch ( final IOException e ) {
1542                 JOptionPane.showMessageDialog( this,
1543                                                e.getMessage(),
1544                                                "Could Not Read Expression Value Table",
1545                                                JOptionPane.ERROR_MESSAGE );
1546                 return;
1547             }
1548             if ( t.getNumberOfColumns() < 2 ) {
1549                 JOptionPane.showMessageDialog( this,
1550                                                "Table contains " + t.getNumberOfColumns() + " column(s)",
1551                                                "Problem with Expression Value Table",
1552                                                JOptionPane.ERROR_MESSAGE );
1553                 return;
1554             }
1555             if ( t.getNumberOfRows() < 1 ) {
1556                 JOptionPane.showMessageDialog( this,
1557                                                "Table contains zero rows",
1558                                                "Problem with Expression Value Table",
1559                                                JOptionPane.ERROR_MESSAGE );
1560                 return;
1561             }
1562             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1563             if ( t.getNumberOfRows() != phy.getNumberOfExternalNodes() ) {
1564                 JOptionPane.showMessageDialog( this,
1565                                                "Table contains " + t.getNumberOfRows() + " rows, but tree contains "
1566                                                        + phy.getNumberOfExternalNodes() + " external nodes",
1567                                                "Warning",
1568                                                JOptionPane.WARNING_MESSAGE );
1569             }
1570             final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
1571             int not_found = 0;
1572             for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1573                 final PhylogenyNode node = iter.next();
1574                 final String node_name = node.getName();
1575                 if ( !ForesterUtil.isEmpty( node_name ) ) {
1576                     int row = -1;
1577                     try {
1578                         row = t.findRow( node_name );
1579                     }
1580                     catch ( final IllegalArgumentException e ) {
1581                         JOptionPane
1582                                 .showMessageDialog( this,
1583                                                     e.getMessage(),
1584                                                     "Error Mapping Node Identifiers to Expression Value Identifiers",
1585                                                     JOptionPane.ERROR_MESSAGE );
1586                         return;
1587                     }
1588                     if ( row < 0 ) {
1589                         if ( node.isExternal() ) {
1590                             not_found++;
1591                         }
1592                         continue;
1593                     }
1594                     final List<Double> l = new ArrayList<Double>();
1595                     for( int col = 1; col < t.getNumberOfColumns(); ++col ) {
1596                         double d = -100;
1597                         try {
1598                             d = Double.parseDouble( t.getValueAsString( col, row ) );
1599                         }
1600                         catch ( final NumberFormatException e ) {
1601                             JOptionPane.showMessageDialog( this,
1602                                                            "Could not parse \"" + t.getValueAsString( col, row )
1603                                                                    + "\" into a decimal value",
1604                                                            "Issue with Expression Value Table",
1605                                                            JOptionPane.ERROR_MESSAGE );
1606                             return;
1607                         }
1608                         stats.addValue( d );
1609                         l.add( d );
1610                     }
1611                     if ( !l.isEmpty() ) {
1612                         if ( node.getNodeData().getProperties() != null ) {
1613                             node.getNodeData().getProperties()
1614                                     .removePropertiesWithGivenReferencePrefix( PhyloXmlUtil.VECTOR_PROPERTY_REF );
1615                         }
1616                         node.getNodeData().setVector( l );
1617                     }
1618                 }
1619             }
1620             if ( not_found > 0 ) {
1621                 JOptionPane.showMessageDialog( this, "Could not fine expression values for " + not_found
1622                         + " external node(s)", "Warning", JOptionPane.WARNING_MESSAGE );
1623             }
1624             getCurrentTreePanel().setStatisticsForExpressionValues( stats );
1625         }
1626     }
1627
1628     private void choosePdfWidth() {
1629         final String s = ( String ) JOptionPane.showInputDialog( this,
1630                                                                  "Please enter the default line width for PDF export.\n"
1631                                                                          + "[current value: "
1632                                                                          + getOptions().getPrintLineWidth() + "]\n",
1633                                                                  "Line Width for PDF Export",
1634                                                                  JOptionPane.QUESTION_MESSAGE,
1635                                                                  null,
1636                                                                  null,
1637                                                                  getOptions().getPrintLineWidth() );
1638         if ( !ForesterUtil.isEmpty( s ) ) {
1639             boolean success = true;
1640             float f = 0.0f;
1641             final String m_str = s.trim();
1642             if ( !ForesterUtil.isEmpty( m_str ) ) {
1643                 try {
1644                     f = Float.parseFloat( m_str );
1645                 }
1646                 catch ( final Exception ex ) {
1647                     success = false;
1648                 }
1649             }
1650             else {
1651                 success = false;
1652             }
1653             if ( success && ( f > 0.0 ) ) {
1654                 getOptions().setPrintLineWidth( f );
1655             }
1656         }
1657     }
1658
1659     private void choosePrintSize() {
1660         final String s = ( String ) JOptionPane.showInputDialog( this,
1661                                                                  "Please enter values for width and height,\nseparated by a comma.\n"
1662                                                                          + "[current values: "
1663                                                                          + getOptions().getPrintSizeX() + ", "
1664                                                                          + getOptions().getPrintSizeY() + "]\n"
1665                                                                          + "[A4: " + Constants.A4_SIZE_X + ", "
1666                                                                          + Constants.A4_SIZE_Y + "]\n" + "[US Letter: "
1667                                                                          + Constants.US_LETTER_SIZE_X + ", "
1668                                                                          + Constants.US_LETTER_SIZE_Y + "]",
1669                                                                  "Default Size for Graphics Export",
1670                                                                  JOptionPane.QUESTION_MESSAGE,
1671                                                                  null,
1672                                                                  null,
1673                                                                  getOptions().getPrintSizeX() + ", "
1674                                                                          + getOptions().getPrintSizeY() );
1675         if ( !ForesterUtil.isEmpty( s ) && ( s.indexOf( ',' ) > 0 ) ) {
1676             boolean success = true;
1677             int x = 0;
1678             int y = 0;
1679             final String[] str_ary = s.split( "," );
1680             if ( str_ary.length == 2 ) {
1681                 final String x_str = str_ary[ 0 ].trim();
1682                 final String y_str = str_ary[ 1 ].trim();
1683                 if ( !ForesterUtil.isEmpty( x_str ) && !ForesterUtil.isEmpty( y_str ) ) {
1684                     try {
1685                         x = Integer.parseInt( x_str );
1686                         y = Integer.parseInt( y_str );
1687                     }
1688                     catch ( final Exception ex ) {
1689                         success = false;
1690                     }
1691                 }
1692                 else {
1693                     success = false;
1694                 }
1695             }
1696             else {
1697                 success = false;
1698             }
1699             if ( success && ( x > 1 ) && ( y > 1 ) ) {
1700                 getOptions().setPrintSizeX( x );
1701                 getOptions().setPrintSizeY( y );
1702             }
1703         }
1704     }
1705
1706     private void closeCurrentPane() {
1707         if ( getMainPanel().getCurrentTreePanel() != null ) {
1708             if ( getMainPanel().getCurrentTreePanel().isEdited() ) {
1709                 final int r = JOptionPane.showConfirmDialog( this,
1710                                                              "Close tab despite potentially unsaved changes?",
1711                                                              "Close Tab?",
1712                                                              JOptionPane.YES_NO_OPTION );
1713                 if ( r != JOptionPane.YES_OPTION ) {
1714                     return;
1715                 }
1716             }
1717             getMainPanel().closeCurrentPane();
1718             activateSaveAllIfNeeded();
1719         }
1720     }
1721
1722     private void collapse( final Phylogeny phy, final double m ) {
1723         final PhylogenyNodeIterator it = phy.iteratorPostorder();
1724         final List<PhylogenyNode> to_be_removed = new ArrayList<PhylogenyNode>();
1725         double min_support = Double.MAX_VALUE;
1726         boolean conf_present = false;
1727         while ( it.hasNext() ) {
1728             final PhylogenyNode n = it.next();
1729             if ( !n.isExternal() && !n.isRoot() ) {
1730                 final List<Confidence> c = n.getBranchData().getConfidences();
1731                 if ( ( c != null ) && ( c.size() > 0 ) ) {
1732                     conf_present = true;
1733                     double max = 0;
1734                     for( final Confidence confidence : c ) {
1735                         if ( confidence.getValue() > max ) {
1736                             max = confidence.getValue();
1737                         }
1738                     }
1739                     if ( max < getMinNotCollapseConfidenceValue() ) {
1740                         to_be_removed.add( n );
1741                     }
1742                     if ( max < min_support ) {
1743                         min_support = max;
1744                     }
1745                 }
1746             }
1747         }
1748         if ( conf_present ) {
1749             for( final PhylogenyNode node : to_be_removed ) {
1750                 PhylogenyMethods.removeNode( node, phy );
1751             }
1752             if ( to_be_removed.size() > 0 ) {
1753                 phy.externalNodesHaveChanged();
1754                 phy.clearHashIdToNodeMap();
1755                 phy.recalculateNumberOfExternalDescendants( true );
1756                 getCurrentTreePanel().resetNodeIdToDistToLeafMap();
1757                 getCurrentTreePanel().updateSetOfCollapsedExternalNodes();
1758                 getCurrentTreePanel().calculateLongestExtNodeInfo();
1759                 getCurrentTreePanel().setNodeInPreorderToNull();
1760                 getCurrentTreePanel().recalculateMaxDistanceToRoot();
1761                 getCurrentTreePanel().resetPreferredSize();
1762                 getCurrentTreePanel().setEdited( true );
1763                 getCurrentTreePanel().repaint();
1764                 repaint();
1765             }
1766             if ( to_be_removed.size() > 0 ) {
1767                 JOptionPane.showMessageDialog( this, "Collapsed " + to_be_removed.size()
1768                         + " branches with\nconfidence values below " + getMinNotCollapseConfidenceValue(), "Collapsed "
1769                         + to_be_removed.size() + " branches", JOptionPane.INFORMATION_MESSAGE );
1770             }
1771             else {
1772                 JOptionPane.showMessageDialog( this, "No branch collapsed,\nminimum confidence value per branch is "
1773                         + min_support, "No branch collapsed", JOptionPane.INFORMATION_MESSAGE );
1774             }
1775         }
1776         else {
1777             JOptionPane.showMessageDialog( this,
1778                                            "No branch collapsed because no confidence values present",
1779                                            "No confidence values present",
1780                                            JOptionPane.INFORMATION_MESSAGE );
1781         }
1782     }
1783
1784     private void collapseBelowThreshold() {
1785         if ( getCurrentTreePanel() != null ) {
1786             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1787             if ( ( phy != null ) && !phy.isEmpty() ) {
1788                 final String s = ( String ) JOptionPane.showInputDialog( this,
1789                                                                          "Please enter the minimum confidence value\n",
1790                                                                          "Minimal Confidence Value",
1791                                                                          JOptionPane.QUESTION_MESSAGE,
1792                                                                          null,
1793                                                                          null,
1794                                                                          getMinNotCollapseConfidenceValue() );
1795                 if ( !ForesterUtil.isEmpty( s ) ) {
1796                     boolean success = true;
1797                     double m = 0.0;
1798                     final String m_str = s.trim();
1799                     if ( !ForesterUtil.isEmpty( m_str ) ) {
1800                         try {
1801                             m = Double.parseDouble( m_str );
1802                         }
1803                         catch ( final Exception ex ) {
1804                             success = false;
1805                         }
1806                     }
1807                     else {
1808                         success = false;
1809                     }
1810                     if ( success && ( m >= 0.0 ) ) {
1811                         setMinNotCollapseConfidenceValue( m );
1812                         collapse( phy, m );
1813                     }
1814                 }
1815             }
1816         }
1817     }
1818
1819     private PhyloXmlParser createPhyloXmlParser() {
1820         PhyloXmlParser xml_parser = null;
1821         if ( getConfiguration().isValidatePhyloXmlAgainstSchema() ) {
1822             try {
1823                 xml_parser = PhyloXmlParser.createPhyloXmlParserXsdValidating();
1824             }
1825             catch ( final Exception e ) {
1826                 JOptionPane.showMessageDialog( this,
1827                                                e.getLocalizedMessage(),
1828                                                "failed to create validating XML parser",
1829                                                JOptionPane.WARNING_MESSAGE );
1830             }
1831         }
1832         if ( xml_parser == null ) {
1833             xml_parser = new PhyloXmlParser();
1834         }
1835         return xml_parser;
1836     }
1837
1838     private void executePhyleneticInference( final boolean from_unaligned_seqs ) {
1839         final PhyloInferenceDialog dialog = new PhyloInferenceDialog( this,
1840                                                                       getPhylogeneticInferenceOptions(),
1841                                                                       from_unaligned_seqs );
1842         dialog.activate();
1843         if ( dialog.getValue() == JOptionPane.OK_OPTION ) {
1844             if ( !from_unaligned_seqs ) {
1845                 if ( getMsa() != null ) {
1846                     final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getMsa(),
1847                                                                                     getPhylogeneticInferenceOptions()
1848                                                                                             .copy(), this );
1849                     new Thread( inferrer ).start();
1850                 }
1851                 else {
1852                     JOptionPane.showMessageDialog( this,
1853                                                    "No multiple sequence alignment selected",
1854                                                    "Phylogenetic Inference Not Launched",
1855                                                    JOptionPane.WARNING_MESSAGE );
1856                 }
1857             }
1858             else {
1859                 if ( getSeqs() != null ) {
1860                     final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getSeqs(),
1861                                                                                     getPhylogeneticInferenceOptions()
1862                                                                                             .copy(), this );
1863                     new Thread( inferrer ).start();
1864                 }
1865                 else {
1866                     JOptionPane.showMessageDialog( this,
1867                                                    "No input sequences selected",
1868                                                    "Phylogenetic Inference Not Launched",
1869                                                    JOptionPane.WARNING_MESSAGE );
1870                 }
1871             }
1872         }
1873     }
1874
1875     private void extractTaxCodeFromNodeNames() throws PhyloXmlDataFormatException {
1876         if ( getCurrentTreePanel() != null ) {
1877             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1878             if ( ( phy != null ) && !phy.isEmpty() ) {
1879                 final PhylogenyNodeIterator it = phy.iteratorPostorder();
1880                 while ( it.hasNext() ) {
1881                     final PhylogenyNode n = it.next();
1882                     final String name = n.getName().trim();
1883                     if ( !ForesterUtil.isEmpty( name ) ) {
1884                         final String code = ParserUtils
1885                                 .extractTaxonomyCodeFromNodeName( name, NHXParser.TAXONOMY_EXTRACTION.YES );
1886                         if ( !ForesterUtil.isEmpty( code ) ) {
1887                             PhylogenyMethods.setTaxonomyCode( n, code );
1888                         }
1889                     }
1890                 }
1891             }
1892         }
1893     }
1894
1895     private ControlPanel getControlPanel() {
1896         return getMainPanel().getControlPanel();
1897     }
1898
1899     private File getCurrentDir() {
1900         if ( ( _current_dir == null ) || !_current_dir.canRead() ) {
1901             if ( ForesterUtil.isWindowns() ) {
1902                 try {
1903                     _current_dir = new File( WindowsUtils.getCurrentUserDesktopPath() );
1904                 }
1905                 catch ( final Exception e ) {
1906                     _current_dir = null;
1907                 }
1908             }
1909         }
1910         if ( ( _current_dir == null ) || !_current_dir.canRead() ) {
1911             if ( System.getProperty( "user.home" ) != null ) {
1912                 _current_dir = new File( System.getProperty( "user.home" ) );
1913             }
1914             else if ( System.getProperty( "user.dir" ) != null ) {
1915                 _current_dir = new File( System.getProperty( "user.dir" ) );
1916             }
1917         }
1918         return _current_dir;
1919     }
1920
1921     private double getMinNotCollapseConfidenceValue() {
1922         return _min_not_collapse;
1923     }
1924
1925     private PhylogeneticInferenceOptions getPhylogeneticInferenceOptions() {
1926         if ( _phylogenetic_inference_options == null ) {
1927             _phylogenetic_inference_options = new PhylogeneticInferenceOptions();
1928         }
1929         return _phylogenetic_inference_options;
1930     }
1931
1932     private boolean isUnsavedDataPresent() {
1933         final List<TreePanel> tps = getMainPanel().getTreePanels();
1934         for( final TreePanel tp : tps ) {
1935             if ( tp.isEdited() ) {
1936                 return true;
1937             }
1938         }
1939         return false;
1940     }
1941
1942     private void moveNodeNamesToSeqNames() throws PhyloXmlDataFormatException {
1943         if ( getCurrentTreePanel() != null ) {
1944             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1945             if ( ( phy != null ) && !phy.isEmpty() ) {
1946                 PhylogenyMethods
1947                         .transferNodeNameToField( phy, PhylogenyMethods.PhylogenyNodeField.SEQUENCE_NAME, false );
1948             }
1949         }
1950     }
1951
1952     private void moveNodeNamesToTaxSn() throws PhyloXmlDataFormatException {
1953         if ( getCurrentTreePanel() != null ) {
1954             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1955             if ( ( phy != null ) && !phy.isEmpty() ) {
1956                 PhylogenyMethods.transferNodeNameToField( phy,
1957                                                           PhylogenyMethods.PhylogenyNodeField.TAXONOMY_SCIENTIFIC_NAME,
1958                                                           false );
1959             }
1960         }
1961     }
1962
1963     private void newTree() {
1964         final Phylogeny[] phys = new Phylogeny[ 1 ];
1965         final Phylogeny phy = new Phylogeny();
1966         final PhylogenyNode node = new PhylogenyNode();
1967         phy.setRoot( node );
1968         phy.setRooted( true );
1969         phys[ 0 ] = phy;
1970         AptxUtil.addPhylogeniesToTabs( phys, "", "", getConfiguration(), getMainPanel() );
1971         _mainpanel.getControlPanel().showWhole();
1972         _mainpanel.getCurrentTreePanel().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1973         _mainpanel.getOptions().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1974         if ( getMainPanel().getMainFrame() == null ) {
1975             // Must be "E" applet version.
1976             ( ( ArchaeopteryxE ) ( ( MainPanelApplets ) getMainPanel() ).getApplet() )
1977                     .setSelectedTypeInTypeMenu( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1978         }
1979         else {
1980             getMainPanel().getMainFrame().setSelectedTypeInTypeMenu( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1981         }
1982         activateSaveAllIfNeeded();
1983         System.gc();
1984     }
1985
1986     private void obtainDetailedTaxonomicInformation() {
1987         if ( getCurrentTreePanel() != null ) {
1988             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1989             if ( ( phy != null ) && !phy.isEmpty() ) {
1990                 final TaxonomyDataManager t = new TaxonomyDataManager( this,
1991                                                                        _mainpanel.getCurrentTreePanel(),
1992                                                                        phy.copy(),
1993                                                                        false,
1994                                                                        true );
1995                 new Thread( t ).start();
1996             }
1997         }
1998     }
1999
2000     private void obtainDetailedTaxonomicInformationDelete() {
2001         if ( getCurrentTreePanel() != null ) {
2002             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
2003             if ( ( phy != null ) && !phy.isEmpty() ) {
2004                 final TaxonomyDataManager t = new TaxonomyDataManager( this,
2005                                                                        _mainpanel.getCurrentTreePanel(),
2006                                                                        phy.copy(),
2007                                                                        true,
2008                                                                        true );
2009                 new Thread( t ).start();
2010             }
2011         }
2012     }
2013
2014     private void obtainSequenceInformation() {
2015         if ( getCurrentTreePanel() != null ) {
2016             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
2017             if ( ( phy != null ) && !phy.isEmpty() ) {
2018                 final SequenceDataRetriver u = new SequenceDataRetriver( this,
2019                                                                          _mainpanel.getCurrentTreePanel(),
2020                                                                          phy.copy() );
2021                 new Thread( u ).start();
2022             }
2023         }
2024     }
2025
2026     private void print() {
2027         if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null )
2028                 || getCurrentTreePanel().getPhylogeny().isEmpty() ) {
2029             return;
2030         }
2031         if ( !getOptions().isPrintUsingActualSize() ) {
2032             getCurrentTreePanel().setParametersForPainting( getOptions().getPrintSizeX() - 80,
2033                                                             getOptions().getPrintSizeY() - 140,
2034                                                             true );
2035             getCurrentTreePanel().resetPreferredSize();
2036             getCurrentTreePanel().repaint();
2037         }
2038         final String job_name = Constants.PRG_NAME;
2039         boolean error = false;
2040         String printer_name = null;
2041         try {
2042             printer_name = Printer.print( getCurrentTreePanel(), job_name );
2043         }
2044         catch ( final Exception e ) {
2045             error = true;
2046             JOptionPane.showMessageDialog( this, e.getMessage(), "Printing Error", JOptionPane.ERROR_MESSAGE );
2047         }
2048         if ( !error && ( printer_name != null ) ) {
2049             String msg = "Printing data sent to printer";
2050             if ( printer_name.length() > 1 ) {
2051                 msg += " [" + printer_name + "]";
2052             }
2053             JOptionPane.showMessageDialog( this, msg, "Printing...", JOptionPane.INFORMATION_MESSAGE );
2054         }
2055         if ( !getOptions().isPrintUsingActualSize() ) {
2056             getControlPanel().showWhole();
2057         }
2058     }
2059
2060     private void printPhylogenyToPdf( final String file_name ) {
2061         if ( !getOptions().isPrintUsingActualSize() ) {
2062             getCurrentTreePanel().setParametersForPainting( getOptions().getPrintSizeX(),
2063                                                             getOptions().getPrintSizeY(),
2064                                                             true );
2065             getCurrentTreePanel().resetPreferredSize();
2066             getCurrentTreePanel().repaint();
2067         }
2068         String pdf_written_to = "";
2069         boolean error = false;
2070         try {
2071             if ( getOptions().isPrintUsingActualSize() ) {
2072                 pdf_written_to = PdfExporter.writePhylogenyToPdf( file_name,
2073                                                                   getCurrentTreePanel(),
2074                                                                   getCurrentTreePanel().getWidth(),
2075                                                                   getCurrentTreePanel().getHeight() );
2076             }
2077             else {
2078                 pdf_written_to = PdfExporter.writePhylogenyToPdf( file_name, getCurrentTreePanel(), getOptions()
2079                         .getPrintSizeX(), getOptions().getPrintSizeY() );
2080             }
2081         }
2082         catch ( final IOException e ) {
2083             error = true;
2084             JOptionPane.showMessageDialog( this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE );
2085         }
2086         if ( !error ) {
2087             if ( !ForesterUtil.isEmpty( pdf_written_to ) ) {
2088                 JOptionPane.showMessageDialog( this,
2089                                                "Wrote PDF to: " + pdf_written_to,
2090                                                "Information",
2091                                                JOptionPane.INFORMATION_MESSAGE );
2092             }
2093             else {
2094                 JOptionPane.showMessageDialog( this,
2095                                                "There was an unknown problem when attempting to write to PDF file: \""
2096                                                        + file_name + "\"",
2097                                                "Error",
2098                                                JOptionPane.ERROR_MESSAGE );
2099             }
2100         }
2101         if ( !getOptions().isPrintUsingActualSize() ) {
2102             getControlPanel().showWhole();
2103         }
2104     }
2105
2106     private void readPhylogeniesFromFile() {
2107         boolean exception = false;
2108         Phylogeny[] phys = null;
2109         // Set an initial directory if none set yet
2110         final File my_dir = getCurrentDir();
2111         _open_filechooser.setMultiSelectionEnabled( true );
2112         // Open file-open dialog and set current directory
2113         if ( my_dir != null ) {
2114             _open_filechooser.setCurrentDirectory( my_dir );
2115         }
2116         final int result = _open_filechooser.showOpenDialog( _contentpane );
2117         // All done: get the file
2118         final File[] files = _open_filechooser.getSelectedFiles();
2119         setCurrentDir( _open_filechooser.getCurrentDirectory() );
2120         boolean nhx_or_nexus = false;
2121         if ( ( files != null ) && ( files.length > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2122             for( final File file : files ) {
2123                 if ( ( file != null ) && !file.isDirectory() ) {
2124                     if ( _mainpanel.getCurrentTreePanel() != null ) {
2125                         _mainpanel.getCurrentTreePanel().setWaitCursor();
2126                     }
2127                     else {
2128                         _mainpanel.setWaitCursor();
2129                     }
2130                     if ( ( _open_filechooser.getFileFilter() == MainFrameApplication.nhfilter )
2131                             || ( _open_filechooser.getFileFilter() == MainFrameApplication.nhxfilter ) ) {
2132                         try {
2133                             final NHXParser nhx = new NHXParser();
2134                             setSpecialOptionsForNhxParser( nhx );
2135                             phys = PhylogenyMethods.readPhylogenies( nhx, file );
2136                             nhx_or_nexus = true;
2137                         }
2138                         catch ( final Exception e ) {
2139                             exception = true;
2140                             exceptionOccuredDuringOpenFile( e );
2141                         }
2142                     }
2143                     else if ( _open_filechooser.getFileFilter() == MainFrameApplication.xmlfilter ) {
2144                         warnIfNotPhyloXmlValidation( getConfiguration() );
2145                         try {
2146                             final PhyloXmlParser xml_parser = createPhyloXmlParser();
2147                             phys = PhylogenyMethods.readPhylogenies( xml_parser, file );
2148                         }
2149                         catch ( final Exception e ) {
2150                             exception = true;
2151                             exceptionOccuredDuringOpenFile( e );
2152                         }
2153                     }
2154                     else if ( _open_filechooser.getFileFilter() == MainFrameApplication.tolfilter ) {
2155                         try {
2156                             phys = PhylogenyMethods.readPhylogenies( new TolParser(), file );
2157                         }
2158                         catch ( final Exception e ) {
2159                             exception = true;
2160                             exceptionOccuredDuringOpenFile( e );
2161                         }
2162                     }
2163                     else if ( _open_filechooser.getFileFilter() == MainFrameApplication.nexusfilter ) {
2164                         try {
2165                             final NexusPhylogeniesParser nex = new NexusPhylogeniesParser();
2166                             setSpecialOptionsForNexParser( nex );
2167                             phys = PhylogenyMethods.readPhylogenies( nex, file );
2168                             nhx_or_nexus = true;
2169                         }
2170                         catch ( final Exception e ) {
2171                             exception = true;
2172                             exceptionOccuredDuringOpenFile( e );
2173                         }
2174                     }
2175                     // "*.*":
2176                     else {
2177                         try {
2178                             final PhylogenyParser parser = ParserUtils
2179                                     .createParserDependingOnFileType( file, getConfiguration()
2180                                             .isValidatePhyloXmlAgainstSchema() );
2181                             if ( parser instanceof NexusPhylogeniesParser ) {
2182                                 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
2183                                 setSpecialOptionsForNexParser( nex );
2184                                 nhx_or_nexus = true;
2185                             }
2186                             else if ( parser instanceof NHXParser ) {
2187                                 final NHXParser nhx = ( NHXParser ) parser;
2188                                 setSpecialOptionsForNhxParser( nhx );
2189                                 nhx_or_nexus = true;
2190                             }
2191                             else if ( parser instanceof PhyloXmlParser ) {
2192                                 warnIfNotPhyloXmlValidation( getConfiguration() );
2193                             }
2194                             phys = PhylogenyMethods.readPhylogenies( parser, file );
2195                         }
2196                         catch ( final Exception e ) {
2197                             exception = true;
2198                             exceptionOccuredDuringOpenFile( e );
2199                         }
2200                     }
2201                     if ( _mainpanel.getCurrentTreePanel() != null ) {
2202                         _mainpanel.getCurrentTreePanel().setArrowCursor();
2203                     }
2204                     else {
2205                         _mainpanel.setArrowCursor();
2206                     }
2207                     if ( !exception && ( phys != null ) && ( phys.length > 0 ) ) {
2208                         boolean one_desc = false;
2209                         if ( nhx_or_nexus ) {
2210                             for( final Phylogeny phy : phys ) {
2211                                 if ( getOptions().isInternalNumberAreConfidenceForNhParsing() ) {
2212                                     PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
2213                                 }
2214                                 if ( PhylogenyMethods.getMinimumDescendentsPerInternalNodes( phy ) == 1 ) {
2215                                     one_desc = true;
2216                                     break;
2217                                 }
2218                             }
2219                         }
2220                         AptxUtil.addPhylogeniesToTabs( phys,
2221                                                        file.getName(),
2222                                                        file.getAbsolutePath(),
2223                                                        getConfiguration(),
2224                                                        getMainPanel() );
2225                         _mainpanel.getControlPanel().showWhole();
2226                         if ( nhx_or_nexus && one_desc ) {
2227                             JOptionPane
2228                                     .showMessageDialog( this,
2229                                                         "One or more trees contain (a) node(s) with one descendant, "
2230                                                                 + ForesterUtil.LINE_SEPARATOR
2231                                                                 + "possibly indicating illegal parentheses within node names.",
2232                                                         "Warning: Possible Error in New Hampshire Formatted Data",
2233                                                         JOptionPane.WARNING_MESSAGE );
2234                         }
2235                     }
2236                 }
2237             }
2238         }
2239         activateSaveAllIfNeeded();
2240         System.gc();
2241     }
2242
2243     private void readSpeciesTreeFromFile() {
2244         Phylogeny t = null;
2245         boolean exception = false;
2246         final File my_dir = getCurrentDir();
2247         _open_filechooser_for_species_tree.setSelectedFile( new File( "" ) );
2248         if ( my_dir != null ) {
2249             _open_filechooser_for_species_tree.setCurrentDirectory( my_dir );
2250         }
2251         final int result = _open_filechooser_for_species_tree.showOpenDialog( _contentpane );
2252         final File file = _open_filechooser_for_species_tree.getSelectedFile();
2253         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2254             if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrameApplication.xmlfilter ) {
2255                 try {
2256                     final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( new PhyloXmlParser(), file );
2257                     t = trees[ 0 ];
2258                 }
2259                 catch ( final Exception e ) {
2260                     exception = true;
2261                     exceptionOccuredDuringOpenFile( e );
2262                 }
2263             }
2264             else if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrameApplication.tolfilter ) {
2265                 try {
2266                     final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( new TolParser(), file );
2267                     t = trees[ 0 ];
2268                 }
2269                 catch ( final Exception e ) {
2270                     exception = true;
2271                     exceptionOccuredDuringOpenFile( e );
2272                 }
2273             }
2274             // "*.*":
2275             else {
2276                 try {
2277                     final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( new PhyloXmlParser(), file );
2278                     t = trees[ 0 ];
2279                 }
2280                 catch ( final Exception e ) {
2281                     exception = true;
2282                     exceptionOccuredDuringOpenFile( e );
2283                 }
2284             }
2285             if ( !exception && ( t != null ) && !t.isRooted() ) {
2286                 exception = true;
2287                 t = null;
2288                 JOptionPane.showMessageDialog( this,
2289                                                "Species tree is not rooted",
2290                                                "Species tree not loaded",
2291                                                JOptionPane.ERROR_MESSAGE );
2292             }
2293             if ( !exception && ( t != null ) ) {
2294                 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
2295                 for( final PhylogenyNodeIterator it = t.iteratorExternalForward(); it.hasNext(); ) {
2296                     final PhylogenyNode node = it.next();
2297                     if ( !node.getNodeData().isHasTaxonomy() ) {
2298                         exception = true;
2299                         t = null;
2300                         JOptionPane
2301                                 .showMessageDialog( this,
2302                                                     "Species tree contains external node(s) without taxonomy information",
2303                                                     "Species tree not loaded",
2304                                                     JOptionPane.ERROR_MESSAGE );
2305                         break;
2306                     }
2307                     else {
2308                         if ( tax_set.contains( node.getNodeData().getTaxonomy() ) ) {
2309                             exception = true;
2310                             t = null;
2311                             JOptionPane.showMessageDialog( this,
2312                                                            "Taxonomy ["
2313                                                                    + node.getNodeData().getTaxonomy().asSimpleText()
2314                                                                    + "] is not unique in species tree",
2315                                                            "Species tree not loaded",
2316                                                            JOptionPane.ERROR_MESSAGE );
2317                             break;
2318                         }
2319                         else {
2320                             tax_set.add( node.getNodeData().getTaxonomy() );
2321                         }
2322                     }
2323                 }
2324             }
2325             if ( !exception && ( t != null ) ) {
2326                 _species_tree = t;
2327                 JOptionPane.showMessageDialog( this,
2328                                                "Species tree successfully loaded",
2329                                                "Species tree loaded",
2330                                                JOptionPane.INFORMATION_MESSAGE );
2331             }
2332             _contentpane.repaint();
2333             System.gc();
2334         }
2335     }
2336
2337     private void setCurrentDir( final File current_dir ) {
2338         _current_dir = current_dir;
2339     }
2340
2341     private void setMinNotCollapseConfidenceValue( final double min_not_collapse ) {
2342         _min_not_collapse = min_not_collapse;
2343     }
2344
2345     private void setPhylogeneticInferenceOptions( final PhylogeneticInferenceOptions phylogenetic_inference_options ) {
2346         _phylogenetic_inference_options = phylogenetic_inference_options;
2347     }
2348
2349     private void setSpecialOptionsForNexParser( final NexusPhylogeniesParser nex ) {
2350         nex.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() );
2351         nex.setTaxonomyExtraction( getOptions().getTaxonomyExtraction() );
2352     }
2353
2354     private void setSpecialOptionsForNhxParser( final NHXParser nhx ) {
2355         nhx.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() );
2356         nhx.setTaxonomyExtraction( getOptions().getTaxonomyExtraction() );
2357     }
2358
2359     private void writeAllToFile() {
2360         if ( ( getMainPanel().getTabbedPane() == null ) || ( getMainPanel().getTabbedPane().getTabCount() < 1 ) ) {
2361             return;
2362         }
2363         final File my_dir = getCurrentDir();
2364         if ( my_dir != null ) {
2365             _save_filechooser.setCurrentDirectory( my_dir );
2366         }
2367         _save_filechooser.setSelectedFile( new File( "" ) );
2368         final int result = _save_filechooser.showSaveDialog( _contentpane );
2369         final File file = _save_filechooser.getSelectedFile();
2370         setCurrentDir( _save_filechooser.getCurrentDirectory() );
2371         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2372             if ( file.exists() ) {
2373                 final int i = JOptionPane.showConfirmDialog( this,
2374                                                              file + " already exists. Overwrite?",
2375                                                              "Warning",
2376                                                              JOptionPane.OK_CANCEL_OPTION,
2377                                                              JOptionPane.WARNING_MESSAGE );
2378                 if ( i != JOptionPane.OK_OPTION ) {
2379                     return;
2380                 }
2381                 else {
2382                     try {
2383                         file.delete();
2384                     }
2385                     catch ( final Exception e ) {
2386                         JOptionPane.showMessageDialog( this,
2387                                                        "Failed to delete: " + file,
2388                                                        "Error",
2389                                                        JOptionPane.WARNING_MESSAGE );
2390                     }
2391                 }
2392             }
2393             final int count = getMainPanel().getTabbedPane().getTabCount();
2394             final List<Phylogeny> trees = new ArrayList<Phylogeny>();
2395             for( int i = 0; i < count; ++i ) {
2396                 trees.add( getMainPanel().getPhylogeny( i ) );
2397                 getMainPanel().getTreePanels().get( i ).setEdited( false );
2398             }
2399             final PhylogenyWriter writer = new PhylogenyWriter();
2400             try {
2401                 writer.toPhyloXML( file, trees, 0, ForesterUtil.LINE_SEPARATOR );
2402             }
2403             catch ( final IOException e ) {
2404                 JOptionPane.showMessageDialog( this,
2405                                                "Failed to write to: " + file,
2406                                                "Error",
2407                                                JOptionPane.WARNING_MESSAGE );
2408             }
2409         }
2410     }
2411
2412     private boolean writeAsNewHampshire( final Phylogeny t, boolean exception, final File file ) {
2413         try {
2414             final PhylogenyWriter writer = new PhylogenyWriter();
2415             writer.toNewHampshire( t, false, true, getOptions().getNhConversionSupportValueStyle(), file );
2416         }
2417         catch ( final Exception e ) {
2418             exception = true;
2419             exceptionOccuredDuringSaveAs( e );
2420         }
2421         return exception;
2422     }
2423
2424     private boolean writeAsNexus( final Phylogeny t, boolean exception, final File file ) {
2425         try {
2426             final PhylogenyWriter writer = new PhylogenyWriter();
2427             writer.toNexus( file, t, getOptions().getNhConversionSupportValueStyle() );
2428         }
2429         catch ( final Exception e ) {
2430             exception = true;
2431             exceptionOccuredDuringSaveAs( e );
2432         }
2433         return exception;
2434     }
2435
2436     private boolean writeAsNHX( final Phylogeny t, boolean exception, final File file ) {
2437         try {
2438             final PhylogenyWriter writer = new PhylogenyWriter();
2439             writer.toNewHampshireX( t, file );
2440         }
2441         catch ( final Exception e ) {
2442             exception = true;
2443             exceptionOccuredDuringSaveAs( e );
2444         }
2445         return exception;
2446     }
2447
2448     private boolean writeAsPhyloXml( final Phylogeny t, boolean exception, final File file ) {
2449         try {
2450             final PhylogenyWriter writer = new PhylogenyWriter();
2451             writer.toPhyloXML( file, t, 0 );
2452         }
2453         catch ( final Exception e ) {
2454             exception = true;
2455             exceptionOccuredDuringSaveAs( e );
2456         }
2457         return exception;
2458     }
2459
2460     private void writeToFile( final Phylogeny t ) {
2461         if ( t == null ) {
2462             return;
2463         }
2464         String initial_filename = null;
2465         if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) {
2466             try {
2467                 initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().getCanonicalPath();
2468             }
2469             catch ( final IOException e ) {
2470                 initial_filename = null;
2471             }
2472         }
2473         if ( !ForesterUtil.isEmpty( initial_filename ) ) {
2474             _save_filechooser.setSelectedFile( new File( initial_filename ) );
2475         }
2476         else {
2477             _save_filechooser.setSelectedFile( new File( "" ) );
2478         }
2479         final File my_dir = getCurrentDir();
2480         if ( my_dir != null ) {
2481             _save_filechooser.setCurrentDirectory( my_dir );
2482         }
2483         final int result = _save_filechooser.showSaveDialog( _contentpane );
2484         final File file = _save_filechooser.getSelectedFile();
2485         setCurrentDir( _save_filechooser.getCurrentDirectory() );
2486         boolean exception = false;
2487         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2488             if ( file.exists() ) {
2489                 final int i = JOptionPane.showConfirmDialog( this,
2490                                                              file + " already exists.\nOverwrite?",
2491                                                              "Overwrite?",
2492                                                              JOptionPane.OK_CANCEL_OPTION,
2493                                                              JOptionPane.QUESTION_MESSAGE );
2494                 if ( i != JOptionPane.OK_OPTION ) {
2495                     return;
2496                 }
2497                 else {
2498                     final File to = new File( file.getAbsoluteFile().toString() + Constants.BACKUP_FILE_SUFFIX );
2499                     try {
2500                         ForesterUtil.copyFile( file, to );
2501                     }
2502                     catch ( final Exception e ) {
2503                         JOptionPane.showMessageDialog( this,
2504                                                        "Failed to create backup copy " + to,
2505                                                        "Failed to Create Backup Copy",
2506                                                        JOptionPane.WARNING_MESSAGE );
2507                     }
2508                     try {
2509                         file.delete();
2510                     }
2511                     catch ( final Exception e ) {
2512                         JOptionPane.showMessageDialog( this,
2513                                                        "Failed to delete: " + file,
2514                                                        "Failed to Delete",
2515                                                        JOptionPane.WARNING_MESSAGE );
2516                     }
2517                 }
2518             }
2519             if ( _save_filechooser.getFileFilter() == MainFrameApplication.nhfilter ) {
2520                 exception = writeAsNewHampshire( t, exception, file );
2521             }
2522             else if ( _save_filechooser.getFileFilter() == MainFrameApplication.nhxfilter ) {
2523                 exception = writeAsNHX( t, exception, file );
2524             }
2525             else if ( _save_filechooser.getFileFilter() == MainFrameApplication.xmlfilter ) {
2526                 exception = writeAsPhyloXml( t, exception, file );
2527             }
2528             else if ( _save_filechooser.getFileFilter() == MainFrameApplication.nexusfilter ) {
2529                 exception = writeAsNexus( t, exception, file );
2530             }
2531             // "*.*":
2532             else {
2533                 final String file_name = file.getName().trim().toLowerCase();
2534                 if ( file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2535                         || file_name.endsWith( ".tree" ) ) {
2536                     exception = writeAsNewHampshire( t, exception, file );
2537                 }
2538                 else if ( file_name.endsWith( ".nhx" ) ) {
2539                     exception = writeAsNHX( t, exception, file );
2540                 }
2541                 else if ( file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) ) {
2542                     exception = writeAsNexus( t, exception, file );
2543                 }
2544                 // XML is default:
2545                 else {
2546                     exception = writeAsPhyloXml( t, exception, file );
2547                 }
2548             }
2549             if ( !exception ) {
2550                 getMainPanel().setTitleOfSelectedTab( file.getName() );
2551                 getMainPanel().getCurrentTreePanel().setTreeFile( file );
2552                 getMainPanel().getCurrentTreePanel().setEdited( false );
2553             }
2554         }
2555     }
2556
2557     private void writeToGraphicsFile( final Phylogeny t, final GraphicsExportType type ) {
2558         if ( ( t == null ) || t.isEmpty() ) {
2559             return;
2560         }
2561         String initial_filename = "";
2562         if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) {
2563             initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().toString();
2564         }
2565         if ( initial_filename.indexOf( '.' ) > 0 ) {
2566             initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) );
2567         }
2568         initial_filename = initial_filename + "." + type;
2569         _writetographics_filechooser.setSelectedFile( new File( initial_filename ) );
2570         final File my_dir = getCurrentDir();
2571         if ( my_dir != null ) {
2572             _writetographics_filechooser.setCurrentDirectory( my_dir );
2573         }
2574         final int result = _writetographics_filechooser.showSaveDialog( _contentpane );
2575         File file = _writetographics_filechooser.getSelectedFile();
2576         setCurrentDir( _writetographics_filechooser.getCurrentDirectory() );
2577         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2578             if ( !file.toString().toLowerCase().endsWith( type.toString() ) ) {
2579                 file = new File( file.toString() + "." + type );
2580             }
2581             if ( file.exists() ) {
2582                 final int i = JOptionPane.showConfirmDialog( this,
2583                                                              file + " already exists. Overwrite?",
2584                                                              "Warning",
2585                                                              JOptionPane.OK_CANCEL_OPTION,
2586                                                              JOptionPane.WARNING_MESSAGE );
2587                 if ( i != JOptionPane.OK_OPTION ) {
2588                     return;
2589                 }
2590                 else {
2591                     try {
2592                         file.delete();
2593                     }
2594                     catch ( final Exception e ) {
2595                         JOptionPane.showMessageDialog( this,
2596                                                        "Failed to delete: " + file,
2597                                                        "Error",
2598                                                        JOptionPane.WARNING_MESSAGE );
2599                     }
2600                 }
2601             }
2602             writePhylogenyToGraphicsFile( file.toString(), type );
2603         }
2604     }
2605
2606     private void writeToPdf( final Phylogeny t ) {
2607         if ( ( t == null ) || t.isEmpty() ) {
2608             return;
2609         }
2610         String initial_filename = "";
2611         if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) {
2612             initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().toString();
2613         }
2614         if ( initial_filename.indexOf( '.' ) > 0 ) {
2615             initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) );
2616         }
2617         initial_filename = initial_filename + ".pdf";
2618         _writetopdf_filechooser.setSelectedFile( new File( initial_filename ) );
2619         final File my_dir = getCurrentDir();
2620         if ( my_dir != null ) {
2621             _writetopdf_filechooser.setCurrentDirectory( my_dir );
2622         }
2623         final int result = _writetopdf_filechooser.showSaveDialog( _contentpane );
2624         File file = _writetopdf_filechooser.getSelectedFile();
2625         setCurrentDir( _writetopdf_filechooser.getCurrentDirectory() );
2626         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2627             if ( !file.toString().toLowerCase().endsWith( ".pdf" ) ) {
2628                 file = new File( file.toString() + ".pdf" );
2629             }
2630             if ( file.exists() ) {
2631                 final int i = JOptionPane.showConfirmDialog( this,
2632                                                              file + " already exists. Overwrite?",
2633                                                              "WARNING",
2634                                                              JOptionPane.OK_CANCEL_OPTION,
2635                                                              JOptionPane.WARNING_MESSAGE );
2636                 if ( i != JOptionPane.OK_OPTION ) {
2637                     return;
2638                 }
2639             }
2640             printPhylogenyToPdf( file.toString() );
2641         }
2642     }
2643
2644     public static MainFrameApplication createInstance( final Phylogeny[] phys, final Configuration config ) {
2645         return new MainFrameApplication( phys, config );
2646     }
2647
2648     public static MainFrame createInstance( final Phylogeny[] phys,
2649                                             final Configuration config,
2650                                             final String title,
2651                                             final File current_dir ) {
2652         return new MainFrameApplication( phys, config, title, current_dir );
2653     }
2654
2655     static MainFrame createInstance( final Phylogeny[] phys, final Configuration config, final String title ) {
2656         return new MainFrameApplication( phys, config, title );
2657     }
2658
2659     static MainFrame createInstance( final Phylogeny[] phys, final String config_file_name, final String title ) {
2660         return new MainFrameApplication( phys, config_file_name, title );
2661     }
2662
2663     static void setTextForGraphicsSizeChooserMenuItem( final JMenuItem mi, final Options o ) {
2664         mi.setText( "Enter Default Size for Graphics Export... (current: " + o.getPrintSizeX() + ", "
2665                 + o.getPrintSizeY() + ")" );
2666     }
2667
2668     static void setTextForPdfLineWidthChooserMenuItem( final JMenuItem mi, final Options o ) {
2669         mi.setText( "Enter Default Line Width for PDF Export... (current: " + o.getPrintLineWidth() + ")" );
2670     }
2671
2672     static void warnIfNotPhyloXmlValidation( final Configuration c ) {
2673         if ( !c.isValidatePhyloXmlAgainstSchema() ) {
2674             JOptionPane
2675                     .showMessageDialog( null,
2676                                         ForesterUtil
2677                                                 .wordWrap( "phyloXML XSD-based validation is turned off [enable with line 'validate_against_phyloxml_xsd_schem: true' in configuration file]",
2678                                                            80 ),
2679                                         "Warning",
2680                                         JOptionPane.WARNING_MESSAGE );
2681         }
2682     }
2683 } // MainFrameApplication.
2684
2685 class DefaultFilter extends FileFilter {
2686
2687     @Override
2688     public boolean accept( final File f ) {
2689         final String file_name = f.getName().trim().toLowerCase();
2690         return file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2691                 || file_name.endsWith( ".nwk" ) || file_name.endsWith( ".phb" ) || file_name.endsWith( ".ph" )
2692                 || file_name.endsWith( ".tr" ) || file_name.endsWith( ".dnd" ) || file_name.endsWith( ".tree" )
2693                 || file_name.endsWith( ".nhx" ) || file_name.endsWith( ".xml" ) || file_name.endsWith( ".phyloxml" )
2694                 || file_name.endsWith( "phylo.xml" ) || file_name.endsWith( ".pxml" ) || file_name.endsWith( ".nexus" )
2695                 || file_name.endsWith( ".nx" ) || file_name.endsWith( ".nex" ) || file_name.endsWith( ".tre" )
2696                 || file_name.endsWith( ".zip" ) || file_name.endsWith( ".tol" ) || file_name.endsWith( ".tolxml" )
2697                 || file_name.endsWith( ".con" ) || f.isDirectory();
2698     }
2699
2700     @Override
2701     public String getDescription() {
2702         return "All supported files (*.xml, *.phyloxml, *phylo.xml, *.nhx, *.nh, *.newick, *.nex, *.nexus, *.phy, *.tre, *.tree, *.tol, ...)";
2703     }
2704 }
2705
2706 class GraphicsFileFilter extends FileFilter {
2707
2708     @Override
2709     public boolean accept( final File f ) {
2710         final String file_name = f.getName().trim().toLowerCase();
2711         return file_name.endsWith( ".jpg" ) || file_name.endsWith( ".jpeg" ) || file_name.endsWith( ".png" )
2712                 || file_name.endsWith( ".gif" ) || file_name.endsWith( ".bmp" ) || f.isDirectory();
2713     }
2714
2715     @Override
2716     public String getDescription() {
2717         return "Image files (*.jpg, *.jpeg, *.png, *.gif, *.bmp)";
2718     }
2719 }
2720
2721 class MsaFileFilter extends FileFilter {
2722
2723     @Override
2724     public boolean accept( final File f ) {
2725         final String file_name = f.getName().trim().toLowerCase();
2726         return file_name.endsWith( ".msa" ) || file_name.endsWith( ".aln" ) || file_name.endsWith( ".fasta" )
2727                 || file_name.endsWith( ".fas" ) || file_name.endsWith( ".fa" ) || f.isDirectory();
2728     }
2729
2730     @Override
2731     public String getDescription() {
2732         return "Multiple sequence alignment files (*.msa, *.aln, *.fasta, *.fa, *.fas)";
2733     }
2734 }
2735
2736 class NexusFilter extends FileFilter {
2737
2738     @Override
2739     public boolean accept( final File f ) {
2740         final String file_name = f.getName().trim().toLowerCase();
2741         return file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) || file_name.endsWith( ".nx" )
2742                 || file_name.endsWith( ".tre" ) || f.isDirectory();
2743     }
2744
2745     @Override
2746     public String getDescription() {
2747         return "Nexus files (*.nex, *.nexus, *.nx, *.tre)";
2748     }
2749 } // NexusFilter
2750
2751 class NHFilter extends FileFilter {
2752
2753     @Override
2754     public boolean accept( final File f ) {
2755         final String file_name = f.getName().trim().toLowerCase();
2756         return file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2757                 || file_name.endsWith( ".tr" ) || file_name.endsWith( ".tree" ) || file_name.endsWith( ".dnd" )
2758                 || file_name.endsWith( ".ph" ) || file_name.endsWith( ".phb" ) || file_name.endsWith( ".nwk" )
2759                 || f.isDirectory();
2760     }
2761
2762     @Override
2763     public String getDescription() {
2764         return "New Hampshire - Newick files (*.nh, *.newick, *.phy, *.tree, *.dnd, *.tr, *.ph, *.phb, *.nwk)";
2765     }
2766 } // NHFilter
2767
2768 class NHXFilter extends FileFilter {
2769
2770     @Override
2771     public boolean accept( final File f ) {
2772         final String file_name = f.getName().trim().toLowerCase();
2773         return file_name.endsWith( ".nhx" ) || f.isDirectory();
2774     }
2775
2776     @Override
2777     public String getDescription() {
2778         return "NHX files (*.nhx)";
2779     }
2780 }
2781
2782 class PdfFilter extends FileFilter {
2783
2784     @Override
2785     public boolean accept( final File f ) {
2786         return f.getName().trim().toLowerCase().endsWith( ".pdf" ) || f.isDirectory();
2787     }
2788
2789     @Override
2790     public String getDescription() {
2791         return "PDF files (*.pdf)";
2792     }
2793 } // PdfFilter
2794
2795 class SequencesFileFilter extends FileFilter {
2796
2797     @Override
2798     public boolean accept( final File f ) {
2799         final String file_name = f.getName().trim().toLowerCase();
2800         return file_name.endsWith( ".fasta" ) || file_name.endsWith( ".fa" ) || file_name.endsWith( ".fas" )
2801                 || file_name.endsWith( ".seqs" ) || f.isDirectory();
2802     }
2803
2804     @Override
2805     public String getDescription() {
2806         return "Sequences files (*.fasta, *.fa, *.fas, *.seqs )";
2807     }
2808 }
2809
2810 class TolFilter extends FileFilter {
2811
2812     @Override
2813     public boolean accept( final File f ) {
2814         final String file_name = f.getName().trim().toLowerCase();
2815         return ( file_name.endsWith( ".tol" ) || file_name.endsWith( ".tolxml" ) || file_name.endsWith( ".zip" ) || f
2816                 .isDirectory() ) && ( !file_name.endsWith( ".xml.zip" ) );
2817     }
2818
2819     @Override
2820     public String getDescription() {
2821         return "Tree of Life files (*.tol, *.tolxml)";
2822     }
2823 } // TolFilter
2824
2825 class XMLFilter extends FileFilter {
2826
2827     @Override
2828     public boolean accept( final File f ) {
2829         final String file_name = f.getName().trim().toLowerCase();
2830         return file_name.endsWith( ".xml" ) || file_name.endsWith( ".phyloxml" ) || file_name.endsWith( "phylo.xml" )
2831                 || file_name.endsWith( ".pxml" ) || file_name.endsWith( ".zip" ) || f.isDirectory();
2832     }
2833
2834     @Override
2835     public String getDescription() {
2836         return "phyloXML files (*.xml, *.phyloxml, *phylo.xml, *.pxml, *.zip)";
2837     }
2838 } // XMLFilter