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