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