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