work on: add ability to perform GSDI in applets
[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.filechooser.FileFilter;
61 import javax.swing.plaf.synth.SynthLookAndFeel;
62
63 import org.forester.analysis.TaxonomyDataManager;
64 import org.forester.archaeopteryx.AptxUtil.GraphicsExportType;
65 import org.forester.archaeopteryx.Options.CLADOGRAM_TYPE;
66 import org.forester.archaeopteryx.Options.NODE_LABEL_DIRECTION;
67 import org.forester.archaeopteryx.Options.PHYLOGENY_GRAPHICS_TYPE;
68 import org.forester.archaeopteryx.tools.AncestralTaxonomyInferrer;
69 import org.forester.archaeopteryx.tools.GoAnnotation;
70 import org.forester.archaeopteryx.tools.InferenceManager;
71 import org.forester.archaeopteryx.tools.PhyloInferenceDialog;
72 import org.forester.archaeopteryx.tools.PhylogeneticInferenceOptions;
73 import org.forester.archaeopteryx.tools.PhylogeneticInferrer;
74 import org.forester.archaeopteryx.tools.SequenceDataRetriver;
75 import org.forester.archaeopteryx.webservices.PhylogeniesWebserviceClient;
76 import org.forester.archaeopteryx.webservices.WebservicesManager;
77 import org.forester.io.parsers.FastaParser;
78 import org.forester.io.parsers.GeneralMsaParser;
79 import org.forester.io.parsers.PhylogenyParser;
80 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
81 import org.forester.io.parsers.nhx.NHXParser;
82 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
83 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
84 import org.forester.io.parsers.phyloxml.PhyloXmlParser;
85 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
86 import org.forester.io.parsers.tol.TolParser;
87 import org.forester.io.parsers.util.ParserUtils;
88 import org.forester.io.writers.PhylogenyWriter;
89 import org.forester.io.writers.SequenceWriter;
90 import org.forester.msa.Msa;
91 import org.forester.msa.MsaFormatException;
92 import org.forester.phylogeny.Phylogeny;
93 import org.forester.phylogeny.PhylogenyMethods;
94 import org.forester.phylogeny.PhylogenyNode;
95 import org.forester.phylogeny.PhylogenyNode.NH_CONVERSION_SUPPORT_VALUE_STYLE;
96 import org.forester.phylogeny.data.Confidence;
97 import org.forester.phylogeny.data.Taxonomy;
98 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
99 import org.forester.phylogeny.factories.PhylogenyFactory;
100 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
101 import org.forester.sdi.GSDI;
102 import org.forester.sdi.GSDIR;
103 import org.forester.sdi.SDIException;
104 import org.forester.sequence.Sequence;
105 import org.forester.util.BasicDescriptiveStatistics;
106 import org.forester.util.BasicTable;
107 import org.forester.util.BasicTableParser;
108 import org.forester.util.DescriptiveStatistics;
109 import org.forester.util.ForesterUtil;
110 import org.forester.util.WindowsUtils;
111
112 public final class MainFrameApplication extends MainFrame {
113
114     static final String                      INFER_ANCESTOR_TAXONOMIES             = "Infer Ancestor Taxonomies";
115     static final String                      OBTAIN_DETAILED_TAXONOMIC_INFORMATION = "Obtain Detailed Taxonomic Information";
116     private final static int                 FRAME_X_SIZE                          = 800;
117     private final static int                 FRAME_Y_SIZE                          = 800;
118     // Filters for the file-open dialog (classes defined in this file)
119     private final static NHFilter            nhfilter                              = new NHFilter();
120     private final static NHXFilter           nhxfilter                             = new NHXFilter();
121     private final static XMLFilter           xmlfilter                             = new XMLFilter();
122     private final static TolFilter           tolfilter                             = new TolFilter();
123     private final static NexusFilter         nexusfilter                           = new NexusFilter();
124     private final static PdfFilter           pdffilter                             = new PdfFilter();
125     private final static GraphicsFileFilter  graphicsfilefilter                    = new GraphicsFileFilter();
126     private final static MsaFileFilter       msafilter                             = new MsaFileFilter();
127     private final static SequencesFileFilter seqsfilter                            = new SequencesFileFilter();
128     private final static DefaultFilter       defaultfilter                         = new DefaultFilter();
129     private static final long                serialVersionUID                      = -799735726778865234L;
130     private final JFileChooser               _values_filechooser;
131     private final JFileChooser               _sequences_filechooser;
132     private final JFileChooser               _open_filechooser;
133     private final JFileChooser               _msa_filechooser;
134     private final JFileChooser               _seqs_pi_filechooser;
135     private final JFileChooser               _open_filechooser_for_species_tree;
136     private final JFileChooser               _save_filechooser;
137     private final JFileChooser               _writetopdf_filechooser;
138     private final JFileChooser               _writetographics_filechooser;
139     // Analysis menu
140     private JMenu                            _analysis_menu;
141     private JMenuItem                        _load_species_tree_item;
142     private JMenuItem                        _gsdi_item;
143     private JMenuItem                        _gsdir_item;
144     private JMenuItem                        _lineage_inference;
145     private JMenuItem                        _function_analysis;
146     // Application-only print menu items
147     private JMenuItem                        _print_item;
148     private JMenuItem                        _write_to_pdf_item;
149     private JMenuItem                        _write_to_jpg_item;
150     private JMenuItem                        _write_to_gif_item;
151     private JMenuItem                        _write_to_tif_item;
152     private JMenuItem                        _write_to_png_item;
153     private JMenuItem                        _write_to_bmp_item;
154     private File                             _current_dir;
155     private ButtonGroup                      _radio_group_1;
156     private ButtonGroup                      _radio_group_2;
157     // Others:
158     double                                   _min_not_collapse                     = Constants.MIN_NOT_COLLAPSE_DEFAULT;
159     // Phylogeny Inference menu
160     private JMenu                            _inference_menu;
161     private JMenuItem                        _inference_from_msa_item;
162     private JMenuItem                        _inference_from_seqs_item;
163     // Phylogeny Inference
164     private PhylogeneticInferenceOptions     _phylogenetic_inference_options       = null;
165     private Msa                              _msa                                  = null;
166     private File                             _msa_file                             = null;
167     private List<Sequence>                   _seqs                                 = null;
168     private File                             _seqs_file                            = null;
169     JMenuItem                                _read_values_jmi;
170     JMenuItem                                _read_seqs_jmi;
171
172     private MainFrameApplication( final Phylogeny[] phys, final Configuration config ) {
173         _configuration = config;
174         if ( _configuration == null ) {
175             throw new IllegalArgumentException( "configuration is null" );
176         }
177         setVisible( false );
178         setOptions( Options.createInstance( _configuration ) );
179         _mainpanel = new MainPanel( _configuration, this );
180         _open_filechooser = null;
181         _open_filechooser_for_species_tree = null;
182         _save_filechooser = null;
183         _writetopdf_filechooser = null;
184         _writetographics_filechooser = null;
185         _msa_filechooser = null;
186         _seqs_pi_filechooser = null;
187         _values_filechooser = null;
188         _sequences_filechooser = null;
189         _jmenubar = new JMenuBar();
190         buildFileMenu();
191         buildTypeMenu();
192         _contentpane = getContentPane();
193         _contentpane.setLayout( new BorderLayout() );
194         _contentpane.add( _mainpanel, BorderLayout.CENTER );
195         // App is this big
196         setSize( MainFrameApplication.FRAME_X_SIZE, MainFrameApplication.FRAME_Y_SIZE );
197         // The window listener
198         setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE );
199         addWindowListener( new WindowAdapter() {
200
201             @Override
202             public void windowClosing( final WindowEvent e ) {
203                 exit();
204             }
205         } );
206         //   setVisible( true );
207         if ( ( phys != null ) && ( phys.length > 0 ) ) {
208             AptxUtil.addPhylogeniesToTabs( phys, "", null, _configuration, _mainpanel );
209             validate();
210             getMainPanel().getControlPanel().showWholeAll();
211             getMainPanel().getControlPanel().showWhole();
212         }
213         //activateSaveAllIfNeeded();
214         // ...and its children
215         _contentpane.repaint();
216     }
217
218     private MainFrameApplication( final Phylogeny[] phys, final Configuration config, final String title ) {
219         this( phys, config, title, null );
220     }
221
222     private MainFrameApplication( final Phylogeny[] phys,
223                                   final Configuration config,
224                                   final String title,
225                                   final File current_dir ) {
226         super();
227         _configuration = config;
228         if ( _configuration == null ) {
229             throw new IllegalArgumentException( "configuration is null" );
230         }
231         try {
232             boolean synth_exception = false;
233             if ( Constants.__SYNTH_LF ) {
234                 try {
235                     final SynthLookAndFeel synth = new SynthLookAndFeel();
236                     synth.load( MainFrameApplication.class.getResourceAsStream( "/resources/synth_look_and_feel_1.xml" ),
237                                 MainFrameApplication.class );
238                     UIManager.setLookAndFeel( synth );
239                 }
240                 catch ( final Exception ex ) {
241                     synth_exception = true;
242                     ForesterUtil.printWarningMessage( Constants.PRG_NAME,
243                                                       "could not create synth look and feel: "
244                                                               + ex.getLocalizedMessage() );
245                 }
246             }
247             if ( !Constants.__SYNTH_LF || synth_exception ) {
248                 if ( _configuration.isUseNativeUI() ) {
249                     UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
250                 }
251                 else {
252                     UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
253                 }
254             }
255             //UIManager.setLookAndFeel( "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel" );
256         }
257         catch ( final UnsupportedLookAndFeelException e ) {
258             AptxUtil.dieWithSystemError( "unsupported look and feel: " + e.toString() );
259         }
260         catch ( final ClassNotFoundException e ) {
261             AptxUtil.dieWithSystemError( "class not found exception: " + e.toString() );
262         }
263         catch ( final InstantiationException e ) {
264             AptxUtil.dieWithSystemError( "instantiation exception: " + e.toString() );
265         }
266         catch ( final IllegalAccessException e ) {
267             AptxUtil.dieWithSystemError( "illegal access exception: " + e.toString() );
268         }
269         if ( ( current_dir != null ) && current_dir.canRead() && current_dir.isDirectory() ) {
270             setCurrentDir( current_dir );
271         }
272         // hide until everything is ready
273         setVisible( false );
274         setOptions( Options.createInstance( _configuration ) );
275         setInferenceManager( InferenceManager.createInstance( _configuration ) );
276         setPhylogeneticInferenceOptions( PhylogeneticInferenceOptions.createInstance( _configuration ) );
277         //     _textframe = null; #~~~~
278         // set title
279         setTitle( Constants.PRG_NAME + " " + Constants.VERSION + " (" + Constants.PRG_DATE + ")" );
280         _mainpanel = new MainPanel( _configuration, this );
281         // The file dialogs
282         _open_filechooser = new JFileChooser();
283         _open_filechooser.setCurrentDirectory( new File( "." ) );
284         _open_filechooser.setMultiSelectionEnabled( false );
285         _open_filechooser.addChoosableFileFilter( MainFrameApplication.xmlfilter );
286         _open_filechooser.addChoosableFileFilter( MainFrameApplication.nhxfilter );
287         _open_filechooser.addChoosableFileFilter( MainFrameApplication.nhfilter );
288         _open_filechooser.addChoosableFileFilter( MainFrameApplication.nexusfilter );
289         _open_filechooser.addChoosableFileFilter( MainFrameApplication.tolfilter );
290         _open_filechooser.addChoosableFileFilter( _open_filechooser.getAcceptAllFileFilter() );
291         _open_filechooser.setFileFilter( MainFrameApplication.defaultfilter );
292         _open_filechooser_for_species_tree = new JFileChooser();
293         _open_filechooser_for_species_tree.setCurrentDirectory( new File( "." ) );
294         _open_filechooser_for_species_tree.setMultiSelectionEnabled( false );
295         _open_filechooser_for_species_tree.addChoosableFileFilter( MainFrameApplication.xmlfilter );
296         _open_filechooser_for_species_tree.addChoosableFileFilter( MainFrameApplication.tolfilter );
297         _open_filechooser_for_species_tree.setFileFilter( MainFrameApplication.xmlfilter );
298         _save_filechooser = new JFileChooser();
299         _save_filechooser.setCurrentDirectory( new File( "." ) );
300         _save_filechooser.setMultiSelectionEnabled( false );
301         _save_filechooser.setFileFilter( MainFrameApplication.xmlfilter );
302         _save_filechooser.addChoosableFileFilter( MainFrameApplication.nhfilter );
303         _save_filechooser.addChoosableFileFilter( MainFrameApplication.nexusfilter );
304         _save_filechooser.addChoosableFileFilter( _save_filechooser.getAcceptAllFileFilter() );
305         _writetopdf_filechooser = new JFileChooser();
306         _writetopdf_filechooser.addChoosableFileFilter( MainFrameApplication.pdffilter );
307         _writetographics_filechooser = new JFileChooser();
308         _writetographics_filechooser.addChoosableFileFilter( MainFrameApplication.graphicsfilefilter );
309         // Msa:
310         _msa_filechooser = new JFileChooser();
311         _msa_filechooser.setName( "Read Multiple Sequence Alignment File" );
312         _msa_filechooser.setCurrentDirectory( new File( "." ) );
313         _msa_filechooser.setMultiSelectionEnabled( false );
314         _msa_filechooser.addChoosableFileFilter( _msa_filechooser.getAcceptAllFileFilter() );
315         _msa_filechooser.addChoosableFileFilter( MainFrameApplication.msafilter );
316         // Seqs:
317         _seqs_pi_filechooser = new JFileChooser();
318         _seqs_pi_filechooser.setName( "Read Sequences File" );
319         _seqs_pi_filechooser.setCurrentDirectory( new File( "." ) );
320         _seqs_pi_filechooser.setMultiSelectionEnabled( false );
321         _seqs_pi_filechooser.addChoosableFileFilter( _seqs_pi_filechooser.getAcceptAllFileFilter() );
322         _seqs_pi_filechooser.addChoosableFileFilter( MainFrameApplication.seqsfilter );
323         // Expression
324         _values_filechooser = new JFileChooser();
325         _values_filechooser.setCurrentDirectory( new File( "." ) );
326         _values_filechooser.setMultiSelectionEnabled( false );
327         // Sequences
328         _sequences_filechooser = new JFileChooser();
329         _sequences_filechooser.setCurrentDirectory( new File( "." ) );
330         _sequences_filechooser.setMultiSelectionEnabled( false );
331         // build the menu bar
332         _jmenubar = new JMenuBar();
333         if ( !_configuration.isUseNativeUI() ) {
334             _jmenubar.setBackground( getConfiguration().getGuiMenuBackgroundColor() );
335         }
336         buildFileMenu();
337         if ( Constants.__ALLOW_PHYLOGENETIC_INFERENCE ) {
338             buildPhylogeneticInferenceMenu();
339         }
340         buildAnalysisMenu();
341         buildToolsMenu();
342         buildViewMenu();
343         buildFontSizeMenu();
344         buildOptionsMenu();
345         buildTypeMenu();
346         buildHelpMenu();
347         setJMenuBar( _jmenubar );
348         _jmenubar.add( _help_jmenu );
349         _contentpane = getContentPane();
350         _contentpane.setLayout( new BorderLayout() );
351         _contentpane.add( _mainpanel, BorderLayout.CENTER );
352         // App is this big
353         setSize( MainFrameApplication.FRAME_X_SIZE, MainFrameApplication.FRAME_Y_SIZE );
354         //        addWindowFocusListener( new WindowAdapter() {
355         //
356         //            @Override
357         //            public void windowGainedFocus( WindowEvent e ) {
358         //                requestFocusInWindow();
359         //            }
360         //        } );
361         // The window listener
362         setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE );
363         addWindowListener( new WindowAdapter() {
364
365             @Override
366             public void windowClosing( final WindowEvent e ) {
367                 if ( isUnsavedDataPresent() ) {
368                     final int r = JOptionPane.showConfirmDialog( null,
369                                                                  "Exit despite potentially unsaved changes?",
370                                                                  "Exit?",
371                                                                  JOptionPane.YES_NO_OPTION );
372                     if ( r != JOptionPane.YES_OPTION ) {
373                         return;
374                     }
375                 }
376                 else {
377                     final int r = JOptionPane.showConfirmDialog( null,
378                                                                  "Exit Archaeopteryx?",
379                                                                  "Exit?",
380                                                                  JOptionPane.YES_NO_OPTION );
381                     if ( r != JOptionPane.YES_OPTION ) {
382                         return;
383                     }
384                 }
385                 exit();
386             }
387         } );
388         // The component listener
389         addComponentListener( new ComponentAdapter() {
390
391             @Override
392             public void componentResized( final ComponentEvent e ) {
393                 if ( _mainpanel.getCurrentTreePanel() != null ) {
394                     _mainpanel.getCurrentTreePanel().calcParametersForPainting( _mainpanel.getCurrentTreePanel()
395                                                                                         .getWidth(),
396                                                                                 _mainpanel.getCurrentTreePanel()
397                                                                                         .getHeight(),
398                                                                                 getOptions().isAllowFontSizeChange() );
399                 }
400             }
401         } );
402         requestFocusInWindow();
403         // addKeyListener( this );
404         setVisible( true );
405         if ( ( phys != null ) && ( phys.length > 0 ) ) {
406             AptxUtil.addPhylogeniesToTabs( phys, title, null, _configuration, _mainpanel );
407             validate();
408             getMainPanel().getControlPanel().showWholeAll();
409             getMainPanel().getControlPanel().showWhole();
410         }
411         activateSaveAllIfNeeded();
412         // ...and its children
413         _contentpane.repaint();
414         System.gc();
415     }
416
417     private MainFrameApplication( final Phylogeny[] phys, final String config_file, final String title ) {
418         // Reads the config file (false, false => not url, not applet):
419         this( phys, new Configuration( config_file, false, false, true ), title );
420     }
421
422     @Override
423     public void actionPerformed( final ActionEvent e ) {
424         try {
425             super.actionPerformed( e );
426             final Object o = e.getSource();
427             // Handle app-specific actions here:
428             if ( o == _open_item ) {
429                 readPhylogeniesFromFile();
430             }
431             else if ( o == _save_item ) {
432                 writeToFile( _mainpanel.getCurrentPhylogeny() );
433                 // If subtree currently displayed, save it, instead of complete
434                 // tree.
435             }
436             else if ( o == _new_item ) {
437                 newTree();
438             }
439             else if ( o == _save_all_item ) {
440                 writeAllToFile();
441             }
442             else if ( o == _close_item ) {
443                 closeCurrentPane();
444             }
445             else if ( o == _write_to_pdf_item ) {
446                 writeToPdf( _mainpanel.getCurrentPhylogeny() );
447             }
448             else if ( o == _write_to_jpg_item ) {
449                 writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.JPG );
450             }
451             else if ( o == _write_to_png_item ) {
452                 writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.PNG );
453             }
454             else if ( o == _write_to_gif_item ) {
455                 writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.GIF );
456             }
457             else if ( o == _write_to_tif_item ) {
458                 writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.TIFF );
459             }
460             else if ( o == _write_to_bmp_item ) {
461                 writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.BMP );
462             }
463             else if ( o == _print_item ) {
464                 print();
465             }
466             else if ( o == _load_species_tree_item ) {
467                 readSpeciesTreeFromFile();
468             }
469             else if ( o == _lineage_inference ) {
470                 if ( isSubtreeDisplayed() ) {
471                     JOptionPane.showMessageDialog( this,
472                                                    "Subtree is shown.",
473                                                    "Cannot infer ancestral taxonomies",
474                                                    JOptionPane.ERROR_MESSAGE );
475                     return;
476                 }
477                 executeLineageInference();
478             }
479             else if ( o == _function_analysis ) {
480                 executeFunctionAnalysis();
481             }
482             else if ( o == _obtain_detailed_taxonomic_information_jmi ) {
483                 if ( isSubtreeDisplayed() ) {
484                     return;
485                 }
486                 obtainDetailedTaxonomicInformation();
487             }
488             else if ( o == _obtain_detailed_taxonomic_information_deleting_jmi ) {
489                 if ( isSubtreeDisplayed() ) {
490                     return;
491                 }
492                 obtainDetailedTaxonomicInformationDelete();
493             }
494             else if ( o == _obtain_seq_information_jmi ) {
495                 obtainSequenceInformation();
496             }
497             else if ( o == _read_values_jmi ) {
498                 if ( isSubtreeDisplayed() ) {
499                     return;
500                 }
501                 addExpressionValuesFromFile();
502             }
503             else if ( o == _read_seqs_jmi ) {
504                 if ( isSubtreeDisplayed() ) {
505                     return;
506                 }
507                 addSequencesFromFile();
508             }
509             else if ( o == _move_node_names_to_tax_sn_jmi ) {
510                 moveNodeNamesToTaxSn();
511             }
512             else if ( o == _move_node_names_to_seq_names_jmi ) {
513                 moveNodeNamesToSeqNames();
514             }
515             else if ( o == _extract_tax_code_from_node_names_jmi ) {
516                 extractTaxDataFromNodeNames();
517             }
518             else if ( o == _gsdi_item ) {
519                 if ( isSubtreeDisplayed() ) {
520                     return;
521                 }
522                 executeGSDI();
523             }
524             else if ( o == _gsdir_item ) {
525                 if ( isSubtreeDisplayed() ) {
526                     return;
527                 }
528                 executeGSDIR();
529             }
530             else if ( o == _graphics_export_visible_only_cbmi ) {
531                 updateOptions( getOptions() );
532             }
533             else if ( o == _antialias_print_cbmi ) {
534                 updateOptions( getOptions() );
535             }
536             else if ( o == _print_black_and_white_cbmi ) {
537                 updateOptions( getOptions() );
538             }
539             else if ( o == _print_using_actual_size_cbmi ) {
540                 updateOptions( getOptions() );
541             }
542             else if ( o == _graphics_export_using_actual_size_cbmi ) {
543                 updateOptions( getOptions() );
544             }
545             else if ( o == _print_size_mi ) {
546                 choosePrintSize();
547             }
548             else if ( o == _choose_pdf_width_mi ) {
549                 choosePdfWidth();
550             }
551             else if ( o == _internal_number_are_confidence_for_nh_parsing_cbmi ) {
552                 updateOptions( getOptions() );
553             }
554             else if ( o == _replace_underscores_cbmi ) {
555                 if ( ( _extract_taxonomy_no_rbmi != null ) && !_extract_taxonomy_no_rbmi.isSelected() ) {
556                     _extract_taxonomy_no_rbmi.setSelected( true );
557                 }
558                 updateOptions( getOptions() );
559             }
560             else if ( o == _collapse_below_threshold ) {
561                 if ( isSubtreeDisplayed() ) {
562                     return;
563                 }
564                 collapseBelowThreshold();
565             }
566             else if ( ( o == _extract_taxonomy_pfam_rbmi ) || ( o == _extract_taxonomy_yes_rbmi ) ) {
567                 if ( _replace_underscores_cbmi != null ) {
568                     _replace_underscores_cbmi.setSelected( false );
569                 }
570                 updateOptions( getOptions() );
571             }
572             else if ( o == _inference_from_msa_item ) {
573                 executePhyleneticInference( false );
574             }
575             else if ( o == _inference_from_seqs_item ) {
576                 executePhyleneticInference( true );
577             }
578             _contentpane.repaint();
579         }
580         catch ( final Exception ex ) {
581             AptxUtil.unexpectedException( ex );
582         }
583         catch ( final Error err ) {
584             AptxUtil.unexpectedError( err );
585         }
586     }
587
588     public void end() {
589         _mainpanel.terminate();
590         _contentpane.removeAll();
591         setVisible( false );
592         dispose();
593     }
594
595     @Override
596     public MainPanel getMainPanel() {
597         return _mainpanel;
598     }
599
600     public Msa getMsa() {
601         return _msa;
602     }
603
604     public File getMsaFile() {
605         return _msa_file;
606     }
607
608     public List<Sequence> getSeqs() {
609         return _seqs;
610     }
611
612     public File getSeqsFile() {
613         return _seqs_file;
614     }
615
616     public void readMsaFromFile() {
617         // Set an initial directory if none set yet
618         final File my_dir = getCurrentDir();
619         _msa_filechooser.setMultiSelectionEnabled( false );
620         // Open file-open dialog and set current directory
621         if ( my_dir != null ) {
622             _msa_filechooser.setCurrentDirectory( my_dir );
623         }
624         final int result = _msa_filechooser.showOpenDialog( _contentpane );
625         // All done: get the msa
626         final File file = _msa_filechooser.getSelectedFile();
627         setCurrentDir( _msa_filechooser.getCurrentDirectory() );
628         if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) {
629             setMsaFile( null );
630             setMsa( null );
631             Msa msa = null;
632             try {
633                 final InputStream is = new FileInputStream( file );
634                 if ( FastaParser.isLikelyFasta( file ) ) {
635                     msa = FastaParser.parseMsa( is );
636                 }
637                 else {
638                     msa = GeneralMsaParser.parse( is );
639                 }
640             }
641             catch ( final MsaFormatException e ) {
642                 setArrowCursor();
643                 JOptionPane.showMessageDialog( this,
644                                                e.getLocalizedMessage(),
645                                                "Multiple sequence alignment format error",
646                                                JOptionPane.ERROR_MESSAGE );
647                 return;
648             }
649             catch ( final IOException e ) {
650                 setArrowCursor();
651                 JOptionPane.showMessageDialog( this,
652                                                e.getLocalizedMessage(),
653                                                "Failed to read multiple sequence alignment",
654                                                JOptionPane.ERROR_MESSAGE );
655                 return;
656             }
657             catch ( final IllegalArgumentException e ) {
658                 setArrowCursor();
659                 JOptionPane.showMessageDialog( this,
660                                                e.getLocalizedMessage(),
661                                                "Unexpected error during reading of multiple sequence alignment",
662                                                JOptionPane.ERROR_MESSAGE );
663                 return;
664             }
665             catch ( final Exception e ) {
666                 setArrowCursor();
667                 e.printStackTrace();
668                 JOptionPane.showMessageDialog( this,
669                                                e.getLocalizedMessage(),
670                                                "Unexpected error during reading of multiple sequence alignment",
671                                                JOptionPane.ERROR_MESSAGE );
672                 return;
673             }
674             if ( ( msa == null ) || ( msa.getNumberOfSequences() < 1 ) ) {
675                 JOptionPane.showMessageDialog( this,
676                                                "Multiple sequence alignment is empty",
677                                                "Illegal Multiple Sequence Alignment",
678                                                JOptionPane.ERROR_MESSAGE );
679                 return;
680             }
681             if ( msa.getNumberOfSequences() < 4 ) {
682                 JOptionPane.showMessageDialog( this,
683                                                "Multiple sequence alignment needs to contain at least 3 sequences",
684                                                "Illegal multiple sequence alignment",
685                                                JOptionPane.ERROR_MESSAGE );
686                 return;
687             }
688             if ( msa.getLength() < 2 ) {
689                 JOptionPane.showMessageDialog( this,
690                                                "Multiple sequence alignment needs to contain at least 2 residues",
691                                                "Illegal multiple sequence alignment",
692                                                JOptionPane.ERROR_MESSAGE );
693                 return;
694             }
695             System.gc();
696             setMsaFile( _msa_filechooser.getSelectedFile() );
697             setMsa( msa );
698         }
699     }
700
701     public void readSeqsFromFileforPI() {
702         // Set an initial directory if none set yet
703         final File my_dir = getCurrentDir();
704         _seqs_pi_filechooser.setMultiSelectionEnabled( false );
705         // Open file-open dialog and set current directory
706         if ( my_dir != null ) {
707             _seqs_pi_filechooser.setCurrentDirectory( my_dir );
708         }
709         final int result = _seqs_pi_filechooser.showOpenDialog( _contentpane );
710         // All done: get the seqs
711         final File file = _seqs_pi_filechooser.getSelectedFile();
712         setCurrentDir( _seqs_pi_filechooser.getCurrentDirectory() );
713         if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) {
714             setSeqsFile( null );
715             setSeqs( null );
716             List<Sequence> seqs = null;
717             try {
718                 if ( FastaParser.isLikelyFasta( new FileInputStream( file ) ) ) {
719                     seqs = FastaParser.parse( new FileInputStream( file ) );
720                     for( final Sequence seq : seqs ) {
721                         System.out.println( SequenceWriter.toFasta( seq, 60 ) );
722                     }
723                 }
724                 else {
725                     //TODO error
726                 }
727             }
728             catch ( final MsaFormatException e ) {
729                 setArrowCursor();
730                 JOptionPane.showMessageDialog( this,
731                                                e.getLocalizedMessage(),
732                                                "Multiple sequence file format error",
733                                                JOptionPane.ERROR_MESSAGE );
734                 return;
735             }
736             catch ( final IOException e ) {
737                 setArrowCursor();
738                 JOptionPane.showMessageDialog( this,
739                                                e.getLocalizedMessage(),
740                                                "Failed to read multiple sequence file",
741                                                JOptionPane.ERROR_MESSAGE );
742                 return;
743             }
744             catch ( final IllegalArgumentException e ) {
745                 setArrowCursor();
746                 JOptionPane.showMessageDialog( this,
747                                                e.getLocalizedMessage(),
748                                                "Unexpected error during reading of multiple sequence file",
749                                                JOptionPane.ERROR_MESSAGE );
750                 return;
751             }
752             catch ( final Exception e ) {
753                 setArrowCursor();
754                 e.printStackTrace();
755                 JOptionPane.showMessageDialog( this,
756                                                e.getLocalizedMessage(),
757                                                "Unexpected error during reading of multiple sequence file",
758                                                JOptionPane.ERROR_MESSAGE );
759                 return;
760             }
761             if ( ( seqs == null ) || ( seqs.size() < 1 ) ) {
762                 JOptionPane.showMessageDialog( this,
763                                                "Multiple sequence file is empty",
764                                                "Illegal multiple sequence file",
765                                                JOptionPane.ERROR_MESSAGE );
766                 return;
767             }
768             if ( seqs.size() < 4 ) {
769                 JOptionPane.showMessageDialog( this,
770                                                "Multiple sequence file needs to contain at least 3 sequences",
771                                                "Illegal multiple sequence file",
772                                                JOptionPane.ERROR_MESSAGE );
773                 return;
774             }
775             //  if ( msa.getLength() < 2 ) {
776             //       JOptionPane.showMessageDialog( this,
777             //                                      "Multiple sequence alignment needs to contain at least 2 residues",
778             //                                      "Illegal multiple sequence file",
779             //                                      JOptionPane.ERROR_MESSAGE );
780             //       return;
781             //   }
782             System.gc();
783             setSeqsFile( _seqs_pi_filechooser.getSelectedFile() );
784             setSeqs( seqs );
785         }
786     }
787
788     void buildAnalysisMenu() {
789         _analysis_menu = MainFrame.createMenu( "Analysis", getConfiguration() );
790         _analysis_menu.add( _gsdi_item = new JMenuItem( "GSDI (Generalized Speciation Duplication Inference)" ) );
791         _analysis_menu.add( _gsdir_item = new JMenuItem( "GSDIR (GSDI with re-rooting)" ) );
792         _analysis_menu.add( _load_species_tree_item = new JMenuItem( "Load Species Tree..." ) );
793         customizeJMenuItem( _gsdi_item );
794         customizeJMenuItem( _gsdir_item );
795         customizeJMenuItem( _load_species_tree_item );
796         _analysis_menu.addSeparator();
797         _analysis_menu.add( _lineage_inference = new JMenuItem( INFER_ANCESTOR_TAXONOMIES ) );
798         customizeJMenuItem( _lineage_inference );
799         _lineage_inference.setToolTipText( "Inference of ancestor taxonomies/lineages" );
800         _jmenubar.add( _analysis_menu );
801     }
802
803     @Override
804     void buildFileMenu() {
805         _file_jmenu = MainFrame.createMenu( "File", getConfiguration() );
806         _file_jmenu.add( _open_item = new JMenuItem( "Read Tree from File..." ) );
807         _file_jmenu.addSeparator();
808         _file_jmenu.add( _open_url_item = new JMenuItem( "Read Tree from URL/Webservice..." ) );
809         _file_jmenu.addSeparator();
810         final WebservicesManager webservices_manager = WebservicesManager.getInstance();
811         _load_phylogeny_from_webservice_menu_items = new JMenuItem[ webservices_manager
812                 .getAvailablePhylogeniesWebserviceClients().size() ];
813         for( int i = 0; i < webservices_manager.getAvailablePhylogeniesWebserviceClients().size(); ++i ) {
814             final PhylogeniesWebserviceClient client = webservices_manager.getAvailablePhylogeniesWebserviceClient( i );
815             _load_phylogeny_from_webservice_menu_items[ i ] = new JMenuItem( client.getMenuName() );
816             _file_jmenu.add( _load_phylogeny_from_webservice_menu_items[ i ] );
817         }
818         if ( getConfiguration().isEditable() ) {
819             _file_jmenu.addSeparator();
820             _file_jmenu.add( _new_item = new JMenuItem( "New" ) );
821             _new_item.setToolTipText( "to create a new tree with one node, as source for manual tree construction" );
822         }
823         _file_jmenu.addSeparator();
824         _file_jmenu.add( _save_item = new JMenuItem( "Save Tree As..." ) );
825         _file_jmenu.add( _save_all_item = new JMenuItem( "Save All Trees As..." ) );
826         _save_all_item.setToolTipText( "Write all phylogenies to one file." );
827         _save_all_item.setEnabled( false );
828         _file_jmenu.addSeparator();
829         _file_jmenu.add( _write_to_pdf_item = new JMenuItem( "Export to PDF file ..." ) );
830         if ( AptxUtil.canWriteFormat( "tif" ) || AptxUtil.canWriteFormat( "tiff" ) || AptxUtil.canWriteFormat( "TIF" ) ) {
831             _file_jmenu.add( _write_to_tif_item = new JMenuItem( "Export to TIFF file..." ) );
832         }
833         _file_jmenu.add( _write_to_png_item = new JMenuItem( "Export to PNG file..." ) );
834         _file_jmenu.add( _write_to_jpg_item = new JMenuItem( "Export to JPG file..." ) );
835         if ( AptxUtil.canWriteFormat( "gif" ) ) {
836             _file_jmenu.add( _write_to_gif_item = new JMenuItem( "Export to GIF file..." ) );
837         }
838         if ( AptxUtil.canWriteFormat( "bmp" ) ) {
839             _file_jmenu.add( _write_to_bmp_item = new JMenuItem( "Export to BMP file..." ) );
840         }
841         _file_jmenu.addSeparator();
842         _file_jmenu.add( _print_item = new JMenuItem( "Print..." ) );
843         _file_jmenu.addSeparator();
844         _file_jmenu.add( _close_item = new JMenuItem( "Close Tab" ) );
845         _close_item.setToolTipText( "To close the current pane." );
846         _close_item.setEnabled( true );
847         _file_jmenu.addSeparator();
848         _file_jmenu.add( _exit_item = new JMenuItem( "Exit" ) );
849         // For print in color option item
850         customizeJMenuItem( _open_item );
851         _open_item
852                 .setFont( new Font( _open_item.getFont().getFontName(), Font.BOLD, _open_item.getFont().getSize() + 4 ) );
853         customizeJMenuItem( _open_url_item );
854         for( int i = 0; i < webservices_manager.getAvailablePhylogeniesWebserviceClients().size(); ++i ) {
855             customizeJMenuItem( _load_phylogeny_from_webservice_menu_items[ i ] );
856         }
857         customizeJMenuItem( _save_item );
858         if ( getConfiguration().isEditable() ) {
859             customizeJMenuItem( _new_item );
860         }
861         customizeJMenuItem( _close_item );
862         customizeJMenuItem( _save_all_item );
863         customizeJMenuItem( _write_to_pdf_item );
864         customizeJMenuItem( _write_to_png_item );
865         customizeJMenuItem( _write_to_jpg_item );
866         customizeJMenuItem( _write_to_gif_item );
867         customizeJMenuItem( _write_to_tif_item );
868         customizeJMenuItem( _write_to_bmp_item );
869         customizeJMenuItem( _print_item );
870         customizeJMenuItem( _exit_item );
871         _jmenubar.add( _file_jmenu );
872     }
873
874     void buildOptionsMenu() {
875         _options_jmenu = MainFrame.createMenu( OPTIONS_HEADER, getConfiguration() );
876         _options_jmenu.addChangeListener( new ChangeListener() {
877
878             @Override
879             public void stateChanged( final ChangeEvent e ) {
880                 MainFrame.setOvPlacementColorChooseMenuItem( _overview_placment_mi, getOptions() );
881                 MainFrame.setTextColorChooseMenuItem( _switch_colors_mi, getCurrentTreePanel() );
882                 MainFrame
883                         .setTextMinSupportMenuItem( _choose_minimal_confidence_mi, getOptions(), getCurrentTreePanel() );
884                 MainFrame.setTextForFontChooserMenuItem( _choose_font_mi, MainFrame
885                         .createCurrentFontDesc( getMainPanel().getTreeFontSet() ) );
886                 setTextForGraphicsSizeChooserMenuItem( _print_size_mi, getOptions() );
887                 setTextForPdfLineWidthChooserMenuItem( _choose_pdf_width_mi, getOptions() );
888                 MainFrame.updateOptionsMenuDependingOnPhylogenyType( getMainPanel(),
889                                                                      _show_scale_cbmi,
890                                                                      _show_branch_length_values_cbmi,
891                                                                      _non_lined_up_cladograms_rbmi,
892                                                                      _uniform_cladograms_rbmi,
893                                                                      _ext_node_dependent_cladogram_rbmi,
894                                                                      _label_direction_cbmi );
895                 MainFrame.setCycleNodeFillMenuItem( _cycle_node_fill_mi, getOptions() );
896                 MainFrame.setCycleNodeShapeMenuItem( _cycle_node_shape_mi, getOptions() );
897                 MainFrame.setTextNodeSizeMenuItem( _choose_node_size_mi, getOptions() );
898             }
899         } );
900         _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( DISPLAY_SUBHEADER ), getConfiguration() ) );
901         _options_jmenu
902                 .add( _ext_node_dependent_cladogram_rbmi = new JRadioButtonMenuItem( MainFrame.NONUNIFORM_CLADOGRAMS_LABEL ) );
903         _options_jmenu.add( _uniform_cladograms_rbmi = new JRadioButtonMenuItem( MainFrame.UNIFORM_CLADOGRAMS_LABEL ) );
904         _options_jmenu.add( _non_lined_up_cladograms_rbmi = new JRadioButtonMenuItem( NON_LINED_UP_CLADOGRAMS_LABEL ) );
905         _radio_group_1 = new ButtonGroup();
906         _radio_group_1.add( _ext_node_dependent_cladogram_rbmi );
907         _radio_group_1.add( _uniform_cladograms_rbmi );
908         _radio_group_1.add( _non_lined_up_cladograms_rbmi );
909         _options_jmenu.add( _show_overview_cbmi = new JCheckBoxMenuItem( SHOW_OVERVIEW_LABEL ) );
910         _options_jmenu.add( _show_scale_cbmi = new JCheckBoxMenuItem( DISPLAY_SCALE_LABEL ) );
911         _options_jmenu
912                 .add( _show_branch_length_values_cbmi = new JCheckBoxMenuItem( DISPLAY_BRANCH_LENGTH_VALUES_LABEL ) );
913         _options_jmenu.add( _show_confidence_stddev_cbmi = new JCheckBoxMenuItem( SHOW_CONF_STDDEV_LABEL ) );
914         _options_jmenu
915                 .add( _show_default_node_shapes_internal_cbmi = new JCheckBoxMenuItem( DISPLAY_NODE_BOXES_LABEL_INT ) );
916         _options_jmenu
917                 .add( _show_default_node_shapes_external_cbmi = new JCheckBoxMenuItem( DISPLAY_NODE_BOXES_LABEL_EXT ) );
918         _options_jmenu
919                 .add( _taxonomy_colorize_node_shapes_cbmi = new JCheckBoxMenuItem( MainFrame.TAXONOMY_COLORIZE_NODE_SHAPES_LABEL ) );
920         _options_jmenu.add( _cycle_node_shape_mi = new JMenuItem( MainFrame.CYCLE_NODE_SHAPE_LABEL ) );
921         _options_jmenu.add( _cycle_node_fill_mi = new JMenuItem( MainFrame.CYCLE_NODE_FILL_LABEL ) );
922         _options_jmenu.add( _choose_node_size_mi = new JMenuItem( MainFrame.CHOOSE_NODE_SIZE_LABEL ) );
923         _options_jmenu.add( _label_direction_cbmi = new JCheckBoxMenuItem( LABEL_DIRECTION_LABEL ) );
924         _label_direction_cbmi.setToolTipText( LABEL_DIRECTION_TIP );
925         _options_jmenu.add( _color_labels_same_as_parent_branch = new JCheckBoxMenuItem( COLOR_LABELS_LABEL ) );
926         _color_labels_same_as_parent_branch.setToolTipText( MainFrame.COLOR_LABELS_TIP );
927         _options_jmenu.add( _abbreviate_scientific_names = new JCheckBoxMenuItem( ABBREV_SN_LABEL ) );
928         _options_jmenu.add( _screen_antialias_cbmi = new JCheckBoxMenuItem( SCREEN_ANTIALIAS_LABEL ) );
929         _options_jmenu.add( _background_gradient_cbmi = new JCheckBoxMenuItem( BG_GRAD_LABEL ) );
930         if ( getConfiguration().doDisplayOption( Configuration.show_domain_architectures ) ) {
931             _options_jmenu.add( _show_domain_labels = new JCheckBoxMenuItem( SHOW_DOMAIN_LABELS_LABEL ) );
932         }
933         _options_jmenu.add( _choose_minimal_confidence_mi = new JMenuItem( "" ) );
934         _options_jmenu.add( _overview_placment_mi = new JMenuItem( "" ) );
935         _options_jmenu.add( _switch_colors_mi = new JMenuItem( "" ) );
936         _options_jmenu.add( _choose_font_mi = new JMenuItem( "" ) );
937         _options_jmenu.addSeparator();
938         _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( SEARCH_SUBHEADER ), getConfiguration() ) );
939         _options_jmenu.add( _search_case_senstive_cbmi = new JCheckBoxMenuItem( SEARCH_CASE_SENSITIVE_LABEL ) );
940         _options_jmenu.add( _search_whole_words_only_cbmi = new JCheckBoxMenuItem( SEARCH_TERMS_ONLY_LABEL ) );
941         _options_jmenu.add( _inverse_search_result_cbmi = new JCheckBoxMenuItem( INVERSE_SEARCH_RESULT_LABEL ) );
942         _options_jmenu.addSeparator();
943         _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( "Graphics Export & Printing:" ),
944                                                       getConfiguration() ) );
945         _options_jmenu.add( _antialias_print_cbmi = new JCheckBoxMenuItem( "Antialias" ) );
946         _options_jmenu.add( _print_black_and_white_cbmi = new JCheckBoxMenuItem( "Export in Black and White" ) );
947         _options_jmenu
948                 .add( _print_using_actual_size_cbmi = new JCheckBoxMenuItem( "Use Current Image Size for PDF export and Printing" ) );
949         _options_jmenu
950                 .add( _graphics_export_using_actual_size_cbmi = new JCheckBoxMenuItem( "Use Current Image Size for PNG, JPG, and GIF export" ) );
951         _options_jmenu
952                 .add( _graphics_export_visible_only_cbmi = new JCheckBoxMenuItem( "Limit to Visible ('Screenshot') for PNG, JPG, and GIF export" ) );
953         _options_jmenu.add( _print_size_mi = new JMenuItem( "" ) );
954         _options_jmenu.add( _choose_pdf_width_mi = new JMenuItem( "" ) );
955         _options_jmenu.addSeparator();
956         _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( "Newick/NHX/Nexus Input:" ), getConfiguration() ) );
957         _options_jmenu
958                 .add( _internal_number_are_confidence_for_nh_parsing_cbmi = new JCheckBoxMenuItem( "Internal Node Names are Confidence Values" ) );
959         _options_jmenu.add( _replace_underscores_cbmi = new JCheckBoxMenuItem( "Replace Underscores with Spaces" ) );
960         //
961         _options_jmenu.add( _extract_taxonomy_no_rbmi = new JRadioButtonMenuItem( "No Taxonomy Extraction" ) );
962         _options_jmenu
963                 .add( _extract_taxonomy_pfam_rbmi = new JRadioButtonMenuItem( "Extract Taxonomy Codes from Pfam-style Node Names" ) );
964         _extract_taxonomy_pfam_rbmi
965                 .setToolTipText( "To extract 5-letter taxonomy codes from node names in the form of \"BCL2_MOUSE/134-298\"" );
966         _options_jmenu
967                 .add( _extract_taxonomy_yes_rbmi = new JRadioButtonMenuItem( "Extract Taxonomy Codes from Node Names" ) );
968         _extract_taxonomy_yes_rbmi
969                 .setToolTipText( "To extract 5-letter taxonomy codes from node names in the form of \"BCL2_MOUSE\" or \"BCL2_MOUSE B-cell lymphoma 2...\"" );
970         _radio_group_2 = new ButtonGroup();
971         _radio_group_2.add( _extract_taxonomy_no_rbmi );
972         _radio_group_2.add( _extract_taxonomy_pfam_rbmi );
973         _radio_group_2.add( _extract_taxonomy_yes_rbmi );
974         // 
975         _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( "Newick/Nexus Output:" ), getConfiguration() ) );
976         _options_jmenu
977                 .add( _use_brackets_for_conf_in_nh_export_cbmi = new JCheckBoxMenuItem( USE_BRACKETS_FOR_CONF_IN_NH_LABEL ) );
978         _use_brackets_for_conf_in_nh_export_cbmi
979                 .setToolTipText( "e.g. \"0.1[90]\" for a branch with support 90 and a length of 0.1" );
980         _options_jmenu
981                 .add( _use_internal_names_for_conf_in_nh_export_cbmi = new JCheckBoxMenuItem( USE_INTERNAL_NAMES_FOR_CONF_IN_NH_LABEL ) );
982         customizeJMenuItem( _choose_font_mi );
983         customizeJMenuItem( _choose_minimal_confidence_mi );
984         customizeJMenuItem( _switch_colors_mi );
985         customizeJMenuItem( _print_size_mi );
986         customizeJMenuItem( _choose_pdf_width_mi );
987         customizeJMenuItem( _overview_placment_mi );
988         customizeCheckBoxMenuItem( _show_default_node_shapes_external_cbmi, getOptions()
989                 .isShowDefaultNodeShapesExternal() );
990         customizeCheckBoxMenuItem( _show_default_node_shapes_internal_cbmi, getOptions()
991                 .isShowDefaultNodeShapesInternal() );
992         customizeCheckBoxMenuItem( _taxonomy_colorize_node_shapes_cbmi, getOptions().isTaxonomyColorizeNodeShapes() );
993         customizeJMenuItem( _cycle_node_shape_mi );
994         customizeJMenuItem( _cycle_node_fill_mi );
995         customizeJMenuItem( _choose_node_size_mi );
996         customizeCheckBoxMenuItem( _color_labels_same_as_parent_branch, getOptions().isColorLabelsSameAsParentBranch() );
997         customizeCheckBoxMenuItem( _screen_antialias_cbmi, getOptions().isAntialiasScreen() );
998         customizeCheckBoxMenuItem( _background_gradient_cbmi, getOptions().isBackgroundColorGradient() );
999         customizeCheckBoxMenuItem( _show_domain_labels, getOptions().isShowDomainLabels() );
1000         customizeCheckBoxMenuItem( _abbreviate_scientific_names, getOptions().isAbbreviateScientificTaxonNames() );
1001         customizeCheckBoxMenuItem( _search_case_senstive_cbmi, getOptions().isSearchCaseSensitive() );
1002         customizeCheckBoxMenuItem( _show_scale_cbmi, getOptions().isShowScale() );
1003         customizeRadioButtonMenuItem( _non_lined_up_cladograms_rbmi,
1004                                       getOptions().getCladogramType() == CLADOGRAM_TYPE.NON_LINED_UP );
1005         customizeRadioButtonMenuItem( _uniform_cladograms_rbmi,
1006                                       getOptions().getCladogramType() == CLADOGRAM_TYPE.TOTAL_NODE_SUM_DEP );
1007         customizeRadioButtonMenuItem( _ext_node_dependent_cladogram_rbmi,
1008                                       getOptions().getCladogramType() == CLADOGRAM_TYPE.EXT_NODE_SUM_DEP );
1009         customizeCheckBoxMenuItem( _show_branch_length_values_cbmi, getOptions().isShowBranchLengthValues() );
1010         customizeCheckBoxMenuItem( _show_overview_cbmi, getOptions().isShowOverview() );
1011         customizeCheckBoxMenuItem( _label_direction_cbmi,
1012                                    getOptions().getNodeLabelDirection() == NODE_LABEL_DIRECTION.RADIAL );
1013         customizeCheckBoxMenuItem( _antialias_print_cbmi, getOptions().isAntialiasPrint() );
1014         customizeCheckBoxMenuItem( _print_black_and_white_cbmi, getOptions().isPrintBlackAndWhite() );
1015         customizeCheckBoxMenuItem( _internal_number_are_confidence_for_nh_parsing_cbmi, getOptions()
1016                 .isInternalNumberAreConfidenceForNhParsing() );
1017         customizeRadioButtonMenuItem( _extract_taxonomy_no_rbmi,
1018                                       getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.NO );
1019         customizeRadioButtonMenuItem( _extract_taxonomy_yes_rbmi,
1020                                       getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED );
1021         customizeRadioButtonMenuItem( _extract_taxonomy_pfam_rbmi,
1022                                       getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.PFAM_STYLE_STRICT );
1023         customizeCheckBoxMenuItem( _replace_underscores_cbmi, getOptions().isReplaceUnderscoresInNhParsing() );
1024         customizeCheckBoxMenuItem( _search_whole_words_only_cbmi, getOptions().isMatchWholeTermsOnly() );
1025         customizeCheckBoxMenuItem( _inverse_search_result_cbmi, getOptions().isInverseSearchResult() );
1026         customizeCheckBoxMenuItem( _graphics_export_visible_only_cbmi, getOptions().isGraphicsExportVisibleOnly() );
1027         customizeCheckBoxMenuItem( _print_using_actual_size_cbmi, getOptions().isPrintUsingActualSize() );
1028         customizeCheckBoxMenuItem( _graphics_export_using_actual_size_cbmi, getOptions()
1029                 .isGraphicsExportUsingActualSize() );
1030         customizeCheckBoxMenuItem( _show_confidence_stddev_cbmi, getOptions().isShowConfidenceStddev() );
1031         customizeCheckBoxMenuItem( _use_brackets_for_conf_in_nh_export_cbmi, getOptions()
1032                 .getNhConversionSupportValueStyle() == NH_CONVERSION_SUPPORT_VALUE_STYLE.IN_SQUARE_BRACKETS );
1033         customizeCheckBoxMenuItem( _use_internal_names_for_conf_in_nh_export_cbmi, getOptions()
1034                 .getNhConversionSupportValueStyle() == NH_CONVERSION_SUPPORT_VALUE_STYLE.AS_INTERNAL_NODE_NAMES );
1035         _jmenubar.add( _options_jmenu );
1036     }
1037
1038     void buildPhylogeneticInferenceMenu() {
1039         final InferenceManager im = getInferenceManager();
1040         _inference_menu = MainFrame.createMenu( "Inference", getConfiguration() );
1041         _inference_menu.add( _inference_from_msa_item = new JMenuItem( "From Multiple Sequence Alignment..." ) );
1042         customizeJMenuItem( _inference_from_msa_item );
1043         _inference_from_msa_item.setToolTipText( "Basic phylogenetic inference from MSA" );
1044         if ( im.canDoMsa() ) {
1045             _inference_menu.add( _inference_from_seqs_item = new JMenuItem( "From Unaligned Sequences..." ) );
1046             customizeJMenuItem( _inference_from_seqs_item );
1047             _inference_from_seqs_item
1048                     .setToolTipText( "Basic phylogenetic inference including multiple sequence alignment" );
1049         }
1050         else {
1051             _inference_menu
1052                     .add( _inference_from_seqs_item = new JMenuItem( "From Unaligned Sequences (no program found)" ) );
1053             customizeJMenuItem( _inference_from_seqs_item );
1054             _inference_from_seqs_item.setEnabled( false );
1055         }
1056         _jmenubar.add( _inference_menu );
1057     }
1058
1059     void buildToolsMenu() {
1060         _tools_menu = createMenu( "Tools", getConfiguration() );
1061         _tools_menu.add( _confcolor_item = new JMenuItem( "Colorize Branches Depending on Confidence" ) );
1062         customizeJMenuItem( _confcolor_item );
1063         _tools_menu.add( _color_rank_jmi = new JMenuItem( "Colorize Subtrees via Taxonomic Rank" ) );
1064         customizeJMenuItem( _color_rank_jmi );
1065         _color_rank_jmi.setToolTipText( "for example, at \"Class\" level, colorize mammal specific subtree red" );
1066         _tools_menu.add( _taxcolor_item = new JMenuItem( "Taxonomy Colorize Branches" ) );
1067         customizeJMenuItem( _taxcolor_item );
1068         _tools_menu.add( _remove_branch_color_item = new JMenuItem( "Delete Branch Colors" ) );
1069         _remove_branch_color_item.setToolTipText( "To delete branch color values from the current phylogeny" );
1070         customizeJMenuItem( _remove_branch_color_item );
1071         _tools_menu.addSeparator();
1072         _tools_menu.add( _annotate_item = new JMenuItem( "Annotate Sequences of Selected Nodes" ) );
1073         customizeJMenuItem( _annotate_item );
1074         _tools_menu.addSeparator();
1075         _tools_menu.add( _midpoint_root_item = new JMenuItem( "Midpoint-Root" ) );
1076         customizeJMenuItem( _midpoint_root_item );
1077         _tools_menu.addSeparator();
1078         _tools_menu.add( _collapse_species_specific_subtrees = new JMenuItem( "Collapse Species-Specific Subtrees" ) );
1079         customizeJMenuItem( _collapse_species_specific_subtrees );
1080         _tools_menu
1081                 .add( _collapse_below_threshold = new JMenuItem( "Collapse Branches with Confidence Below Threshold into Multifurcations" ) );
1082         customizeJMenuItem( _collapse_below_threshold );
1083         _collapse_below_threshold
1084                 .setToolTipText( "To 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)" );
1085         _tools_menu.addSeparator();
1086         _tools_menu
1087                 .add( _extract_tax_code_from_node_names_jmi = new JMenuItem( "Extract Taxonomic Data from Node Names" ) );
1088         customizeJMenuItem( _extract_tax_code_from_node_names_jmi );
1089         _extract_tax_code_from_node_names_jmi
1090                 .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'" );
1091         _tools_menu
1092                 .add( _move_node_names_to_tax_sn_jmi = new JMenuItem( "Transfer Node Names to Taxonomic Scientific Names" ) );
1093         customizeJMenuItem( _move_node_names_to_tax_sn_jmi );
1094         _move_node_names_to_tax_sn_jmi.setToolTipText( "To interpret node names as taxonomic scientific names" );
1095         _tools_menu.add( _move_node_names_to_seq_names_jmi = new JMenuItem( "Transfer Node Names to Sequence Names" ) );
1096         customizeJMenuItem( _move_node_names_to_seq_names_jmi );
1097         _move_node_names_to_seq_names_jmi.setToolTipText( "To interpret node names as sequence (protein, gene) names" );
1098         _tools_menu.addSeparator();
1099         _tools_menu
1100                 .add( _obtain_detailed_taxonomic_information_jmi = new JMenuItem( OBTAIN_DETAILED_TAXONOMIC_INFORMATION ) );
1101         customizeJMenuItem( _obtain_detailed_taxonomic_information_jmi );
1102         _obtain_detailed_taxonomic_information_jmi
1103                 .setToolTipText( "To add additional taxonomic information (from UniProt Taxonomy)" );
1104         _tools_menu
1105                 .add( _obtain_detailed_taxonomic_information_deleting_jmi = new JMenuItem( "Obtain Detailed Taxonomic Information (deletes nodes!)" ) );
1106         customizeJMenuItem( _obtain_detailed_taxonomic_information_deleting_jmi );
1107         _obtain_detailed_taxonomic_information_deleting_jmi
1108                 .setToolTipText( "To add additional taxonomic information, deletes nodes for which taxonomy cannot found (from UniProt Taxonomy)" );
1109         _tools_menu.add( _obtain_seq_information_jmi = new JMenuItem( "Obtain Sequence Information" ) );
1110         customizeJMenuItem( _obtain_seq_information_jmi );
1111         _obtain_seq_information_jmi.setToolTipText( "To add additional sequence information" );
1112         _tools_menu.addSeparator();
1113         if ( !Constants.__RELEASE ) {
1114             _tools_menu.add( _function_analysis = new JMenuItem( "Add UniProtKB Annotations" ) );
1115             customizeJMenuItem( _function_analysis );
1116             _function_analysis
1117                     .setToolTipText( "To add UniProtKB annotations for sequences with appropriate identifiers" );
1118             _tools_menu.addSeparator();
1119         }
1120         _tools_menu.add( _read_values_jmi = new JMenuItem( "Attach Vector/Expression Values" ) );
1121         customizeJMenuItem( _read_values_jmi );
1122         _read_values_jmi.setToolTipText( "To attach vector (e.g. gene expression) values to tree nodes (beta)" );
1123         _jmenubar.add( _tools_menu );
1124         _tools_menu.add( _read_seqs_jmi = new JMenuItem( "Attach Molecular Sequences" ) );
1125         customizeJMenuItem( _read_seqs_jmi );
1126         _read_seqs_jmi
1127                 .setToolTipText( "To attach molecular sequences to tree nodes (from Fasta-formatted file) (beta)" );
1128         _jmenubar.add( _tools_menu );
1129     }
1130
1131     @Override
1132     void close() {
1133         if ( isUnsavedDataPresent() ) {
1134             final int r = JOptionPane.showConfirmDialog( this,
1135                                                          "Exit despite potentially unsaved changes?",
1136                                                          "Exit?",
1137                                                          JOptionPane.YES_NO_OPTION );
1138             if ( r != JOptionPane.YES_OPTION ) {
1139                 return;
1140             }
1141         }
1142         exit();
1143     }
1144
1145     void executeFunctionAnalysis() {
1146         if ( ( _mainpanel.getCurrentPhylogeny() == null ) || ( _mainpanel.getCurrentPhylogeny().isEmpty() ) ) {
1147             return;
1148         }
1149         final GoAnnotation a = new GoAnnotation( this,
1150                                                  _mainpanel.getCurrentTreePanel(),
1151                                                  _mainpanel.getCurrentPhylogeny() );
1152         new Thread( a ).start();
1153     }
1154
1155     void executeGSDI() {
1156         if ( !isOKforSDI( false, true ) ) {
1157             return;
1158         }
1159         if ( !_mainpanel.getCurrentPhylogeny().isRooted() ) {
1160             JOptionPane.showMessageDialog( this,
1161                                            "Gene tree is not rooted.",
1162                                            "Cannot execute GSDI",
1163                                            JOptionPane.ERROR_MESSAGE );
1164             return;
1165         }
1166         final Phylogeny gene_tree = _mainpanel.getCurrentPhylogeny().copy();
1167         gene_tree.setAllNodesToNotCollapse();
1168         gene_tree.recalculateNumberOfExternalDescendants( false );
1169         GSDI gsdi = null;
1170         final Phylogeny species_tree = _species_tree.copy();
1171         try {
1172             gsdi = new GSDI( gene_tree, species_tree, false, true, true );
1173         }
1174         catch ( final SDIException e ) {
1175             JOptionPane.showMessageDialog( this,
1176                                            e.getLocalizedMessage(),
1177                                            "Error during GSDI",
1178                                            JOptionPane.ERROR_MESSAGE );
1179             return;
1180         }
1181         catch ( final Exception e ) {
1182             AptxUtil.unexpectedException( e );
1183             return;
1184         }
1185         gene_tree.setRerootable( false );
1186         gene_tree.clearHashIdToNodeMap();
1187         gene_tree.recalculateNumberOfExternalDescendants( true );
1188         _mainpanel.addPhylogenyInNewTab( gene_tree, getConfiguration(), "gene tree", null );
1189         getControlPanel().setShowEvents( true );
1190         showWhole();
1191         final int selected = _mainpanel.getTabbedPane().getSelectedIndex();
1192         _mainpanel.addPhylogenyInNewTab( species_tree, getConfiguration(), "species tree", null );
1193         showWhole();
1194         _mainpanel.getTabbedPane().setSelectedIndex( selected );
1195         showWhole();
1196         _mainpanel.getCurrentTreePanel().setEdited( true );
1197         final int poly = PhylogenyMethods.countNumberOfPolytomies( species_tree );
1198         if ( gsdi.getStrippedExternalGeneTreeNodes().size() > 0 ) {
1199             JOptionPane.showMessageDialog( this,
1200                                            "Duplications: " + gsdi.getDuplicationsSum() + "\n"
1201                                                    + "Potential duplications: "
1202                                                    + gsdi.getSpeciationOrDuplicationEventsSum() + "\n"
1203                                                    + "Speciations: " + gsdi.getSpeciationsSum() + "\n"
1204                                                    + "Stripped gene tree nodes: "
1205                                                    + gsdi.getStrippedExternalGeneTreeNodes().size() + "\n"
1206                                                    + "Taxonomy linkage based on: " + gsdi.getTaxCompBase() + "\n"
1207                                                    + "Number of polytomies in species tree used: " + poly + "\n",
1208                                            "GSDI successfully completed",
1209                                            JOptionPane.WARNING_MESSAGE );
1210         }
1211         else {
1212             JOptionPane.showMessageDialog( this,
1213                                            "Duplications: " + gsdi.getDuplicationsSum() + "\n"
1214                                                    + "Potential duplications: "
1215                                                    + gsdi.getSpeciationOrDuplicationEventsSum() + "\n"
1216                                                    + "Speciations: " + gsdi.getSpeciationsSum() + "\n"
1217                                                    + "Stripped gene tree nodes: "
1218                                                    + gsdi.getStrippedExternalGeneTreeNodes().size() + "\n"
1219                                                    + "Taxonomy linkage based on: " + gsdi.getTaxCompBase() + "\n"
1220                                                    + "Number of polytomies in species tree used: " + poly + "\n",
1221                                            "GSDI successfully completed",
1222                                            JOptionPane.INFORMATION_MESSAGE );
1223         }
1224     }
1225
1226     void executeGSDIR() {
1227         if ( !isOKforSDI( false, false ) ) {
1228             return;
1229         }
1230         final int p = PhylogenyMethods.countNumberOfPolytomies( _mainpanel.getCurrentPhylogeny() );
1231         if ( ( p > 0 )
1232                 && !( ( p == 1 ) && ( _mainpanel.getCurrentPhylogeny().getRoot().getNumberOfDescendants() == 3 ) ) ) {
1233             JOptionPane.showMessageDialog( this,
1234                                            "Gene tree is not completely binary",
1235                                            "Cannot execute GSDI",
1236                                            JOptionPane.ERROR_MESSAGE );
1237             return;
1238         }
1239         final Phylogeny gene_tree = _mainpanel.getCurrentPhylogeny().copy();
1240         gene_tree.setAllNodesToNotCollapse();
1241         gene_tree.recalculateNumberOfExternalDescendants( false );
1242         GSDIR gsdir = null;
1243         final Phylogeny species_tree = _species_tree.copy();
1244         try {
1245             gsdir = new GSDIR( gene_tree, species_tree, true, true );
1246         }
1247         catch ( final SDIException e ) {
1248             JOptionPane.showMessageDialog( this,
1249                                            e.getLocalizedMessage(),
1250                                            "Error during GSDIR",
1251                                            JOptionPane.ERROR_MESSAGE );
1252             return;
1253         }
1254         catch ( final Exception e ) {
1255             AptxUtil.unexpectedException( e );
1256             return;
1257         }
1258         final Phylogeny result_gene_tree = gsdir.getMinDuplicationsSumGeneTree();
1259         result_gene_tree.setRerootable( false );
1260         result_gene_tree.clearHashIdToNodeMap();
1261         result_gene_tree.recalculateNumberOfExternalDescendants( true );
1262         _mainpanel.addPhylogenyInNewTab( result_gene_tree, getConfiguration(), "gene tree", null );
1263         getControlPanel().setShowEvents( true );
1264         showWhole();
1265         final int selected = _mainpanel.getTabbedPane().getSelectedIndex();
1266         _mainpanel.addPhylogenyInNewTab( species_tree, getConfiguration(), "species tree", null );
1267         showWhole();
1268         _mainpanel.getTabbedPane().setSelectedIndex( selected );
1269         showWhole();
1270         _mainpanel.getCurrentTreePanel().setEdited( true );
1271         final int poly = PhylogenyMethods.countNumberOfPolytomies( species_tree );
1272         if ( gsdir.getStrippedExternalGeneTreeNodes().size() > 0 ) {
1273             JOptionPane.showMessageDialog( this,
1274                                            "Minimal duplications: " + gsdir.getMinDuplicationsSum() + "\n"
1275                                                    + "Speciations: " + gsdir.getSpeciationsSum() + "\n"
1276                                                    + "Stripped gene tree nodes: "
1277                                                    + gsdir.getStrippedExternalGeneTreeNodes().size() + "\n"
1278                                                    + "Taxonomy linkage based on: " + gsdir.getTaxCompBase() + "\n"
1279                                                    + "Number of polytomies in species tree used: " + poly + "\n",
1280                                            "GSDIR successfully completed",
1281                                            JOptionPane.WARNING_MESSAGE );
1282         }
1283         else {
1284             JOptionPane.showMessageDialog( this,
1285                                            "Minimal duplications: " + gsdir.getMinDuplicationsSum() + "\n"
1286                                                    + "Speciations: " + gsdir.getSpeciationsSum() + "\n"
1287                                                    + "Stripped gene tree nodes: "
1288                                                    + gsdir.getStrippedExternalGeneTreeNodes().size() + "\n"
1289                                                    + "Taxonomy linkage based on: " + gsdir.getTaxCompBase() + "\n"
1290                                                    + "Number of polytomies in species tree used: " + poly + "\n",
1291                                            "GSDIR successfully completed",
1292                                            JOptionPane.INFORMATION_MESSAGE );
1293         }
1294     }
1295
1296     void executeLineageInference() {
1297         if ( ( _mainpanel.getCurrentPhylogeny() == null ) || ( _mainpanel.getCurrentPhylogeny().isEmpty() ) ) {
1298             return;
1299         }
1300         if ( !_mainpanel.getCurrentPhylogeny().isRooted() ) {
1301             JOptionPane.showMessageDialog( this,
1302                                            "Phylogeny is not rooted.",
1303                                            "Cannot infer ancestral taxonomies",
1304                                            JOptionPane.ERROR_MESSAGE );
1305             return;
1306         }
1307         final AncestralTaxonomyInferrer inferrer = new AncestralTaxonomyInferrer( this,
1308                                                                                   _mainpanel.getCurrentTreePanel(),
1309                                                                                   _mainpanel.getCurrentPhylogeny()
1310                                                                                           .copy() );
1311         new Thread( inferrer ).start();
1312     }
1313
1314     void exit() {
1315         removeAllTextFrames();
1316         _mainpanel.terminate();
1317         _contentpane.removeAll();
1318         setVisible( false );
1319         dispose();
1320         System.exit( 0 );
1321     }
1322
1323     boolean isOKforSDI( final boolean species_tree_has_to_binary, final boolean gene_tree_has_to_binary ) {
1324         if ( ( _mainpanel.getCurrentPhylogeny() == null ) || _mainpanel.getCurrentPhylogeny().isEmpty() ) {
1325             return false;
1326         }
1327         else if ( ( _species_tree == null ) || _species_tree.isEmpty() ) {
1328             JOptionPane.showMessageDialog( this,
1329                                            "No species tree loaded",
1330                                            "Cannot execute GSDI",
1331                                            JOptionPane.ERROR_MESSAGE );
1332             return false;
1333         }
1334         else if ( species_tree_has_to_binary && !_species_tree.isCompletelyBinary() ) {
1335             JOptionPane.showMessageDialog( this,
1336                                            "Species tree is not completely binary",
1337                                            "Cannot execute GSDI",
1338                                            JOptionPane.ERROR_MESSAGE );
1339             return false;
1340         }
1341         else if ( gene_tree_has_to_binary && !_mainpanel.getCurrentPhylogeny().isCompletelyBinary() ) {
1342             JOptionPane.showMessageDialog( this,
1343                                            "Gene tree is not completely binary",
1344                                            "Cannot execute GSDI",
1345                                            JOptionPane.ERROR_MESSAGE );
1346             return false;
1347         }
1348         else {
1349             return true;
1350         }
1351     }
1352
1353     @Override
1354     void readPhylogeniesFromURL() {
1355         URL url = null;
1356         Phylogeny[] phys = null;
1357         final String message = "Please enter a complete URL, for example \"http://www.phyloxml.org/examples/apaf.xml\"";
1358         final String url_string = JOptionPane.showInputDialog( this,
1359                                                                message,
1360                                                                "Use URL/webservice to obtain a phylogeny",
1361                                                                JOptionPane.QUESTION_MESSAGE );
1362         boolean nhx_or_nexus = false;
1363         if ( ( url_string != null ) && ( url_string.length() > 0 ) ) {
1364             try {
1365                 url = new URL( url_string );
1366                 PhylogenyParser parser = null;
1367                 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
1368                     parser = new TolParser();
1369                 }
1370                 else {
1371                     parser = ParserUtils.createParserDependingOnUrlContents( url, getConfiguration()
1372                             .isValidatePhyloXmlAgainstSchema() );
1373                 }
1374                 if ( parser instanceof NexusPhylogeniesParser ) {
1375                     nhx_or_nexus = true;
1376                 }
1377                 else if ( parser instanceof NHXParser ) {
1378                     nhx_or_nexus = true;
1379                 }
1380                 if ( _mainpanel.getCurrentTreePanel() != null ) {
1381                     _mainpanel.getCurrentTreePanel().setWaitCursor();
1382                 }
1383                 else {
1384                     _mainpanel.setWaitCursor();
1385                 }
1386                 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
1387                 phys = factory.create( url.openStream(), parser );
1388             }
1389             catch ( final MalformedURLException e ) {
1390                 JOptionPane.showMessageDialog( this,
1391                                                "Malformed URL: " + url + "\n" + e.getLocalizedMessage(),
1392                                                "Malformed URL",
1393                                                JOptionPane.ERROR_MESSAGE );
1394             }
1395             catch ( final IOException e ) {
1396                 JOptionPane.showMessageDialog( this,
1397                                                "Could not read from " + url + "\n"
1398                                                        + ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ),
1399                                                "Failed to read URL",
1400                                                JOptionPane.ERROR_MESSAGE );
1401             }
1402             catch ( final Exception e ) {
1403                 JOptionPane.showMessageDialog( this,
1404                                                ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ),
1405                                                "Unexpected Exception",
1406                                                JOptionPane.ERROR_MESSAGE );
1407             }
1408             finally {
1409                 if ( _mainpanel.getCurrentTreePanel() != null ) {
1410                     _mainpanel.getCurrentTreePanel().setArrowCursor();
1411                 }
1412                 else {
1413                     _mainpanel.setArrowCursor();
1414                 }
1415             }
1416             if ( ( phys != null ) && ( phys.length > 0 ) ) {
1417                 if ( nhx_or_nexus && getOptions().isInternalNumberAreConfidenceForNhParsing() ) {
1418                     for( final Phylogeny phy : phys ) {
1419                         PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
1420                     }
1421                 }
1422                 AptxUtil.addPhylogeniesToTabs( phys,
1423                                                new File( url.getFile() ).getName(),
1424                                                new File( url.getFile() ).toString(),
1425                                                getConfiguration(),
1426                                                getMainPanel() );
1427                 _mainpanel.getControlPanel().showWhole();
1428             }
1429         }
1430         activateSaveAllIfNeeded();
1431         System.gc();
1432     }
1433
1434     void setMsa( final Msa msa ) {
1435         _msa = msa;
1436     }
1437
1438     void setMsaFile( final File msa_file ) {
1439         _msa_file = msa_file;
1440     }
1441
1442     void setSeqs( final List<Sequence> seqs ) {
1443         _seqs = seqs;
1444     }
1445
1446     void setSeqsFile( final File seqs_file ) {
1447         _seqs_file = seqs_file;
1448     }
1449
1450     void writePhylogenyToGraphicsFile( final String file_name, final GraphicsExportType type ) {
1451         _mainpanel.getCurrentTreePanel().calcParametersForPainting( _mainpanel.getCurrentTreePanel().getWidth(),
1452                                                                     _mainpanel.getCurrentTreePanel().getHeight(),
1453                                                                     true );
1454         String file_written_to = "";
1455         boolean error = false;
1456         try {
1457             file_written_to = AptxUtil.writePhylogenyToGraphicsFile( file_name,
1458                                                                      _mainpanel.getCurrentTreePanel().getWidth(),
1459                                                                      _mainpanel.getCurrentTreePanel().getHeight(),
1460                                                                      _mainpanel.getCurrentTreePanel(),
1461                                                                      _mainpanel.getControlPanel(),
1462                                                                      type,
1463                                                                      getOptions() );
1464         }
1465         catch ( final IOException e ) {
1466             error = true;
1467             JOptionPane.showMessageDialog( this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE );
1468         }
1469         if ( !error ) {
1470             if ( ( file_written_to != null ) && ( file_written_to.length() > 0 ) ) {
1471                 JOptionPane.showMessageDialog( this,
1472                                                "Wrote image to: " + file_written_to,
1473                                                "Graphics Export",
1474                                                JOptionPane.INFORMATION_MESSAGE );
1475             }
1476             else {
1477                 JOptionPane.showMessageDialog( this,
1478                                                "There was an unknown problem when attempting to write to an image file: \""
1479                                                        + file_name + "\"",
1480                                                "Error",
1481                                                JOptionPane.ERROR_MESSAGE );
1482             }
1483         }
1484         _contentpane.repaint();
1485     }
1486
1487     private void addSequencesFromFile() {
1488         if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) ) {
1489             JOptionPane.showMessageDialog( this,
1490                                            "Need to load evolutionary tree first",
1491                                            "Can Not Read Sequences",
1492                                            JOptionPane.WARNING_MESSAGE );
1493             return;
1494         }
1495         final File my_dir = getCurrentDir();
1496         if ( my_dir != null ) {
1497             _sequences_filechooser.setCurrentDirectory( my_dir );
1498         }
1499         final int result = _sequences_filechooser.showOpenDialog( _contentpane );
1500         final File file = _sequences_filechooser.getSelectedFile();
1501         List<Sequence> seqs = null;
1502         if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) {
1503             try {
1504                 if ( FastaParser.isLikelyFasta( new FileInputStream( file ) ) ) {
1505                     seqs = FastaParser.parse( new FileInputStream( file ) );
1506                 }
1507                 else {
1508                     JOptionPane.showMessageDialog( this,
1509                                                    "Format does not appear to be Fasta",
1510                                                    "Multiple sequence file format error",
1511                                                    JOptionPane.ERROR_MESSAGE );
1512                     return;
1513                 }
1514             }
1515             catch ( final MsaFormatException e ) {
1516                 setArrowCursor();
1517                 JOptionPane.showMessageDialog( this,
1518                                                e.getLocalizedMessage(),
1519                                                "Multiple sequence file format error",
1520                                                JOptionPane.ERROR_MESSAGE );
1521                 return;
1522             }
1523             catch ( final IOException e ) {
1524                 setArrowCursor();
1525                 JOptionPane.showMessageDialog( this,
1526                                                e.getLocalizedMessage(),
1527                                                "Failed to read multiple sequence file",
1528                                                JOptionPane.ERROR_MESSAGE );
1529                 return;
1530             }
1531             catch ( final Exception e ) {
1532                 setArrowCursor();
1533                 e.printStackTrace();
1534                 JOptionPane.showMessageDialog( this,
1535                                                e.getLocalizedMessage(),
1536                                                "Unexpected error during reading of multiple sequence file",
1537                                                JOptionPane.ERROR_MESSAGE );
1538                 return;
1539             }
1540             if ( ( seqs == null ) || ( seqs.size() < 1 ) ) {
1541                 JOptionPane.showMessageDialog( this,
1542                                                "Multiple sequence file is empty",
1543                                                "Empty multiple sequence file",
1544                                                JOptionPane.ERROR_MESSAGE );
1545                 setArrowCursor();
1546                 return;
1547             }
1548         }
1549         if ( seqs != null ) {
1550             for( final Sequence seq : seqs ) {
1551                 System.out.println( seq.getIdentifier() );
1552             }
1553             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1554             int total_counter = 0;
1555             int attached_counter = 0;
1556             for( final Sequence seq : seqs ) {
1557                 ++total_counter;
1558                 final String seq_name = seq.getIdentifier();
1559                 if ( !ForesterUtil.isEmpty( seq_name ) ) {
1560                     List<PhylogenyNode> nodes = phy.getNodesViaSequenceName( seq_name );
1561                     if ( nodes.isEmpty() ) {
1562                         nodes = phy.getNodesViaSequenceSymbol( seq_name );
1563                     }
1564                     if ( nodes.isEmpty() ) {
1565                         nodes = phy.getNodes( seq_name );
1566                     }
1567                     if ( nodes.size() > 1 ) {
1568                         JOptionPane.showMessageDialog( this,
1569                                                        "Sequence name \"" + seq_name + "\" is not unique",
1570                                                        "Sequence name not unique",
1571                                                        JOptionPane.ERROR_MESSAGE );
1572                         setArrowCursor();
1573                         return;
1574                     }
1575                     final String[] a = seq_name.split( "\\s" );
1576                     if ( nodes.isEmpty() && ( a.length > 1 ) ) {
1577                         final String seq_name_split = a[ 0 ];
1578                         nodes = phy.getNodesViaSequenceName( seq_name_split );
1579                         if ( nodes.isEmpty() ) {
1580                             nodes = phy.getNodesViaSequenceSymbol( seq_name_split );
1581                         }
1582                         if ( nodes.isEmpty() ) {
1583                             nodes = phy.getNodes( seq_name_split );
1584                         }
1585                         if ( nodes.size() > 1 ) {
1586                             JOptionPane.showMessageDialog( this, "Split sequence name \"" + seq_name_split
1587                                     + "\" is not unique", "Sequence name not unique", JOptionPane.ERROR_MESSAGE );
1588                             setArrowCursor();
1589                             return;
1590                         }
1591                     }
1592                     if ( nodes.size() == 1 ) {
1593                         ++attached_counter;
1594                         final PhylogenyNode n = nodes.get( 0 );
1595                         if ( !n.getNodeData().isHasSequence() ) {
1596                             n.getNodeData().addSequence( new org.forester.phylogeny.data.Sequence() );
1597                         }
1598                         n.getNodeData().getSequence().setMolecularSequence( seq.getMolecularSequenceAsString() );
1599                         if ( ForesterUtil.isEmpty( n.getNodeData().getSequence().getName() ) ) {
1600                             n.getNodeData().getSequence().setName( seq_name );
1601                         }
1602                     }
1603                 }
1604             }
1605             if ( attached_counter > 0 ) {
1606                 int ext_nodes = 0;
1607                 int ext_nodes_with_seq = 0;
1608                 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
1609                     ++ext_nodes;
1610                     final PhylogenyNode n = iter.next();
1611                     if ( n.getNodeData().isHasSequence()
1612                             && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getMolecularSequence() ) ) {
1613                         ++ext_nodes_with_seq;
1614                     }
1615                 }
1616                 final String s;
1617                 if ( ext_nodes == ext_nodes_with_seq ) {
1618                     s = "All " + ext_nodes_with_seq + " external nodes now have a molecular sequence attached to them.";
1619                 }
1620                 else {
1621                     s = ext_nodes_with_seq + " out of " + ext_nodes
1622                             + " external nodes now have a molecular sequence attached to them.";
1623                 }
1624                 if ( ( attached_counter == total_counter ) && ( ext_nodes == ext_nodes_with_seq ) ) {
1625                     JOptionPane.showMessageDialog( this,
1626                                                    "Attached all " + total_counter + " sequences to tree nodes.\n" + s,
1627                                                    "All sequences attached",
1628                                                    JOptionPane.INFORMATION_MESSAGE );
1629                 }
1630                 else {
1631                     JOptionPane.showMessageDialog( this, "Attached " + attached_counter
1632                             + " sequences out of a total of " + total_counter + " sequences.\n" + s, attached_counter
1633                             + " sequences attached", JOptionPane.WARNING_MESSAGE );
1634                 }
1635             }
1636             else {
1637                 JOptionPane.showMessageDialog( this, "No maching tree node for any of the " + total_counter
1638                         + " sequences", "Could not attach any sequences", JOptionPane.ERROR_MESSAGE );
1639             }
1640         }
1641     }
1642
1643     private void setArrowCursor() {
1644         try {
1645             _mainpanel.getCurrentTreePanel().setArrowCursor();
1646         }
1647         catch ( final Exception ex ) {
1648             // Do nothing.
1649         }
1650     }
1651
1652     private void addExpressionValuesFromFile() {
1653         if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) ) {
1654             JOptionPane.showMessageDialog( this,
1655                                            "Need to load evolutionary tree first",
1656                                            "Can Not Read Expression Values",
1657                                            JOptionPane.WARNING_MESSAGE );
1658             return;
1659         }
1660         final File my_dir = getCurrentDir();
1661         if ( my_dir != null ) {
1662             _values_filechooser.setCurrentDirectory( my_dir );
1663         }
1664         final int result = _values_filechooser.showOpenDialog( _contentpane );
1665         final File file = _values_filechooser.getSelectedFile();
1666         if ( ( file != null ) && ( file.length() > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
1667             BasicTable<String> t = null;
1668             try {
1669                 t = BasicTableParser.parse( file, "\t" );
1670                 if ( t.getNumberOfColumns() < 2 ) {
1671                     t = BasicTableParser.parse( file, "," );
1672                 }
1673                 if ( t.getNumberOfColumns() < 2 ) {
1674                     t = BasicTableParser.parse( file, " " );
1675                 }
1676             }
1677             catch ( final IOException e ) {
1678                 JOptionPane.showMessageDialog( this,
1679                                                e.getMessage(),
1680                                                "Could Not Read Expression Value Table",
1681                                                JOptionPane.ERROR_MESSAGE );
1682                 return;
1683             }
1684             if ( t.getNumberOfColumns() < 2 ) {
1685                 JOptionPane.showMessageDialog( this,
1686                                                "Table contains " + t.getNumberOfColumns() + " column(s)",
1687                                                "Problem with Expression Value Table",
1688                                                JOptionPane.ERROR_MESSAGE );
1689                 return;
1690             }
1691             if ( t.getNumberOfRows() < 1 ) {
1692                 JOptionPane.showMessageDialog( this,
1693                                                "Table contains zero rows",
1694                                                "Problem with Expression Value Table",
1695                                                JOptionPane.ERROR_MESSAGE );
1696                 return;
1697             }
1698             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1699             if ( t.getNumberOfRows() != phy.getNumberOfExternalNodes() ) {
1700                 JOptionPane.showMessageDialog( this,
1701                                                "Table contains " + t.getNumberOfRows() + " rows, but tree contains "
1702                                                        + phy.getNumberOfExternalNodes() + " external nodes",
1703                                                "Warning",
1704                                                JOptionPane.WARNING_MESSAGE );
1705             }
1706             final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
1707             int not_found = 0;
1708             for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1709                 final PhylogenyNode node = iter.next();
1710                 final String node_name = node.getName();
1711                 if ( !ForesterUtil.isEmpty( node_name ) ) {
1712                     int row = -1;
1713                     try {
1714                         row = t.findRow( node_name );
1715                     }
1716                     catch ( final IllegalArgumentException e ) {
1717                         JOptionPane
1718                                 .showMessageDialog( this,
1719                                                     e.getMessage(),
1720                                                     "Error Mapping Node Identifiers to Expression Value Identifiers",
1721                                                     JOptionPane.ERROR_MESSAGE );
1722                         return;
1723                     }
1724                     if ( row < 0 ) {
1725                         if ( node.isExternal() ) {
1726                             not_found++;
1727                         }
1728                         continue;
1729                     }
1730                     final List<Double> l = new ArrayList<Double>();
1731                     for( int col = 1; col < t.getNumberOfColumns(); ++col ) {
1732                         double d = -100;
1733                         try {
1734                             d = Double.parseDouble( t.getValueAsString( col, row ) );
1735                         }
1736                         catch ( final NumberFormatException e ) {
1737                             JOptionPane.showMessageDialog( this,
1738                                                            "Could not parse \"" + t.getValueAsString( col, row )
1739                                                                    + "\" into a decimal value",
1740                                                            "Issue with Expression Value Table",
1741                                                            JOptionPane.ERROR_MESSAGE );
1742                             return;
1743                         }
1744                         stats.addValue( d );
1745                         l.add( d );
1746                     }
1747                     if ( !l.isEmpty() ) {
1748                         if ( node.getNodeData().getProperties() != null ) {
1749                             node.getNodeData().getProperties()
1750                                     .removePropertiesWithGivenReferencePrefix( PhyloXmlUtil.VECTOR_PROPERTY_REF );
1751                         }
1752                         node.getNodeData().setVector( l );
1753                     }
1754                 }
1755             }
1756             if ( not_found > 0 ) {
1757                 JOptionPane.showMessageDialog( this, "Could not fine expression values for " + not_found
1758                         + " external node(s)", "Warning", JOptionPane.WARNING_MESSAGE );
1759             }
1760             getCurrentTreePanel().setStatisticsForExpressionValues( stats );
1761         }
1762     }
1763
1764     private void choosePdfWidth() {
1765         final String s = ( String ) JOptionPane.showInputDialog( this,
1766                                                                  "Please enter the default line width for PDF export.\n"
1767                                                                          + "[current value: "
1768                                                                          + getOptions().getPrintLineWidth() + "]\n",
1769                                                                  "Line Width for PDF Export",
1770                                                                  JOptionPane.QUESTION_MESSAGE,
1771                                                                  null,
1772                                                                  null,
1773                                                                  getOptions().getPrintLineWidth() );
1774         if ( !ForesterUtil.isEmpty( s ) ) {
1775             boolean success = true;
1776             float f = 0.0f;
1777             final String m_str = s.trim();
1778             if ( !ForesterUtil.isEmpty( m_str ) ) {
1779                 try {
1780                     f = Float.parseFloat( m_str );
1781                 }
1782                 catch ( final Exception ex ) {
1783                     success = false;
1784                 }
1785             }
1786             else {
1787                 success = false;
1788             }
1789             if ( success && ( f > 0.0 ) ) {
1790                 getOptions().setPrintLineWidth( f );
1791             }
1792         }
1793     }
1794
1795     private void choosePrintSize() {
1796         final String s = ( String ) JOptionPane.showInputDialog( this,
1797                                                                  "Please enter values for width and height,\nseparated by a comma.\n"
1798                                                                          + "[current values: "
1799                                                                          + getOptions().getPrintSizeX() + ", "
1800                                                                          + getOptions().getPrintSizeY() + "]\n"
1801                                                                          + "[A4: " + Constants.A4_SIZE_X + ", "
1802                                                                          + Constants.A4_SIZE_Y + "]\n" + "[US Letter: "
1803                                                                          + Constants.US_LETTER_SIZE_X + ", "
1804                                                                          + Constants.US_LETTER_SIZE_Y + "]",
1805                                                                  "Default Size for Graphics Export",
1806                                                                  JOptionPane.QUESTION_MESSAGE,
1807                                                                  null,
1808                                                                  null,
1809                                                                  getOptions().getPrintSizeX() + ", "
1810                                                                          + getOptions().getPrintSizeY() );
1811         if ( !ForesterUtil.isEmpty( s ) && ( s.indexOf( ',' ) > 0 ) ) {
1812             boolean success = true;
1813             int x = 0;
1814             int y = 0;
1815             final String[] str_ary = s.split( "," );
1816             if ( str_ary.length == 2 ) {
1817                 final String x_str = str_ary[ 0 ].trim();
1818                 final String y_str = str_ary[ 1 ].trim();
1819                 if ( !ForesterUtil.isEmpty( x_str ) && !ForesterUtil.isEmpty( y_str ) ) {
1820                     try {
1821                         x = Integer.parseInt( x_str );
1822                         y = Integer.parseInt( y_str );
1823                     }
1824                     catch ( final Exception ex ) {
1825                         success = false;
1826                     }
1827                 }
1828                 else {
1829                     success = false;
1830                 }
1831             }
1832             else {
1833                 success = false;
1834             }
1835             if ( success && ( x > 1 ) && ( y > 1 ) ) {
1836                 getOptions().setPrintSizeX( x );
1837                 getOptions().setPrintSizeY( y );
1838             }
1839         }
1840     }
1841
1842     private void closeCurrentPane() {
1843         if ( getMainPanel().getCurrentTreePanel() != null ) {
1844             if ( getMainPanel().getCurrentTreePanel().isEdited() ) {
1845                 final int r = JOptionPane.showConfirmDialog( this,
1846                                                              "Close tab despite potentially unsaved changes?",
1847                                                              "Close Tab?",
1848                                                              JOptionPane.YES_NO_OPTION );
1849                 if ( r != JOptionPane.YES_OPTION ) {
1850                     return;
1851                 }
1852             }
1853             getMainPanel().closeCurrentPane();
1854             activateSaveAllIfNeeded();
1855         }
1856     }
1857
1858     private void collapse( final Phylogeny phy, final double m ) {
1859         final PhylogenyNodeIterator it = phy.iteratorPostorder();
1860         final List<PhylogenyNode> to_be_removed = new ArrayList<PhylogenyNode>();
1861         double min_support = Double.MAX_VALUE;
1862         boolean conf_present = false;
1863         while ( it.hasNext() ) {
1864             final PhylogenyNode n = it.next();
1865             if ( !n.isExternal() && !n.isRoot() ) {
1866                 final List<Confidence> c = n.getBranchData().getConfidences();
1867                 if ( ( c != null ) && ( c.size() > 0 ) ) {
1868                     conf_present = true;
1869                     double max = 0;
1870                     for( final Confidence confidence : c ) {
1871                         if ( confidence.getValue() > max ) {
1872                             max = confidence.getValue();
1873                         }
1874                     }
1875                     if ( max < getMinNotCollapseConfidenceValue() ) {
1876                         to_be_removed.add( n );
1877                     }
1878                     if ( max < min_support ) {
1879                         min_support = max;
1880                     }
1881                 }
1882             }
1883         }
1884         if ( conf_present ) {
1885             for( final PhylogenyNode node : to_be_removed ) {
1886                 PhylogenyMethods.removeNode( node, phy );
1887             }
1888             if ( to_be_removed.size() > 0 ) {
1889                 phy.externalNodesHaveChanged();
1890                 phy.clearHashIdToNodeMap();
1891                 phy.recalculateNumberOfExternalDescendants( true );
1892                 getCurrentTreePanel().resetNodeIdToDistToLeafMap();
1893                 getCurrentTreePanel().updateSetOfCollapsedExternalNodes();
1894                 getCurrentTreePanel().calculateLongestExtNodeInfo();
1895                 getCurrentTreePanel().setNodeInPreorderToNull();
1896                 getCurrentTreePanel().recalculateMaxDistanceToRoot();
1897                 getCurrentTreePanel().resetPreferredSize();
1898                 getCurrentTreePanel().setEdited( true );
1899                 getCurrentTreePanel().repaint();
1900                 repaint();
1901             }
1902             if ( to_be_removed.size() > 0 ) {
1903                 JOptionPane.showMessageDialog( this, "Collapsed " + to_be_removed.size()
1904                         + " branches with\nconfidence values below " + getMinNotCollapseConfidenceValue(), "Collapsed "
1905                         + to_be_removed.size() + " branches", JOptionPane.INFORMATION_MESSAGE );
1906             }
1907             else {
1908                 JOptionPane.showMessageDialog( this, "No branch collapsed,\nminimum confidence value per branch is "
1909                         + min_support, "No branch collapsed", JOptionPane.INFORMATION_MESSAGE );
1910             }
1911         }
1912         else {
1913             JOptionPane.showMessageDialog( this,
1914                                            "No branch collapsed because no confidence values present",
1915                                            "No confidence values present",
1916                                            JOptionPane.INFORMATION_MESSAGE );
1917         }
1918     }
1919
1920     private void collapseBelowThreshold() {
1921         if ( getCurrentTreePanel() != null ) {
1922             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1923             if ( ( phy != null ) && !phy.isEmpty() ) {
1924                 final String s = ( String ) JOptionPane.showInputDialog( this,
1925                                                                          "Please enter the minimum confidence value\n",
1926                                                                          "Minimal Confidence Value",
1927                                                                          JOptionPane.QUESTION_MESSAGE,
1928                                                                          null,
1929                                                                          null,
1930                                                                          getMinNotCollapseConfidenceValue() );
1931                 if ( !ForesterUtil.isEmpty( s ) ) {
1932                     boolean success = true;
1933                     double m = 0.0;
1934                     final String m_str = s.trim();
1935                     if ( !ForesterUtil.isEmpty( m_str ) ) {
1936                         try {
1937                             m = Double.parseDouble( m_str );
1938                         }
1939                         catch ( final Exception ex ) {
1940                             success = false;
1941                         }
1942                     }
1943                     else {
1944                         success = false;
1945                     }
1946                     if ( success && ( m >= 0.0 ) ) {
1947                         setMinNotCollapseConfidenceValue( m );
1948                         collapse( phy, m );
1949                     }
1950                 }
1951             }
1952         }
1953     }
1954
1955     private PhyloXmlParser createPhyloXmlParser() {
1956         PhyloXmlParser xml_parser = null;
1957         if ( getConfiguration().isValidatePhyloXmlAgainstSchema() ) {
1958             try {
1959                 xml_parser = PhyloXmlParser.createPhyloXmlParserXsdValidating();
1960             }
1961             catch ( final Exception e ) {
1962                 JOptionPane.showMessageDialog( this,
1963                                                e.getLocalizedMessage(),
1964                                                "failed to create validating XML parser",
1965                                                JOptionPane.WARNING_MESSAGE );
1966             }
1967         }
1968         if ( xml_parser == null ) {
1969             xml_parser = new PhyloXmlParser();
1970         }
1971         return xml_parser;
1972     }
1973
1974     private void executePhyleneticInference( final boolean from_unaligned_seqs ) {
1975         final PhyloInferenceDialog dialog = new PhyloInferenceDialog( this,
1976                                                                       getPhylogeneticInferenceOptions(),
1977                                                                       from_unaligned_seqs );
1978         dialog.activate();
1979         if ( dialog.getValue() == JOptionPane.OK_OPTION ) {
1980             if ( !from_unaligned_seqs ) {
1981                 if ( getMsa() != null ) {
1982                     final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getMsa(),
1983                                                                                     getPhylogeneticInferenceOptions()
1984                                                                                             .copy(), this );
1985                     new Thread( inferrer ).start();
1986                 }
1987                 else {
1988                     JOptionPane.showMessageDialog( this,
1989                                                    "No multiple sequence alignment selected",
1990                                                    "Phylogenetic Inference Not Launched",
1991                                                    JOptionPane.WARNING_MESSAGE );
1992                 }
1993             }
1994             else {
1995                 if ( getSeqs() != null ) {
1996                     final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getSeqs(),
1997                                                                                     getPhylogeneticInferenceOptions()
1998                                                                                             .copy(), this );
1999                     new Thread( inferrer ).start();
2000                 }
2001                 else {
2002                     JOptionPane.showMessageDialog( this,
2003                                                    "No input sequences selected",
2004                                                    "Phylogenetic Inference Not Launched",
2005                                                    JOptionPane.WARNING_MESSAGE );
2006                 }
2007             }
2008         }
2009     }
2010
2011     private void extractTaxDataFromNodeNames() throws PhyloXmlDataFormatException {
2012         final StringBuilder sb = new StringBuilder();
2013         final StringBuilder sb_failed = new StringBuilder();
2014         int counter = 0;
2015         int counter_failed = 0;
2016         if ( getCurrentTreePanel() != null ) {
2017             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
2018             if ( ( phy != null ) && !phy.isEmpty() ) {
2019                 final PhylogenyNodeIterator it = phy.iteratorExternalForward();
2020                 while ( it.hasNext() ) {
2021                     final PhylogenyNode n = it.next();
2022                     final String name = n.getName().trim();
2023                     if ( !ForesterUtil.isEmpty( name ) ) {
2024                         final String nt = ParserUtils
2025                                 .extractTaxonomyDataFromNodeName( n, TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED );
2026                         if ( !ForesterUtil.isEmpty( nt ) ) {
2027                             if ( counter < 15 ) {
2028                                 sb.append( name + ": " + nt + "\n" );
2029                             }
2030                             else if ( counter == 15 ) {
2031                                 sb.append( "...\n" );
2032                             }
2033                             counter++;
2034                         }
2035                         else {
2036                             if ( counter_failed < 15 ) {
2037                                 sb_failed.append( name + "\n" );
2038                             }
2039                             else if ( counter_failed == 15 ) {
2040                                 sb_failed.append( "...\n" );
2041                             }
2042                             counter_failed++;
2043                         }
2044                     }
2045                 }
2046                 if ( counter > 0 ) {
2047                     String failed = "";
2048                     String all = "all ";
2049                     if ( counter_failed > 0 ) {
2050                         all = "";
2051                         failed = "\nCould not extract taxonomic data for " + counter_failed
2052                                 + " named external nodes:\n" + sb_failed;
2053                     }
2054                     JOptionPane.showMessageDialog( this,
2055                                                    "Extracted taxonomic data from " + all + counter
2056                                                            + " named external nodes:\n" + sb.toString() + failed,
2057                                                    "Taxonomic Data Extraction Completed",
2058                                                    counter_failed > 0 ? JOptionPane.WARNING_MESSAGE
2059                                                            : JOptionPane.INFORMATION_MESSAGE );
2060                 }
2061                 else {
2062                     JOptionPane
2063                             .showMessageDialog( this,
2064                                                 "Could not extract any taxonomic data.\nMaybe node names are empty\n"
2065                                                         + "or not in the forms \"XYZ_CAEEL\", \"XYZ_6239\", or \"XYZ_Caenorhabditis_elegans\"\n"
2066                                                         + "or nodes already have taxonomic data?\n",
2067                                                 "No Taxonomic Data Extracted",
2068                                                 JOptionPane.ERROR_MESSAGE );
2069                 }
2070             }
2071         }
2072     }
2073
2074     private ControlPanel getControlPanel() {
2075         return getMainPanel().getControlPanel();
2076     }
2077
2078     private File getCurrentDir() {
2079         if ( ( _current_dir == null ) || !_current_dir.canRead() ) {
2080             if ( ForesterUtil.isWindowns() ) {
2081                 try {
2082                     _current_dir = new File( WindowsUtils.getCurrentUserDesktopPath() );
2083                 }
2084                 catch ( final Exception e ) {
2085                     _current_dir = null;
2086                 }
2087             }
2088         }
2089         if ( ( _current_dir == null ) || !_current_dir.canRead() ) {
2090             if ( System.getProperty( "user.home" ) != null ) {
2091                 _current_dir = new File( System.getProperty( "user.home" ) );
2092             }
2093             else if ( System.getProperty( "user.dir" ) != null ) {
2094                 _current_dir = new File( System.getProperty( "user.dir" ) );
2095             }
2096         }
2097         return _current_dir;
2098     }
2099
2100     private double getMinNotCollapseConfidenceValue() {
2101         return _min_not_collapse;
2102     }
2103
2104     private PhylogeneticInferenceOptions getPhylogeneticInferenceOptions() {
2105         if ( _phylogenetic_inference_options == null ) {
2106             _phylogenetic_inference_options = new PhylogeneticInferenceOptions();
2107         }
2108         return _phylogenetic_inference_options;
2109     }
2110
2111     private boolean isUnsavedDataPresent() {
2112         final List<TreePanel> tps = getMainPanel().getTreePanels();
2113         for( final TreePanel tp : tps ) {
2114             if ( tp.isEdited() ) {
2115                 return true;
2116             }
2117         }
2118         return false;
2119     }
2120
2121     private void moveNodeNamesToSeqNames() throws PhyloXmlDataFormatException {
2122         if ( getCurrentTreePanel() != null ) {
2123             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
2124             if ( ( phy != null ) && !phy.isEmpty() ) {
2125                 PhylogenyMethods
2126                         .transferNodeNameToField( phy, PhylogenyMethods.PhylogenyNodeField.SEQUENCE_NAME, false );
2127             }
2128         }
2129     }
2130
2131     private void moveNodeNamesToTaxSn() throws PhyloXmlDataFormatException {
2132         if ( getCurrentTreePanel() != null ) {
2133             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
2134             if ( ( phy != null ) && !phy.isEmpty() ) {
2135                 PhylogenyMethods.transferNodeNameToField( phy,
2136                                                           PhylogenyMethods.PhylogenyNodeField.TAXONOMY_SCIENTIFIC_NAME,
2137                                                           false );
2138             }
2139         }
2140     }
2141
2142     private void newTree() {
2143         final Phylogeny[] phys = new Phylogeny[ 1 ];
2144         final Phylogeny phy = new Phylogeny();
2145         final PhylogenyNode node = new PhylogenyNode();
2146         phy.setRoot( node );
2147         phy.setRooted( true );
2148         phys[ 0 ] = phy;
2149         AptxUtil.addPhylogeniesToTabs( phys, "", "", getConfiguration(), getMainPanel() );
2150         _mainpanel.getControlPanel().showWhole();
2151         _mainpanel.getCurrentTreePanel().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
2152         _mainpanel.getOptions().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
2153         if ( getMainPanel().getMainFrame() == null ) {
2154             // Must be "E" applet version.
2155             ( ( ArchaeopteryxE ) ( ( MainPanelApplets ) getMainPanel() ).getApplet() )
2156                     .setSelectedTypeInTypeMenu( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
2157         }
2158         else {
2159             getMainPanel().getMainFrame().setSelectedTypeInTypeMenu( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
2160         }
2161         activateSaveAllIfNeeded();
2162         System.gc();
2163     }
2164
2165     private void obtainDetailedTaxonomicInformation() {
2166         if ( getCurrentTreePanel() != null ) {
2167             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
2168             if ( ( phy != null ) && !phy.isEmpty() ) {
2169                 final TaxonomyDataManager t = new TaxonomyDataManager( this,
2170                                                                        _mainpanel.getCurrentTreePanel(),
2171                                                                        phy.copy(),
2172                                                                        false,
2173                                                                        true );
2174                 new Thread( t ).start();
2175             }
2176         }
2177     }
2178
2179     private void obtainDetailedTaxonomicInformationDelete() {
2180         if ( getCurrentTreePanel() != null ) {
2181             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
2182             if ( ( phy != null ) && !phy.isEmpty() ) {
2183                 final TaxonomyDataManager t = new TaxonomyDataManager( this,
2184                                                                        _mainpanel.getCurrentTreePanel(),
2185                                                                        phy.copy(),
2186                                                                        true,
2187                                                                        true );
2188                 new Thread( t ).start();
2189             }
2190         }
2191     }
2192
2193     private void obtainSequenceInformation() {
2194         if ( getCurrentTreePanel() != null ) {
2195             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
2196             if ( ( phy != null ) && !phy.isEmpty() ) {
2197                 final SequenceDataRetriver u = new SequenceDataRetriver( this,
2198                                                                          _mainpanel.getCurrentTreePanel(),
2199                                                                          phy.copy() );
2200                 new Thread( u ).start();
2201             }
2202         }
2203     }
2204
2205     private void print() {
2206         if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null )
2207                 || getCurrentTreePanel().getPhylogeny().isEmpty() ) {
2208             return;
2209         }
2210         if ( !getOptions().isPrintUsingActualSize() ) {
2211             getCurrentTreePanel().calcParametersForPainting( getOptions().getPrintSizeX() - 80,
2212                                                              getOptions().getPrintSizeY() - 140,
2213                                                              true );
2214             getCurrentTreePanel().resetPreferredSize();
2215             getCurrentTreePanel().repaint();
2216         }
2217         final String job_name = Constants.PRG_NAME;
2218         boolean error = false;
2219         String printer_name = null;
2220         try {
2221             printer_name = Printer.print( getCurrentTreePanel(), job_name );
2222         }
2223         catch ( final Exception e ) {
2224             error = true;
2225             JOptionPane.showMessageDialog( this, e.getMessage(), "Printing Error", JOptionPane.ERROR_MESSAGE );
2226         }
2227         if ( !error && ( printer_name != null ) ) {
2228             String msg = "Printing data sent to printer";
2229             if ( printer_name.length() > 1 ) {
2230                 msg += " [" + printer_name + "]";
2231             }
2232             JOptionPane.showMessageDialog( this, msg, "Printing...", JOptionPane.INFORMATION_MESSAGE );
2233         }
2234         if ( !getOptions().isPrintUsingActualSize() ) {
2235             getControlPanel().showWhole();
2236         }
2237     }
2238
2239     private void printPhylogenyToPdf( final String file_name ) {
2240         if ( !getOptions().isPrintUsingActualSize() ) {
2241             getCurrentTreePanel().calcParametersForPainting( getOptions().getPrintSizeX(),
2242                                                              getOptions().getPrintSizeY(),
2243                                                              true );
2244             getCurrentTreePanel().resetPreferredSize();
2245             getCurrentTreePanel().repaint();
2246         }
2247         String pdf_written_to = "";
2248         boolean error = false;
2249         try {
2250             if ( getOptions().isPrintUsingActualSize() ) {
2251                 pdf_written_to = PdfExporter.writePhylogenyToPdf( file_name,
2252                                                                   getCurrentTreePanel(),
2253                                                                   getCurrentTreePanel().getWidth(),
2254                                                                   getCurrentTreePanel().getHeight() );
2255             }
2256             else {
2257                 pdf_written_to = PdfExporter.writePhylogenyToPdf( file_name, getCurrentTreePanel(), getOptions()
2258                         .getPrintSizeX(), getOptions().getPrintSizeY() );
2259             }
2260         }
2261         catch ( final IOException e ) {
2262             error = true;
2263             JOptionPane.showMessageDialog( this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE );
2264         }
2265         if ( !error ) {
2266             if ( !ForesterUtil.isEmpty( pdf_written_to ) ) {
2267                 JOptionPane.showMessageDialog( this,
2268                                                "Wrote PDF to: " + pdf_written_to,
2269                                                "Information",
2270                                                JOptionPane.INFORMATION_MESSAGE );
2271             }
2272             else {
2273                 JOptionPane.showMessageDialog( this,
2274                                                "There was an unknown problem when attempting to write to PDF file: \""
2275                                                        + file_name + "\"",
2276                                                "Error",
2277                                                JOptionPane.ERROR_MESSAGE );
2278             }
2279         }
2280         if ( !getOptions().isPrintUsingActualSize() ) {
2281             getControlPanel().showWhole();
2282         }
2283     }
2284
2285     private void readPhylogeniesFromFile() {
2286         boolean exception = false;
2287         Phylogeny[] phys = null;
2288         // Set an initial directory if none set yet
2289         final File my_dir = getCurrentDir();
2290         _open_filechooser.setMultiSelectionEnabled( true );
2291         // Open file-open dialog and set current directory
2292         if ( my_dir != null ) {
2293             _open_filechooser.setCurrentDirectory( my_dir );
2294         }
2295         final int result = _open_filechooser.showOpenDialog( _contentpane );
2296         // All done: get the file
2297         final File[] files = _open_filechooser.getSelectedFiles();
2298         setCurrentDir( _open_filechooser.getCurrentDirectory() );
2299         boolean nhx_or_nexus = false;
2300         if ( ( files != null ) && ( files.length > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2301             for( final File file : files ) {
2302                 if ( ( file != null ) && !file.isDirectory() ) {
2303                     if ( _mainpanel.getCurrentTreePanel() != null ) {
2304                         _mainpanel.getCurrentTreePanel().setWaitCursor();
2305                     }
2306                     else {
2307                         _mainpanel.setWaitCursor();
2308                     }
2309                     if ( ( _open_filechooser.getFileFilter() == MainFrameApplication.nhfilter )
2310                             || ( _open_filechooser.getFileFilter() == MainFrameApplication.nhxfilter ) ) {
2311                         try {
2312                             final NHXParser nhx = new NHXParser();
2313                             setSpecialOptionsForNhxParser( nhx );
2314                             phys = PhylogenyMethods.readPhylogenies( nhx, file );
2315                             nhx_or_nexus = true;
2316                         }
2317                         catch ( final Exception e ) {
2318                             exception = true;
2319                             exceptionOccuredDuringOpenFile( e );
2320                         }
2321                     }
2322                     else if ( _open_filechooser.getFileFilter() == MainFrameApplication.xmlfilter ) {
2323                         warnIfNotPhyloXmlValidation( getConfiguration() );
2324                         try {
2325                             final PhyloXmlParser xml_parser = createPhyloXmlParser();
2326                             phys = PhylogenyMethods.readPhylogenies( xml_parser, file );
2327                         }
2328                         catch ( final Exception e ) {
2329                             exception = true;
2330                             exceptionOccuredDuringOpenFile( e );
2331                         }
2332                     }
2333                     else if ( _open_filechooser.getFileFilter() == MainFrameApplication.tolfilter ) {
2334                         try {
2335                             phys = PhylogenyMethods.readPhylogenies( new TolParser(), file );
2336                         }
2337                         catch ( final Exception e ) {
2338                             exception = true;
2339                             exceptionOccuredDuringOpenFile( e );
2340                         }
2341                     }
2342                     else if ( _open_filechooser.getFileFilter() == MainFrameApplication.nexusfilter ) {
2343                         try {
2344                             final NexusPhylogeniesParser nex = new NexusPhylogeniesParser();
2345                             setSpecialOptionsForNexParser( nex );
2346                             phys = PhylogenyMethods.readPhylogenies( nex, file );
2347                             nhx_or_nexus = true;
2348                         }
2349                         catch ( final Exception e ) {
2350                             exception = true;
2351                             exceptionOccuredDuringOpenFile( e );
2352                         }
2353                     }
2354                     // "*.*":
2355                     else {
2356                         try {
2357                             final PhylogenyParser parser = ParserUtils
2358                                     .createParserDependingOnFileType( file, getConfiguration()
2359                                             .isValidatePhyloXmlAgainstSchema() );
2360                             if ( parser instanceof NexusPhylogeniesParser ) {
2361                                 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
2362                                 setSpecialOptionsForNexParser( nex );
2363                                 nhx_or_nexus = true;
2364                             }
2365                             else if ( parser instanceof NHXParser ) {
2366                                 final NHXParser nhx = ( NHXParser ) parser;
2367                                 setSpecialOptionsForNhxParser( nhx );
2368                                 nhx_or_nexus = true;
2369                             }
2370                             else if ( parser instanceof PhyloXmlParser ) {
2371                                 warnIfNotPhyloXmlValidation( getConfiguration() );
2372                             }
2373                             phys = PhylogenyMethods.readPhylogenies( parser, file );
2374                         }
2375                         catch ( final Exception e ) {
2376                             exception = true;
2377                             exceptionOccuredDuringOpenFile( e );
2378                         }
2379                     }
2380                     if ( _mainpanel.getCurrentTreePanel() != null ) {
2381                         _mainpanel.getCurrentTreePanel().setArrowCursor();
2382                     }
2383                     else {
2384                         _mainpanel.setArrowCursor();
2385                     }
2386                     if ( !exception && ( phys != null ) && ( phys.length > 0 ) ) {
2387                         boolean one_desc = false;
2388                         if ( nhx_or_nexus ) {
2389                             for( final Phylogeny phy : phys ) {
2390                                 if ( getOptions().isInternalNumberAreConfidenceForNhParsing() ) {
2391                                     PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
2392                                 }
2393                                 if ( PhylogenyMethods.getMinimumDescendentsPerInternalNodes( phy ) == 1 ) {
2394                                     one_desc = true;
2395                                     break;
2396                                 }
2397                             }
2398                         }
2399                         AptxUtil.addPhylogeniesToTabs( phys,
2400                                                        file.getName(),
2401                                                        file.getAbsolutePath(),
2402                                                        getConfiguration(),
2403                                                        getMainPanel() );
2404                         _mainpanel.getControlPanel().showWhole();
2405                         if ( nhx_or_nexus && one_desc ) {
2406                             JOptionPane
2407                                     .showMessageDialog( this,
2408                                                         "One or more trees contain (a) node(s) with one descendant, "
2409                                                                 + ForesterUtil.LINE_SEPARATOR
2410                                                                 + "possibly indicating illegal parentheses within node names.",
2411                                                         "Warning: Possible Error in New Hampshire Formatted Data",
2412                                                         JOptionPane.WARNING_MESSAGE );
2413                         }
2414                     }
2415                 }
2416             }
2417         }
2418         activateSaveAllIfNeeded();
2419         System.gc();
2420     }
2421
2422     private void readSpeciesTreeFromFile() {
2423         Phylogeny t = null;
2424         boolean exception = false;
2425         final File my_dir = getCurrentDir();
2426         _open_filechooser_for_species_tree.setSelectedFile( new File( "" ) );
2427         if ( my_dir != null ) {
2428             _open_filechooser_for_species_tree.setCurrentDirectory( my_dir );
2429         }
2430         final int result = _open_filechooser_for_species_tree.showOpenDialog( _contentpane );
2431         final File file = _open_filechooser_for_species_tree.getSelectedFile();
2432         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2433             if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrameApplication.xmlfilter ) {
2434                 try {
2435                     final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( new PhyloXmlParser(), file );
2436                     t = trees[ 0 ];
2437                 }
2438                 catch ( final Exception e ) {
2439                     exception = true;
2440                     exceptionOccuredDuringOpenFile( e );
2441                 }
2442             }
2443             else if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrameApplication.tolfilter ) {
2444                 try {
2445                     final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( new TolParser(), file );
2446                     t = trees[ 0 ];
2447                 }
2448                 catch ( final Exception e ) {
2449                     exception = true;
2450                     exceptionOccuredDuringOpenFile( e );
2451                 }
2452             }
2453             // "*.*":
2454             else {
2455                 try {
2456                     final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( new PhyloXmlParser(), file );
2457                     t = trees[ 0 ];
2458                 }
2459                 catch ( final Exception e ) {
2460                     exception = true;
2461                     exceptionOccuredDuringOpenFile( e );
2462                 }
2463             }
2464             if ( !exception && ( t != null ) && !t.isRooted() ) {
2465                 exception = true;
2466                 t = null;
2467                 JOptionPane.showMessageDialog( this,
2468                                                "Species tree is not rooted",
2469                                                "Species tree not loaded",
2470                                                JOptionPane.ERROR_MESSAGE );
2471             }
2472             if ( !exception && ( t != null ) ) {
2473                 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
2474                 for( final PhylogenyNodeIterator it = t.iteratorExternalForward(); it.hasNext(); ) {
2475                     final PhylogenyNode node = it.next();
2476                     if ( !node.getNodeData().isHasTaxonomy() ) {
2477                         exception = true;
2478                         t = null;
2479                         JOptionPane
2480                                 .showMessageDialog( this,
2481                                                     "Species tree contains external node(s) without taxonomy information",
2482                                                     "Species tree not loaded",
2483                                                     JOptionPane.ERROR_MESSAGE );
2484                         break;
2485                     }
2486                     else {
2487                         if ( tax_set.contains( node.getNodeData().getTaxonomy() ) ) {
2488                             exception = true;
2489                             t = null;
2490                             JOptionPane.showMessageDialog( this,
2491                                                            "Taxonomy ["
2492                                                                    + node.getNodeData().getTaxonomy().asSimpleText()
2493                                                                    + "] is not unique in species tree",
2494                                                            "Species tree not loaded",
2495                                                            JOptionPane.ERROR_MESSAGE );
2496                             break;
2497                         }
2498                         else {
2499                             tax_set.add( node.getNodeData().getTaxonomy() );
2500                         }
2501                     }
2502                 }
2503             }
2504             if ( !exception && ( t != null ) ) {
2505                 _species_tree = t;
2506                 JOptionPane.showMessageDialog( this,
2507                                                "Species tree successfully loaded",
2508                                                "Species tree loaded",
2509                                                JOptionPane.INFORMATION_MESSAGE );
2510             }
2511             _contentpane.repaint();
2512             System.gc();
2513         }
2514     }
2515
2516     private void setCurrentDir( final File current_dir ) {
2517         _current_dir = current_dir;
2518     }
2519
2520     private void setMinNotCollapseConfidenceValue( final double min_not_collapse ) {
2521         _min_not_collapse = min_not_collapse;
2522     }
2523
2524     private void setPhylogeneticInferenceOptions( final PhylogeneticInferenceOptions phylogenetic_inference_options ) {
2525         _phylogenetic_inference_options = phylogenetic_inference_options;
2526     }
2527
2528     private void setSpecialOptionsForNexParser( final NexusPhylogeniesParser nex ) {
2529         nex.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() );
2530         nex.setTaxonomyExtraction( getOptions().getTaxonomyExtraction() );
2531     }
2532
2533     private void setSpecialOptionsForNhxParser( final NHXParser nhx ) {
2534         nhx.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() );
2535         nhx.setTaxonomyExtraction( getOptions().getTaxonomyExtraction() );
2536     }
2537
2538     private void writeAllToFile() {
2539         if ( ( getMainPanel().getTabbedPane() == null ) || ( getMainPanel().getTabbedPane().getTabCount() < 1 ) ) {
2540             return;
2541         }
2542         final File my_dir = getCurrentDir();
2543         if ( my_dir != null ) {
2544             _save_filechooser.setCurrentDirectory( my_dir );
2545         }
2546         _save_filechooser.setSelectedFile( new File( "" ) );
2547         final int result = _save_filechooser.showSaveDialog( _contentpane );
2548         final File file = _save_filechooser.getSelectedFile();
2549         setCurrentDir( _save_filechooser.getCurrentDirectory() );
2550         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2551             if ( file.exists() ) {
2552                 final int i = JOptionPane.showConfirmDialog( this,
2553                                                              file + " already exists. Overwrite?",
2554                                                              "Warning",
2555                                                              JOptionPane.OK_CANCEL_OPTION,
2556                                                              JOptionPane.WARNING_MESSAGE );
2557                 if ( i != JOptionPane.OK_OPTION ) {
2558                     return;
2559                 }
2560                 else {
2561                     try {
2562                         file.delete();
2563                     }
2564                     catch ( final Exception e ) {
2565                         JOptionPane.showMessageDialog( this,
2566                                                        "Failed to delete: " + file,
2567                                                        "Error",
2568                                                        JOptionPane.WARNING_MESSAGE );
2569                     }
2570                 }
2571             }
2572             final int count = getMainPanel().getTabbedPane().getTabCount();
2573             final List<Phylogeny> trees = new ArrayList<Phylogeny>();
2574             for( int i = 0; i < count; ++i ) {
2575                 final Phylogeny phy = getMainPanel().getPhylogeny( i );
2576                 if ( ForesterUtil.isEmpty( phy.getName() )
2577                         && !ForesterUtil.isEmpty( getMainPanel().getTabbedPane().getTitleAt( i ) ) ) {
2578                     phy.setName( getMainPanel().getTabbedPane().getTitleAt( i ) );
2579                 }
2580                 trees.add( phy );
2581                 getMainPanel().getTreePanels().get( i ).setEdited( false );
2582             }
2583             final PhylogenyWriter writer = new PhylogenyWriter();
2584             try {
2585                 writer.toPhyloXML( file, trees, 0, ForesterUtil.LINE_SEPARATOR );
2586             }
2587             catch ( final IOException e ) {
2588                 JOptionPane.showMessageDialog( this,
2589                                                "Failed to write to: " + file,
2590                                                "Error",
2591                                                JOptionPane.WARNING_MESSAGE );
2592             }
2593         }
2594     }
2595
2596     private boolean writeAsNewHampshire( final Phylogeny t, boolean exception, final File file ) {
2597         try {
2598             final PhylogenyWriter writer = new PhylogenyWriter();
2599             writer.toNewHampshire( t, false, true, getOptions().getNhConversionSupportValueStyle(), file );
2600         }
2601         catch ( final Exception e ) {
2602             exception = true;
2603             exceptionOccuredDuringSaveAs( e );
2604         }
2605         return exception;
2606     }
2607
2608     private boolean writeAsNexus( final Phylogeny t, boolean exception, final File file ) {
2609         try {
2610             final PhylogenyWriter writer = new PhylogenyWriter();
2611             writer.toNexus( file, t, getOptions().getNhConversionSupportValueStyle() );
2612         }
2613         catch ( final Exception e ) {
2614             exception = true;
2615             exceptionOccuredDuringSaveAs( e );
2616         }
2617         return exception;
2618     }
2619
2620     private boolean writeAsPhyloXml( final Phylogeny t, boolean exception, final File file ) {
2621         try {
2622             final PhylogenyWriter writer = new PhylogenyWriter();
2623             writer.toPhyloXML( file, t, 0 );
2624         }
2625         catch ( final Exception e ) {
2626             exception = true;
2627             exceptionOccuredDuringSaveAs( e );
2628         }
2629         return exception;
2630     }
2631
2632     private void writeToFile( final Phylogeny t ) {
2633         if ( t == null ) {
2634             return;
2635         }
2636         String initial_filename = null;
2637         if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) {
2638             try {
2639                 initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().getCanonicalPath();
2640             }
2641             catch ( final IOException e ) {
2642                 initial_filename = null;
2643             }
2644         }
2645         if ( !ForesterUtil.isEmpty( initial_filename ) ) {
2646             _save_filechooser.setSelectedFile( new File( initial_filename ) );
2647         }
2648         else {
2649             _save_filechooser.setSelectedFile( new File( "" ) );
2650         }
2651         final File my_dir = getCurrentDir();
2652         if ( my_dir != null ) {
2653             _save_filechooser.setCurrentDirectory( my_dir );
2654         }
2655         final int result = _save_filechooser.showSaveDialog( _contentpane );
2656         final File file = _save_filechooser.getSelectedFile();
2657         setCurrentDir( _save_filechooser.getCurrentDirectory() );
2658         boolean exception = false;
2659         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2660             if ( file.exists() ) {
2661                 final int i = JOptionPane.showConfirmDialog( this,
2662                                                              file + " already exists.\nOverwrite?",
2663                                                              "Overwrite?",
2664                                                              JOptionPane.OK_CANCEL_OPTION,
2665                                                              JOptionPane.QUESTION_MESSAGE );
2666                 if ( i != JOptionPane.OK_OPTION ) {
2667                     return;
2668                 }
2669                 else {
2670                     final File to = new File( file.getAbsoluteFile().toString() + Constants.BACKUP_FILE_SUFFIX );
2671                     try {
2672                         ForesterUtil.copyFile( file, to );
2673                     }
2674                     catch ( final Exception e ) {
2675                         JOptionPane.showMessageDialog( this,
2676                                                        "Failed to create backup copy " + to,
2677                                                        "Failed to Create Backup Copy",
2678                                                        JOptionPane.WARNING_MESSAGE );
2679                     }
2680                     try {
2681                         file.delete();
2682                     }
2683                     catch ( final Exception e ) {
2684                         JOptionPane.showMessageDialog( this,
2685                                                        "Failed to delete: " + file,
2686                                                        "Failed to Delete",
2687                                                        JOptionPane.WARNING_MESSAGE );
2688                     }
2689                 }
2690             }
2691             if ( _save_filechooser.getFileFilter() == MainFrameApplication.nhfilter ) {
2692                 exception = writeAsNewHampshire( t, exception, file );
2693             }
2694             else if ( _save_filechooser.getFileFilter() == MainFrameApplication.xmlfilter ) {
2695                 exception = writeAsPhyloXml( t, exception, file );
2696             }
2697             else if ( _save_filechooser.getFileFilter() == MainFrameApplication.nexusfilter ) {
2698                 exception = writeAsNexus( t, exception, file );
2699             }
2700             // "*.*":
2701             else {
2702                 final String file_name = file.getName().trim().toLowerCase();
2703                 if ( file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2704                         || file_name.endsWith( ".tree" ) ) {
2705                     exception = writeAsNewHampshire( t, exception, file );
2706                 }
2707                 else if ( file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) ) {
2708                     exception = writeAsNexus( t, exception, file );
2709                 }
2710                 // XML is default:
2711                 else {
2712                     exception = writeAsPhyloXml( t, exception, file );
2713                 }
2714             }
2715             if ( !exception ) {
2716                 getMainPanel().setTitleOfSelectedTab( file.getName() );
2717                 getMainPanel().getCurrentTreePanel().setTreeFile( file );
2718                 getMainPanel().getCurrentTreePanel().setEdited( false );
2719             }
2720         }
2721     }
2722
2723     private void writeToGraphicsFile( final Phylogeny t, final GraphicsExportType type ) {
2724         if ( ( t == null ) || t.isEmpty() ) {
2725             return;
2726         }
2727         String initial_filename = "";
2728         if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) {
2729             initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().toString();
2730         }
2731         if ( initial_filename.indexOf( '.' ) > 0 ) {
2732             initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) );
2733         }
2734         initial_filename = initial_filename + "." + type;
2735         _writetographics_filechooser.setSelectedFile( new File( initial_filename ) );
2736         final File my_dir = getCurrentDir();
2737         if ( my_dir != null ) {
2738             _writetographics_filechooser.setCurrentDirectory( my_dir );
2739         }
2740         final int result = _writetographics_filechooser.showSaveDialog( _contentpane );
2741         File file = _writetographics_filechooser.getSelectedFile();
2742         setCurrentDir( _writetographics_filechooser.getCurrentDirectory() );
2743         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2744             if ( !file.toString().toLowerCase().endsWith( type.toString() ) ) {
2745                 file = new File( file.toString() + "." + type );
2746             }
2747             if ( file.exists() ) {
2748                 final int i = JOptionPane.showConfirmDialog( this,
2749                                                              file + " already exists. Overwrite?",
2750                                                              "Warning",
2751                                                              JOptionPane.OK_CANCEL_OPTION,
2752                                                              JOptionPane.WARNING_MESSAGE );
2753                 if ( i != JOptionPane.OK_OPTION ) {
2754                     return;
2755                 }
2756                 else {
2757                     try {
2758                         file.delete();
2759                     }
2760                     catch ( final Exception e ) {
2761                         JOptionPane.showMessageDialog( this,
2762                                                        "Failed to delete: " + file,
2763                                                        "Error",
2764                                                        JOptionPane.WARNING_MESSAGE );
2765                     }
2766                 }
2767             }
2768             writePhylogenyToGraphicsFile( file.toString(), type );
2769         }
2770     }
2771
2772     private void writeToPdf( final Phylogeny t ) {
2773         if ( ( t == null ) || t.isEmpty() ) {
2774             return;
2775         }
2776         String initial_filename = "";
2777         if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) {
2778             initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().toString();
2779         }
2780         if ( initial_filename.indexOf( '.' ) > 0 ) {
2781             initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) );
2782         }
2783         initial_filename = initial_filename + ".pdf";
2784         _writetopdf_filechooser.setSelectedFile( new File( initial_filename ) );
2785         final File my_dir = getCurrentDir();
2786         if ( my_dir != null ) {
2787             _writetopdf_filechooser.setCurrentDirectory( my_dir );
2788         }
2789         final int result = _writetopdf_filechooser.showSaveDialog( _contentpane );
2790         File file = _writetopdf_filechooser.getSelectedFile();
2791         setCurrentDir( _writetopdf_filechooser.getCurrentDirectory() );
2792         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2793             if ( !file.toString().toLowerCase().endsWith( ".pdf" ) ) {
2794                 file = new File( file.toString() + ".pdf" );
2795             }
2796             if ( file.exists() ) {
2797                 final int i = JOptionPane.showConfirmDialog( this,
2798                                                              file + " already exists. Overwrite?",
2799                                                              "WARNING",
2800                                                              JOptionPane.OK_CANCEL_OPTION,
2801                                                              JOptionPane.WARNING_MESSAGE );
2802                 if ( i != JOptionPane.OK_OPTION ) {
2803                     return;
2804                 }
2805             }
2806             printPhylogenyToPdf( file.toString() );
2807         }
2808     }
2809
2810     public static MainFrameApplication createInstance( final Phylogeny[] phys, final Configuration config ) {
2811         return new MainFrameApplication( phys, config );
2812     }
2813
2814     public static MainFrame createInstance( final Phylogeny[] phys,
2815                                             final Configuration config,
2816                                             final String title,
2817                                             final File current_dir ) {
2818         return new MainFrameApplication( phys, config, title, current_dir );
2819     }
2820
2821     static MainFrame createInstance( final Phylogeny[] phys, final Configuration config, final String title ) {
2822         return new MainFrameApplication( phys, config, title );
2823     }
2824
2825     static MainFrame createInstance( final Phylogeny[] phys, final String config_file_name, final String title ) {
2826         return new MainFrameApplication( phys, config_file_name, title );
2827     }
2828
2829     static void setTextForGraphicsSizeChooserMenuItem( final JMenuItem mi, final Options o ) {
2830         mi.setText( "Enter Default Size for Graphics Export... (current: " + o.getPrintSizeX() + ", "
2831                 + o.getPrintSizeY() + ")" );
2832     }
2833
2834     static void setTextForPdfLineWidthChooserMenuItem( final JMenuItem mi, final Options o ) {
2835         mi.setText( "Enter Default Line Width for PDF Export... (current: " + o.getPrintLineWidth() + ")" );
2836     }
2837
2838     static void warnIfNotPhyloXmlValidation( final Configuration c ) {
2839         if ( !c.isValidatePhyloXmlAgainstSchema() ) {
2840             JOptionPane
2841                     .showMessageDialog( null,
2842                                         ForesterUtil
2843                                                 .wordWrap( "phyloXML XSD-based validation is turned off [enable with line 'validate_against_phyloxml_xsd_schem: true' in configuration file]",
2844                                                            80 ),
2845                                         "Warning",
2846                                         JOptionPane.WARNING_MESSAGE );
2847         }
2848     }
2849 } // MainFrameApplication.
2850
2851 class DefaultFilter extends FileFilter {
2852
2853     @Override
2854     public boolean accept( final File f ) {
2855         final String file_name = f.getName().trim().toLowerCase();
2856         return file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2857                 || file_name.endsWith( ".nwk" ) || file_name.endsWith( ".phb" ) || file_name.endsWith( ".ph" )
2858                 || file_name.endsWith( ".tr" ) || file_name.endsWith( ".dnd" ) || file_name.endsWith( ".tree" )
2859                 || file_name.endsWith( ".nhx" ) || file_name.endsWith( ".xml" ) || file_name.endsWith( ".phyloxml" )
2860                 || file_name.endsWith( "phylo.xml" ) || file_name.endsWith( ".pxml" ) || file_name.endsWith( ".nexus" )
2861                 || file_name.endsWith( ".nx" ) || file_name.endsWith( ".nex" ) || file_name.endsWith( ".tre" )
2862                 || file_name.endsWith( ".zip" ) || file_name.endsWith( ".tol" ) || file_name.endsWith( ".tolxml" )
2863                 || file_name.endsWith( ".con" ) || f.isDirectory();
2864     }
2865
2866     @Override
2867     public String getDescription() {
2868         return "All supported files (*.xml, *.phyloxml, *phylo.xml, *.nhx, *.nh, *.newick, *.nex, *.nexus, *.phy, *.tre, *.tree, *.tol, ...)";
2869     }
2870 }
2871
2872 class GraphicsFileFilter extends FileFilter {
2873
2874     @Override
2875     public boolean accept( final File f ) {
2876         final String file_name = f.getName().trim().toLowerCase();
2877         return file_name.endsWith( ".jpg" ) || file_name.endsWith( ".jpeg" ) || file_name.endsWith( ".png" )
2878                 || file_name.endsWith( ".gif" ) || file_name.endsWith( ".bmp" ) || f.isDirectory();
2879     }
2880
2881     @Override
2882     public String getDescription() {
2883         return "Image files (*.jpg, *.jpeg, *.png, *.gif, *.bmp)";
2884     }
2885 }
2886
2887 class MsaFileFilter extends FileFilter {
2888
2889     @Override
2890     public boolean accept( final File f ) {
2891         final String file_name = f.getName().trim().toLowerCase();
2892         return file_name.endsWith( ".msa" ) || file_name.endsWith( ".aln" ) || file_name.endsWith( ".fasta" )
2893                 || file_name.endsWith( ".fas" ) || file_name.endsWith( ".fa" ) || f.isDirectory();
2894     }
2895
2896     @Override
2897     public String getDescription() {
2898         return "Multiple sequence alignment files (*.msa, *.aln, *.fasta, *.fa, *.fas)";
2899     }
2900 }
2901
2902 class NexusFilter extends FileFilter {
2903
2904     @Override
2905     public boolean accept( final File f ) {
2906         final String file_name = f.getName().trim().toLowerCase();
2907         return file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) || file_name.endsWith( ".nx" )
2908                 || file_name.endsWith( ".tre" ) || f.isDirectory();
2909     }
2910
2911     @Override
2912     public String getDescription() {
2913         return "Nexus files (*.nex, *.nexus, *.nx, *.tre)";
2914     }
2915 } // NexusFilter
2916
2917 class NHFilter extends FileFilter {
2918
2919     @Override
2920     public boolean accept( final File f ) {
2921         final String file_name = f.getName().trim().toLowerCase();
2922         return file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2923                 || file_name.endsWith( ".tr" ) || file_name.endsWith( ".tree" ) || file_name.endsWith( ".dnd" )
2924                 || file_name.endsWith( ".ph" ) || file_name.endsWith( ".phb" ) || file_name.endsWith( ".nwk" )
2925                 || f.isDirectory();
2926     }
2927
2928     @Override
2929     public String getDescription() {
2930         return "New Hampshire - Newick files (*.nh, *.newick, *.phy, *.tree, *.dnd, *.tr, *.ph, *.phb, *.nwk)";
2931     }
2932 } // NHFilter
2933
2934 class NHXFilter extends FileFilter {
2935
2936     @Override
2937     public boolean accept( final File f ) {
2938         final String file_name = f.getName().trim().toLowerCase();
2939         return file_name.endsWith( ".nhx" ) || f.isDirectory();
2940     }
2941
2942     @Override
2943     public String getDescription() {
2944         return "NHX files (*.nhx) [deprecated]";
2945     }
2946 }
2947
2948 class PdfFilter extends FileFilter {
2949
2950     @Override
2951     public boolean accept( final File f ) {
2952         return f.getName().trim().toLowerCase().endsWith( ".pdf" ) || f.isDirectory();
2953     }
2954
2955     @Override
2956     public String getDescription() {
2957         return "PDF files (*.pdf)";
2958     }
2959 } // PdfFilter
2960
2961 class SequencesFileFilter extends FileFilter {
2962
2963     @Override
2964     public boolean accept( final File f ) {
2965         final String file_name = f.getName().trim().toLowerCase();
2966         return file_name.endsWith( ".fasta" ) || file_name.endsWith( ".fa" ) || file_name.endsWith( ".fas" )
2967                 || file_name.endsWith( ".seqs" ) || f.isDirectory();
2968     }
2969
2970     @Override
2971     public String getDescription() {
2972         return "Sequences files (*.fasta, *.fa, *.fas, *.seqs )";
2973     }
2974 }
2975
2976 class TolFilter extends FileFilter {
2977
2978     @Override
2979     public boolean accept( final File f ) {
2980         final String file_name = f.getName().trim().toLowerCase();
2981         return ( file_name.endsWith( ".tol" ) || file_name.endsWith( ".tolxml" ) || file_name.endsWith( ".zip" ) || f
2982                 .isDirectory() ) && ( !file_name.endsWith( ".xml.zip" ) );
2983     }
2984
2985     @Override
2986     public String getDescription() {
2987         return "Tree of Life files (*.tol, *.tolxml)";
2988     }
2989 } // TolFilter
2990
2991 class XMLFilter extends FileFilter {
2992
2993     @Override
2994     public boolean accept( final File f ) {
2995         final String file_name = f.getName().trim().toLowerCase();
2996         return file_name.endsWith( ".xml" ) || file_name.endsWith( ".phyloxml" ) || file_name.endsWith( "phylo.xml" )
2997                 || file_name.endsWith( ".pxml" ) || file_name.endsWith( ".zip" ) || f.isDirectory();
2998     }
2999
3000     @Override
3001     public String getDescription() {
3002         return "phyloXML files (*.xml, *.phyloxml, *phylo.xml, *.pxml, *.zip)";
3003     }
3004 } // XMLFilter