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