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