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