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