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