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