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