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