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