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