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