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