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