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