"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 Phylogeny result_gene_tree = gsdir.getMinDuplicationsSumGeneTrees().get( 0 );
1298         result_gene_tree.setRerootable( false );
1299         result_gene_tree.clearHashIdToNodeMap();
1300         result_gene_tree.recalculateNumberOfExternalDescendants( true );
1301         _mainpanel.addPhylogenyInNewTab( result_gene_tree, getConfiguration(), "gene tree", null );
1302         //_mainpanel.getCurrentTreePanel().setTree( gene_tree );
1303         // _mainpanel.getCurrentTreePanel().setEdited( true );
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: " + gsdir.getMinDuplicationsSum() + "\n" + "Speciations: "
1314                                                + gsdir.getSpeciationsSum() + "\n"
1315                                                + "Number of root positions minimizing duplications sum: "
1316                                                + gsdir.getMinDuplicationsSumGeneTrees().size(),
1317                                        "GSDIR successfully completed",
1318                                        JOptionPane.INFORMATION_MESSAGE );
1319     }
1320
1321     void executeFunctionAnalysis() {
1322         if ( ( _mainpanel.getCurrentPhylogeny() == null ) || ( _mainpanel.getCurrentPhylogeny().isEmpty() ) ) {
1323             return;
1324         }
1325         final GoAnnotation a = new GoAnnotation( this,
1326                                                  _mainpanel.getCurrentTreePanel(),
1327                                                  _mainpanel.getCurrentPhylogeny() );
1328         new Thread( a ).start();
1329     }
1330
1331     void executeLineageInference() {
1332         if ( ( _mainpanel.getCurrentPhylogeny() == null ) || ( _mainpanel.getCurrentPhylogeny().isEmpty() ) ) {
1333             return;
1334         }
1335         if ( !_mainpanel.getCurrentPhylogeny().isRooted() ) {
1336             JOptionPane.showMessageDialog( this,
1337                                            "Phylogeny is not rooted.",
1338                                            "Cannot infer ancestral taxonomies",
1339                                            JOptionPane.ERROR_MESSAGE );
1340             return;
1341         }
1342         final AncestralTaxonomyInferrer inferrer = new AncestralTaxonomyInferrer( this,
1343                                                                                   _mainpanel.getCurrentTreePanel(),
1344                                                                                   _mainpanel.getCurrentPhylogeny()
1345                                                                                           .copy() );
1346         new Thread( inferrer ).start();
1347     }
1348
1349     private void executePhyleneticInference( final boolean from_unaligned_seqs ) {
1350         final PhyloInferenceDialog dialog = new PhyloInferenceDialog( this,
1351                                                                       getPhylogeneticInferenceOptions(),
1352                                                                       from_unaligned_seqs );
1353         dialog.activate();
1354         if ( dialog.getValue() == JOptionPane.OK_OPTION ) {
1355             if ( !from_unaligned_seqs ) {
1356                 if ( getMsa() != null ) {
1357                     final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getMsa(),
1358                                                                                     getPhylogeneticInferenceOptions()
1359                                                                                             .copy(), this );
1360                     new Thread( inferrer ).start();
1361                 }
1362                 else {
1363                     JOptionPane.showMessageDialog( this,
1364                                                    "No multiple sequence alignment selected",
1365                                                    "Phylogenetic Inference Not Launched",
1366                                                    JOptionPane.WARNING_MESSAGE );
1367                 }
1368             }
1369             else {
1370                 if ( getSeqs() != null ) {
1371                     final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getSeqs(),
1372                                                                                     getPhylogeneticInferenceOptions()
1373                                                                                             .copy(), this );
1374                     new Thread( inferrer ).start();
1375                 }
1376                 else {
1377                     JOptionPane.showMessageDialog( this,
1378                                                    "No input sequences selected",
1379                                                    "Phylogenetic Inference Not Launched",
1380                                                    JOptionPane.WARNING_MESSAGE );
1381                 }
1382             }
1383         }
1384     }
1385
1386     void executeSDIR( final boolean minimize_cost ) {
1387         if ( !isOKforSDI( true, true ) ) {
1388             return;
1389         }
1390         Phylogeny gene_tree = _mainpanel.getCurrentPhylogeny().copy();
1391         final SDIR sdiunrooted = new SDIR();
1392         gene_tree.setAllNodesToNotCollapse();
1393         gene_tree.recalculateNumberOfExternalDescendants( false );
1394         try {
1395             gene_tree = sdiunrooted.infer( gene_tree, _species_tree, minimize_cost, // minimize cost
1396                                            !minimize_cost, // minimize sum of dups
1397                                            true, // minimize height
1398                                            true, // return tree(s)
1399                                            1 )[ 0 ]; // # of trees to return
1400         }
1401         catch ( final Exception e ) {
1402             JOptionPane.showMessageDialog( this, e.toString(), "Error during SDIR", JOptionPane.ERROR_MESSAGE );
1403             return;
1404         }
1405         final int duplications = sdiunrooted.getMinimalDuplications();
1406         gene_tree.setRerootable( false );
1407         _mainpanel.getCurrentTreePanel().setTree( gene_tree );
1408         getControlPanel().setShowEvents( true );
1409         showWhole();
1410         _mainpanel.getCurrentTreePanel().setEdited( true );
1411         JOptionPane.showMessageDialog( this,
1412                                        "Number of duplications: " + duplications,
1413                                        "SDIR successfully completed",
1414                                        JOptionPane.INFORMATION_MESSAGE );
1415     }
1416
1417     void exit() {
1418         removeAllTextFrames();
1419         _mainpanel.terminate();
1420         _contentpane.removeAll();
1421         setVisible( false );
1422         dispose();
1423         System.exit( 0 );
1424     }
1425
1426     public void end() {
1427         _mainpanel.terminate();
1428         _contentpane.removeAll();
1429         setVisible( false );
1430         dispose();
1431     }
1432
1433     private void extractTaxCodeFromNodeNames() throws PhyloXmlDataFormatException {
1434         if ( getCurrentTreePanel() != null ) {
1435             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1436             if ( ( phy != null ) && !phy.isEmpty() ) {
1437                 final PhylogenyNodeIterator it = phy.iteratorPostorder();
1438                 while ( it.hasNext() ) {
1439                     final PhylogenyNode n = it.next();
1440                     final String name = n.getName().trim();
1441                     if ( !ForesterUtil.isEmpty( name ) ) {
1442                         final String code = ParserUtils
1443                                 .extractTaxonomyCodeFromNodeName( name, NHXParser.TAXONOMY_EXTRACTION.YES );
1444                         if ( !ForesterUtil.isEmpty( code ) ) {
1445                             PhylogenyMethods.setTaxonomyCode( n, code );
1446                         }
1447                     }
1448                 }
1449             }
1450         }
1451     }
1452
1453     private ControlPanel getControlPanel() {
1454         return getMainPanel().getControlPanel();
1455     }
1456
1457     private File getCurrentDir() {
1458         if ( ( _current_dir == null ) || !_current_dir.canRead() ) {
1459             if ( ForesterUtil.isWindowns() ) {
1460                 try {
1461                     _current_dir = new File( WindowsUtils.getCurrentUserDesktopPath() );
1462                 }
1463                 catch ( final Exception e ) {
1464                     _current_dir = null;
1465                 }
1466             }
1467         }
1468         if ( ( _current_dir == null ) || !_current_dir.canRead() ) {
1469             if ( System.getProperty( "user.home" ) != null ) {
1470                 _current_dir = new File( System.getProperty( "user.home" ) );
1471             }
1472             else if ( System.getProperty( "user.dir" ) != null ) {
1473                 _current_dir = new File( System.getProperty( "user.dir" ) );
1474             }
1475         }
1476         return _current_dir;
1477     }
1478
1479     @Override
1480     public MainPanel getMainPanel() {
1481         return _mainpanel;
1482     }
1483
1484     private double getMinNotCollapseConfidenceValue() {
1485         return _min_not_collapse;
1486     }
1487
1488     boolean isOKforSDI( final boolean species_tree_has_to_binary, final boolean gene_tree_has_to_binary ) {
1489         if ( ( _mainpanel.getCurrentPhylogeny() == null ) || _mainpanel.getCurrentPhylogeny().isEmpty() ) {
1490             return false;
1491         }
1492         else if ( ( _species_tree == null ) || _species_tree.isEmpty() ) {
1493             JOptionPane.showMessageDialog( this,
1494                                            "No species tree loaded",
1495                                            "Cannot execute SDI",
1496                                            JOptionPane.ERROR_MESSAGE );
1497             return false;
1498         }
1499         else if ( species_tree_has_to_binary && !_species_tree.isCompletelyBinary() ) {
1500             JOptionPane.showMessageDialog( this,
1501                                            "Species tree is not completely binary",
1502                                            "Cannot execute SDI",
1503                                            JOptionPane.ERROR_MESSAGE );
1504             return false;
1505         }
1506         else if ( gene_tree_has_to_binary && !_mainpanel.getCurrentPhylogeny().isCompletelyBinary() ) {
1507             JOptionPane.showMessageDialog( this,
1508                                            "Gene tree is not completely binary",
1509                                            "Cannot execute SDI",
1510                                            JOptionPane.ERROR_MESSAGE );
1511             return false;
1512         }
1513         else {
1514             return true;
1515         }
1516     }
1517
1518     private boolean isUnsavedDataPresent() {
1519         final List<TreePanel> tps = getMainPanel().getTreePanels();
1520         for( final TreePanel tp : tps ) {
1521             if ( tp.isEdited() ) {
1522                 return true;
1523             }
1524         }
1525         return false;
1526     }
1527
1528     private void moveNodeNamesToSeqNames() throws PhyloXmlDataFormatException {
1529         if ( getCurrentTreePanel() != null ) {
1530             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1531             if ( ( phy != null ) && !phy.isEmpty() ) {
1532                 PhylogenyMethods
1533                         .transferNodeNameToField( phy, PhylogenyMethods.PhylogenyNodeField.SEQUENCE_NAME, false );
1534             }
1535         }
1536     }
1537
1538     private void moveNodeNamesToTaxSn() throws PhyloXmlDataFormatException {
1539         if ( getCurrentTreePanel() != null ) {
1540             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1541             if ( ( phy != null ) && !phy.isEmpty() ) {
1542                 PhylogenyMethods.transferNodeNameToField( phy,
1543                                                           PhylogenyMethods.PhylogenyNodeField.TAXONOMY_SCIENTIFIC_NAME,
1544                                                           false );
1545             }
1546         }
1547     }
1548
1549     private void newTree() {
1550         final Phylogeny[] phys = new Phylogeny[ 1 ];
1551         final Phylogeny phy = new Phylogeny();
1552         final PhylogenyNode node = new PhylogenyNode();
1553         phy.setRoot( node );
1554         phy.setRooted( true );
1555         phys[ 0 ] = phy;
1556         AptxUtil.addPhylogeniesToTabs( phys, "", "", getConfiguration(), getMainPanel() );
1557         _mainpanel.getControlPanel().showWhole();
1558         _mainpanel.getCurrentTreePanel().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1559         _mainpanel.getOptions().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1560         if ( getMainPanel().getMainFrame() == null ) {
1561             // Must be "E" applet version.
1562             ( ( ArchaeopteryxE ) ( ( MainPanelApplets ) getMainPanel() ).getApplet() )
1563                     .setSelectedTypeInTypeMenu( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1564         }
1565         else {
1566             getMainPanel().getMainFrame().setSelectedTypeInTypeMenu( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1567         }
1568         activateSaveAllIfNeeded();
1569         System.gc();
1570     }
1571
1572     private void obtainDetailedTaxonomicInformation() {
1573         if ( getCurrentTreePanel() != null ) {
1574             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1575             if ( ( phy != null ) && !phy.isEmpty() ) {
1576                 final TaxonomyDataManager t = new TaxonomyDataManager( this,
1577                                                                        _mainpanel.getCurrentTreePanel(),
1578                                                                        phy.copy(),
1579                                                                        false,
1580                                                                        true );
1581                 new Thread( t ).start();
1582             }
1583         }
1584     }
1585
1586     private void obtainDetailedTaxonomicInformationDelete() {
1587         if ( getCurrentTreePanel() != null ) {
1588             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1589             if ( ( phy != null ) && !phy.isEmpty() ) {
1590                 final TaxonomyDataManager t = new TaxonomyDataManager( this,
1591                                                                        _mainpanel.getCurrentTreePanel(),
1592                                                                        phy.copy(),
1593                                                                        true,
1594                                                                        true );
1595                 new Thread( t ).start();
1596             }
1597         }
1598     }
1599
1600     private void obtainSequenceInformation() {
1601         if ( getCurrentTreePanel() != null ) {
1602             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1603             if ( ( phy != null ) && !phy.isEmpty() ) {
1604                 final SequenceDataRetriver u = new SequenceDataRetriver( this,
1605                                                                          _mainpanel.getCurrentTreePanel(),
1606                                                                          phy.copy() );
1607                 new Thread( u ).start();
1608             }
1609         }
1610     }
1611
1612     private void print() {
1613         if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null )
1614                 || getCurrentTreePanel().getPhylogeny().isEmpty() ) {
1615             return;
1616         }
1617         if ( !getOptions().isPrintUsingActualSize() ) {
1618             getCurrentTreePanel().setParametersForPainting( getOptions().getPrintSizeX() - 80,
1619                                                             getOptions().getPrintSizeY() - 140,
1620                                                             true );
1621             getCurrentTreePanel().resetPreferredSize();
1622             getCurrentTreePanel().repaint();
1623         }
1624         final String job_name = Constants.PRG_NAME;
1625         boolean error = false;
1626         String printer_name = null;
1627         try {
1628             printer_name = Printer.print( getCurrentTreePanel(), job_name );
1629         }
1630         catch ( final Exception e ) {
1631             error = true;
1632             JOptionPane.showMessageDialog( this, e.getMessage(), "Printing Error", JOptionPane.ERROR_MESSAGE );
1633         }
1634         if ( !error && ( printer_name != null ) ) {
1635             String msg = "Printing data sent to printer";
1636             if ( printer_name.length() > 1 ) {
1637                 msg += " [" + printer_name + "]";
1638             }
1639             JOptionPane.showMessageDialog( this, msg, "Printing...", JOptionPane.INFORMATION_MESSAGE );
1640         }
1641         if ( !getOptions().isPrintUsingActualSize() ) {
1642             getControlPanel().showWhole();
1643         }
1644     }
1645
1646     private void printPhylogenyToPdf( final String file_name ) {
1647         if ( !getOptions().isPrintUsingActualSize() ) {
1648             getCurrentTreePanel().setParametersForPainting( getOptions().getPrintSizeX(),
1649                                                             getOptions().getPrintSizeY(),
1650                                                             true );
1651             getCurrentTreePanel().resetPreferredSize();
1652             getCurrentTreePanel().repaint();
1653         }
1654         String pdf_written_to = "";
1655         boolean error = false;
1656         try {
1657             if ( getOptions().isPrintUsingActualSize() ) {
1658                 pdf_written_to = PdfExporter.writePhylogenyToPdf( file_name,
1659                                                                   getCurrentTreePanel(),
1660                                                                   getCurrentTreePanel().getWidth(),
1661                                                                   getCurrentTreePanel().getHeight() );
1662             }
1663             else {
1664                 pdf_written_to = PdfExporter.writePhylogenyToPdf( file_name, getCurrentTreePanel(), getOptions()
1665                         .getPrintSizeX(), getOptions().getPrintSizeY() );
1666             }
1667         }
1668         catch ( final IOException e ) {
1669             error = true;
1670             JOptionPane.showMessageDialog( this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE );
1671         }
1672         if ( !error ) {
1673             if ( !ForesterUtil.isEmpty( pdf_written_to ) ) {
1674                 JOptionPane.showMessageDialog( this,
1675                                                "Wrote PDF to: " + pdf_written_to,
1676                                                "Information",
1677                                                JOptionPane.INFORMATION_MESSAGE );
1678             }
1679             else {
1680                 JOptionPane.showMessageDialog( this,
1681                                                "There was an unknown problem when attempting to write to PDF file: \""
1682                                                        + file_name + "\"",
1683                                                "Error",
1684                                                JOptionPane.ERROR_MESSAGE );
1685             }
1686         }
1687         if ( !getOptions().isPrintUsingActualSize() ) {
1688             getControlPanel().showWhole();
1689         }
1690     }
1691
1692     private void addExpressionValuesFromFile() {
1693         if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) ) {
1694             JOptionPane.showMessageDialog( this,
1695                                            "Need to load evolutionary tree first",
1696                                            "Can Not Read Expression Values",
1697                                            JOptionPane.WARNING_MESSAGE );
1698             return;
1699         }
1700         final File my_dir = getCurrentDir();
1701         if ( my_dir != null ) {
1702             _values_filechooser.setCurrentDirectory( my_dir );
1703         }
1704         final int result = _values_filechooser.showOpenDialog( _contentpane );
1705         final File file = _values_filechooser.getSelectedFile();
1706         if ( ( file != null ) && ( file.length() > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
1707             BasicTable<String> t = null;
1708             try {
1709                 t = BasicTableParser.parse( file, "\t" );
1710                 if ( t.getNumberOfColumns() < 2 ) {
1711                     t = BasicTableParser.parse( file, "," );
1712                 }
1713                 if ( t.getNumberOfColumns() < 2 ) {
1714                     t = BasicTableParser.parse( file, " " );
1715                 }
1716             }
1717             catch ( final IOException e ) {
1718                 JOptionPane.showMessageDialog( this,
1719                                                e.getMessage(),
1720                                                "Could Not Read Expression Value Table",
1721                                                JOptionPane.ERROR_MESSAGE );
1722                 return;
1723             }
1724             if ( t.getNumberOfColumns() < 2 ) {
1725                 JOptionPane.showMessageDialog( this,
1726                                                "Table contains " + t.getNumberOfColumns() + " column(s)",
1727                                                "Problem with Expression Value Table",
1728                                                JOptionPane.ERROR_MESSAGE );
1729                 return;
1730             }
1731             if ( t.getNumberOfRows() < 1 ) {
1732                 JOptionPane.showMessageDialog( this,
1733                                                "Table contains zero rows",
1734                                                "Problem with Expression Value Table",
1735                                                JOptionPane.ERROR_MESSAGE );
1736                 return;
1737             }
1738             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1739             if ( t.getNumberOfRows() != phy.getNumberOfExternalNodes() ) {
1740                 JOptionPane.showMessageDialog( this,
1741                                                "Table contains " + t.getNumberOfRows() + " rows, but tree contains "
1742                                                        + phy.getNumberOfExternalNodes() + " external nodes",
1743                                                "Warning",
1744                                                JOptionPane.WARNING_MESSAGE );
1745             }
1746             final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
1747             int not_found = 0;
1748             for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1749                 final PhylogenyNode node = iter.next();
1750                 final String node_name = node.getName();
1751                 if ( !ForesterUtil.isEmpty( node_name ) ) {
1752                     int row = -1;
1753                     try {
1754                         row = t.findRow( node_name );
1755                     }
1756                     catch ( final IllegalArgumentException e ) {
1757                         JOptionPane
1758                                 .showMessageDialog( this,
1759                                                     e.getMessage(),
1760                                                     "Error Mapping Node Identifiers to Expression Value Identifiers",
1761                                                     JOptionPane.ERROR_MESSAGE );
1762                         return;
1763                     }
1764                     if ( row < 0 ) {
1765                         if ( node.isExternal() ) {
1766                             not_found++;
1767                         }
1768                         continue;
1769                     }
1770                     final List<Double> l = new ArrayList<Double>();
1771                     for( int col = 1; col < t.getNumberOfColumns(); ++col ) {
1772                         double d = -100;
1773                         try {
1774                             d = Double.parseDouble( t.getValueAsString( col, row ) );
1775                         }
1776                         catch ( final NumberFormatException e ) {
1777                             JOptionPane.showMessageDialog( this,
1778                                                            "Could not parse \"" + t.getValueAsString( col, row )
1779                                                                    + "\" into a decimal value",
1780                                                            "Issue with Expression Value Table",
1781                                                            JOptionPane.ERROR_MESSAGE );
1782                             return;
1783                         }
1784                         stats.addValue( d );
1785                         l.add( d );
1786                     }
1787                     if ( !l.isEmpty() ) {
1788                         if ( node.getNodeData().getProperties() != null ) {
1789                             node.getNodeData().getProperties()
1790                                     .removePropertiesWithGivenReferencePrefix( PhyloXmlUtil.VECTOR_PROPERTY_REF );
1791                         }
1792                         node.getNodeData().setVector( l );
1793                     }
1794                 }
1795             }
1796             if ( not_found > 0 ) {
1797                 JOptionPane.showMessageDialog( this, "Could not fine expression values for " + not_found
1798                         + " external node(s)", "Warning", JOptionPane.WARNING_MESSAGE );
1799             }
1800             getCurrentTreePanel().setStatisticsForExpressionValues( stats );
1801         }
1802     }
1803
1804     private void readPhylogeniesFromFile() {
1805         boolean exception = false;
1806         Phylogeny[] phys = null;
1807         // Set an initial directory if none set yet
1808         final File my_dir = getCurrentDir();
1809         _open_filechooser.setMultiSelectionEnabled( true );
1810         // Open file-open dialog and set current directory
1811         if ( my_dir != null ) {
1812             _open_filechooser.setCurrentDirectory( my_dir );
1813         }
1814         final int result = _open_filechooser.showOpenDialog( _contentpane );
1815         // All done: get the file
1816         final File[] files = _open_filechooser.getSelectedFiles();
1817         setCurrentDir( _open_filechooser.getCurrentDirectory() );
1818         boolean nhx_or_nexus = false;
1819         if ( ( files != null ) && ( files.length > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
1820             for( final File file : files ) {
1821                 if ( ( file != null ) && !file.isDirectory() ) {
1822                     if ( _mainpanel.getCurrentTreePanel() != null ) {
1823                         _mainpanel.getCurrentTreePanel().setWaitCursor();
1824                     }
1825                     else {
1826                         _mainpanel.setWaitCursor();
1827                     }
1828                     if ( ( _open_filechooser.getFileFilter() == MainFrameApplication.nhfilter )
1829                             || ( _open_filechooser.getFileFilter() == MainFrameApplication.nhxfilter ) ) {
1830                         try {
1831                             final NHXParser nhx = new NHXParser();
1832                             setSpecialOptionsForNhxParser( nhx );
1833                             phys = PhylogenyMethods.readPhylogenies( nhx, file );
1834                             nhx_or_nexus = true;
1835                         }
1836                         catch ( final Exception e ) {
1837                             exception = true;
1838                             exceptionOccuredDuringOpenFile( e );
1839                         }
1840                     }
1841                     else if ( _open_filechooser.getFileFilter() == MainFrameApplication.xmlfilter ) {
1842                         warnIfNotPhyloXmlValidation( getConfiguration() );
1843                         try {
1844                             final PhyloXmlParser xml_parser = createPhyloXmlParser();
1845                             phys = PhylogenyMethods.readPhylogenies( xml_parser, file );
1846                         }
1847                         catch ( final Exception e ) {
1848                             exception = true;
1849                             exceptionOccuredDuringOpenFile( e );
1850                         }
1851                     }
1852                     else if ( _open_filechooser.getFileFilter() == MainFrameApplication.tolfilter ) {
1853                         try {
1854                             phys = PhylogenyMethods.readPhylogenies( new TolParser(), file );
1855                         }
1856                         catch ( final Exception e ) {
1857                             exception = true;
1858                             exceptionOccuredDuringOpenFile( e );
1859                         }
1860                     }
1861                     else if ( _open_filechooser.getFileFilter() == MainFrameApplication.nexusfilter ) {
1862                         try {
1863                             final NexusPhylogeniesParser nex = new NexusPhylogeniesParser();
1864                             setSpecialOptionsForNexParser( nex );
1865                             phys = PhylogenyMethods.readPhylogenies( nex, file );
1866                             nhx_or_nexus = true;
1867                         }
1868                         catch ( final Exception e ) {
1869                             exception = true;
1870                             exceptionOccuredDuringOpenFile( e );
1871                         }
1872                     }
1873                     // "*.*":
1874                     else {
1875                         try {
1876                             final PhylogenyParser parser = ParserUtils
1877                                     .createParserDependingOnFileType( file, getConfiguration()
1878                                             .isValidatePhyloXmlAgainstSchema() );
1879                             if ( parser instanceof NexusPhylogeniesParser ) {
1880                                 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
1881                                 setSpecialOptionsForNexParser( nex );
1882                                 nhx_or_nexus = true;
1883                             }
1884                             else if ( parser instanceof NHXParser ) {
1885                                 final NHXParser nhx = ( NHXParser ) parser;
1886                                 setSpecialOptionsForNhxParser( nhx );
1887                                 nhx_or_nexus = true;
1888                             }
1889                             else if ( parser instanceof PhyloXmlParser ) {
1890                                 warnIfNotPhyloXmlValidation( getConfiguration() );
1891                             }
1892                             phys = PhylogenyMethods.readPhylogenies( parser, file );
1893                         }
1894                         catch ( final Exception e ) {
1895                             exception = true;
1896                             exceptionOccuredDuringOpenFile( e );
1897                         }
1898                     }
1899                     if ( _mainpanel.getCurrentTreePanel() != null ) {
1900                         _mainpanel.getCurrentTreePanel().setArrowCursor();
1901                     }
1902                     else {
1903                         _mainpanel.setArrowCursor();
1904                     }
1905                     if ( !exception && ( phys != null ) && ( phys.length > 0 ) ) {
1906                         boolean one_desc = false;
1907                         if ( nhx_or_nexus ) {
1908                             for( final Phylogeny phy : phys ) {
1909                                 if ( getOptions().isInternalNumberAreConfidenceForNhParsing() ) {
1910                                     PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
1911                                 }
1912                                 if ( PhylogenyMethods.getMinimumDescendentsPerInternalNodes( phy ) == 1 ) {
1913                                     one_desc = true;
1914                                     break;
1915                                 }
1916                             }
1917                         }
1918                         AptxUtil.addPhylogeniesToTabs( phys,
1919                                                        file.getName(),
1920                                                        file.getAbsolutePath(),
1921                                                        getConfiguration(),
1922                                                        getMainPanel() );
1923                         _mainpanel.getControlPanel().showWhole();
1924                         if ( nhx_or_nexus && one_desc ) {
1925                             JOptionPane
1926                                     .showMessageDialog( this,
1927                                                         "One or more trees contain (a) node(s) with one descendant, "
1928                                                                 + ForesterUtil.LINE_SEPARATOR
1929                                                                 + "possibly indicating illegal parentheses within node names.",
1930                                                         "Warning: Possible Error in New Hampshire Formatted Data",
1931                                                         JOptionPane.WARNING_MESSAGE );
1932                         }
1933                     }
1934                 }
1935             }
1936         }
1937         activateSaveAllIfNeeded();
1938         System.gc();
1939     }
1940
1941     public void readSeqsFromFile() {
1942         // Set an initial directory if none set yet
1943         final File my_dir = getCurrentDir();
1944         _seqs_filechooser.setMultiSelectionEnabled( false );
1945         // Open file-open dialog and set current directory
1946         if ( my_dir != null ) {
1947             _seqs_filechooser.setCurrentDirectory( my_dir );
1948         }
1949         final int result = _seqs_filechooser.showOpenDialog( _contentpane );
1950         // All done: get the seqs
1951         final File file = _seqs_filechooser.getSelectedFile();
1952         setCurrentDir( _seqs_filechooser.getCurrentDirectory() );
1953         if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) {
1954             setSeqsFile( null );
1955             setSeqs( null );
1956             List<Sequence> seqs = null;
1957             try {
1958                 if ( FastaParser.isLikelyFasta( new FileInputStream( file ) ) ) {
1959                     seqs = FastaParser.parse( new FileInputStream( file ) );
1960                     for( final Sequence seq : seqs ) {
1961                         System.out.println( SequenceWriter.toFasta( seq, 60 ) );
1962                     }
1963                 }
1964                 else {
1965                     //TODO error
1966                 }
1967             }
1968             catch ( final MsaFormatException e ) {
1969                 try {
1970                     _mainpanel.getCurrentTreePanel().setArrowCursor();
1971                 }
1972                 catch ( final Exception ex ) {
1973                     // Do nothing.
1974                 }
1975                 JOptionPane.showMessageDialog( this,
1976                                                e.getLocalizedMessage(),
1977                                                "Multiple sequence file format error",
1978                                                JOptionPane.ERROR_MESSAGE );
1979                 return;
1980             }
1981             catch ( final IOException e ) {
1982                 try {
1983                     _mainpanel.getCurrentTreePanel().setArrowCursor();
1984                 }
1985                 catch ( final Exception ex ) {
1986                     // Do nothing.
1987                 }
1988                 JOptionPane.showMessageDialog( this,
1989                                                e.getLocalizedMessage(),
1990                                                "Failed to read multiple sequence file",
1991                                                JOptionPane.ERROR_MESSAGE );
1992                 return;
1993             }
1994             catch ( final IllegalArgumentException e ) {
1995                 try {
1996                     _mainpanel.getCurrentTreePanel().setArrowCursor();
1997                 }
1998                 catch ( final Exception ex ) {
1999                     // Do nothing.
2000                 }
2001                 JOptionPane.showMessageDialog( this,
2002                                                e.getLocalizedMessage(),
2003                                                "Unexpected error during reading of multiple sequence file",
2004                                                JOptionPane.ERROR_MESSAGE );
2005                 return;
2006             }
2007             catch ( final Exception e ) {
2008                 try {
2009                     _mainpanel.getCurrentTreePanel().setArrowCursor();
2010                 }
2011                 catch ( final Exception ex ) {
2012                     // Do nothing.
2013                 }
2014                 e.printStackTrace();
2015                 JOptionPane.showMessageDialog( this,
2016                                                e.getLocalizedMessage(),
2017                                                "Unexpected error during reading of multiple sequence file",
2018                                                JOptionPane.ERROR_MESSAGE );
2019                 return;
2020             }
2021             if ( ( seqs == null ) || ( seqs.size() < 1 ) ) {
2022                 JOptionPane.showMessageDialog( this,
2023                                                "Multiple sequence file is empty",
2024                                                "Illegal multiple sequence file",
2025                                                JOptionPane.ERROR_MESSAGE );
2026                 return;
2027             }
2028             if ( seqs.size() < 4 ) {
2029                 JOptionPane.showMessageDialog( this,
2030                                                "Multiple sequence file needs to contain at least 3 sequences",
2031                                                "Illegal multiple sequence file",
2032                                                JOptionPane.ERROR_MESSAGE );
2033                 return;
2034             }
2035             //  if ( msa.getLength() < 2 ) {
2036             //       JOptionPane.showMessageDialog( this,
2037             //                                      "Multiple sequence alignment needs to contain at least 2 residues",
2038             //                                      "Illegal multiple sequence file",
2039             //                                      JOptionPane.ERROR_MESSAGE );
2040             //       return;
2041             //   }
2042             System.gc();
2043             setSeqsFile( _seqs_filechooser.getSelectedFile() );
2044             setSeqs( seqs );
2045         }
2046     }
2047
2048     public void readMsaFromFile() {
2049         // Set an initial directory if none set yet
2050         final File my_dir = getCurrentDir();
2051         _msa_filechooser.setMultiSelectionEnabled( false );
2052         // Open file-open dialog and set current directory
2053         if ( my_dir != null ) {
2054             _msa_filechooser.setCurrentDirectory( my_dir );
2055         }
2056         final int result = _msa_filechooser.showOpenDialog( _contentpane );
2057         // All done: get the msa
2058         final File file = _msa_filechooser.getSelectedFile();
2059         setCurrentDir( _msa_filechooser.getCurrentDirectory() );
2060         if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) {
2061             setMsaFile( null );
2062             setMsa( null );
2063             Msa msa = null;
2064             try {
2065                 final InputStream is = new FileInputStream( file );
2066                 if ( FastaParser.isLikelyFasta( file ) ) {
2067                     msa = FastaParser.parseMsa( is );
2068                 }
2069                 else {
2070                     msa = GeneralMsaParser.parse( is );
2071                 }
2072             }
2073             catch ( final MsaFormatException e ) {
2074                 try {
2075                     _mainpanel.getCurrentTreePanel().setArrowCursor();
2076                 }
2077                 catch ( final Exception ex ) {
2078                     // Do nothing.
2079                 }
2080                 JOptionPane.showMessageDialog( this,
2081                                                e.getLocalizedMessage(),
2082                                                "Multiple sequence alignment format error",
2083                                                JOptionPane.ERROR_MESSAGE );
2084                 return;
2085             }
2086             catch ( final IOException e ) {
2087                 try {
2088                     _mainpanel.getCurrentTreePanel().setArrowCursor();
2089                 }
2090                 catch ( final Exception ex ) {
2091                     // Do nothing.
2092                 }
2093                 JOptionPane.showMessageDialog( this,
2094                                                e.getLocalizedMessage(),
2095                                                "Failed to read multiple sequence alignment",
2096                                                JOptionPane.ERROR_MESSAGE );
2097                 return;
2098             }
2099             catch ( final IllegalArgumentException e ) {
2100                 try {
2101                     _mainpanel.getCurrentTreePanel().setArrowCursor();
2102                 }
2103                 catch ( final Exception ex ) {
2104                     // Do nothing.
2105                 }
2106                 JOptionPane.showMessageDialog( this,
2107                                                e.getLocalizedMessage(),
2108                                                "Unexpected error during reading of multiple sequence alignment",
2109                                                JOptionPane.ERROR_MESSAGE );
2110                 return;
2111             }
2112             catch ( final Exception e ) {
2113                 try {
2114                     _mainpanel.getCurrentTreePanel().setArrowCursor();
2115                 }
2116                 catch ( final Exception ex ) {
2117                     // Do nothing.
2118                 }
2119                 e.printStackTrace();
2120                 JOptionPane.showMessageDialog( this,
2121                                                e.getLocalizedMessage(),
2122                                                "Unexpected error during reading of multiple sequence alignment",
2123                                                JOptionPane.ERROR_MESSAGE );
2124                 return;
2125             }
2126             if ( ( msa == null ) || ( msa.getNumberOfSequences() < 1 ) ) {
2127                 JOptionPane.showMessageDialog( this,
2128                                                "Multiple sequence alignment is empty",
2129                                                "Illegal Multiple Sequence Alignment",
2130                                                JOptionPane.ERROR_MESSAGE );
2131                 return;
2132             }
2133             if ( msa.getNumberOfSequences() < 4 ) {
2134                 JOptionPane.showMessageDialog( this,
2135                                                "Multiple sequence alignment needs to contain at least 3 sequences",
2136                                                "Illegal multiple sequence alignment",
2137                                                JOptionPane.ERROR_MESSAGE );
2138                 return;
2139             }
2140             if ( msa.getLength() < 2 ) {
2141                 JOptionPane.showMessageDialog( this,
2142                                                "Multiple sequence alignment needs to contain at least 2 residues",
2143                                                "Illegal multiple sequence alignment",
2144                                                JOptionPane.ERROR_MESSAGE );
2145                 return;
2146             }
2147             System.gc();
2148             setMsaFile( _msa_filechooser.getSelectedFile() );
2149             setMsa( msa );
2150         }
2151     }
2152
2153     @Override
2154     void readPhylogeniesFromURL() {
2155         URL url = null;
2156         Phylogeny[] phys = null;
2157         final String message = "Please enter a complete URL, for example \"http://www.phyloxml.org/examples/apaf.xml\"";
2158         final String url_string = JOptionPane.showInputDialog( this,
2159                                                                message,
2160                                                                "Use URL/webservice to obtain a phylogeny",
2161                                                                JOptionPane.QUESTION_MESSAGE );
2162         boolean nhx_or_nexus = false;
2163         if ( ( url_string != null ) && ( url_string.length() > 0 ) ) {
2164             try {
2165                 url = new URL( url_string );
2166                 PhylogenyParser parser = null;
2167                 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
2168                     parser = new TolParser();
2169                 }
2170                 else {
2171                     parser = ParserUtils.createParserDependingOnUrlContents( url, getConfiguration()
2172                             .isValidatePhyloXmlAgainstSchema() );
2173                 }
2174                 if ( parser instanceof NexusPhylogeniesParser ) {
2175                     nhx_or_nexus = true;
2176                 }
2177                 else if ( parser instanceof NHXParser ) {
2178                     nhx_or_nexus = true;
2179                 }
2180                 if ( _mainpanel.getCurrentTreePanel() != null ) {
2181                     _mainpanel.getCurrentTreePanel().setWaitCursor();
2182                 }
2183                 else {
2184                     _mainpanel.setWaitCursor();
2185                 }
2186                 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
2187                 phys = factory.create( url.openStream(), parser );
2188             }
2189             catch ( final MalformedURLException e ) {
2190                 JOptionPane.showMessageDialog( this,
2191                                                "Malformed URL: " + url + "\n" + e.getLocalizedMessage(),
2192                                                "Malformed URL",
2193                                                JOptionPane.ERROR_MESSAGE );
2194             }
2195             catch ( final IOException e ) {
2196                 JOptionPane.showMessageDialog( this,
2197                                                "Could not read from " + url + "\n"
2198                                                        + ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ),
2199                                                "Failed to read URL",
2200                                                JOptionPane.ERROR_MESSAGE );
2201             }
2202             catch ( final Exception e ) {
2203                 JOptionPane.showMessageDialog( this,
2204                                                ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ),
2205                                                "Unexpected Exception",
2206                                                JOptionPane.ERROR_MESSAGE );
2207             }
2208             finally {
2209                 if ( _mainpanel.getCurrentTreePanel() != null ) {
2210                     _mainpanel.getCurrentTreePanel().setArrowCursor();
2211                 }
2212                 else {
2213                     _mainpanel.setArrowCursor();
2214                 }
2215             }
2216             if ( ( phys != null ) && ( phys.length > 0 ) ) {
2217                 if ( nhx_or_nexus && getOptions().isInternalNumberAreConfidenceForNhParsing() ) {
2218                     for( final Phylogeny phy : phys ) {
2219                         PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
2220                     }
2221                 }
2222                 AptxUtil.addPhylogeniesToTabs( phys,
2223                                                new File( url.getFile() ).getName(),
2224                                                new File( url.getFile() ).toString(),
2225                                                getConfiguration(),
2226                                                getMainPanel() );
2227                 _mainpanel.getControlPanel().showWhole();
2228             }
2229         }
2230         activateSaveAllIfNeeded();
2231         System.gc();
2232     }
2233
2234     private void readSpeciesTreeFromFile() {
2235         Phylogeny t = null;
2236         boolean exception = false;
2237         final File my_dir = getCurrentDir();
2238         _open_filechooser_for_species_tree.setSelectedFile( new File( "" ) );
2239         if ( my_dir != null ) {
2240             _open_filechooser_for_species_tree.setCurrentDirectory( my_dir );
2241         }
2242         final int result = _open_filechooser_for_species_tree.showOpenDialog( _contentpane );
2243         final File file = _open_filechooser_for_species_tree.getSelectedFile();
2244         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2245             if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrameApplication.xmlfilter ) {
2246                 try {
2247                     final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( new PhyloXmlParser(), file );
2248                     t = trees[ 0 ];
2249                 }
2250                 catch ( final Exception e ) {
2251                     exception = true;
2252                     exceptionOccuredDuringOpenFile( e );
2253                 }
2254             }
2255             else if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrameApplication.tolfilter ) {
2256                 try {
2257                     final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( new TolParser(), file );
2258                     t = trees[ 0 ];
2259                 }
2260                 catch ( final Exception e ) {
2261                     exception = true;
2262                     exceptionOccuredDuringOpenFile( e );
2263                 }
2264             }
2265             // "*.*":
2266             else {
2267                 try {
2268                     final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( new PhyloXmlParser(), file );
2269                     t = trees[ 0 ];
2270                 }
2271                 catch ( final Exception e ) {
2272                     exception = true;
2273                     exceptionOccuredDuringOpenFile( e );
2274                 }
2275             }
2276             if ( !exception && ( t != null ) && !t.isRooted() ) {
2277                 exception = true;
2278                 t = null;
2279                 JOptionPane.showMessageDialog( this,
2280                                                "Species tree is not rooted",
2281                                                "Species tree not loaded",
2282                                                JOptionPane.ERROR_MESSAGE );
2283             }
2284             if ( !exception && ( t != null ) ) {
2285                 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
2286                 for( final PhylogenyNodeIterator it = t.iteratorExternalForward(); it.hasNext(); ) {
2287                     final PhylogenyNode node = it.next();
2288                     if ( !node.getNodeData().isHasTaxonomy() ) {
2289                         exception = true;
2290                         t = null;
2291                         JOptionPane
2292                                 .showMessageDialog( this,
2293                                                     "Species tree contains external node(s) without taxonomy information",
2294                                                     "Species tree not loaded",
2295                                                     JOptionPane.ERROR_MESSAGE );
2296                         break;
2297                     }
2298                     else {
2299                         if ( tax_set.contains( node.getNodeData().getTaxonomy() ) ) {
2300                             exception = true;
2301                             t = null;
2302                             JOptionPane.showMessageDialog( this,
2303                                                            "Taxonomy ["
2304                                                                    + node.getNodeData().getTaxonomy().asSimpleText()
2305                                                                    + "] is not unique in species tree",
2306                                                            "Species tree not loaded",
2307                                                            JOptionPane.ERROR_MESSAGE );
2308                             break;
2309                         }
2310                         else {
2311                             tax_set.add( node.getNodeData().getTaxonomy() );
2312                         }
2313                     }
2314                 }
2315             }
2316             if ( !exception && ( t != null ) ) {
2317                 _species_tree = t;
2318                 JOptionPane.showMessageDialog( this,
2319                                                "Species tree successfully loaded",
2320                                                "Species tree loaded",
2321                                                JOptionPane.INFORMATION_MESSAGE );
2322             }
2323             _contentpane.repaint();
2324             System.gc();
2325         }
2326     }
2327
2328     private void setCurrentDir( final File current_dir ) {
2329         _current_dir = current_dir;
2330     }
2331
2332     private void setMinNotCollapseConfidenceValue( final double min_not_collapse ) {
2333         _min_not_collapse = min_not_collapse;
2334     }
2335
2336     private void setSpecialOptionsForNexParser( final NexusPhylogeniesParser nex ) {
2337         nex.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() );
2338     }
2339
2340     private void setSpecialOptionsForNhxParser( final NHXParser nhx ) {
2341         nhx.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() );
2342         nhx.setTaxonomyExtraction( getOptions().getTaxonomyExtraction() );
2343     }
2344
2345     private void writeAllToFile() {
2346         if ( ( getMainPanel().getTabbedPane() == null ) || ( getMainPanel().getTabbedPane().getTabCount() < 1 ) ) {
2347             return;
2348         }
2349         final File my_dir = getCurrentDir();
2350         if ( my_dir != null ) {
2351             _save_filechooser.setCurrentDirectory( my_dir );
2352         }
2353         _save_filechooser.setSelectedFile( new File( "" ) );
2354         final int result = _save_filechooser.showSaveDialog( _contentpane );
2355         final File file = _save_filechooser.getSelectedFile();
2356         setCurrentDir( _save_filechooser.getCurrentDirectory() );
2357         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2358             if ( file.exists() ) {
2359                 final int i = JOptionPane.showConfirmDialog( this,
2360                                                              file + " already exists. Overwrite?",
2361                                                              "Warning",
2362                                                              JOptionPane.OK_CANCEL_OPTION,
2363                                                              JOptionPane.WARNING_MESSAGE );
2364                 if ( i != JOptionPane.OK_OPTION ) {
2365                     return;
2366                 }
2367                 else {
2368                     try {
2369                         file.delete();
2370                     }
2371                     catch ( final Exception e ) {
2372                         JOptionPane.showMessageDialog( this,
2373                                                        "Failed to delete: " + file,
2374                                                        "Error",
2375                                                        JOptionPane.WARNING_MESSAGE );
2376                     }
2377                 }
2378             }
2379             final int count = getMainPanel().getTabbedPane().getTabCount();
2380             final List<Phylogeny> trees = new ArrayList<Phylogeny>();
2381             for( int i = 0; i < count; ++i ) {
2382                 trees.add( getMainPanel().getPhylogeny( i ) );
2383                 getMainPanel().getTreePanels().get( i ).setEdited( false );
2384             }
2385             final PhylogenyWriter writer = new PhylogenyWriter();
2386             try {
2387                 writer.toPhyloXML( file, trees, 0, ForesterUtil.LINE_SEPARATOR );
2388             }
2389             catch ( final IOException e ) {
2390                 JOptionPane.showMessageDialog( this,
2391                                                "Failed to write to: " + file,
2392                                                "Error",
2393                                                JOptionPane.WARNING_MESSAGE );
2394             }
2395         }
2396     }
2397
2398     private boolean writeAsNewHampshire( final Phylogeny t, boolean exception, final File file ) {
2399         try {
2400             final PhylogenyWriter writer = new PhylogenyWriter();
2401             writer.toNewHampshire( t, false, true, getOptions().getNhConversionSupportValueStyle(), file );
2402         }
2403         catch ( final Exception e ) {
2404             exception = true;
2405             exceptionOccuredDuringSaveAs( e );
2406         }
2407         return exception;
2408     }
2409
2410     private boolean writeAsNexus( final Phylogeny t, boolean exception, final File file ) {
2411         try {
2412             final PhylogenyWriter writer = new PhylogenyWriter();
2413             writer.toNexus( file, t, getOptions().getNhConversionSupportValueStyle() );
2414         }
2415         catch ( final Exception e ) {
2416             exception = true;
2417             exceptionOccuredDuringSaveAs( e );
2418         }
2419         return exception;
2420     }
2421
2422     private boolean writeAsNHX( final Phylogeny t, boolean exception, final File file ) {
2423         try {
2424             final PhylogenyWriter writer = new PhylogenyWriter();
2425             writer.toNewHampshireX( t, file );
2426         }
2427         catch ( final Exception e ) {
2428             exception = true;
2429             exceptionOccuredDuringSaveAs( e );
2430         }
2431         return exception;
2432     }
2433
2434     private boolean writeAsPhyloXml( final Phylogeny t, boolean exception, final File file ) {
2435         try {
2436             final PhylogenyWriter writer = new PhylogenyWriter();
2437             writer.toPhyloXML( file, t, 0 );
2438         }
2439         catch ( final Exception e ) {
2440             exception = true;
2441             exceptionOccuredDuringSaveAs( e );
2442         }
2443         return exception;
2444     }
2445
2446     void writePhylogenyToGraphicsFile( final String file_name, final GraphicsExportType type ) {
2447         _mainpanel.getCurrentTreePanel().setParametersForPainting( _mainpanel.getCurrentTreePanel().getWidth(),
2448                                                                    _mainpanel.getCurrentTreePanel().getHeight(),
2449                                                                    true );
2450         String file_written_to = "";
2451         boolean error = false;
2452         try {
2453             file_written_to = AptxUtil.writePhylogenyToGraphicsFile( file_name,
2454                                                                      _mainpanel.getCurrentTreePanel().getWidth(),
2455                                                                      _mainpanel.getCurrentTreePanel().getHeight(),
2456                                                                      _mainpanel.getCurrentTreePanel(),
2457                                                                      _mainpanel.getControlPanel(),
2458                                                                      type,
2459                                                                      getOptions() );
2460         }
2461         catch ( final IOException e ) {
2462             error = true;
2463             JOptionPane.showMessageDialog( this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE );
2464         }
2465         if ( !error ) {
2466             if ( ( file_written_to != null ) && ( file_written_to.length() > 0 ) ) {
2467                 JOptionPane.showMessageDialog( this,
2468                                                "Wrote image to: " + file_written_to,
2469                                                "Graphics Export",
2470                                                JOptionPane.INFORMATION_MESSAGE );
2471             }
2472             else {
2473                 JOptionPane.showMessageDialog( this,
2474                                                "There was an unknown problem when attempting to write to an image file: \""
2475                                                        + file_name + "\"",
2476                                                "Error",
2477                                                JOptionPane.ERROR_MESSAGE );
2478             }
2479         }
2480         _contentpane.repaint();
2481     }
2482
2483     private void writeToFile( final Phylogeny t ) {
2484         if ( t == null ) {
2485             return;
2486         }
2487         String initial_filename = null;
2488         if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) {
2489             try {
2490                 initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().getCanonicalPath();
2491             }
2492             catch ( final IOException e ) {
2493                 initial_filename = null;
2494             }
2495         }
2496         if ( !ForesterUtil.isEmpty( initial_filename ) ) {
2497             _save_filechooser.setSelectedFile( new File( initial_filename ) );
2498         }
2499         else {
2500             _save_filechooser.setSelectedFile( new File( "" ) );
2501         }
2502         final File my_dir = getCurrentDir();
2503         if ( my_dir != null ) {
2504             _save_filechooser.setCurrentDirectory( my_dir );
2505         }
2506         final int result = _save_filechooser.showSaveDialog( _contentpane );
2507         final File file = _save_filechooser.getSelectedFile();
2508         setCurrentDir( _save_filechooser.getCurrentDirectory() );
2509         boolean exception = false;
2510         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2511             if ( file.exists() ) {
2512                 final int i = JOptionPane.showConfirmDialog( this,
2513                                                              file + " already exists.\nOverwrite?",
2514                                                              "Overwrite?",
2515                                                              JOptionPane.OK_CANCEL_OPTION,
2516                                                              JOptionPane.QUESTION_MESSAGE );
2517                 if ( i != JOptionPane.OK_OPTION ) {
2518                     return;
2519                 }
2520                 else {
2521                     final File to = new File( file.getAbsoluteFile().toString() + Constants.BACKUP_FILE_SUFFIX );
2522                     try {
2523                         ForesterUtil.copyFile( file, to );
2524                     }
2525                     catch ( final Exception e ) {
2526                         JOptionPane.showMessageDialog( this,
2527                                                        "Failed to create backup copy " + to,
2528                                                        "Failed to Create Backup Copy",
2529                                                        JOptionPane.WARNING_MESSAGE );
2530                     }
2531                     try {
2532                         file.delete();
2533                     }
2534                     catch ( final Exception e ) {
2535                         JOptionPane.showMessageDialog( this,
2536                                                        "Failed to delete: " + file,
2537                                                        "Failed to Delete",
2538                                                        JOptionPane.WARNING_MESSAGE );
2539                     }
2540                 }
2541             }
2542             if ( _save_filechooser.getFileFilter() == MainFrameApplication.nhfilter ) {
2543                 exception = writeAsNewHampshire( t, exception, file );
2544             }
2545             else if ( _save_filechooser.getFileFilter() == MainFrameApplication.nhxfilter ) {
2546                 exception = writeAsNHX( t, exception, file );
2547             }
2548             else if ( _save_filechooser.getFileFilter() == MainFrameApplication.xmlfilter ) {
2549                 exception = writeAsPhyloXml( t, exception, file );
2550             }
2551             else if ( _save_filechooser.getFileFilter() == MainFrameApplication.nexusfilter ) {
2552                 exception = writeAsNexus( t, exception, file );
2553             }
2554             // "*.*":
2555             else {
2556                 final String file_name = file.getName().trim().toLowerCase();
2557                 if ( file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2558                         || file_name.endsWith( ".tree" ) ) {
2559                     exception = writeAsNewHampshire( t, exception, file );
2560                 }
2561                 else if ( file_name.endsWith( ".nhx" ) ) {
2562                     exception = writeAsNHX( t, exception, file );
2563                 }
2564                 else if ( file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) ) {
2565                     exception = writeAsNexus( t, exception, file );
2566                 }
2567                 // XML is default:
2568                 else {
2569                     exception = writeAsPhyloXml( t, exception, file );
2570                 }
2571             }
2572             if ( !exception ) {
2573                 getMainPanel().setTitleOfSelectedTab( file.getName() );
2574                 getMainPanel().getCurrentTreePanel().setTreeFile( file );
2575                 getMainPanel().getCurrentTreePanel().setEdited( false );
2576             }
2577         }
2578     }
2579
2580     private void writeToGraphicsFile( final Phylogeny t, final GraphicsExportType type ) {
2581         if ( ( t == null ) || t.isEmpty() ) {
2582             return;
2583         }
2584         String initial_filename = "";
2585         if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) {
2586             initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().toString();
2587         }
2588         if ( initial_filename.indexOf( '.' ) > 0 ) {
2589             initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) );
2590         }
2591         initial_filename = initial_filename + "." + type;
2592         _writetographics_filechooser.setSelectedFile( new File( initial_filename ) );
2593         final File my_dir = getCurrentDir();
2594         if ( my_dir != null ) {
2595             _writetographics_filechooser.setCurrentDirectory( my_dir );
2596         }
2597         final int result = _writetographics_filechooser.showSaveDialog( _contentpane );
2598         File file = _writetographics_filechooser.getSelectedFile();
2599         setCurrentDir( _writetographics_filechooser.getCurrentDirectory() );
2600         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2601             if ( !file.toString().toLowerCase().endsWith( type.toString() ) ) {
2602                 file = new File( file.toString() + "." + type );
2603             }
2604             if ( file.exists() ) {
2605                 final int i = JOptionPane.showConfirmDialog( this,
2606                                                              file + " already exists. Overwrite?",
2607                                                              "Warning",
2608                                                              JOptionPane.OK_CANCEL_OPTION,
2609                                                              JOptionPane.WARNING_MESSAGE );
2610                 if ( i != JOptionPane.OK_OPTION ) {
2611                     return;
2612                 }
2613                 else {
2614                     try {
2615                         file.delete();
2616                     }
2617                     catch ( final Exception e ) {
2618                         JOptionPane.showMessageDialog( this,
2619                                                        "Failed to delete: " + file,
2620                                                        "Error",
2621                                                        JOptionPane.WARNING_MESSAGE );
2622                     }
2623                 }
2624             }
2625             writePhylogenyToGraphicsFile( file.toString(), type );
2626         }
2627     }
2628
2629     private void writeToPdf( final Phylogeny t ) {
2630         if ( ( t == null ) || t.isEmpty() ) {
2631             return;
2632         }
2633         String initial_filename = "";
2634         if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) {
2635             initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().toString();
2636         }
2637         if ( initial_filename.indexOf( '.' ) > 0 ) {
2638             initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) );
2639         }
2640         initial_filename = initial_filename + ".pdf";
2641         _writetopdf_filechooser.setSelectedFile( new File( initial_filename ) );
2642         final File my_dir = getCurrentDir();
2643         if ( my_dir != null ) {
2644             _writetopdf_filechooser.setCurrentDirectory( my_dir );
2645         }
2646         final int result = _writetopdf_filechooser.showSaveDialog( _contentpane );
2647         File file = _writetopdf_filechooser.getSelectedFile();
2648         setCurrentDir( _writetopdf_filechooser.getCurrentDirectory() );
2649         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2650             if ( !file.toString().toLowerCase().endsWith( ".pdf" ) ) {
2651                 file = new File( file.toString() + ".pdf" );
2652             }
2653             if ( file.exists() ) {
2654                 final int i = JOptionPane.showConfirmDialog( this,
2655                                                              file + " already exists. Overwrite?",
2656                                                              "WARNING",
2657                                                              JOptionPane.OK_CANCEL_OPTION,
2658                                                              JOptionPane.WARNING_MESSAGE );
2659                 if ( i != JOptionPane.OK_OPTION ) {
2660                     return;
2661                 }
2662             }
2663             printPhylogenyToPdf( file.toString() );
2664         }
2665     }
2666
2667     static MainFrame createInstance( final Phylogeny[] phys, final Configuration config, final String title ) {
2668         return new MainFrameApplication( phys, config, title );
2669     }
2670
2671     public static MainFrameApplication createInstance( final Phylogeny[] phys, final Configuration config ) {
2672         return new MainFrameApplication( phys, config );
2673     }
2674
2675     static MainFrame createInstance( final Phylogeny[] phys, final String config_file_name, final String title ) {
2676         return new MainFrameApplication( phys, config_file_name, title );
2677     }
2678
2679     public static MainFrame createInstance( final Phylogeny[] phys,
2680                                             final Configuration config,
2681                                             final String title,
2682                                             final File current_dir ) {
2683         return new MainFrameApplication( phys, config, title, current_dir );
2684     }
2685
2686     static void setTextForGraphicsSizeChooserMenuItem( final JMenuItem mi, final Options o ) {
2687         mi.setText( "Enter Default Size for Graphics Export... (current: " + o.getPrintSizeX() + ", "
2688                 + o.getPrintSizeY() + ")" );
2689     }
2690
2691     static void setTextForPdfLineWidthChooserMenuItem( final JMenuItem mi, final Options o ) {
2692         mi.setText( "Enter Default Line Width for PDF Export... (current: " + o.getPrintLineWidth() + ")" );
2693     }
2694
2695     static void warnIfNotPhyloXmlValidation( final Configuration c ) {
2696         if ( !c.isValidatePhyloXmlAgainstSchema() ) {
2697             JOptionPane
2698                     .showMessageDialog( null,
2699                                         ForesterUtil
2700                                                 .wordWrap( "phyloXML XSD-based validation is turned off [enable with line 'validate_against_phyloxml_xsd_schem: true' in configuration file]",
2701                                                            80 ),
2702                                         "Warning",
2703                                         JOptionPane.WARNING_MESSAGE );
2704         }
2705     }
2706
2707     private void setPhylogeneticInferenceOptions( final PhylogeneticInferenceOptions phylogenetic_inference_options ) {
2708         _phylogenetic_inference_options = phylogenetic_inference_options;
2709     }
2710
2711     private PhylogeneticInferenceOptions getPhylogeneticInferenceOptions() {
2712         if ( _phylogenetic_inference_options == null ) {
2713             _phylogenetic_inference_options = new PhylogeneticInferenceOptions();
2714         }
2715         return _phylogenetic_inference_options;
2716     }
2717
2718     public Msa getMsa() {
2719         return _msa;
2720     }
2721
2722     void setMsa( final Msa msa ) {
2723         _msa = msa;
2724     }
2725
2726     void setMsaFile( final File msa_file ) {
2727         _msa_file = msa_file;
2728     }
2729
2730     public File getMsaFile() {
2731         return _msa_file;
2732     }
2733
2734     public List<Sequence> getSeqs() {
2735         return _seqs;
2736     }
2737
2738     void setSeqs( final List<Sequence> seqs ) {
2739         _seqs = seqs;
2740     }
2741
2742     void setSeqsFile( final File seqs_file ) {
2743         _seqs_file = seqs_file;
2744     }
2745
2746     public File getSeqsFile() {
2747         return _seqs_file;
2748     }
2749 } // MainFrameApplication.
2750
2751 class NexusFilter extends FileFilter {
2752
2753     @Override
2754     public boolean accept( final File f ) {
2755         final String file_name = f.getName().trim().toLowerCase();
2756         return file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) || file_name.endsWith( ".nx" )
2757                 || file_name.endsWith( ".tre" ) || f.isDirectory();
2758     }
2759
2760     @Override
2761     public String getDescription() {
2762         return "Nexus files (*.nex, *.nexus, *.nx, *.tre)";
2763     }
2764 } // NexusFilter
2765
2766 class NHFilter extends FileFilter {
2767
2768     @Override
2769     public boolean accept( final File f ) {
2770         final String file_name = f.getName().trim().toLowerCase();
2771         return file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2772                 || file_name.endsWith( ".tr" ) || file_name.endsWith( ".tree" ) || file_name.endsWith( ".dnd" )
2773                 || file_name.endsWith( ".ph" ) || file_name.endsWith( ".phb" ) || file_name.endsWith( ".nwk" )
2774                 || f.isDirectory();
2775     }
2776
2777     @Override
2778     public String getDescription() {
2779         return "New Hampshire - Newick files (*.nh, *.newick, *.phy, *.tree, *.dnd, *.tr, *.ph, *.phb, *.nwk)";
2780     }
2781 } // NHFilter
2782
2783 class NHXFilter extends FileFilter {
2784
2785     @Override
2786     public boolean accept( final File f ) {
2787         final String file_name = f.getName().trim().toLowerCase();
2788         return file_name.endsWith( ".nhx" ) || f.isDirectory();
2789     }
2790
2791     @Override
2792     public String getDescription() {
2793         return "NHX files (*.nhx)";
2794     }
2795 }
2796
2797 class PdfFilter extends FileFilter {
2798
2799     @Override
2800     public boolean accept( final File f ) {
2801         return f.getName().trim().toLowerCase().endsWith( ".pdf" ) || f.isDirectory();
2802     }
2803
2804     @Override
2805     public String getDescription() {
2806         return "PDF files (*.pdf)";
2807     }
2808 } // PdfFilter
2809
2810 class TolFilter extends FileFilter {
2811
2812     @Override
2813     public boolean accept( final File f ) {
2814         final String file_name = f.getName().trim().toLowerCase();
2815         return ( file_name.endsWith( ".tol" ) || file_name.endsWith( ".tolxml" ) || file_name.endsWith( ".zip" ) || f
2816                 .isDirectory() ) && ( !file_name.endsWith( ".xml.zip" ) );
2817     }
2818
2819     @Override
2820     public String getDescription() {
2821         return "Tree of Life files (*.tol, *.tolxml)";
2822     }
2823 } // TolFilter
2824
2825 class XMLFilter extends FileFilter {
2826
2827     @Override
2828     public boolean accept( final File f ) {
2829         final String file_name = f.getName().trim().toLowerCase();
2830         return file_name.endsWith( ".xml" ) || file_name.endsWith( ".phyloxml" ) || file_name.endsWith( "phylo.xml" )
2831                 || file_name.endsWith( ".pxml" ) || file_name.endsWith( ".zip" ) || f.isDirectory();
2832     }
2833
2834     @Override
2835     public String getDescription() {
2836         return "phyloXML files (*.xml, *.phyloxml, *phylo.xml, *.pxml, *.zip)";
2837     }
2838 } // XMLFilter