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