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