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