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