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