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