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