some additions being added
[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.Map;
46 import java.util.Set;
47
48 import javax.swing.ButtonGroup;
49 import javax.swing.JCheckBoxMenuItem;
50 import javax.swing.JFileChooser;
51 import javax.swing.JMenu;
52 import javax.swing.JMenuBar;
53 import javax.swing.JMenuItem;
54 import javax.swing.JOptionPane;
55 import javax.swing.JRadioButtonMenuItem;
56 import javax.swing.UIManager;
57 import javax.swing.UnsupportedLookAndFeelException;
58 import javax.swing.WindowConstants;
59 import javax.swing.event.ChangeEvent;
60 import javax.swing.event.ChangeListener;
61
62 import org.forester.analysis.TaxonomyDataManager;
63 import org.forester.archaeopteryx.Options.CLADOGRAM_TYPE;
64 import org.forester.archaeopteryx.Options.NODE_LABEL_DIRECTION;
65 import org.forester.archaeopteryx.Options.PHYLOGENY_GRAPHICS_TYPE;
66 import org.forester.archaeopteryx.tools.InferenceManager;
67 import org.forester.archaeopteryx.tools.PhyloInferenceDialog;
68 import org.forester.archaeopteryx.tools.PhylogeneticInferenceOptions;
69 import org.forester.archaeopteryx.tools.PhylogeneticInferrer;
70 import org.forester.archaeopteryx.tools.SequenceDataRetriver;
71 import org.forester.archaeopteryx.webservices.PhylogeniesWebserviceClient;
72 import org.forester.archaeopteryx.webservices.WebservicesManager;
73 import org.forester.io.parsers.FastaParser;
74 import org.forester.io.parsers.GeneralMsaParser;
75 import org.forester.io.parsers.PhylogenyParser;
76 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
77 import org.forester.io.parsers.nhx.NHXParser;
78 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
79 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
80 import org.forester.io.parsers.phyloxml.PhyloXmlParser;
81 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
82 import org.forester.io.parsers.tol.TolParser;
83 import org.forester.io.parsers.util.ParserUtils;
84 import org.forester.io.writers.SequenceWriter;
85 import org.forester.msa.Msa;
86 import org.forester.msa.MsaFormatException;
87 import org.forester.phylogeny.Phylogeny;
88 import org.forester.phylogeny.PhylogenyMethods;
89 import org.forester.phylogeny.PhylogenyNode;
90 import org.forester.phylogeny.PhylogenyNode.NH_CONVERSION_SUPPORT_VALUE_STYLE;
91 import org.forester.phylogeny.data.Confidence;
92 import org.forester.phylogeny.data.PhylogenyDataUtil;
93 import org.forester.phylogeny.data.Sequence;
94 import org.forester.phylogeny.data.Taxonomy;
95 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
96 import org.forester.phylogeny.factories.PhylogenyFactory;
97 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
98 import org.forester.sequence.MolecularSequence;
99 import org.forester.util.BasicDescriptiveStatistics;
100 import org.forester.util.BasicTable;
101 import org.forester.util.BasicTableParser;
102 import org.forester.util.DescriptiveStatistics;
103 import org.forester.util.ForesterUtil;
104
105 public final class MainFrameApplication extends MainFrame {
106
107     private final static int             FRAME_X_SIZE                    = 800;
108     private final static int             FRAME_Y_SIZE                    = 800;
109     // Filters for the file-open dialog (classes defined in this file)
110     private static final long            serialVersionUID                = -799735726778865234L;
111     private static final boolean         PREPROCESS_TREES                = false;
112     private final JFileChooser           _values_filechooser;
113     private final JFileChooser           _sequences_filechooser;
114     private final JFileChooser           _open_filechooser;
115     private final JFileChooser           _msa_filechooser;
116     private final JFileChooser           _seqs_pi_filechooser;
117     private final JFileChooser           _open_filechooser_for_species_tree;
118     // Application-only print menu items
119     private JMenuItem                    _collapse_below_threshold;
120     private JMenuItem                    _collapse_below_branch_length;
121     private JMenuItem                    _collapse_by_taxonomic_rank;
122     private ButtonGroup                  _radio_group_1;
123     private ButtonGroup                  _radio_group_2;
124     // Others:
125     double                               _min_not_collapse               = AptxConstants.MIN_NOT_COLLAPSE_DEFAULT;
126     double                               _min_not_collapse_bl            = 0.001;
127     // Phylogeny Inference menu
128     private JMenu                        _inference_menu;
129     private JMenuItem                    _inference_from_msa_item;
130     private JMenuItem                    _inference_from_seqs_item;
131     // Phylogeny Inference
132     private PhylogeneticInferenceOptions _phylogenetic_inference_options = null;
133     private Msa                          _msa                            = null;
134     private File                         _msa_file                       = null;
135     private List<MolecularSequence>      _seqs                           = null;
136     private File                         _seqs_file                      = null;
137     JMenuItem                            _read_values_jmi;
138     JMenuItem                            _read_seqs_jmi;
139
140     private MainFrameApplication( final Phylogeny[] phys, final Configuration config ) {
141         _configuration = config;
142         if ( _configuration == null ) {
143             throw new IllegalArgumentException( "configuration is null" );
144         }
145         setVisible( false );
146         setOptions( Options.createInstance( _configuration ) );
147         _mainpanel = new MainPanel( _configuration, this );
148         _open_filechooser = null;
149         _open_filechooser_for_species_tree = null;
150         _save_filechooser = null;
151         _writetopdf_filechooser = null;
152         _writetographics_filechooser = null;
153         _msa_filechooser = null;
154         _seqs_pi_filechooser = null;
155         _values_filechooser = null;
156         _sequences_filechooser = null;
157         _jmenubar = new JMenuBar();
158         buildFileMenu();
159         buildTypeMenu();
160         _contentpane = getContentPane();
161         _contentpane.setLayout( new BorderLayout() );
162         _contentpane.add( _mainpanel, BorderLayout.CENTER );
163         // App is this big
164         setSize( MainFrameApplication.FRAME_X_SIZE, MainFrameApplication.FRAME_Y_SIZE );
165         // The window listener
166         setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE );
167         addWindowListener( new WindowAdapter() {
168
169             @Override
170             public void windowClosing( final WindowEvent e ) {
171                 exit();
172             }
173         } );
174         //   setVisible( true );
175         if ( ( phys != null ) && ( phys.length > 0 ) ) {
176             AptxUtil.addPhylogeniesToTabs( phys, "", null, _configuration, _mainpanel );
177             validate();
178             getMainPanel().getControlPanel().showWholeAll();
179             getMainPanel().getControlPanel().showWhole();
180         }
181         //activateSaveAllIfNeeded();
182         // ...and its children
183         _contentpane.repaint();
184     }
185
186     private MainFrameApplication( final Phylogeny[] phys, final Configuration config, final String title ) {
187         this( phys, config, title, null );
188     }
189
190     private MainFrameApplication( final Phylogeny[] phys,
191                                   final Configuration config,
192                                   final String title,
193                                   final File current_dir ) {
194         super();
195         _configuration = config;
196         if ( _configuration == null ) {
197             throw new IllegalArgumentException( "configuration is null" );
198         }
199         try {
200             if ( _configuration.isUseNativeUI() ) {
201                 UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
202             }
203             else {
204                 UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
205             }
206         }
207         catch ( final UnsupportedLookAndFeelException e ) {
208             AptxUtil.dieWithSystemError( "unsupported look and feel: " + e.toString() );
209         }
210         catch ( final ClassNotFoundException e ) {
211             AptxUtil.dieWithSystemError( "class not found exception: " + e.toString() );
212         }
213         catch ( final InstantiationException e ) {
214             AptxUtil.dieWithSystemError( "instantiation exception: " + e.toString() );
215         }
216         catch ( final IllegalAccessException e ) {
217             AptxUtil.dieWithSystemError( "illegal access exception: " + e.toString() );
218         }
219         if ( ( current_dir != null ) && current_dir.canRead() && current_dir.isDirectory() ) {
220             setCurrentDir( current_dir );
221         }
222         // hide until everything is ready
223         setVisible( false );
224         setOptions( Options.createInstance( _configuration ) );
225         setInferenceManager( InferenceManager.createInstance( _configuration ) );
226         setPhylogeneticInferenceOptions( PhylogeneticInferenceOptions.createInstance( _configuration ) );
227         // set title
228         setTitle( AptxConstants.PRG_NAME + " " + AptxConstants.VERSION + " (" + AptxConstants.PRG_DATE + ")" );
229         _mainpanel = new MainPanel( _configuration, this );
230         // The file dialogs
231         _open_filechooser = new JFileChooser();
232         _open_filechooser.setMultiSelectionEnabled( true );
233         _open_filechooser.addChoosableFileFilter( MainFrame.xmlfilter );
234         _open_filechooser.addChoosableFileFilter( MainFrame.nhxfilter );
235         _open_filechooser.addChoosableFileFilter( MainFrame.nhfilter );
236         _open_filechooser.addChoosableFileFilter( MainFrame.nexusfilter );
237         _open_filechooser.addChoosableFileFilter( MainFrame.tolfilter );
238         _open_filechooser.addChoosableFileFilter( _open_filechooser.getAcceptAllFileFilter() );
239         _open_filechooser.setFileFilter( MainFrame.defaultfilter );
240         _open_filechooser_for_species_tree = new JFileChooser();
241         _open_filechooser_for_species_tree.setMultiSelectionEnabled( false );
242         _open_filechooser_for_species_tree.addChoosableFileFilter( MainFrame.xmlfilter );
243         _open_filechooser_for_species_tree.addChoosableFileFilter( MainFrame.tolfilter );
244         _open_filechooser_for_species_tree.setFileFilter( MainFrame.xmlfilter );
245         // Msa:
246         _msa_filechooser = new JFileChooser();
247         _msa_filechooser.setName( "Read Multiple Sequence Alignment File" );
248         _msa_filechooser.setMultiSelectionEnabled( false );
249         _msa_filechooser.addChoosableFileFilter( _msa_filechooser.getAcceptAllFileFilter() );
250         _msa_filechooser.addChoosableFileFilter( MainFrame.msafilter );
251         // Seqs:
252         _seqs_pi_filechooser = new JFileChooser();
253         _seqs_pi_filechooser.setName( "Read Sequences File" );
254         _seqs_pi_filechooser.setMultiSelectionEnabled( false );
255         _seqs_pi_filechooser.addChoosableFileFilter( _seqs_pi_filechooser.getAcceptAllFileFilter() );
256         _seqs_pi_filechooser.addChoosableFileFilter( MainFrame.seqsfilter );
257         // Expression
258         _values_filechooser = new JFileChooser();
259         _values_filechooser.setMultiSelectionEnabled( false );
260         // Sequences
261         _sequences_filechooser = new JFileChooser();
262         _sequences_filechooser.setMultiSelectionEnabled( false );
263         try {
264             final String home_dir = System.getProperty( "user.home" );
265             _open_filechooser.setCurrentDirectory( new File( home_dir ) );
266             _open_filechooser_for_species_tree.setCurrentDirectory( new File( home_dir ) );
267             _msa_filechooser.setCurrentDirectory( new File( home_dir ) );
268             _seqs_pi_filechooser.setCurrentDirectory( new File( home_dir ) );
269             _values_filechooser.setCurrentDirectory( new File( home_dir ) );
270             _sequences_filechooser.setCurrentDirectory( new File( home_dir ) );
271         }
272         catch ( final Exception e ) {
273             e.printStackTrace();
274             // Do nothing. Not important.
275         }
276         // build the menu bar
277         _jmenubar = new JMenuBar();
278         if ( !_configuration.isUseNativeUI() ) {
279             _jmenubar.setBackground( getConfiguration().getGuiMenuBackgroundColor() );
280         }
281         buildFileMenu();
282         if ( AptxConstants.__ALLOW_PHYLOGENETIC_INFERENCE ) {
283             buildPhylogeneticInferenceMenu();
284         }
285         buildAnalysisMenu();
286         buildToolsMenu();
287         buildViewMenu();
288         buildFontSizeMenu();
289         buildOptionsMenu();
290         buildTypeMenu();
291         buildHelpMenu();
292         setJMenuBar( _jmenubar );
293         _jmenubar.add( _help_jmenu );
294         _contentpane = getContentPane();
295         _contentpane.setLayout( new BorderLayout() );
296         _contentpane.add( _mainpanel, BorderLayout.CENTER );
297         // App is this big
298         setSize( MainFrameApplication.FRAME_X_SIZE, MainFrameApplication.FRAME_Y_SIZE );
299         //        addWindowFocusListener( new WindowAdapter() {
300         //
301         //            @Override
302         //            public void windowGainedFocus( WindowEvent e ) {
303         //                requestFocusInWindow();
304         //            }
305         //        } );
306         // The window listener
307         setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE );
308         addWindowListener( new WindowAdapter() {
309
310             @Override
311             public void windowClosing( final WindowEvent e ) {
312                 if ( isUnsavedDataPresent() ) {
313                     final int r = JOptionPane.showConfirmDialog( null,
314                                                                  "Exit despite potentially unsaved changes?",
315                                                                  "Exit?",
316                                                                  JOptionPane.YES_NO_OPTION );
317                     if ( r != JOptionPane.YES_OPTION ) {
318                         return;
319                     }
320                 }
321                 else {
322                     final int r = JOptionPane
323                             .showConfirmDialog( null, "Exit Archaeopteryx?", "Exit?", JOptionPane.YES_NO_OPTION );
324                     if ( r != JOptionPane.YES_OPTION ) {
325                         return;
326                     }
327                 }
328                 exit();
329             }
330         } );
331         // The component listener
332         addComponentListener( new ComponentAdapter() {
333
334             @Override
335             public void componentResized( final ComponentEvent e ) {
336                 if ( _mainpanel.getCurrentTreePanel() != null ) {
337                     _mainpanel.getCurrentTreePanel()
338                             .calcParametersForPainting( _mainpanel.getCurrentTreePanel().getWidth(),
339                                                         _mainpanel.getCurrentTreePanel().getHeight() );
340                 }
341             }
342         } );
343         requestFocusInWindow();
344         // addKeyListener( this );
345         setVisible( true );
346         if ( ( phys != null ) && ( phys.length > 0 ) ) {
347             AptxUtil.addPhylogeniesToTabs( phys, title, null, _configuration, _mainpanel );
348             validate();
349             getMainPanel().getControlPanel().showWholeAll();
350             getMainPanel().getControlPanel().showWhole();
351         }
352         activateSaveAllIfNeeded();
353         // ...and its children
354         _contentpane.repaint();
355         System.gc();
356     }
357
358     private MainFrameApplication( final Phylogeny[] phys, final String config_file, final String title ) {
359         // Reads the config file (false, false => not url, not applet):
360         this( phys, new Configuration( config_file, false, false, true ), title );
361     }
362
363     @Override
364     public void actionPerformed( final ActionEvent e ) {
365         try {
366             super.actionPerformed( e );
367             final Object o = e.getSource();
368             // Handle app-specific actions here:
369             if ( o == _open_item ) {
370                 readPhylogeniesFromFile();
371             }
372             if ( o == _open_url_item ) {
373                 readPhylogeniesFromURL();
374             }
375             else if ( o == _new_item ) {
376                 newTree();
377             }
378             else if ( o == _close_item ) {
379                 closeCurrentPane();
380             }
381             else if ( o == _load_species_tree_item ) {
382                 readSpeciesTreeFromFile();
383             }
384             else if ( o == _obtain_detailed_taxonomic_information_jmi ) {
385                 if ( isSubtreeDisplayed() ) {
386                     return;
387                 }
388                 obtainDetailedTaxonomicInformation();
389             }
390             else if ( o == _obtain_detailed_taxonomic_information_deleting_jmi ) {
391                 if ( isSubtreeDisplayed() ) {
392                     return;
393                 }
394                 obtainDetailedTaxonomicInformationDelete();
395             }
396             else if ( o == _obtain_seq_information_jmi ) {
397                 obtainSequenceInformation();
398             }
399             else if ( o == _read_values_jmi ) {
400                 if ( isSubtreeDisplayed() ) {
401                     return;
402                 }
403                 addExpressionValuesFromFile();
404             }
405             else if ( o == _read_seqs_jmi ) {
406                 if ( isSubtreeDisplayed() ) {
407                     return;
408                 }
409                 addSequencesFromFile();
410             }
411             else if ( o == _move_node_names_to_tax_sn_jmi ) {
412                 moveNodeNamesToTaxSn();
413             }
414             else if ( o == _move_node_names_to_seq_names_jmi ) {
415                 moveNodeNamesToSeqNames();
416             }
417             else if ( o == _extract_tax_code_from_node_names_jmi ) {
418                 extractTaxDataFromNodeNames();
419             }
420             else if ( o == _internal_number_are_confidence_for_nh_parsing_cbmi ) {
421                 updateOptions( getOptions() );
422             }
423             else if ( o == _replace_underscores_cbmi ) {
424                 if ( ( _extract_taxonomy_no_rbmi != null ) && !_extract_taxonomy_no_rbmi.isSelected() ) {
425                     _extract_taxonomy_no_rbmi.setSelected( true );
426                 }
427                 updateOptions( getOptions() );
428             }
429             else if ( o == _allow_errors_in_distance_to_parent_cbmi ) {
430                 updateOptions( getOptions() );
431             }
432             else if ( o == _collapse_below_threshold ) {
433                 if ( isSubtreeDisplayed() ) {
434                     return;
435                 }
436                 collapseBelowThreshold();
437             }
438             else if ( o == _collapse_by_taxonomic_rank ) {
439                 if ( isSubtreeDisplayed() ) {
440                     return;
441                 }
442                 collapseByTaxonomicRank();
443             }
444             else if ( o == _collapse_below_branch_length ) {
445                 if ( isSubtreeDisplayed() ) {
446                     return;
447                 }
448                 collapseBelowBranchLengthThreshold();
449             }
450             else if ( ( o == _extract_taxonomy_pfam_strict_rbmi ) || ( o == _extract_taxonomy_pfam_relaxed_rbmi )
451                     || ( o == _extract_taxonomy_agressive_rbmi ) ) {
452                 if ( _replace_underscores_cbmi != null ) {
453                     _replace_underscores_cbmi.setSelected( false );
454                 }
455                 updateOptions( getOptions() );
456             }
457             else if ( o == _extract_taxonomy_no_rbmi ) {
458                 updateOptions( getOptions() );
459             }
460             else if ( o == _inference_from_msa_item ) {
461                 executePhyleneticInference( false );
462             }
463             else if ( o == _inference_from_seqs_item ) {
464                 executePhyleneticInference( true );
465             }
466             _contentpane.repaint();
467         }
468         catch ( final Exception ex ) {
469             AptxUtil.unexpectedException( ex );
470         }
471         catch ( final Error err ) {
472             AptxUtil.unexpectedError( err );
473         }
474     }
475
476     public void end() {
477         _mainpanel.terminate();
478         _contentpane.removeAll();
479         setVisible( false );
480         dispose();
481     }
482
483     @Override
484     public MainPanel getMainPanel() {
485         return _mainpanel;
486     }
487
488     public Msa getMsa() {
489         return _msa;
490     }
491
492     public File getMsaFile() {
493         return _msa_file;
494     }
495
496     public List<MolecularSequence> getSeqs() {
497         return _seqs;
498     }
499
500     public File getSeqsFile() {
501         return _seqs_file;
502     }
503
504     public void readMsaFromFile() {
505         // Set an initial directory if none set yet
506         final File my_dir = getCurrentDir();
507         _msa_filechooser.setMultiSelectionEnabled( false );
508         // Open file-open dialog and set current directory
509         if ( my_dir != null ) {
510             _msa_filechooser.setCurrentDirectory( my_dir );
511         }
512         final int result = _msa_filechooser.showOpenDialog( _contentpane );
513         // All done: get the msa
514         final File file = _msa_filechooser.getSelectedFile();
515         setCurrentDir( _msa_filechooser.getCurrentDirectory() );
516         if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) {
517             setMsaFile( null );
518             setMsa( null );
519             Msa msa = null;
520             try {
521                 final InputStream is = new FileInputStream( file );
522                 if ( FastaParser.isLikelyFasta( file ) ) {
523                     msa = FastaParser.parseMsa( is );
524                 }
525                 else {
526                     msa = GeneralMsaParser.parse( is );
527                 }
528             }
529             catch ( final MsaFormatException e ) {
530                 setArrowCursor();
531                 JOptionPane.showMessageDialog( this,
532                                                e.getLocalizedMessage(),
533                                                "Multiple sequence alignment format error",
534                                                JOptionPane.ERROR_MESSAGE );
535                 return;
536             }
537             catch ( final IOException e ) {
538                 setArrowCursor();
539                 JOptionPane.showMessageDialog( this,
540                                                e.getLocalizedMessage(),
541                                                "Failed to read multiple sequence alignment",
542                                                JOptionPane.ERROR_MESSAGE );
543                 return;
544             }
545             catch ( final IllegalArgumentException e ) {
546                 setArrowCursor();
547                 JOptionPane.showMessageDialog( this,
548                                                e.getLocalizedMessage(),
549                                                "Unexpected error during reading of multiple sequence alignment",
550                                                JOptionPane.ERROR_MESSAGE );
551                 return;
552             }
553             catch ( final Exception e ) {
554                 setArrowCursor();
555                 e.printStackTrace();
556                 JOptionPane.showMessageDialog( this,
557                                                e.getLocalizedMessage(),
558                                                "Unexpected error during reading of multiple sequence alignment",
559                                                JOptionPane.ERROR_MESSAGE );
560                 return;
561             }
562             if ( ( msa == null ) || ( msa.getNumberOfSequences() < 1 ) ) {
563                 JOptionPane.showMessageDialog( this,
564                                                "Multiple sequence alignment is empty",
565                                                "Illegal Multiple Sequence Alignment",
566                                                JOptionPane.ERROR_MESSAGE );
567                 return;
568             }
569             if ( msa.getNumberOfSequences() < 4 ) {
570                 JOptionPane.showMessageDialog( this,
571                                                "Multiple sequence alignment needs to contain at least 3 sequences",
572                                                "Illegal multiple sequence alignment",
573                                                JOptionPane.ERROR_MESSAGE );
574                 return;
575             }
576             if ( msa.getLength() < 2 ) {
577                 JOptionPane.showMessageDialog( this,
578                                                "Multiple sequence alignment needs to contain at least 2 residues",
579                                                "Illegal multiple sequence alignment",
580                                                JOptionPane.ERROR_MESSAGE );
581                 return;
582             }
583             System.gc();
584             setMsaFile( _msa_filechooser.getSelectedFile() );
585             setMsa( msa );
586         }
587     }
588
589     public void readSeqsFromFileforPI() {
590         // Set an initial directory if none set yet
591         final File my_dir = getCurrentDir();
592         _seqs_pi_filechooser.setMultiSelectionEnabled( false );
593         // Open file-open dialog and set current directory
594         if ( my_dir != null ) {
595             _seqs_pi_filechooser.setCurrentDirectory( my_dir );
596         }
597         final int result = _seqs_pi_filechooser.showOpenDialog( _contentpane );
598         // All done: get the seqs
599         final File file = _seqs_pi_filechooser.getSelectedFile();
600         setCurrentDir( _seqs_pi_filechooser.getCurrentDirectory() );
601         if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) {
602             setSeqsFile( null );
603             setSeqs( null );
604             List<MolecularSequence> seqs = null;
605             try {
606                 if ( FastaParser.isLikelyFasta( new FileInputStream( file ) ) ) {
607                     seqs = FastaParser.parse( new FileInputStream( file ) );
608                     for( final MolecularSequence seq : seqs ) {
609                         System.out.println( SequenceWriter.toFasta( seq, 60 ) );
610                     }
611                 }
612                 else {
613                     //TODO error
614                 }
615             }
616             catch ( final MsaFormatException e ) {
617                 setArrowCursor();
618                 JOptionPane.showMessageDialog( this,
619                                                e.getLocalizedMessage(),
620                                                "Multiple sequence file format error",
621                                                JOptionPane.ERROR_MESSAGE );
622                 return;
623             }
624             catch ( final IOException e ) {
625                 setArrowCursor();
626                 JOptionPane.showMessageDialog( this,
627                                                e.getLocalizedMessage(),
628                                                "Failed to read multiple sequence file",
629                                                JOptionPane.ERROR_MESSAGE );
630                 return;
631             }
632             catch ( final IllegalArgumentException e ) {
633                 setArrowCursor();
634                 JOptionPane.showMessageDialog( this,
635                                                e.getLocalizedMessage(),
636                                                "Unexpected error during reading of multiple sequence file",
637                                                JOptionPane.ERROR_MESSAGE );
638                 return;
639             }
640             catch ( final Exception e ) {
641                 setArrowCursor();
642                 e.printStackTrace();
643                 JOptionPane.showMessageDialog( this,
644                                                e.getLocalizedMessage(),
645                                                "Unexpected error during reading of multiple sequence file",
646                                                JOptionPane.ERROR_MESSAGE );
647                 return;
648             }
649             if ( ( seqs == null ) || ( seqs.size() < 1 ) ) {
650                 JOptionPane.showMessageDialog( this,
651                                                "Multiple sequence file is empty",
652                                                "Illegal multiple sequence file",
653                                                JOptionPane.ERROR_MESSAGE );
654                 return;
655             }
656             if ( seqs.size() < 4 ) {
657                 JOptionPane.showMessageDialog( this,
658                                                "Multiple sequence file needs to contain at least 3 sequences",
659                                                "Illegal multiple sequence file",
660                                                JOptionPane.ERROR_MESSAGE );
661                 return;
662             }
663             //  if ( msa.getLength() < 2 ) {
664             //       JOptionPane.showMessageDialog( this,
665             //                                      "Multiple sequence alignment needs to contain at least 2 residues",
666             //                                      "Illegal multiple sequence file",
667             //                                      JOptionPane.ERROR_MESSAGE );
668             //       return;
669             //   }
670             System.gc();
671             setSeqsFile( _seqs_pi_filechooser.getSelectedFile() );
672             setSeqs( seqs );
673         }
674     }
675
676     private void addExpressionValuesFromFile() {
677         if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) ) {
678             JOptionPane.showMessageDialog( this,
679                                            "Need to load evolutionary tree first",
680                                            "Can Not Read Expression Values",
681                                            JOptionPane.WARNING_MESSAGE );
682             return;
683         }
684         final File my_dir = getCurrentDir();
685         if ( my_dir != null ) {
686             _values_filechooser.setCurrentDirectory( my_dir );
687         }
688         final int result = _values_filechooser.showOpenDialog( _contentpane );
689         final File file = _values_filechooser.getSelectedFile();
690         if ( ( file != null ) && ( file.length() > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
691             BasicTable<String> t = null;
692             try {
693                 t = BasicTableParser.parse( file, '\t' );
694                 if ( t.getNumberOfColumns() < 2 ) {
695                     t = BasicTableParser.parse( file, ',' );
696                 }
697                 if ( t.getNumberOfColumns() < 2 ) {
698                     t = BasicTableParser.parse( file, ' ' );
699                 }
700             }
701             catch ( final IOException e ) {
702                 JOptionPane.showMessageDialog( this,
703                                                e.getMessage(),
704                                                "Could Not Read Expression Value Table",
705                                                JOptionPane.ERROR_MESSAGE );
706                 return;
707             }
708             if ( t.getNumberOfColumns() < 2 ) {
709                 JOptionPane.showMessageDialog( this,
710                                                "Table contains " + t.getNumberOfColumns() + " column(s)",
711                                                "Problem with Expression Value Table",
712                                                JOptionPane.ERROR_MESSAGE );
713                 return;
714             }
715             if ( t.getNumberOfRows() < 1 ) {
716                 JOptionPane.showMessageDialog( this,
717                                                "Table contains zero rows",
718                                                "Problem with Expression Value Table",
719                                                JOptionPane.ERROR_MESSAGE );
720                 return;
721             }
722             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
723             if ( t.getNumberOfRows() != phy.getNumberOfExternalNodes() ) {
724                 JOptionPane.showMessageDialog( this,
725                                                "Table contains " + t.getNumberOfRows() + " rows, but tree contains "
726                                                        + phy.getNumberOfExternalNodes() + " external nodes",
727                                                "Warning",
728                                                JOptionPane.WARNING_MESSAGE );
729             }
730             final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
731             int not_found = 0;
732             for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
733                 final PhylogenyNode node = iter.next();
734                 final String node_name = node.getName();
735                 if ( !ForesterUtil.isEmpty( node_name ) ) {
736                     int row = -1;
737                     try {
738                         row = t.findRow( node_name );
739                     }
740                     catch ( final IllegalArgumentException e ) {
741                         JOptionPane.showMessageDialog( this,
742                                                        e.getMessage(),
743                                                        "Error Mapping Node Identifiers to Expression Value Identifiers",
744                                                        JOptionPane.ERROR_MESSAGE );
745                         return;
746                     }
747                     if ( row < 0 ) {
748                         if ( node.isExternal() ) {
749                             not_found++;
750                         }
751                         continue;
752                     }
753                     final List<Double> l = new ArrayList<Double>();
754                     for( int col = 1; col < t.getNumberOfColumns(); ++col ) {
755                         double d = -100;
756                         try {
757                             d = Double.parseDouble( t.getValueAsString( col, row ) );
758                         }
759                         catch ( final NumberFormatException e ) {
760                             JOptionPane.showMessageDialog( this,
761                                                            "Could not parse \"" + t.getValueAsString( col, row )
762                                                                    + "\" into a decimal value",
763                                                            "Issue with Expression Value Table",
764                                                            JOptionPane.ERROR_MESSAGE );
765                             return;
766                         }
767                         stats.addValue( d );
768                         l.add( d );
769                     }
770                     if ( !l.isEmpty() ) {
771                         if ( node.getNodeData().getProperties() != null ) {
772                             node.getNodeData().getProperties()
773                                     .removePropertiesWithGivenReferencePrefix( PhyloXmlUtil.VECTOR_PROPERTY_REF );
774                         }
775                         node.getNodeData().setVector( l );
776                     }
777                 }
778             }
779             if ( not_found > 0 ) {
780                 JOptionPane
781                         .showMessageDialog( this,
782                                             "Could not fine expression values for " + not_found + " external node(s)",
783                                             "Warning",
784                                             JOptionPane.WARNING_MESSAGE );
785             }
786             getCurrentTreePanel().setStatisticsForExpressionValues( stats );
787         }
788     }
789
790     private void addSequencesFromFile() {
791         if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) ) {
792             JOptionPane.showMessageDialog( this,
793                                            "Need to load evolutionary tree first",
794                                            "Can Not Read Sequences",
795                                            JOptionPane.WARNING_MESSAGE );
796             return;
797         }
798         final File my_dir = getCurrentDir();
799         if ( my_dir != null ) {
800             _sequences_filechooser.setCurrentDirectory( my_dir );
801         }
802         final int result = _sequences_filechooser.showOpenDialog( _contentpane );
803         final File file = _sequences_filechooser.getSelectedFile();
804         List<MolecularSequence> seqs = null;
805         if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) {
806             try {
807                 final FileInputStream fis1 = new FileInputStream( file );
808                 if ( FastaParser.isLikelyFasta( fis1 ) ) {
809                     final FileInputStream fis2 = new FileInputStream( file );
810                     seqs = FastaParser.parse( fis2 );
811                     try {
812                         fis2.close();
813                     }
814                     catch ( final Exception e ) {
815                         // Ignore.
816                     }
817                 }
818                 else {
819                     JOptionPane.showMessageDialog( this,
820                                                    "Format does not appear to be Fasta",
821                                                    "Multiple sequence file format error",
822                                                    JOptionPane.ERROR_MESSAGE );
823                     return;
824                 }
825                 try {
826                     fis1.close();
827                 }
828                 catch ( final Exception e ) {
829                     // Ignore.
830                 }
831             }
832             catch ( final MsaFormatException e ) {
833                 setArrowCursor();
834                 JOptionPane.showMessageDialog( this,
835                                                e.getLocalizedMessage(),
836                                                "Multiple sequence file format error",
837                                                JOptionPane.ERROR_MESSAGE );
838                 return;
839             }
840             catch ( final IOException e ) {
841                 setArrowCursor();
842                 JOptionPane.showMessageDialog( this,
843                                                e.getLocalizedMessage(),
844                                                "Failed to read multiple sequence file",
845                                                JOptionPane.ERROR_MESSAGE );
846                 return;
847             }
848             catch ( final Exception e ) {
849                 setArrowCursor();
850                 e.printStackTrace();
851                 JOptionPane.showMessageDialog( this,
852                                                e.getLocalizedMessage(),
853                                                "Unexpected error during reading of multiple sequence file",
854                                                JOptionPane.ERROR_MESSAGE );
855                 return;
856             }
857             if ( ( seqs == null ) || ( seqs.size() < 1 ) ) {
858                 JOptionPane.showMessageDialog( this,
859                                                "Multiple sequence file is empty",
860                                                "Empty multiple sequence file",
861                                                JOptionPane.ERROR_MESSAGE );
862                 setArrowCursor();
863                 return;
864             }
865         }
866         if ( seqs != null ) {
867             for( final MolecularSequence seq : seqs ) {
868                 System.out.println( seq.getIdentifier() );
869             }
870             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
871             int total_counter = 0;
872             int attached_counter = 0;
873             for( final MolecularSequence seq : seqs ) {
874                 ++total_counter;
875                 final String seq_name = seq.getIdentifier();
876                 if ( !ForesterUtil.isEmpty( seq_name ) ) {
877                     List<PhylogenyNode> nodes = phy.getNodesViaSequenceName( seq_name );
878                     if ( nodes.isEmpty() ) {
879                         nodes = phy.getNodesViaSequenceSymbol( seq_name );
880                     }
881                     if ( nodes.isEmpty() ) {
882                         nodes = phy.getNodesViaGeneName( seq_name );
883                     }
884                     if ( nodes.isEmpty() ) {
885                         nodes = phy.getNodes( seq_name );
886                     }
887                     if ( nodes.size() > 1 ) {
888                         JOptionPane.showMessageDialog( this,
889                                                        "Sequence name \"" + seq_name + "\" is not unique",
890                                                        "Sequence name not unique",
891                                                        JOptionPane.ERROR_MESSAGE );
892                         setArrowCursor();
893                         return;
894                     }
895                     final String[] a = seq_name.split( "\\s" );
896                     if ( nodes.isEmpty() && ( a.length > 1 ) ) {
897                         final String seq_name_split = a[ 0 ];
898                         nodes = phy.getNodesViaSequenceName( seq_name_split );
899                         if ( nodes.isEmpty() ) {
900                             nodes = phy.getNodesViaSequenceSymbol( seq_name_split );
901                         }
902                         if ( nodes.isEmpty() ) {
903                             nodes = phy.getNodes( seq_name_split );
904                         }
905                         if ( nodes.size() > 1 ) {
906                             JOptionPane.showMessageDialog( this,
907                                                            "Split sequence name \"" + seq_name_split
908                                                                    + "\" is not unique",
909                                                            "Sequence name not unique",
910                                                            JOptionPane.ERROR_MESSAGE );
911                             setArrowCursor();
912                             return;
913                         }
914                     }
915                     if ( nodes.size() == 1 ) {
916                         ++attached_counter;
917                         final PhylogenyNode n = nodes.get( 0 );
918                         if ( !n.getNodeData().isHasSequence() ) {
919                             n.getNodeData().addSequence( new org.forester.phylogeny.data.Sequence() );
920                         }
921                         n.getNodeData().getSequence().setMolecularSequence( seq.getMolecularSequenceAsString() );
922                         if ( ForesterUtil.isEmpty( n.getNodeData().getSequence().getName() ) ) {
923                             n.getNodeData().getSequence().setName( seq_name );
924                         }
925                     }
926                 }
927             }
928             if ( attached_counter > 0 ) {
929                 int ext_nodes = 0;
930                 int ext_nodes_with_seq = 0;
931                 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
932                     ++ext_nodes;
933                     final PhylogenyNode n = iter.next();
934                     if ( n.getNodeData().isHasSequence()
935                             && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getMolecularSequence() ) ) {
936                         ++ext_nodes_with_seq;
937                     }
938                 }
939                 final String s;
940                 if ( ext_nodes == ext_nodes_with_seq ) {
941                     s = "All " + ext_nodes_with_seq + " external nodes now have a molecular sequence attached to them.";
942                 }
943                 else {
944                     s = ext_nodes_with_seq + " out of " + ext_nodes
945                             + " external nodes now have a molecular sequence attached to them.";
946                 }
947                 if ( ( attached_counter == total_counter ) && ( ext_nodes == ext_nodes_with_seq ) ) {
948                     JOptionPane.showMessageDialog( this,
949                                                    "Attached all " + total_counter + " sequences to tree nodes.\n" + s,
950                                                    "All sequences attached",
951                                                    JOptionPane.INFORMATION_MESSAGE );
952                 }
953                 else {
954                     JOptionPane.showMessageDialog( this,
955                                                    "Attached " + attached_counter + " sequences out of a total of "
956                                                            + total_counter + " sequences.\n" + s,
957                                                    attached_counter + " sequences attached",
958                                                    JOptionPane.WARNING_MESSAGE );
959                 }
960             }
961             else {
962                 JOptionPane.showMessageDialog( this,
963                                                "No maching tree node for any of the " + total_counter + " sequences",
964                                                "Could not attach any sequences",
965                                                JOptionPane.ERROR_MESSAGE );
966             }
967         }
968     }
969
970     private void closeCurrentPane() {
971         if ( getMainPanel().getCurrentTreePanel() != null ) {
972             if ( getMainPanel().getCurrentTreePanel().isEdited() ) {
973                 final int r = JOptionPane.showConfirmDialog( this,
974                                                              "Close tab despite potentially unsaved changes?",
975                                                              "Close Tab?",
976                                                              JOptionPane.YES_NO_OPTION );
977                 if ( r != JOptionPane.YES_OPTION ) {
978                     return;
979                 }
980             }
981             getMainPanel().closeCurrentPane();
982             activateSaveAllIfNeeded();
983         }
984     }
985
986     private void collapse( final Phylogeny phy ) {
987         final PhylogenyNodeIterator it = phy.iteratorPostorder();
988         final List<PhylogenyNode> to_be_removed = new ArrayList<PhylogenyNode>();
989         double min_support = Double.MAX_VALUE;
990         boolean conf_present = false;
991         while ( it.hasNext() ) {
992             final PhylogenyNode n = it.next();
993             if ( !n.isExternal() && !n.isRoot() ) {
994                 final List<Confidence> c = n.getBranchData().getConfidences();
995                 if ( ( c != null ) && ( c.size() > 0 ) ) {
996                     conf_present = true;
997                     double max = 0;
998                     for( final Confidence confidence : c ) {
999                         if ( confidence.getValue() > max ) {
1000                             max = confidence.getValue();
1001                         }
1002                     }
1003                     if ( max < getMinNotCollapseConfidenceValue() ) {
1004                         to_be_removed.add( n );
1005                     }
1006                     if ( max < min_support ) {
1007                         min_support = max;
1008                     }
1009                 }
1010             }
1011         }
1012         if ( conf_present ) {
1013             for( final PhylogenyNode node : to_be_removed ) {
1014                 PhylogenyMethods.removeNode( node, phy );
1015             }
1016             if ( to_be_removed.size() > 0 ) {
1017                 phy.externalNodesHaveChanged();
1018                 phy.clearHashIdToNodeMap();
1019                 phy.recalculateNumberOfExternalDescendants( true );
1020                 getCurrentTreePanel().resetNodeIdToDistToLeafMap();
1021                 getCurrentTreePanel().updateSetOfCollapsedExternalNodes();
1022                 getCurrentTreePanel().calculateLongestExtNodeInfo();
1023                 getCurrentTreePanel().setNodeInPreorderToNull();
1024                 getCurrentTreePanel().recalculateMaxDistanceToRoot();
1025                 getCurrentTreePanel().resetPreferredSize();
1026                 getCurrentTreePanel().setEdited( true );
1027                 getCurrentTreePanel().repaint();
1028                 repaint();
1029             }
1030             if ( to_be_removed.size() > 0 ) {
1031                 JOptionPane.showMessageDialog( this,
1032                                                "Collapsed " + to_be_removed.size()
1033                                                        + " branches with\nconfidence values below "
1034                                                        + getMinNotCollapseConfidenceValue(),
1035                                                "Collapsed " + to_be_removed.size() + " branches",
1036                                                JOptionPane.INFORMATION_MESSAGE );
1037             }
1038             else {
1039                 JOptionPane.showMessageDialog( this,
1040                                                "No branch collapsed,\nminimum confidence value per branch is "
1041                                                        + min_support,
1042                                                "No branch collapsed",
1043                                                JOptionPane.INFORMATION_MESSAGE );
1044             }
1045         }
1046         else {
1047             JOptionPane.showMessageDialog( this,
1048                                            "No branch collapsed because no confidence values present",
1049                                            "No confidence values present",
1050                                            JOptionPane.INFORMATION_MESSAGE );
1051         }
1052     }
1053
1054     private void collapseByTaxonomicRank() {
1055         if ( _mainpanel.getCurrentTreePanel() != null ) {
1056             final Map<String, Integer> present_ranks = AptxUtil.getRankCounts( _mainpanel.getCurrentTreePanel().getPhylogeny());
1057             final String[] ranks = AptxUtil.getAllPossibleRanks(present_ranks);
1058              String rank = ( String ) JOptionPane
1059                     .showInputDialog( this,
1060                                       "What rank should the collapsing be based on",
1061                                       "Rank Selection",
1062                                       JOptionPane.QUESTION_MESSAGE,
1063                                       null,
1064                                       ranks,
1065                                       null );
1066             if ( !ForesterUtil.isEmpty( rank ) ) {
1067                 if ( rank.indexOf( '(' ) > 0 ) {
1068                     rank = rank.substring( 0, rank.indexOf( '(' ) ).trim();
1069                 }
1070                 _mainpanel.getCurrentTreePanel().collapseByTaxonomicRank( rank );
1071             }
1072         }
1073     }
1074
1075     private void collapseBelowBranchLengthThreshold() {
1076         if ( getCurrentTreePanel() != null ) {
1077             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1078             if ( ( phy != null ) && !phy.isEmpty() ) {
1079                 final String s = ( String ) JOptionPane.showInputDialog( this,
1080                                                                          "Please enter the minimum branch length value\n",
1081                                                                          "Minimal Branch Length Value",
1082                                                                          JOptionPane.QUESTION_MESSAGE,
1083                                                                          null,
1084                                                                          null,
1085                                                                          getMinNotCollapseBlValue() );
1086                 if ( !ForesterUtil.isEmpty( s ) ) {
1087                     boolean success = true;
1088                     double m = 0.0;
1089                     final String m_str = s.trim();
1090                     if ( !ForesterUtil.isEmpty( m_str ) ) {
1091                         try {
1092                             m = Double.parseDouble( m_str );
1093                         }
1094                         catch ( final Exception ex ) {
1095                             success = false;
1096                         }
1097                     }
1098                     else {
1099                         success = false;
1100                     }
1101                     if ( success && ( m >= 0.0 ) ) {
1102                         setMinNotCollapseBlValue( m );
1103                         collapseBl( phy );
1104                     }
1105                 }
1106             }
1107         }
1108     }
1109
1110     private void collapseBelowThreshold() {
1111         if ( getCurrentTreePanel() != null ) {
1112             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1113             if ( ( phy != null ) && !phy.isEmpty() ) {
1114                 final String s = ( String ) JOptionPane.showInputDialog( this,
1115                                                                          "Please enter the minimum confidence value\n",
1116                                                                          "Minimal Confidence Value",
1117                                                                          JOptionPane.QUESTION_MESSAGE,
1118                                                                          null,
1119                                                                          null,
1120                                                                          getMinNotCollapseConfidenceValue() );
1121                 if ( !ForesterUtil.isEmpty( s ) ) {
1122                     boolean success = true;
1123                     double m = 0.0;
1124                     final String m_str = s.trim();
1125                     if ( !ForesterUtil.isEmpty( m_str ) ) {
1126                         try {
1127                             m = Double.parseDouble( m_str );
1128                         }
1129                         catch ( final Exception ex ) {
1130                             success = false;
1131                         }
1132                     }
1133                     else {
1134                         success = false;
1135                     }
1136                     if ( success && ( m >= 0.0 ) ) {
1137                         setMinNotCollapseConfidenceValue( m );
1138                         collapse( phy );
1139                     }
1140                 }
1141             }
1142         }
1143     }
1144
1145     private void collapseBl( final Phylogeny phy ) {
1146         final PhylogenyNodeIterator it = phy.iteratorPostorder();
1147         final List<PhylogenyNode> to_be_removed = new ArrayList<PhylogenyNode>();
1148         double min_bl = Double.MAX_VALUE;
1149         boolean bl_present = false;
1150         while ( it.hasNext() ) {
1151             final PhylogenyNode n = it.next();
1152             if ( !n.isExternal() && !n.isRoot() ) {
1153                 final double bl = n.getDistanceToParent();
1154                 if ( bl != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
1155                     bl_present = true;
1156                     if ( bl < getMinNotCollapseBlValue() ) {
1157                         to_be_removed.add( n );
1158                     }
1159                     if ( bl < min_bl ) {
1160                         min_bl = bl;
1161                     }
1162                 }
1163             }
1164         }
1165         if ( bl_present ) {
1166             for( final PhylogenyNode node : to_be_removed ) {
1167                 PhylogenyMethods.removeNode( node, phy );
1168             }
1169             if ( to_be_removed.size() > 0 ) {
1170                 phy.externalNodesHaveChanged();
1171                 phy.clearHashIdToNodeMap();
1172                 phy.recalculateNumberOfExternalDescendants( true );
1173                 getCurrentTreePanel().resetNodeIdToDistToLeafMap();
1174                 getCurrentTreePanel().updateSetOfCollapsedExternalNodes();
1175                 getCurrentTreePanel().calculateLongestExtNodeInfo();
1176                 getCurrentTreePanel().setNodeInPreorderToNull();
1177                 getCurrentTreePanel().recalculateMaxDistanceToRoot();
1178                 getCurrentTreePanel().resetPreferredSize();
1179                 getCurrentTreePanel().setEdited( true );
1180                 getCurrentTreePanel().repaint();
1181                 repaint();
1182             }
1183             if ( to_be_removed.size() > 0 ) {
1184                 JOptionPane.showMessageDialog( this,
1185                                                "Collapsed " + to_be_removed.size()
1186                                                        + " branches with\nbranch length values below "
1187                                                        + getMinNotCollapseBlValue(),
1188                                                "Collapsed " + to_be_removed.size() + " branches",
1189                                                JOptionPane.INFORMATION_MESSAGE );
1190             }
1191             else {
1192                 JOptionPane.showMessageDialog( this,
1193                                                "No branch collapsed,\nminimum branch length is " + min_bl,
1194                                                "No branch collapsed",
1195                                                JOptionPane.INFORMATION_MESSAGE );
1196             }
1197         }
1198         else {
1199             JOptionPane.showMessageDialog( this,
1200                                            "No branch collapsed because no branch length values present",
1201                                            "No branch length values present",
1202                                            JOptionPane.INFORMATION_MESSAGE );
1203         }
1204     }
1205
1206     private PhyloXmlParser createPhyloXmlParser() {
1207         PhyloXmlParser xml_parser = null;
1208         if ( getConfiguration().isValidatePhyloXmlAgainstSchema() ) {
1209             try {
1210                 xml_parser = PhyloXmlParser.createPhyloXmlParserXsdValidating();
1211             }
1212             catch ( final Exception e ) {
1213                 JOptionPane.showMessageDialog( this,
1214                                                e.getLocalizedMessage(),
1215                                                "failed to create validating XML parser",
1216                                                JOptionPane.WARNING_MESSAGE );
1217             }
1218         }
1219         if ( xml_parser == null ) {
1220             xml_parser = PhyloXmlParser.createPhyloXmlParser();
1221         }
1222         return xml_parser;
1223     }
1224
1225     private void executePhyleneticInference( final boolean from_unaligned_seqs ) {
1226         final PhyloInferenceDialog dialog = new PhyloInferenceDialog( this,
1227                                                                       getPhylogeneticInferenceOptions(),
1228                                                                       from_unaligned_seqs );
1229         dialog.activate();
1230         if ( dialog.getValue() == JOptionPane.OK_OPTION ) {
1231             if ( !from_unaligned_seqs ) {
1232                 if ( getMsa() != null ) {
1233                     final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getMsa(),
1234                                                                                     getPhylogeneticInferenceOptions()
1235                                                                                             .copy(),
1236                                                                                     this );
1237                     new Thread( inferrer ).start();
1238                 }
1239                 else {
1240                     JOptionPane.showMessageDialog( this,
1241                                                    "No multiple sequence alignment selected",
1242                                                    "Phylogenetic Inference Not Launched",
1243                                                    JOptionPane.WARNING_MESSAGE );
1244                 }
1245             }
1246             else {
1247                 if ( getSeqs() != null ) {
1248                     final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getSeqs(),
1249                                                                                     getPhylogeneticInferenceOptions()
1250                                                                                             .copy(),
1251                                                                                     this );
1252                     new Thread( inferrer ).start();
1253                 }
1254                 else {
1255                     JOptionPane.showMessageDialog( this,
1256                                                    "No input sequences selected",
1257                                                    "Phylogenetic Inference Not Launched",
1258                                                    JOptionPane.WARNING_MESSAGE );
1259                 }
1260             }
1261         }
1262     }
1263
1264     private void extractTaxDataFromNodeNames() throws PhyloXmlDataFormatException {
1265         final StringBuilder sb = new StringBuilder();
1266         final StringBuilder sb_failed = new StringBuilder();
1267         int counter = 0;
1268         int counter_failed = 0;
1269         if ( getCurrentTreePanel() != null ) {
1270             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1271             if ( ( phy != null ) && !phy.isEmpty() ) {
1272                 final PhylogenyNodeIterator it = phy.iteratorExternalForward();
1273                 while ( it.hasNext() ) {
1274                     final PhylogenyNode n = it.next();
1275                     final String name = n.getName().trim();
1276                     if ( !ForesterUtil.isEmpty( name ) ) {
1277                         final String nt = ParserUtils.extractTaxonomyDataFromNodeName( n,
1278                                                                                        TAXONOMY_EXTRACTION.AGGRESSIVE );
1279                         if ( !ForesterUtil.isEmpty( nt ) ) {
1280                             if ( counter < 15 ) {
1281                                 sb.append( name + ": " + nt + "\n" );
1282                             }
1283                             else if ( counter == 15 ) {
1284                                 sb.append( "...\n" );
1285                             }
1286                             counter++;
1287                         }
1288                         else {
1289                             if ( counter_failed < 15 ) {
1290                                 sb_failed.append( name + "\n" );
1291                             }
1292                             else if ( counter_failed == 15 ) {
1293                                 sb_failed.append( "...\n" );
1294                             }
1295                             counter_failed++;
1296                         }
1297                     }
1298                 }
1299                 if ( counter > 0 ) {
1300                     String failed = "";
1301                     String all = "all ";
1302                     if ( counter_failed > 0 ) {
1303                         all = "";
1304                         failed = "\nCould not extract taxonomic data for " + counter_failed + " named external nodes:\n"
1305                                 + sb_failed;
1306                     }
1307                     JOptionPane.showMessageDialog( this,
1308                                                    "Extracted taxonomic data from " + all + counter
1309                                                            + " named external nodes:\n" + sb.toString() + failed,
1310                                                    "Taxonomic Data Extraction Completed",
1311                                                    counter_failed > 0 ? JOptionPane.WARNING_MESSAGE
1312                                                            : JOptionPane.INFORMATION_MESSAGE );
1313                 }
1314                 else {
1315                     JOptionPane.showMessageDialog( this,
1316                                                    "Could not extract any taxonomic data.\nMaybe node names are empty\n"
1317                                                            + "or not in the forms \"XYZ_CAEEL\", \"XYZ_6239\", or \"XYZ_Caenorhabditis_elegans\"\n"
1318                                                            + "or nodes already have taxonomic data?\n",
1319                                                    "No Taxonomic Data Extracted",
1320                                                    JOptionPane.ERROR_MESSAGE );
1321                 }
1322             }
1323         }
1324     }
1325
1326     private double getMinNotCollapseBlValue() {
1327         return _min_not_collapse_bl;
1328     }
1329
1330     private double getMinNotCollapseConfidenceValue() {
1331         return _min_not_collapse;
1332     }
1333
1334     private PhylogeneticInferenceOptions getPhylogeneticInferenceOptions() {
1335         if ( _phylogenetic_inference_options == null ) {
1336             _phylogenetic_inference_options = new PhylogeneticInferenceOptions();
1337         }
1338         return _phylogenetic_inference_options;
1339     }
1340
1341     private boolean isUnsavedDataPresent() {
1342         final List<TreePanel> tps = getMainPanel().getTreePanels();
1343         for( final TreePanel tp : tps ) {
1344             if ( tp.isEdited() ) {
1345                 return true;
1346             }
1347         }
1348         return false;
1349     }
1350
1351     private void moveNodeNamesToSeqNames() throws PhyloXmlDataFormatException {
1352         if ( getCurrentTreePanel() != null ) {
1353             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1354             if ( ( phy != null ) && !phy.isEmpty() ) {
1355                 PhylogenyMethods.transferNodeNameToField( phy,
1356                                                           PhylogenyMethods.PhylogenyNodeField.SEQUENCE_NAME,
1357                                                           false );
1358             }
1359         }
1360     }
1361
1362     private void moveNodeNamesToTaxSn() throws PhyloXmlDataFormatException {
1363         if ( getCurrentTreePanel() != null ) {
1364             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1365             if ( ( phy != null ) && !phy.isEmpty() ) {
1366                 PhylogenyMethods.transferNodeNameToField( phy,
1367                                                           PhylogenyMethods.PhylogenyNodeField.TAXONOMY_SCIENTIFIC_NAME,
1368                                                           false );
1369             }
1370         }
1371     }
1372
1373     private void newTree() {
1374         final Phylogeny[] phys = new Phylogeny[ 1 ];
1375         final Phylogeny phy = new Phylogeny();
1376         final PhylogenyNode node = new PhylogenyNode();
1377         phy.setRoot( node );
1378         phy.setRooted( true );
1379         phys[ 0 ] = phy;
1380         AptxUtil.addPhylogeniesToTabs( phys, "", "", getConfiguration(), getMainPanel() );
1381         _mainpanel.getControlPanel().showWhole();
1382         _mainpanel.getCurrentTreePanel().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1383         _mainpanel.getOptions().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1384         if ( getMainPanel().getMainFrame() == null ) {
1385             // Must be "E" applet version.
1386             ( ( ArchaeopteryxE ) ( ( MainPanelApplets ) getMainPanel() ).getApplet() )
1387                     .setSelectedTypeInTypeMenu( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1388         }
1389         else {
1390             getMainPanel().getMainFrame().setSelectedTypeInTypeMenu( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1391         }
1392         activateSaveAllIfNeeded();
1393         System.gc();
1394     }
1395
1396     private void obtainDetailedTaxonomicInformation() {
1397         if ( getCurrentTreePanel() != null ) {
1398             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1399             if ( ( phy != null ) && !phy.isEmpty() ) {
1400                 final TaxonomyDataManager t = new TaxonomyDataManager( this,
1401                                                                        _mainpanel.getCurrentTreePanel(),
1402                                                                        phy.copy(),
1403                                                                        false,
1404                                                                        true );
1405                 new Thread( t ).start();
1406             }
1407         }
1408     }
1409
1410     private void obtainDetailedTaxonomicInformationDelete() {
1411         if ( getCurrentTreePanel() != null ) {
1412             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1413             if ( ( phy != null ) && !phy.isEmpty() ) {
1414                 final TaxonomyDataManager t = new TaxonomyDataManager( this,
1415                                                                        _mainpanel.getCurrentTreePanel(),
1416                                                                        phy.copy(),
1417                                                                        true,
1418                                                                        true );
1419                 new Thread( t ).start();
1420             }
1421         }
1422     }
1423
1424     private void obtainSequenceInformation() {
1425         if ( getCurrentTreePanel() != null ) {
1426             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1427             if ( ( phy != null ) && !phy.isEmpty() ) {
1428                 final SequenceDataRetriver u = new SequenceDataRetriver( this,
1429                                                                          _mainpanel.getCurrentTreePanel(),
1430                                                                          phy.copy() );
1431                 new Thread( u ).start();
1432             }
1433         }
1434     }
1435
1436     private void preProcessTreesUponReading( final Phylogeny[] phys ) {
1437         for( final Phylogeny phy : phys ) {
1438             if ( ( phy != null ) && !phy.isEmpty() ) {
1439                 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
1440                     final PhylogenyNode n = it.next();
1441                     if ( n.isExternal() ) {
1442                         if ( n.getNodeData().isHasSequence() ) {
1443                             final Sequence s = n.getNodeData().getSequence();
1444                             if ( ForesterUtil.isEmpty( s.getGeneName() ) || s.getGeneName().startsWith( "LOC" ) ) {
1445                                 if ( ( s.getAccession() != null )
1446                                         && !ForesterUtil.isEmpty( s.getAccession().getValue() ) ) {
1447                                     s.setGeneName( s.getAccession().getValue() );
1448                                 }
1449                                 else if ( !ForesterUtil.isEmpty( n.getName() ) ) {
1450                                     s.setGeneName( n.getName() );
1451                                 }
1452                             }
1453                         }
1454                     }
1455                 }
1456             }
1457         }
1458     }
1459
1460     private void readPhylogeniesFromFile() {
1461         boolean exception = false;
1462         Phylogeny[] phys = null;
1463         // Set an initial directory if none set yet
1464         final File my_dir = getCurrentDir();
1465         // Open file-open dialog and set current directory
1466         if ( my_dir != null ) {
1467             _open_filechooser.setCurrentDirectory( my_dir );
1468         }
1469         final int result = _open_filechooser.showOpenDialog( _contentpane );
1470         // All done: get the file
1471         final File[] files = _open_filechooser.getSelectedFiles();
1472         setCurrentDir( _open_filechooser.getCurrentDirectory() );
1473         boolean nhx_or_nexus = false;
1474         if ( ( files != null ) && ( files.length > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
1475             for( final File file : files ) {
1476                 if ( ( file != null ) && !file.isDirectory() ) {
1477                     if ( _mainpanel.getCurrentTreePanel() != null ) {
1478                         _mainpanel.getCurrentTreePanel().setWaitCursor();
1479                     }
1480                     else {
1481                         _mainpanel.setWaitCursor();
1482                     }
1483                     if ( ( _open_filechooser.getFileFilter() == MainFrame.nhfilter )
1484                             || ( _open_filechooser.getFileFilter() == MainFrame.nhxfilter ) ) {
1485                         try {
1486                             final NHXParser nhx = new NHXParser();
1487                             setSpecialOptionsForNhxParser( nhx );
1488                             phys = PhylogenyMethods.readPhylogenies( nhx, file );
1489                             nhx_or_nexus = true;
1490                         }
1491                         catch ( final Exception e ) {
1492                             exception = true;
1493                             exceptionOccuredDuringOpenFile( e );
1494                         }
1495                     }
1496                     else if ( _open_filechooser.getFileFilter() == MainFrame.xmlfilter ) {
1497                         warnIfNotPhyloXmlValidation( getConfiguration() );
1498                         try {
1499                             final PhyloXmlParser xml_parser = createPhyloXmlParser();
1500                             phys = PhylogenyMethods.readPhylogenies( xml_parser, file );
1501                         }
1502                         catch ( final Exception e ) {
1503                             exception = true;
1504                             exceptionOccuredDuringOpenFile( e );
1505                         }
1506                     }
1507                     else if ( _open_filechooser.getFileFilter() == MainFrame.tolfilter ) {
1508                         try {
1509                             phys = PhylogenyMethods.readPhylogenies( new TolParser(), file );
1510                         }
1511                         catch ( final Exception e ) {
1512                             exception = true;
1513                             exceptionOccuredDuringOpenFile( e );
1514                         }
1515                     }
1516                     else if ( _open_filechooser.getFileFilter() == MainFrame.nexusfilter ) {
1517                         try {
1518                             final NexusPhylogeniesParser nex = new NexusPhylogeniesParser();
1519                             setSpecialOptionsForNexParser( nex );
1520                             phys = PhylogenyMethods.readPhylogenies( nex, file );
1521                             nhx_or_nexus = true;
1522                         }
1523                         catch ( final Exception e ) {
1524                             exception = true;
1525                             exceptionOccuredDuringOpenFile( e );
1526                         }
1527                     }
1528                     // "*.*":
1529                     else {
1530                         try {
1531                             final PhylogenyParser parser = ParserUtils
1532                                     .createParserDependingOnFileType( file,
1533                                                                       getConfiguration()
1534                                                                               .isValidatePhyloXmlAgainstSchema() );
1535                             if ( parser instanceof NexusPhylogeniesParser ) {
1536                                 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
1537                                 setSpecialOptionsForNexParser( nex );
1538                                 nhx_or_nexus = true;
1539                             }
1540                             else if ( parser instanceof NHXParser ) {
1541                                 final NHXParser nhx = ( NHXParser ) parser;
1542                                 setSpecialOptionsForNhxParser( nhx );
1543                                 nhx_or_nexus = true;
1544                             }
1545                             else if ( parser instanceof PhyloXmlParser ) {
1546                                 warnIfNotPhyloXmlValidation( getConfiguration() );
1547                             }
1548                             phys = PhylogenyMethods.readPhylogenies( parser, file );
1549                         }
1550                         catch ( final Exception e ) {
1551                             exception = true;
1552                             exceptionOccuredDuringOpenFile( e );
1553                         }
1554                     }
1555                     if ( _mainpanel.getCurrentTreePanel() != null ) {
1556                         _mainpanel.getCurrentTreePanel().setArrowCursor();
1557                     }
1558                     else {
1559                         _mainpanel.setArrowCursor();
1560                     }
1561                     if ( !exception && ( phys != null ) && ( phys.length > 0 ) ) {
1562                         boolean one_desc = false;
1563                         if ( nhx_or_nexus ) {
1564                             for( final Phylogeny phy : phys ) {
1565                                 if ( getOptions().isInternalNumberAreConfidenceForNhParsing() ) {
1566                                     PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
1567                                 }
1568                                 if ( PhylogenyMethods.getMinimumDescendentsPerInternalNodes( phy ) == 1 ) {
1569                                     one_desc = true;
1570                                     break;
1571                                 }
1572                             }
1573                         }
1574                         if ( PREPROCESS_TREES ) {
1575                             preProcessTreesUponReading( phys );
1576                         }
1577                         AptxUtil.addPhylogeniesToTabs( phys,
1578                                                        file.getName(),
1579                                                        file.getAbsolutePath(),
1580                                                        getConfiguration(),
1581                                                        getMainPanel() );
1582                         _mainpanel.getControlPanel().showWhole();
1583                         if ( nhx_or_nexus && one_desc ) {
1584                             JOptionPane.showMessageDialog( this,
1585                                                            "One or more trees contain (a) node(s) with one descendant, "
1586                                                                    + ForesterUtil.LINE_SEPARATOR
1587                                                                    + "possibly indicating illegal parentheses within node names.",
1588                                                            "Warning: Possible Error in New Hampshire Formatted Data",
1589                                                            JOptionPane.WARNING_MESSAGE );
1590                         }
1591                     }
1592                 }
1593             }
1594         }
1595         activateSaveAllIfNeeded();
1596         System.gc();
1597     }
1598
1599     private void readSpeciesTreeFromFile() {
1600         Phylogeny t = null;
1601         boolean exception = false;
1602         final File my_dir = getCurrentDir();
1603         _open_filechooser_for_species_tree.setSelectedFile( new File( "" ) );
1604         if ( my_dir != null ) {
1605             _open_filechooser_for_species_tree.setCurrentDirectory( my_dir );
1606         }
1607         final int result = _open_filechooser_for_species_tree.showOpenDialog( _contentpane );
1608         final File file = _open_filechooser_for_species_tree.getSelectedFile();
1609         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
1610             if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrame.xmlfilter ) {
1611                 try {
1612                     final Phylogeny[] trees = PhylogenyMethods
1613                             .readPhylogenies( PhyloXmlParser.createPhyloXmlParserXsdValidating(), file );
1614                     t = trees[ 0 ];
1615                 }
1616                 catch ( final Exception e ) {
1617                     exception = true;
1618                     exceptionOccuredDuringOpenFile( e );
1619                 }
1620             }
1621             else if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrame.tolfilter ) {
1622                 try {
1623                     final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( new TolParser(), file );
1624                     t = trees[ 0 ];
1625                 }
1626                 catch ( final Exception e ) {
1627                     exception = true;
1628                     exceptionOccuredDuringOpenFile( e );
1629                 }
1630             }
1631             // "*.*":
1632             else {
1633                 try {
1634                     final Phylogeny[] trees = PhylogenyMethods
1635                             .readPhylogenies( PhyloXmlParser.createPhyloXmlParserXsdValidating(), file );
1636                     t = trees[ 0 ];
1637                 }
1638                 catch ( final Exception e ) {
1639                     exception = true;
1640                     exceptionOccuredDuringOpenFile( e );
1641                 }
1642             }
1643             if ( !exception && ( t != null ) && !t.isRooted() ) {
1644                 exception = true;
1645                 t = null;
1646                 JOptionPane.showMessageDialog( this,
1647                                                "Species tree is not rooted",
1648                                                "Species tree not loaded",
1649                                                JOptionPane.ERROR_MESSAGE );
1650             }
1651             if ( !exception && ( t != null ) ) {
1652                 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
1653                 for( final PhylogenyNodeIterator it = t.iteratorExternalForward(); it.hasNext(); ) {
1654                     final PhylogenyNode node = it.next();
1655                     if ( !node.getNodeData().isHasTaxonomy() ) {
1656                         exception = true;
1657                         t = null;
1658                         JOptionPane.showMessageDialog( this,
1659                                                        "Species tree contains external node(s) without taxonomy information",
1660                                                        "Species tree not loaded",
1661                                                        JOptionPane.ERROR_MESSAGE );
1662                         break;
1663                     }
1664                     else {
1665                         if ( tax_set.contains( node.getNodeData().getTaxonomy() ) ) {
1666                             exception = true;
1667                             t = null;
1668                             JOptionPane
1669                                     .showMessageDialog( this,
1670                                                         "Taxonomy [" + node.getNodeData().getTaxonomy().asSimpleText()
1671                                                                 + "] is not unique in species tree",
1672                                                         "Species tree not loaded",
1673                                                         JOptionPane.ERROR_MESSAGE );
1674                             break;
1675                         }
1676                         else {
1677                             tax_set.add( node.getNodeData().getTaxonomy() );
1678                         }
1679                     }
1680                 }
1681             }
1682             if ( !exception && ( t != null ) ) {
1683                 setSpeciesTree( t );
1684                 JOptionPane.showMessageDialog( this,
1685                                                "Species tree successfully loaded",
1686                                                "Species tree loaded",
1687                                                JOptionPane.INFORMATION_MESSAGE );
1688             }
1689             _contentpane.repaint();
1690             System.gc();
1691         }
1692     }
1693
1694     private void setArrowCursor() {
1695         try {
1696             _mainpanel.getCurrentTreePanel().setArrowCursor();
1697         }
1698         catch ( final Exception ex ) {
1699             // Do nothing.
1700         }
1701     }
1702
1703     private void setMinNotCollapseBlValue( final double min_not_collapse_bl ) {
1704         _min_not_collapse_bl = min_not_collapse_bl;
1705     }
1706
1707     private void setMinNotCollapseConfidenceValue( final double min_not_collapse ) {
1708         _min_not_collapse = min_not_collapse;
1709     }
1710
1711     private void setPhylogeneticInferenceOptions( final PhylogeneticInferenceOptions phylogenetic_inference_options ) {
1712         _phylogenetic_inference_options = phylogenetic_inference_options;
1713     }
1714
1715     private void setSpecialOptionsForNexParser( final NexusPhylogeniesParser nex ) {
1716         nex.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() );
1717         nex.setTaxonomyExtraction( getOptions().getTaxonomyExtraction() );
1718         nex.setParseBeastStyleExtendedTags( getOptions().isParseBeastStyleExtendedNexusTags() );
1719     }
1720
1721     private void setSpecialOptionsForNhxParser( final NHXParser nhx ) {
1722         nhx.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() );
1723         nhx.setTaxonomyExtraction( getOptions().getTaxonomyExtraction() );
1724         nhx.setAllowErrorsInDistanceToParent( getOptions().isAllowErrorsInDistanceToParent() );
1725         nhx.setParseBeastStyleExtendedTags( getOptions().isParseBeastStyleExtendedNexusTags() );
1726     }
1727
1728     void buildAnalysisMenu() {
1729         _analysis_menu = MainFrame.createMenu( "Analysis", getConfiguration() );
1730         _analysis_menu.add( _gsdi_item = new JMenuItem( "GSDI (Generalized Speciation Duplication Inference)" ) );
1731         _analysis_menu.add( _gsdir_item = new JMenuItem( "GSDIR (GSDI with re-rooting)" ) );
1732         _analysis_menu.add( _load_species_tree_item = new JMenuItem( "Load Species Tree..." ) );
1733         customizeJMenuItem( _gsdi_item );
1734         customizeJMenuItem( _gsdir_item );
1735         customizeJMenuItem( _load_species_tree_item );
1736         _analysis_menu.addSeparator();
1737         _analysis_menu.add( _lineage_inference = new JMenuItem( INFER_ANCESTOR_TAXONOMIES ) );
1738         customizeJMenuItem( _lineage_inference );
1739         _lineage_inference.setToolTipText( "Inference of ancestor taxonomies/lineages" );
1740         _jmenubar.add( _analysis_menu );
1741     }
1742
1743     @Override
1744     void buildFileMenu() {
1745         _file_jmenu = MainFrame.createMenu( "File", getConfiguration() );
1746         _file_jmenu.add( _open_item = new JMenuItem( "Read Tree from File..." ) );
1747         _file_jmenu.addSeparator();
1748         _file_jmenu.add( _open_url_item = new JMenuItem( "Read Tree from URL/Webservice..." ) );
1749         _file_jmenu.addSeparator();
1750         final WebservicesManager webservices_manager = WebservicesManager.getInstance();
1751         _load_phylogeny_from_webservice_menu_items = new JMenuItem[ webservices_manager
1752                 .getAvailablePhylogeniesWebserviceClients().size() ];
1753         for( int i = 0; i < webservices_manager.getAvailablePhylogeniesWebserviceClients().size(); ++i ) {
1754             final PhylogeniesWebserviceClient client = webservices_manager.getAvailablePhylogeniesWebserviceClient( i );
1755             _load_phylogeny_from_webservice_menu_items[ i ] = new JMenuItem( client.getMenuName() );
1756             _file_jmenu.add( _load_phylogeny_from_webservice_menu_items[ i ] );
1757         }
1758         if ( getConfiguration().isEditable() ) {
1759             _file_jmenu.addSeparator();
1760             _file_jmenu.add( _new_item = new JMenuItem( "New" ) );
1761             _new_item.setToolTipText( "to create a new tree with one node, as source for manual tree construction" );
1762         }
1763         _file_jmenu.addSeparator();
1764         _file_jmenu.add( _save_item = new JMenuItem( "Save Tree As..." ) );
1765         _file_jmenu.add( _save_all_item = new JMenuItem( "Save All Trees As..." ) );
1766         _save_all_item.setToolTipText( "Write all phylogenies to one file." );
1767         _save_all_item.setEnabled( false );
1768         _file_jmenu.addSeparator();
1769         _file_jmenu.add( _write_to_pdf_item = new JMenuItem( "Export to PDF file ..." ) );
1770         if ( AptxUtil.canWriteFormat( "tif" ) || AptxUtil.canWriteFormat( "tiff" )
1771                 || AptxUtil.canWriteFormat( "TIF" ) ) {
1772             _file_jmenu.add( _write_to_tif_item = new JMenuItem( "Export to TIFF file..." ) );
1773         }
1774         _file_jmenu.add( _write_to_png_item = new JMenuItem( "Export to PNG file..." ) );
1775         _file_jmenu.add( _write_to_jpg_item = new JMenuItem( "Export to JPG file..." ) );
1776         if ( AptxUtil.canWriteFormat( "gif" ) ) {
1777             _file_jmenu.add( _write_to_gif_item = new JMenuItem( "Export to GIF file..." ) );
1778         }
1779         if ( AptxUtil.canWriteFormat( "bmp" ) ) {
1780             _file_jmenu.add( _write_to_bmp_item = new JMenuItem( "Export to BMP file..." ) );
1781         }
1782         _file_jmenu.addSeparator();
1783         _file_jmenu.add( _print_item = new JMenuItem( "Print..." ) );
1784         _file_jmenu.addSeparator();
1785         _file_jmenu.add( _close_item = new JMenuItem( "Close Tab" ) );
1786         _close_item.setToolTipText( "To close the current pane." );
1787         _close_item.setEnabled( true );
1788         _file_jmenu.addSeparator();
1789         _file_jmenu.add( _exit_item = new JMenuItem( "Exit" ) );
1790         customizeJMenuItem( _open_item );
1791         _open_item.setFont( new Font( _open_item.getFont().getFontName(),
1792                                       Font.BOLD,
1793                                       _open_item.getFont().getSize() + 4 ) );
1794         customizeJMenuItem( _open_url_item );
1795         for( int i = 0; i < webservices_manager.getAvailablePhylogeniesWebserviceClients().size(); ++i ) {
1796             customizeJMenuItem( _load_phylogeny_from_webservice_menu_items[ i ] );
1797         }
1798         customizeJMenuItem( _save_item );
1799         if ( getConfiguration().isEditable() ) {
1800             customizeJMenuItem( _new_item );
1801         }
1802         customizeJMenuItem( _close_item );
1803         customizeJMenuItem( _save_all_item );
1804         customizeJMenuItem( _write_to_pdf_item );
1805         customizeJMenuItem( _write_to_png_item );
1806         customizeJMenuItem( _write_to_jpg_item );
1807         customizeJMenuItem( _write_to_gif_item );
1808         customizeJMenuItem( _write_to_tif_item );
1809         customizeJMenuItem( _write_to_bmp_item );
1810         customizeJMenuItem( _print_item );
1811         customizeJMenuItem( _exit_item );
1812         _jmenubar.add( _file_jmenu );
1813     }
1814
1815     void buildOptionsMenu() {
1816         _options_jmenu = MainFrame.createMenu( OPTIONS_HEADER, getConfiguration() );
1817         _options_jmenu.addChangeListener( new ChangeListener() {
1818
1819             @Override
1820             public void stateChanged( final ChangeEvent e ) {
1821                 MainFrame.setOvPlacementColorChooseMenuItem( _overview_placment_mi, getOptions() );
1822                 MainFrame.setTextColorChooseMenuItem( _switch_colors_mi, getCurrentTreePanel() );
1823                 MainFrame.setTextMinSupportMenuItem( _choose_minimal_confidence_mi,
1824                                                      getOptions(),
1825                                                      getCurrentTreePanel() );
1826                 MainFrame.setTextForFontChooserMenuItem( _choose_font_mi,
1827                                                          MainFrame.createCurrentFontDesc( getMainPanel()
1828                                                                  .getTreeFontSet() ) );
1829                 //  MainFrame.setTextForGraphicsSizeChooserMenuItem( _print_size_mi, getOptions() );
1830                 MainFrame.setTextForPdfLineWidthChooserMenuItem( _choose_pdf_width_mi, getOptions() );
1831                 MainFrame.setCycleNodeFillMenuItem( _cycle_node_fill_mi, getOptions() );
1832                 MainFrame.setCycleNodeShapeMenuItem( _cycle_node_shape_mi, getOptions() );
1833                 MainFrame.setCycleDataReturnMenuItem( _cycle_data_return, getOptions() );
1834                 MainFrame.setTextNodeSizeMenuItem( _choose_node_size_mi, getOptions() );
1835                 try {
1836                     getMainPanel().getControlPanel().setVisibilityOfDomainStrucureCB();
1837                     getMainPanel().getControlPanel().setVisibilityOfX();
1838                 }
1839                 catch ( final Exception ignore ) {
1840                     // do nothing, not important.
1841                 }
1842             }
1843         } );
1844         _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( DISPLAY_SUBHEADER ), getConfiguration() ) );
1845         _options_jmenu
1846                 .add( _ext_node_dependent_cladogram_rbmi = new JRadioButtonMenuItem( MainFrame.NONUNIFORM_CLADOGRAMS_LABEL ) );
1847         _options_jmenu.add( _uniform_cladograms_rbmi = new JRadioButtonMenuItem( MainFrame.UNIFORM_CLADOGRAMS_LABEL ) );
1848         _options_jmenu.add( _non_lined_up_cladograms_rbmi = new JRadioButtonMenuItem( NON_LINED_UP_CLADOGRAMS_LABEL ) );
1849         _radio_group_1 = new ButtonGroup();
1850         _radio_group_1.add( _ext_node_dependent_cladogram_rbmi );
1851         _radio_group_1.add( _uniform_cladograms_rbmi );
1852         _radio_group_1.add( _non_lined_up_cladograms_rbmi );
1853         _options_jmenu.add( _show_overview_cbmi = new JCheckBoxMenuItem( SHOW_OVERVIEW_LABEL ) );
1854         _options_jmenu.add( _show_scale_cbmi = new JCheckBoxMenuItem( DISPLAY_SCALE_LABEL ) );
1855         _options_jmenu
1856                 .add( _show_default_node_shapes_internal_cbmi = new JCheckBoxMenuItem( DISPLAY_NODE_BOXES_LABEL_INT ) );
1857         _options_jmenu
1858                 .add( _show_default_node_shapes_external_cbmi = new JCheckBoxMenuItem( DISPLAY_NODE_BOXES_LABEL_EXT ) );
1859         _options_jmenu
1860                 .add( _show_default_node_shapes_for_marked_cbmi = new JCheckBoxMenuItem( MainFrame.DISPLAY_NODE_BOXES_LABEL_MARKED ) );
1861         _options_jmenu
1862                 .add( _line_up_renderable_data_cbmi = new JCheckBoxMenuItem( MainFrame.LINE_UP_RENDERABLE_DATA ) );
1863         if ( getConfiguration().doDisplayOption( Configuration.show_domain_architectures ) ) {
1864             _options_jmenu
1865                     .add( _right_line_up_domains_cbmi = new JCheckBoxMenuItem( MainFrame.RIGHT_LINE_UP_DOMAINS ) );
1866             _options_jmenu.add( _show_domain_labels = new JCheckBoxMenuItem( MainFrame.SHOW_DOMAIN_LABELS_LABEL ) );
1867         }
1868         _options_jmenu.add( _show_annotation_ref_source = new JCheckBoxMenuItem( SHOW_ANN_REF_SOURCE_LABEL ) );
1869         _options_jmenu.add( _show_confidence_stddev_cbmi = new JCheckBoxMenuItem( SHOW_CONF_STDDEV_LABEL ) );
1870         _options_jmenu.add( _color_by_taxonomic_group_cbmi = new JCheckBoxMenuItem( COLOR_BY_TAXONOMIC_GROUP ) );
1871         _options_jmenu.add( _color_labels_same_as_parent_branch = new JCheckBoxMenuItem( COLOR_LABELS_LABEL ) );
1872         _color_labels_same_as_parent_branch.setToolTipText( MainFrame.COLOR_LABELS_TIP );
1873         _options_jmenu.add( _abbreviate_scientific_names = new JCheckBoxMenuItem( ABBREV_SN_LABEL ) );
1874         _options_jmenu.add( _label_direction_cbmi = new JCheckBoxMenuItem( LABEL_DIRECTION_LABEL ) );
1875         _label_direction_cbmi.setToolTipText( LABEL_DIRECTION_TIP );
1876         _options_jmenu.add( _screen_antialias_cbmi = new JCheckBoxMenuItem( SCREEN_ANTIALIAS_LABEL ) );
1877         _options_jmenu.add( _background_gradient_cbmi = new JCheckBoxMenuItem( BG_GRAD_LABEL ) );
1878         _options_jmenu.add( _cycle_node_shape_mi = new JMenuItem( MainFrame.CYCLE_NODE_SHAPE_LABEL ) );
1879         _options_jmenu.add( _cycle_node_fill_mi = new JMenuItem( MainFrame.CYCLE_NODE_FILL_LABEL ) );
1880         _options_jmenu.add( _choose_node_size_mi = new JMenuItem( MainFrame.CHOOSE_NODE_SIZE_LABEL ) );
1881         _options_jmenu.add( _choose_minimal_confidence_mi = new JMenuItem( "" ) );
1882         _options_jmenu.add( _overview_placment_mi = new JMenuItem( "" ) );
1883         _options_jmenu.add( _switch_colors_mi = new JMenuItem( "" ) );
1884         _options_jmenu.add( _choose_font_mi = new JMenuItem( "" ) );
1885         _options_jmenu.addSeparator();
1886         _options_jmenu.add( _cycle_data_return = new JMenuItem( "Cycle Data Return" ) );
1887         _options_jmenu.addSeparator();
1888         _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( SEARCH_SUBHEADER ), getConfiguration() ) );
1889         _options_jmenu.add( _search_case_senstive_cbmi = new JCheckBoxMenuItem( SEARCH_CASE_SENSITIVE_LABEL ) );
1890         _options_jmenu.add( _search_whole_words_only_cbmi = new JCheckBoxMenuItem( SEARCH_TERMS_ONLY_LABEL ) );
1891         _options_jmenu.add( _search_with_regex_cbmi = new JCheckBoxMenuItem( MainFrame.SEARCH_REGEX_LABEL ) );
1892         _search_with_regex_cbmi.setToolTipText( MainFrame.SEARCH_WITH_REGEX_TIP );
1893         _options_jmenu.add( _inverse_search_result_cbmi = new JCheckBoxMenuItem( INVERSE_SEARCH_RESULT_LABEL ) );
1894         _options_jmenu
1895                 .add( _color_all_found_nodes_when_coloring_subtree_cbmi = new JCheckBoxMenuItem( "Colorize All Found Nodes When Colorizing Subtree(s)" ) );
1896         _options_jmenu.addSeparator();
1897         _options_jmenu
1898                 .add( customizeMenuItemAsLabel( new JMenuItem( "Graphics Export & Printing:" ), getConfiguration() ) );
1899         _options_jmenu.add( _antialias_print_cbmi = new JCheckBoxMenuItem( "Antialias" ) );
1900         _options_jmenu.add( _print_black_and_white_cbmi = new JCheckBoxMenuItem( "Export in Black and White" ) );
1901         _options_jmenu
1902                 .add( _graphics_export_visible_only_cbmi = new JCheckBoxMenuItem( "Limit to Visible ('Screenshot') for PNG, JPG, and GIF export" ) );
1903         _options_jmenu.add( _choose_pdf_width_mi = new JMenuItem( "" ) );
1904         _options_jmenu.addSeparator();
1905         _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( "Newick/NHX/Nexus Read:" ), getConfiguration() ) );
1906         _options_jmenu
1907                 .add( _internal_number_are_confidence_for_nh_parsing_cbmi = new JCheckBoxMenuItem( "Internal Node Names are Confidence Values" ) );
1908         _options_jmenu.add( _replace_underscores_cbmi = new JCheckBoxMenuItem( "Replace Underscores with Spaces" ) );
1909         _options_jmenu
1910                 .add( _parse_beast_style_extended_nexus_tags_cbmi = new JCheckBoxMenuItem( "Parse BEAST-style extended Newick/Nexus tags" ) );
1911         _parse_beast_style_extended_nexus_tags_cbmi
1912                 .setToolTipText( "to parse elements in the form of \"[&!color=#800080]\" in Newick/Nexus formatted trees" );
1913         _options_jmenu
1914                 .add( _allow_errors_in_distance_to_parent_cbmi = new JCheckBoxMenuItem( "Ignore Distance Values Format Errors" ) );
1915         _options_jmenu.add( _extract_taxonomy_no_rbmi = new JRadioButtonMenuItem( "No Taxonomy Extraction" ) );
1916         _options_jmenu
1917                 .add( _extract_taxonomy_pfam_strict_rbmi = new JRadioButtonMenuItem( "Extract Taxonomy Codes/Ids from Pfam-style Node Names" ) );
1918         _options_jmenu
1919                 .add( _extract_taxonomy_pfam_relaxed_rbmi = new JRadioButtonMenuItem( "Extract Taxonomy Codes/Ids from Pfam-style like Node Names" ) );
1920         _options_jmenu
1921                 .add( _extract_taxonomy_agressive_rbmi = new JRadioButtonMenuItem( "Extract Taxonomy Codes/Ids/Scientific Names from Node Names" ) );
1922         _extract_taxonomy_pfam_strict_rbmi
1923                 .setToolTipText( "To extract taxonomy codes/ids from node names in the form of e.g. \"BCL2_MOUSE/123-304\" or \"BCL2_10090/123-304\"" );
1924         _extract_taxonomy_pfam_relaxed_rbmi
1925                 .setToolTipText( "To extract taxonomy codes/ids from node names in the form of e.g. \"bax_MOUSE\" or \"bax_10090\"" );
1926         _extract_taxonomy_agressive_rbmi
1927                 .setToolTipText( "To extract taxonomy codes/ids or scientific names from node names in the form of e.g. \"MOUSE\" or \"10090\" or \"xyz_Nematostella_vectensis\"" );
1928         _radio_group_2 = new ButtonGroup();
1929         _radio_group_2.add( _extract_taxonomy_no_rbmi );
1930         _radio_group_2.add( _extract_taxonomy_pfam_strict_rbmi );
1931         _radio_group_2.add( _extract_taxonomy_pfam_relaxed_rbmi );
1932         _radio_group_2.add( _extract_taxonomy_agressive_rbmi );
1933         _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( "Newick/Nexus Save:" ), getConfiguration() ) );
1934         _options_jmenu
1935                 .add( _use_brackets_for_conf_in_nh_export_cbmi = new JCheckBoxMenuItem( USE_BRACKETS_FOR_CONF_IN_NH_LABEL ) );
1936         _use_brackets_for_conf_in_nh_export_cbmi
1937                 .setToolTipText( "e.g. \"0.1[90]\" for a branch with support 90 and a length of 0.1" );
1938         _options_jmenu
1939                 .add( _use_internal_names_for_conf_in_nh_export_cbmi = new JCheckBoxMenuItem( USE_INTERNAL_NAMES_FOR_CONF_IN_NH_LABEL ) );
1940         customizeJMenuItem( _choose_font_mi );
1941         customizeJMenuItem( _choose_minimal_confidence_mi );
1942         customizeJMenuItem( _switch_colors_mi );
1943         customizeJMenuItem( _choose_pdf_width_mi );
1944         customizeJMenuItem( _overview_placment_mi );
1945         customizeCheckBoxMenuItem( _show_default_node_shapes_external_cbmi,
1946                                    getOptions().isShowDefaultNodeShapesExternal() );
1947         customizeCheckBoxMenuItem( _show_default_node_shapes_internal_cbmi,
1948                                    getOptions().isShowDefaultNodeShapesInternal() );
1949         customizeCheckBoxMenuItem( _show_default_node_shapes_for_marked_cbmi,
1950                                    getOptions().isShowDefaultNodeShapesForMarkedNodes() );
1951         customizeJMenuItem( _cycle_node_shape_mi );
1952         customizeJMenuItem( _cycle_node_fill_mi );
1953         customizeJMenuItem( _choose_node_size_mi );
1954         customizeJMenuItem( _cycle_data_return );
1955         customizeCheckBoxMenuItem( _color_labels_same_as_parent_branch,
1956                                    getOptions().isColorLabelsSameAsParentBranch() );
1957         customizeCheckBoxMenuItem( _color_by_taxonomic_group_cbmi, getOptions().isColorByTaxonomicGroup() );
1958         customizeCheckBoxMenuItem( _screen_antialias_cbmi, getOptions().isAntialiasScreen() );
1959         customizeCheckBoxMenuItem( _background_gradient_cbmi, getOptions().isBackgroundColorGradient() );
1960         customizeCheckBoxMenuItem( _show_domain_labels, getOptions().isShowDomainLabels() );
1961         customizeCheckBoxMenuItem( _show_annotation_ref_source, getOptions().isShowAnnotationRefSource() );
1962         customizeCheckBoxMenuItem( _abbreviate_scientific_names, getOptions().isAbbreviateScientificTaxonNames() );
1963         customizeCheckBoxMenuItem( _search_case_senstive_cbmi, getOptions().isSearchCaseSensitive() );
1964         customizeCheckBoxMenuItem( _show_scale_cbmi, getOptions().isShowScale() );
1965         customizeRadioButtonMenuItem( _non_lined_up_cladograms_rbmi,
1966                                       getOptions().getCladogramType() == CLADOGRAM_TYPE.NON_LINED_UP );
1967         customizeRadioButtonMenuItem( _uniform_cladograms_rbmi,
1968                                       getOptions().getCladogramType() == CLADOGRAM_TYPE.TOTAL_NODE_SUM_DEP );
1969         customizeRadioButtonMenuItem( _ext_node_dependent_cladogram_rbmi,
1970                                       getOptions().getCladogramType() == CLADOGRAM_TYPE.EXT_NODE_SUM_DEP );
1971         customizeCheckBoxMenuItem( _show_overview_cbmi, getOptions().isShowOverview() );
1972         customizeCheckBoxMenuItem( _label_direction_cbmi,
1973                                    getOptions().getNodeLabelDirection() == NODE_LABEL_DIRECTION.RADIAL );
1974         customizeCheckBoxMenuItem( _antialias_print_cbmi, getOptions().isAntialiasPrint() );
1975         customizeCheckBoxMenuItem( _print_black_and_white_cbmi, getOptions().isPrintBlackAndWhite() );
1976         customizeCheckBoxMenuItem( _internal_number_are_confidence_for_nh_parsing_cbmi,
1977                                    getOptions().isInternalNumberAreConfidenceForNhParsing() );
1978         customizeRadioButtonMenuItem( _extract_taxonomy_no_rbmi,
1979                                       getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.NO );
1980         customizeRadioButtonMenuItem( _extract_taxonomy_pfam_strict_rbmi,
1981                                       getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.PFAM_STYLE_STRICT );
1982         customizeRadioButtonMenuItem( _extract_taxonomy_pfam_relaxed_rbmi,
1983                                       getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED );
1984         customizeRadioButtonMenuItem( _extract_taxonomy_agressive_rbmi,
1985                                       getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.AGGRESSIVE );
1986         customizeCheckBoxMenuItem( _replace_underscores_cbmi, getOptions().isReplaceUnderscoresInNhParsing() );
1987         customizeCheckBoxMenuItem( _allow_errors_in_distance_to_parent_cbmi,
1988                                    getOptions().isReplaceUnderscoresInNhParsing() );
1989         customizeCheckBoxMenuItem( _search_with_regex_cbmi, getOptions().isSearchWithRegex() );
1990         customizeCheckBoxMenuItem( _search_whole_words_only_cbmi, getOptions().isMatchWholeTermsOnly() );
1991         customizeCheckBoxMenuItem( _inverse_search_result_cbmi, getOptions().isInverseSearchResult() );
1992         customizeCheckBoxMenuItem( _color_all_found_nodes_when_coloring_subtree_cbmi,
1993                                    getOptions().isColorAllFoundNodesWhenColoringSubtree() );
1994         customizeCheckBoxMenuItem( _parse_beast_style_extended_nexus_tags_cbmi,
1995                                    getOptions().isParseBeastStyleExtendedNexusTags() );
1996         customizeCheckBoxMenuItem( _graphics_export_visible_only_cbmi, getOptions().isGraphicsExportVisibleOnly() );
1997         customizeCheckBoxMenuItem( _show_confidence_stddev_cbmi, getOptions().isShowConfidenceStddev() );
1998         customizeCheckBoxMenuItem( _use_brackets_for_conf_in_nh_export_cbmi,
1999                                    getOptions()
2000                                            .getNhConversionSupportValueStyle() == NH_CONVERSION_SUPPORT_VALUE_STYLE.IN_SQUARE_BRACKETS );
2001         customizeCheckBoxMenuItem( _use_internal_names_for_conf_in_nh_export_cbmi,
2002                                    getOptions()
2003                                            .getNhConversionSupportValueStyle() == NH_CONVERSION_SUPPORT_VALUE_STYLE.AS_INTERNAL_NODE_NAMES );
2004         customizeCheckBoxMenuItem( _line_up_renderable_data_cbmi, getOptions().isLineUpRendarableNodeData() );
2005         customizeCheckBoxMenuItem( _right_line_up_domains_cbmi, getOptions().isRightLineUpDomains() );
2006         _jmenubar.add( _options_jmenu );
2007     }
2008
2009     void buildPhylogeneticInferenceMenu() {
2010         final InferenceManager im = getInferenceManager();
2011         _inference_menu = MainFrame.createMenu( "Inference", getConfiguration() );
2012         _inference_menu.add( _inference_from_msa_item = new JMenuItem( "From Multiple Sequence Alignment..." ) );
2013         customizeJMenuItem( _inference_from_msa_item );
2014         _inference_from_msa_item.setToolTipText( "Basic phylogenetic inference from MSA" );
2015         if ( im.canDoMsa() ) {
2016             _inference_menu.add( _inference_from_seqs_item = new JMenuItem( "From Unaligned Sequences..." ) );
2017             customizeJMenuItem( _inference_from_seqs_item );
2018             _inference_from_seqs_item
2019                     .setToolTipText( "Basic phylogenetic inference including multiple sequence alignment" );
2020         }
2021         else {
2022             _inference_menu
2023                     .add( _inference_from_seqs_item = new JMenuItem( "From Unaligned Sequences (no program found)" ) );
2024             customizeJMenuItem( _inference_from_seqs_item );
2025             _inference_from_seqs_item.setEnabled( false );
2026         }
2027         _jmenubar.add( _inference_menu );
2028     }
2029
2030     void buildToolsMenu() {
2031         _tools_menu = createMenu( "Tools", getConfiguration() );
2032         _tools_menu.add( _confcolor_item = new JMenuItem( "Colorize Branches Depending on Confidence" ) );
2033         customizeJMenuItem( _confcolor_item );
2034         _tools_menu.add( _color_rank_jmi = new JMenuItem( "Colorize Subtrees via Taxonomic Rank" ) );
2035         customizeJMenuItem( _color_rank_jmi );
2036         _color_rank_jmi.setToolTipText( "for example, at \"Class\" level, colorize mammal specific subtree red" );
2037         _tools_menu.add( _taxcolor_item = new JMenuItem( "Taxonomy Colorize Branches" ) );
2038         customizeJMenuItem( _taxcolor_item );
2039         _tools_menu.addSeparator();
2040         _tools_menu.add( _remove_visual_styles_item = new JMenuItem( "Delete All Visual Styles From Nodes" ) );
2041         _remove_visual_styles_item
2042                 .setToolTipText( "To remove all node visual styles (fonts, colors) from the current phylogeny" );
2043         customizeJMenuItem( _remove_visual_styles_item );
2044         _tools_menu.add( _remove_branch_color_item = new JMenuItem( "Delete All Colors From Branches" ) );
2045         _remove_branch_color_item.setToolTipText( "To remove all branch color values from the current phylogeny" );
2046         customizeJMenuItem( _remove_branch_color_item );
2047         _tools_menu.addSeparator();
2048         _tools_menu.add( _annotate_item = new JMenuItem( "Annotate Sequences of Selected Nodes" ) );
2049         customizeJMenuItem( _annotate_item );
2050         _tools_menu.addSeparator();
2051         _tools_menu.add( _midpoint_root_item = new JMenuItem( "Midpoint-Root" ) );
2052         customizeJMenuItem( _midpoint_root_item );
2053         _tools_menu.addSeparator();
2054         _tools_menu.add( _delete_selected_nodes_item = new JMenuItem( "Delete Selected Nodes" ) );
2055         _delete_selected_nodes_item.setToolTipText( "To delete all selected external nodes" );
2056         customizeJMenuItem( _delete_selected_nodes_item );
2057         _tools_menu.add( _delete_not_selected_nodes_item = new JMenuItem( "Retain Selected Nodes" ) );
2058         _delete_not_selected_nodes_item.setToolTipText( "To delete all not selected external nodes" );
2059         customizeJMenuItem( _delete_not_selected_nodes_item );
2060         _tools_menu.addSeparator();
2061         _tools_menu.add( _collapse_species_specific_subtrees = new JMenuItem( "Collapse Species-Specific Subtrees" ) );
2062         customizeJMenuItem( _collapse_species_specific_subtrees );
2063         _collapse_species_specific_subtrees.setToolTipText( "To (reversibly) collapse species-specific subtrees" );
2064         _tools_menu.add( _collapse_by_taxonomic_rank = new JMenuItem( "Collapse By Taxonomic Rank" ) );
2065         customizeJMenuItem( _collapse_by_taxonomic_rank );
2066         _collapse_by_taxonomic_rank.setToolTipText( "To (reversibly) collapse subtrees by taxonomic rank" );
2067         _tools_menu
2068                 .add( _collapse_below_threshold = new JMenuItem( "Collapse Branches with Confidence Below Threshold into Multifurcations" ) );
2069         customizeJMenuItem( _collapse_below_threshold );
2070         _collapse_below_threshold
2071                 .setToolTipText( "To (permanently) 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)" );
2072         //
2073         _tools_menu
2074                 .add( _collapse_below_branch_length = new JMenuItem( "Collapse Branches with Branch Lengths Below Threshold into Multifurcations" ) );
2075         customizeJMenuItem( _collapse_below_branch_length );
2076         _collapse_below_branch_length
2077                 .setToolTipText( "To (permanently) collapse branches with branches with branch lengths below a threshold into multifurcations" );
2078         //
2079         _tools_menu.addSeparator();
2080         _tools_menu
2081                 .add( _extract_tax_code_from_node_names_jmi = new JMenuItem( "Extract Taxonomic Data from Node Names" ) );
2082         customizeJMenuItem( _extract_tax_code_from_node_names_jmi );
2083         _extract_tax_code_from_node_names_jmi
2084                 .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'" );
2085         _tools_menu
2086                 .add( _move_node_names_to_tax_sn_jmi = new JMenuItem( "Transfer Node Names to Taxonomic Scientific Names" ) );
2087         customizeJMenuItem( _move_node_names_to_tax_sn_jmi );
2088         _move_node_names_to_tax_sn_jmi.setToolTipText( "To interpret node names as taxonomic scientific names" );
2089         _tools_menu.add( _move_node_names_to_seq_names_jmi = new JMenuItem( "Transfer Node Names to Sequence Names" ) );
2090         customizeJMenuItem( _move_node_names_to_seq_names_jmi );
2091         _move_node_names_to_seq_names_jmi.setToolTipText( "To interpret node names as sequence (protein, gene) names" );
2092         _tools_menu.addSeparator();
2093         _tools_menu.add( _obtain_seq_information_jmi = new JMenuItem( "Obtain Sequence Information" ) );
2094         customizeJMenuItem( _obtain_seq_information_jmi );
2095         _obtain_seq_information_jmi.setToolTipText( "To add additional sequence information" );
2096         _tools_menu
2097                 .add( _obtain_detailed_taxonomic_information_jmi = new JMenuItem( OBTAIN_DETAILED_TAXONOMIC_INFORMATION ) );
2098         customizeJMenuItem( _obtain_detailed_taxonomic_information_jmi );
2099         _obtain_detailed_taxonomic_information_jmi
2100                 .setToolTipText( "To add additional taxonomic information (from UniProt Taxonomy)" );
2101         _tools_menu
2102                 .add( _obtain_detailed_taxonomic_information_deleting_jmi = new JMenuItem( "Obtain Detailed Taxonomic Information (deletes nodes!)" ) );
2103         customizeJMenuItem( _obtain_detailed_taxonomic_information_deleting_jmi );
2104         _obtain_detailed_taxonomic_information_deleting_jmi
2105                 .setToolTipText( "To add additional taxonomic information, deletes nodes for which taxonomy cannot found (from UniProt Taxonomy)" );
2106         _tools_menu.addSeparator();
2107         _tools_menu.add( _read_values_jmi = new JMenuItem( "Attach Vector/Expression Values" ) );
2108         customizeJMenuItem( _read_values_jmi );
2109         _read_values_jmi.setToolTipText( "To attach vector (e.g. gene expression) values to tree nodes (beta)" );
2110         _jmenubar.add( _tools_menu );
2111         _tools_menu.add( _read_seqs_jmi = new JMenuItem( "Attach Molecular Sequences" ) );
2112         customizeJMenuItem( _read_seqs_jmi );
2113         _read_seqs_jmi
2114                 .setToolTipText( "To attach molecular sequences to tree nodes (from Fasta-formatted file) (beta)" );
2115         _jmenubar.add( _tools_menu );
2116     }
2117
2118     @Override
2119     void close() {
2120         if ( isUnsavedDataPresent() ) {
2121             final int r = JOptionPane.showConfirmDialog( this,
2122                                                          "Exit despite potentially unsaved changes?",
2123                                                          "Exit?",
2124                                                          JOptionPane.YES_NO_OPTION );
2125             if ( r != JOptionPane.YES_OPTION ) {
2126                 return;
2127             }
2128         }
2129         exit();
2130     }
2131
2132     void exit() {
2133         removeAllTextFrames();
2134         _mainpanel.terminate();
2135         _contentpane.removeAll();
2136         setVisible( false );
2137         dispose();
2138         // System.exit( 0 ); //TODO reconfirm that this is OK, then remove.
2139     }
2140
2141     void readPhylogeniesFromURL() {
2142         URL url = null;
2143         Phylogeny[] phys = null;
2144         final String message = "Please enter a complete URL, for example \"http://purl.org/phylo/treebase/phylows/study/TB2:S15480?format=nexus\"";
2145         final String url_string = JOptionPane
2146                 .showInputDialog( this,
2147                                   message,
2148                                   "Use URL/webservice to obtain a phylogeny",
2149                                   JOptionPane.QUESTION_MESSAGE );
2150         boolean nhx_or_nexus = false;
2151         if ( ( url_string != null ) && ( url_string.length() > 0 ) ) {
2152             try {
2153                 url = new URL( url_string );
2154                 PhylogenyParser parser = null;
2155                 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
2156                     parser = new TolParser();
2157                 }
2158                 else {
2159                     parser = ParserUtils
2160                             .createParserDependingOnUrlContents( url,
2161                                                                  getConfiguration().isValidatePhyloXmlAgainstSchema() );
2162                 }
2163                 if ( parser instanceof NexusPhylogeniesParser ) {
2164                     nhx_or_nexus = true;
2165                 }
2166                 else if ( parser instanceof NHXParser ) {
2167                     nhx_or_nexus = true;
2168                 }
2169                 if ( _mainpanel.getCurrentTreePanel() != null ) {
2170                     _mainpanel.getCurrentTreePanel().setWaitCursor();
2171                 }
2172                 else {
2173                     _mainpanel.setWaitCursor();
2174                 }
2175                 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
2176                 phys = factory.create( url.openStream(), parser );
2177             }
2178             catch ( final MalformedURLException e ) {
2179                 JOptionPane.showMessageDialog( this,
2180                                                "Malformed URL: " + url + "\n" + e.getLocalizedMessage(),
2181                                                "Malformed URL",
2182                                                JOptionPane.ERROR_MESSAGE );
2183             }
2184             catch ( final IOException e ) {
2185                 JOptionPane.showMessageDialog( this,
2186                                                "Could not read from " + url + "\n"
2187                                                        + ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ),
2188                                                "Failed to read URL",
2189                                                JOptionPane.ERROR_MESSAGE );
2190             }
2191             catch ( final Exception e ) {
2192                 JOptionPane.showMessageDialog( this,
2193                                                ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ),
2194                                                "Unexpected Exception",
2195                                                JOptionPane.ERROR_MESSAGE );
2196             }
2197             finally {
2198                 if ( _mainpanel.getCurrentTreePanel() != null ) {
2199                     _mainpanel.getCurrentTreePanel().setArrowCursor();
2200                 }
2201                 else {
2202                     _mainpanel.setArrowCursor();
2203                 }
2204             }
2205             if ( ( phys != null ) && ( phys.length > 0 ) ) {
2206                 if ( nhx_or_nexus && getOptions().isInternalNumberAreConfidenceForNhParsing() ) {
2207                     for( final Phylogeny phy : phys ) {
2208                         PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
2209                     }
2210                 }
2211                 AptxUtil.addPhylogeniesToTabs( phys,
2212                                                new File( url.getFile() ).getName(),
2213                                                new File( url.getFile() ).toString(),
2214                                                getConfiguration(),
2215                                                getMainPanel() );
2216                 _mainpanel.getControlPanel().showWhole();
2217             }
2218         }
2219         activateSaveAllIfNeeded();
2220         System.gc();
2221     }
2222
2223     void setMsa( final Msa msa ) {
2224         _msa = msa;
2225     }
2226
2227     void setMsaFile( final File msa_file ) {
2228         _msa_file = msa_file;
2229     }
2230
2231     void setSeqs( final List<MolecularSequence> seqs ) {
2232         _seqs = seqs;
2233     }
2234
2235     void setSeqsFile( final File seqs_file ) {
2236         _seqs_file = seqs_file;
2237     }
2238
2239     public static MainFrameApplication createInstance( final Phylogeny[] phys, final Configuration config ) {
2240         return new MainFrameApplication( phys, config );
2241     }
2242
2243     public static MainFrame createInstance( final Phylogeny[] phys,
2244                                             final Configuration config,
2245                                             final String title,
2246                                             final File current_dir ) {
2247         return new MainFrameApplication( phys, config, title, current_dir );
2248     }
2249
2250     static MainFrame createInstance( final Phylogeny[] phys, final Configuration config, final String title ) {
2251         return new MainFrameApplication( phys, config, title );
2252     }
2253
2254     static MainFrame createInstance( final Phylogeny[] phys, final String config_file_name, final String title ) {
2255         return new MainFrameApplication( phys, config_file_name, title );
2256     }
2257
2258     static void warnIfNotPhyloXmlValidation( final Configuration c ) {
2259         if ( !c.isValidatePhyloXmlAgainstSchema() ) {
2260             JOptionPane.showMessageDialog( null,
2261                                            ForesterUtil.wordWrap(
2262                                                                   "phyloXML XSD-based validation is turned off [enable with line 'validate_against_phyloxml_xsd_schem: true' in configuration file]",
2263                                                                   80 ),
2264                                            "Warning",
2265                                            JOptionPane.WARNING_MESSAGE );
2266         }
2267     }
2268 } // MainFrameApplication.