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.addSeparator();
1057         _tools_menu.add( _remove_visual_styles_item = new JMenuItem( "Delete All Visual Styles From Nodes" ) );
1058         _remove_visual_styles_item
1059                 .setToolTipText( "To remove all node visual styles (fonts, colors) from the current phylogeny." );
1060         customizeJMenuItem( _remove_visual_styles_item );
1061         _tools_menu.add( _remove_branch_color_item = new JMenuItem( "Delete All Colors From Branches" ) );
1062         _remove_branch_color_item.setToolTipText( "To remove all branch color values from the current phylogeny." );
1063         customizeJMenuItem( _remove_branch_color_item );
1064         _tools_menu.addSeparator();
1065         _tools_menu.add( _annotate_item = new JMenuItem( "Annotate Sequences of Selected Nodes" ) );
1066         customizeJMenuItem( _annotate_item );
1067         _tools_menu.addSeparator();
1068         _tools_menu.add( _midpoint_root_item = new JMenuItem( "Midpoint-Root" ) );
1069         customizeJMenuItem( _midpoint_root_item );
1070         _tools_menu.addSeparator();
1071         _tools_menu.add( _collapse_species_specific_subtrees = new JMenuItem( "Collapse Species-Specific Subtrees" ) );
1072         customizeJMenuItem( _collapse_species_specific_subtrees );
1073         _tools_menu
1074                 .add( _collapse_below_threshold = new JMenuItem( "Collapse Branches with Confidence Below Threshold into Multifurcations" ) );
1075         customizeJMenuItem( _collapse_below_threshold );
1076         _collapse_below_threshold
1077                 .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)" );
1078         _tools_menu.addSeparator();
1079         _tools_menu
1080                 .add( _extract_tax_code_from_node_names_jmi = new JMenuItem( "Extract Taxonomic Data from Node Names" ) );
1081         customizeJMenuItem( _extract_tax_code_from_node_names_jmi );
1082         _extract_tax_code_from_node_names_jmi
1083                 .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'" );
1084         _tools_menu
1085                 .add( _move_node_names_to_tax_sn_jmi = new JMenuItem( "Transfer Node Names to Taxonomic Scientific Names" ) );
1086         customizeJMenuItem( _move_node_names_to_tax_sn_jmi );
1087         _move_node_names_to_tax_sn_jmi.setToolTipText( "To interpret node names as taxonomic scientific names" );
1088         _tools_menu.add( _move_node_names_to_seq_names_jmi = new JMenuItem( "Transfer Node Names to Sequence Names" ) );
1089         customizeJMenuItem( _move_node_names_to_seq_names_jmi );
1090         _move_node_names_to_seq_names_jmi.setToolTipText( "To interpret node names as sequence (protein, gene) names" );
1091         _tools_menu.addSeparator();
1092         _tools_menu.add( _obtain_seq_information_jmi = new JMenuItem( "Obtain Sequence Information" ) );
1093         customizeJMenuItem( _obtain_seq_information_jmi );
1094         _obtain_seq_information_jmi.setToolTipText( "To add additional sequence information" );
1095         _tools_menu
1096                 .add( _obtain_detailed_taxonomic_information_jmi = new JMenuItem( OBTAIN_DETAILED_TAXONOMIC_INFORMATION ) );
1097         customizeJMenuItem( _obtain_detailed_taxonomic_information_jmi );
1098         _obtain_detailed_taxonomic_information_jmi
1099                 .setToolTipText( "To add additional taxonomic information (from UniProt Taxonomy)" );
1100         _tools_menu
1101                 .add( _obtain_detailed_taxonomic_information_deleting_jmi = new JMenuItem( "Obtain Detailed Taxonomic Information (deletes nodes!)" ) );
1102         customizeJMenuItem( _obtain_detailed_taxonomic_information_deleting_jmi );
1103         _obtain_detailed_taxonomic_information_deleting_jmi
1104                 .setToolTipText( "To add additional taxonomic information, deletes nodes for which taxonomy cannot found (from UniProt Taxonomy)" );
1105         _tools_menu.addSeparator();
1106         _tools_menu.add( _read_values_jmi = new JMenuItem( "Attach Vector/Expression Values" ) );
1107         customizeJMenuItem( _read_values_jmi );
1108         _read_values_jmi.setToolTipText( "To attach vector (e.g. gene expression) values to tree nodes (beta)" );
1109         _jmenubar.add( _tools_menu );
1110         _tools_menu.add( _read_seqs_jmi = new JMenuItem( "Attach Molecular Sequences" ) );
1111         customizeJMenuItem( _read_seqs_jmi );
1112         _read_seqs_jmi
1113                 .setToolTipText( "To attach molecular sequences to tree nodes (from Fasta-formatted file) (beta)" );
1114         _jmenubar.add( _tools_menu );
1115     }
1116
1117     @Override
1118     void close() {
1119         if ( isUnsavedDataPresent() ) {
1120             final int r = JOptionPane.showConfirmDialog( this,
1121                                                          "Exit despite potentially unsaved changes?",
1122                                                          "Exit?",
1123                                                          JOptionPane.YES_NO_OPTION );
1124             if ( r != JOptionPane.YES_OPTION ) {
1125                 return;
1126             }
1127         }
1128         exit();
1129     }
1130
1131     void executeLineageInference() {
1132         if ( ( _mainpanel.getCurrentPhylogeny() == null ) || ( _mainpanel.getCurrentPhylogeny().isEmpty() ) ) {
1133             return;
1134         }
1135         if ( !_mainpanel.getCurrentPhylogeny().isRooted() ) {
1136             JOptionPane.showMessageDialog( this,
1137                                            "Phylogeny is not rooted.",
1138                                            "Cannot infer ancestral taxonomies",
1139                                            JOptionPane.ERROR_MESSAGE );
1140             return;
1141         }
1142         final AncestralTaxonomyInferrer inferrer = new AncestralTaxonomyInferrer( this,
1143                                                                                   _mainpanel.getCurrentTreePanel(),
1144                                                                                   _mainpanel.getCurrentPhylogeny()
1145                                                                                           .copy() );
1146         new Thread( inferrer ).start();
1147     }
1148
1149     void exit() {
1150         removeAllTextFrames();
1151         _mainpanel.terminate();
1152         _contentpane.removeAll();
1153         setVisible( false );
1154         dispose();
1155         System.exit( 0 );
1156     }
1157
1158     void setMsa( final Msa msa ) {
1159         _msa = msa;
1160     }
1161
1162     void setMsaFile( final File msa_file ) {
1163         _msa_file = msa_file;
1164     }
1165
1166     void setSeqs( final List<Sequence> seqs ) {
1167         _seqs = seqs;
1168     }
1169
1170     void setSeqsFile( final File seqs_file ) {
1171         _seqs_file = seqs_file;
1172     }
1173
1174     void writePhylogenyToGraphicsFile( final String file_name, final GraphicsExportType type ) {
1175         _mainpanel.getCurrentTreePanel().calcParametersForPainting( _mainpanel.getCurrentTreePanel().getWidth(),
1176                                                                     _mainpanel.getCurrentTreePanel().getHeight(),
1177                                                                     true );
1178         String file_written_to = "";
1179         boolean error = false;
1180         try {
1181             file_written_to = AptxUtil.writePhylogenyToGraphicsFile( file_name,
1182                                                                      _mainpanel.getCurrentTreePanel().getWidth(),
1183                                                                      _mainpanel.getCurrentTreePanel().getHeight(),
1184                                                                      _mainpanel.getCurrentTreePanel(),
1185                                                                      _mainpanel.getControlPanel(),
1186                                                                      type,
1187                                                                      getOptions() );
1188         }
1189         catch ( final IOException e ) {
1190             error = true;
1191             JOptionPane.showMessageDialog( this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE );
1192         }
1193         if ( !error ) {
1194             if ( ( file_written_to != null ) && ( file_written_to.length() > 0 ) ) {
1195                 JOptionPane.showMessageDialog( this,
1196                                                "Wrote image to: " + file_written_to,
1197                                                "Graphics Export",
1198                                                JOptionPane.INFORMATION_MESSAGE );
1199             }
1200             else {
1201                 JOptionPane.showMessageDialog( this,
1202                                                "There was an unknown problem when attempting to write to an image file: \""
1203                                                        + file_name + "\"",
1204                                                "Error",
1205                                                JOptionPane.ERROR_MESSAGE );
1206             }
1207         }
1208         _contentpane.repaint();
1209     }
1210
1211     private void addExpressionValuesFromFile() {
1212         if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) ) {
1213             JOptionPane.showMessageDialog( this,
1214                                            "Need to load evolutionary tree first",
1215                                            "Can Not Read Expression Values",
1216                                            JOptionPane.WARNING_MESSAGE );
1217             return;
1218         }
1219         final File my_dir = getCurrentDir();
1220         if ( my_dir != null ) {
1221             _values_filechooser.setCurrentDirectory( my_dir );
1222         }
1223         final int result = _values_filechooser.showOpenDialog( _contentpane );
1224         final File file = _values_filechooser.getSelectedFile();
1225         if ( ( file != null ) && ( file.length() > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
1226             BasicTable<String> t = null;
1227             try {
1228                 t = BasicTableParser.parse( file, '\t' );
1229                 if ( t.getNumberOfColumns() < 2 ) {
1230                     t = BasicTableParser.parse( file, ',' );
1231                 }
1232                 if ( t.getNumberOfColumns() < 2 ) {
1233                     t = BasicTableParser.parse( file, ' ' );
1234                 }
1235             }
1236             catch ( final IOException e ) {
1237                 JOptionPane.showMessageDialog( this,
1238                                                e.getMessage(),
1239                                                "Could Not Read Expression Value Table",
1240                                                JOptionPane.ERROR_MESSAGE );
1241                 return;
1242             }
1243             if ( t.getNumberOfColumns() < 2 ) {
1244                 JOptionPane.showMessageDialog( this,
1245                                                "Table contains " + t.getNumberOfColumns() + " column(s)",
1246                                                "Problem with Expression Value Table",
1247                                                JOptionPane.ERROR_MESSAGE );
1248                 return;
1249             }
1250             if ( t.getNumberOfRows() < 1 ) {
1251                 JOptionPane.showMessageDialog( this,
1252                                                "Table contains zero rows",
1253                                                "Problem with Expression Value Table",
1254                                                JOptionPane.ERROR_MESSAGE );
1255                 return;
1256             }
1257             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1258             if ( t.getNumberOfRows() != phy.getNumberOfExternalNodes() ) {
1259                 JOptionPane.showMessageDialog( this,
1260                                                "Table contains " + t.getNumberOfRows() + " rows, but tree contains "
1261                                                        + phy.getNumberOfExternalNodes() + " external nodes",
1262                                                "Warning",
1263                                                JOptionPane.WARNING_MESSAGE );
1264             }
1265             final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
1266             int not_found = 0;
1267             for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1268                 final PhylogenyNode node = iter.next();
1269                 final String node_name = node.getName();
1270                 if ( !ForesterUtil.isEmpty( node_name ) ) {
1271                     int row = -1;
1272                     try {
1273                         row = t.findRow( node_name );
1274                     }
1275                     catch ( final IllegalArgumentException e ) {
1276                         JOptionPane
1277                                 .showMessageDialog( this,
1278                                                     e.getMessage(),
1279                                                     "Error Mapping Node Identifiers to Expression Value Identifiers",
1280                                                     JOptionPane.ERROR_MESSAGE );
1281                         return;
1282                     }
1283                     if ( row < 0 ) {
1284                         if ( node.isExternal() ) {
1285                             not_found++;
1286                         }
1287                         continue;
1288                     }
1289                     final List<Double> l = new ArrayList<Double>();
1290                     for( int col = 1; col < t.getNumberOfColumns(); ++col ) {
1291                         double d = -100;
1292                         try {
1293                             d = Double.parseDouble( t.getValueAsString( col, row ) );
1294                         }
1295                         catch ( final NumberFormatException e ) {
1296                             JOptionPane.showMessageDialog( this,
1297                                                            "Could not parse \"" + t.getValueAsString( col, row )
1298                                                                    + "\" into a decimal value",
1299                                                            "Issue with Expression Value Table",
1300                                                            JOptionPane.ERROR_MESSAGE );
1301                             return;
1302                         }
1303                         stats.addValue( d );
1304                         l.add( d );
1305                     }
1306                     if ( !l.isEmpty() ) {
1307                         if ( node.getNodeData().getProperties() != null ) {
1308                             node.getNodeData().getProperties()
1309                                     .removePropertiesWithGivenReferencePrefix( PhyloXmlUtil.VECTOR_PROPERTY_REF );
1310                         }
1311                         node.getNodeData().setVector( l );
1312                     }
1313                 }
1314             }
1315             if ( not_found > 0 ) {
1316                 JOptionPane.showMessageDialog( this, "Could not fine expression values for " + not_found
1317                         + " external node(s)", "Warning", JOptionPane.WARNING_MESSAGE );
1318             }
1319             getCurrentTreePanel().setStatisticsForExpressionValues( stats );
1320         }
1321     }
1322
1323     private void addSequencesFromFile() {
1324         if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) ) {
1325             JOptionPane.showMessageDialog( this,
1326                                            "Need to load evolutionary tree first",
1327                                            "Can Not Read Sequences",
1328                                            JOptionPane.WARNING_MESSAGE );
1329             return;
1330         }
1331         final File my_dir = getCurrentDir();
1332         if ( my_dir != null ) {
1333             _sequences_filechooser.setCurrentDirectory( my_dir );
1334         }
1335         final int result = _sequences_filechooser.showOpenDialog( _contentpane );
1336         final File file = _sequences_filechooser.getSelectedFile();
1337         List<Sequence> seqs = null;
1338         if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) {
1339             try {
1340                 if ( FastaParser.isLikelyFasta( new FileInputStream( file ) ) ) {
1341                     seqs = FastaParser.parse( new FileInputStream( file ) );
1342                 }
1343                 else {
1344                     JOptionPane.showMessageDialog( this,
1345                                                    "Format does not appear to be Fasta",
1346                                                    "Multiple sequence file format error",
1347                                                    JOptionPane.ERROR_MESSAGE );
1348                     return;
1349                 }
1350             }
1351             catch ( final MsaFormatException e ) {
1352                 setArrowCursor();
1353                 JOptionPane.showMessageDialog( this,
1354                                                e.getLocalizedMessage(),
1355                                                "Multiple sequence file format error",
1356                                                JOptionPane.ERROR_MESSAGE );
1357                 return;
1358             }
1359             catch ( final IOException e ) {
1360                 setArrowCursor();
1361                 JOptionPane.showMessageDialog( this,
1362                                                e.getLocalizedMessage(),
1363                                                "Failed to read multiple sequence file",
1364                                                JOptionPane.ERROR_MESSAGE );
1365                 return;
1366             }
1367             catch ( final Exception e ) {
1368                 setArrowCursor();
1369                 e.printStackTrace();
1370                 JOptionPane.showMessageDialog( this,
1371                                                e.getLocalizedMessage(),
1372                                                "Unexpected error during reading of multiple sequence file",
1373                                                JOptionPane.ERROR_MESSAGE );
1374                 return;
1375             }
1376             if ( ( seqs == null ) || ( seqs.size() < 1 ) ) {
1377                 JOptionPane.showMessageDialog( this,
1378                                                "Multiple sequence file is empty",
1379                                                "Empty multiple sequence file",
1380                                                JOptionPane.ERROR_MESSAGE );
1381                 setArrowCursor();
1382                 return;
1383             }
1384         }
1385         if ( seqs != null ) {
1386             for( final Sequence seq : seqs ) {
1387                 System.out.println( seq.getIdentifier() );
1388             }
1389             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1390             int total_counter = 0;
1391             int attached_counter = 0;
1392             for( final Sequence seq : seqs ) {
1393                 ++total_counter;
1394                 final String seq_name = seq.getIdentifier();
1395                 if ( !ForesterUtil.isEmpty( seq_name ) ) {
1396                     List<PhylogenyNode> nodes = phy.getNodesViaSequenceName( seq_name );
1397                     if ( nodes.isEmpty() ) {
1398                         nodes = phy.getNodesViaSequenceSymbol( seq_name );
1399                     }
1400                     if ( nodes.isEmpty() ) {
1401                         nodes = phy.getNodesViaGeneName( seq_name );
1402                     }
1403                     if ( nodes.isEmpty() ) {
1404                         nodes = phy.getNodes( seq_name );
1405                     }
1406                     if ( nodes.size() > 1 ) {
1407                         JOptionPane.showMessageDialog( this,
1408                                                        "Sequence name \"" + seq_name + "\" is not unique",
1409                                                        "Sequence name not unique",
1410                                                        JOptionPane.ERROR_MESSAGE );
1411                         setArrowCursor();
1412                         return;
1413                     }
1414                     final String[] a = seq_name.split( "\\s" );
1415                     if ( nodes.isEmpty() && ( a.length > 1 ) ) {
1416                         final String seq_name_split = a[ 0 ];
1417                         nodes = phy.getNodesViaSequenceName( seq_name_split );
1418                         if ( nodes.isEmpty() ) {
1419                             nodes = phy.getNodesViaSequenceSymbol( seq_name_split );
1420                         }
1421                         if ( nodes.isEmpty() ) {
1422                             nodes = phy.getNodes( seq_name_split );
1423                         }
1424                         if ( nodes.size() > 1 ) {
1425                             JOptionPane.showMessageDialog( this, "Split sequence name \"" + seq_name_split
1426                                     + "\" is not unique", "Sequence name not unique", JOptionPane.ERROR_MESSAGE );
1427                             setArrowCursor();
1428                             return;
1429                         }
1430                     }
1431                     if ( nodes.size() == 1 ) {
1432                         ++attached_counter;
1433                         final PhylogenyNode n = nodes.get( 0 );
1434                         if ( !n.getNodeData().isHasSequence() ) {
1435                             n.getNodeData().addSequence( new org.forester.phylogeny.data.Sequence() );
1436                         }
1437                         n.getNodeData().getSequence().setMolecularSequence( seq.getMolecularSequenceAsString() );
1438                         if ( ForesterUtil.isEmpty( n.getNodeData().getSequence().getName() ) ) {
1439                             n.getNodeData().getSequence().setName( seq_name );
1440                         }
1441                     }
1442                 }
1443             }
1444             if ( attached_counter > 0 ) {
1445                 int ext_nodes = 0;
1446                 int ext_nodes_with_seq = 0;
1447                 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
1448                     ++ext_nodes;
1449                     final PhylogenyNode n = iter.next();
1450                     if ( n.getNodeData().isHasSequence()
1451                             && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getMolecularSequence() ) ) {
1452                         ++ext_nodes_with_seq;
1453                     }
1454                 }
1455                 final String s;
1456                 if ( ext_nodes == ext_nodes_with_seq ) {
1457                     s = "All " + ext_nodes_with_seq + " external nodes now have a molecular sequence attached to them.";
1458                 }
1459                 else {
1460                     s = ext_nodes_with_seq + " out of " + ext_nodes
1461                             + " external nodes now have a molecular sequence attached to them.";
1462                 }
1463                 if ( ( attached_counter == total_counter ) && ( ext_nodes == ext_nodes_with_seq ) ) {
1464                     JOptionPane.showMessageDialog( this,
1465                                                    "Attached all " + total_counter + " sequences to tree nodes.\n" + s,
1466                                                    "All sequences attached",
1467                                                    JOptionPane.INFORMATION_MESSAGE );
1468                 }
1469                 else {
1470                     JOptionPane.showMessageDialog( this, "Attached " + attached_counter
1471                             + " sequences out of a total of " + total_counter + " sequences.\n" + s, attached_counter
1472                             + " sequences attached", JOptionPane.WARNING_MESSAGE );
1473                 }
1474             }
1475             else {
1476                 JOptionPane.showMessageDialog( this, "No maching tree node for any of the " + total_counter
1477                         + " sequences", "Could not attach any sequences", JOptionPane.ERROR_MESSAGE );
1478             }
1479         }
1480     }
1481
1482     private void choosePdfWidth() {
1483         final String s = ( String ) JOptionPane.showInputDialog( this,
1484                                                                  "Please enter the default line width for PDF export.\n"
1485                                                                          + "[current value: "
1486                                                                          + getOptions().getPrintLineWidth() + "]\n",
1487                                                                  "Line Width for PDF Export",
1488                                                                  JOptionPane.QUESTION_MESSAGE,
1489                                                                  null,
1490                                                                  null,
1491                                                                  getOptions().getPrintLineWidth() );
1492         if ( !ForesterUtil.isEmpty( s ) ) {
1493             boolean success = true;
1494             float f = 0.0f;
1495             final String m_str = s.trim();
1496             if ( !ForesterUtil.isEmpty( m_str ) ) {
1497                 try {
1498                     f = Float.parseFloat( m_str );
1499                 }
1500                 catch ( final Exception ex ) {
1501                     success = false;
1502                 }
1503             }
1504             else {
1505                 success = false;
1506             }
1507             if ( success && ( f > 0.0 ) ) {
1508                 getOptions().setPrintLineWidth( f );
1509             }
1510         }
1511     }
1512
1513     private void choosePrintSize() {
1514         final String s = ( String ) JOptionPane.showInputDialog( this,
1515                                                                  "Please enter values for width and height,\nseparated by a comma.\n"
1516                                                                          + "[current values: "
1517                                                                          + getOptions().getPrintSizeX() + ", "
1518                                                                          + getOptions().getPrintSizeY() + "]\n"
1519                                                                          + "[A4: " + Constants.A4_SIZE_X + ", "
1520                                                                          + Constants.A4_SIZE_Y + "]\n" + "[US Letter: "
1521                                                                          + Constants.US_LETTER_SIZE_X + ", "
1522                                                                          + Constants.US_LETTER_SIZE_Y + "]",
1523                                                                  "Default Size for Graphics Export",
1524                                                                  JOptionPane.QUESTION_MESSAGE,
1525                                                                  null,
1526                                                                  null,
1527                                                                  getOptions().getPrintSizeX() + ", "
1528                                                                          + getOptions().getPrintSizeY() );
1529         if ( !ForesterUtil.isEmpty( s ) && ( s.indexOf( ',' ) > 0 ) ) {
1530             boolean success = true;
1531             int x = 0;
1532             int y = 0;
1533             final String[] str_ary = s.split( "," );
1534             if ( str_ary.length == 2 ) {
1535                 final String x_str = str_ary[ 0 ].trim();
1536                 final String y_str = str_ary[ 1 ].trim();
1537                 if ( !ForesterUtil.isEmpty( x_str ) && !ForesterUtil.isEmpty( y_str ) ) {
1538                     try {
1539                         x = Integer.parseInt( x_str );
1540                         y = Integer.parseInt( y_str );
1541                     }
1542                     catch ( final Exception ex ) {
1543                         success = false;
1544                     }
1545                 }
1546                 else {
1547                     success = false;
1548                 }
1549             }
1550             else {
1551                 success = false;
1552             }
1553             if ( success && ( x > 1 ) && ( y > 1 ) ) {
1554                 getOptions().setPrintSizeX( x );
1555                 getOptions().setPrintSizeY( y );
1556             }
1557         }
1558     }
1559
1560     private void closeCurrentPane() {
1561         if ( getMainPanel().getCurrentTreePanel() != null ) {
1562             if ( getMainPanel().getCurrentTreePanel().isEdited() ) {
1563                 final int r = JOptionPane.showConfirmDialog( this,
1564                                                              "Close tab despite potentially unsaved changes?",
1565                                                              "Close Tab?",
1566                                                              JOptionPane.YES_NO_OPTION );
1567                 if ( r != JOptionPane.YES_OPTION ) {
1568                     return;
1569                 }
1570             }
1571             getMainPanel().closeCurrentPane();
1572             activateSaveAllIfNeeded();
1573         }
1574     }
1575
1576     private void collapse( final Phylogeny phy, final double m ) {
1577         final PhylogenyNodeIterator it = phy.iteratorPostorder();
1578         final List<PhylogenyNode> to_be_removed = new ArrayList<PhylogenyNode>();
1579         double min_support = Double.MAX_VALUE;
1580         boolean conf_present = false;
1581         while ( it.hasNext() ) {
1582             final PhylogenyNode n = it.next();
1583             if ( !n.isExternal() && !n.isRoot() ) {
1584                 final List<Confidence> c = n.getBranchData().getConfidences();
1585                 if ( ( c != null ) && ( c.size() > 0 ) ) {
1586                     conf_present = true;
1587                     double max = 0;
1588                     for( final Confidence confidence : c ) {
1589                         if ( confidence.getValue() > max ) {
1590                             max = confidence.getValue();
1591                         }
1592                     }
1593                     if ( max < getMinNotCollapseConfidenceValue() ) {
1594                         to_be_removed.add( n );
1595                     }
1596                     if ( max < min_support ) {
1597                         min_support = max;
1598                     }
1599                 }
1600             }
1601         }
1602         if ( conf_present ) {
1603             for( final PhylogenyNode node : to_be_removed ) {
1604                 PhylogenyMethods.removeNode( node, phy );
1605             }
1606             if ( to_be_removed.size() > 0 ) {
1607                 phy.externalNodesHaveChanged();
1608                 phy.clearHashIdToNodeMap();
1609                 phy.recalculateNumberOfExternalDescendants( true );
1610                 getCurrentTreePanel().resetNodeIdToDistToLeafMap();
1611                 getCurrentTreePanel().updateSetOfCollapsedExternalNodes();
1612                 getCurrentTreePanel().calculateLongestExtNodeInfo();
1613                 getCurrentTreePanel().setNodeInPreorderToNull();
1614                 getCurrentTreePanel().recalculateMaxDistanceToRoot();
1615                 getCurrentTreePanel().resetPreferredSize();
1616                 getCurrentTreePanel().setEdited( true );
1617                 getCurrentTreePanel().repaint();
1618                 repaint();
1619             }
1620             if ( to_be_removed.size() > 0 ) {
1621                 JOptionPane.showMessageDialog( this, "Collapsed " + to_be_removed.size()
1622                         + " branches with\nconfidence values below " + getMinNotCollapseConfidenceValue(), "Collapsed "
1623                         + to_be_removed.size() + " branches", JOptionPane.INFORMATION_MESSAGE );
1624             }
1625             else {
1626                 JOptionPane.showMessageDialog( this, "No branch collapsed,\nminimum confidence value per branch is "
1627                         + min_support, "No branch collapsed", JOptionPane.INFORMATION_MESSAGE );
1628             }
1629         }
1630         else {
1631             JOptionPane.showMessageDialog( this,
1632                                            "No branch collapsed because no confidence values present",
1633                                            "No confidence values present",
1634                                            JOptionPane.INFORMATION_MESSAGE );
1635         }
1636     }
1637
1638     private void collapseBelowThreshold() {
1639         if ( getCurrentTreePanel() != null ) {
1640             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1641             if ( ( phy != null ) && !phy.isEmpty() ) {
1642                 final String s = ( String ) JOptionPane.showInputDialog( this,
1643                                                                          "Please enter the minimum confidence value\n",
1644                                                                          "Minimal Confidence Value",
1645                                                                          JOptionPane.QUESTION_MESSAGE,
1646                                                                          null,
1647                                                                          null,
1648                                                                          getMinNotCollapseConfidenceValue() );
1649                 if ( !ForesterUtil.isEmpty( s ) ) {
1650                     boolean success = true;
1651                     double m = 0.0;
1652                     final String m_str = s.trim();
1653                     if ( !ForesterUtil.isEmpty( m_str ) ) {
1654                         try {
1655                             m = Double.parseDouble( m_str );
1656                         }
1657                         catch ( final Exception ex ) {
1658                             success = false;
1659                         }
1660                     }
1661                     else {
1662                         success = false;
1663                     }
1664                     if ( success && ( m >= 0.0 ) ) {
1665                         setMinNotCollapseConfidenceValue( m );
1666                         collapse( phy, m );
1667                     }
1668                 }
1669             }
1670         }
1671     }
1672
1673     private PhyloXmlParser createPhyloXmlParser() {
1674         PhyloXmlParser xml_parser = null;
1675         if ( getConfiguration().isValidatePhyloXmlAgainstSchema() ) {
1676             try {
1677                 xml_parser = PhyloXmlParser.createPhyloXmlParserXsdValidating();
1678             }
1679             catch ( final Exception e ) {
1680                 JOptionPane.showMessageDialog( this,
1681                                                e.getLocalizedMessage(),
1682                                                "failed to create validating XML parser",
1683                                                JOptionPane.WARNING_MESSAGE );
1684             }
1685         }
1686         if ( xml_parser == null ) {
1687             xml_parser = PhyloXmlParser.createPhyloXmlParser();
1688         }
1689         return xml_parser;
1690     }
1691
1692     private void executePhyleneticInference( final boolean from_unaligned_seqs ) {
1693         final PhyloInferenceDialog dialog = new PhyloInferenceDialog( this,
1694                                                                       getPhylogeneticInferenceOptions(),
1695                                                                       from_unaligned_seqs );
1696         dialog.activate();
1697         if ( dialog.getValue() == JOptionPane.OK_OPTION ) {
1698             if ( !from_unaligned_seqs ) {
1699                 if ( getMsa() != null ) {
1700                     final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getMsa(),
1701                                                                                     getPhylogeneticInferenceOptions()
1702                                                                                             .copy(), this );
1703                     new Thread( inferrer ).start();
1704                 }
1705                 else {
1706                     JOptionPane.showMessageDialog( this,
1707                                                    "No multiple sequence alignment selected",
1708                                                    "Phylogenetic Inference Not Launched",
1709                                                    JOptionPane.WARNING_MESSAGE );
1710                 }
1711             }
1712             else {
1713                 if ( getSeqs() != null ) {
1714                     final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getSeqs(),
1715                                                                                     getPhylogeneticInferenceOptions()
1716                                                                                             .copy(), this );
1717                     new Thread( inferrer ).start();
1718                 }
1719                 else {
1720                     JOptionPane.showMessageDialog( this,
1721                                                    "No input sequences selected",
1722                                                    "Phylogenetic Inference Not Launched",
1723                                                    JOptionPane.WARNING_MESSAGE );
1724                 }
1725             }
1726         }
1727     }
1728
1729     private void extractTaxDataFromNodeNames() throws PhyloXmlDataFormatException {
1730         final StringBuilder sb = new StringBuilder();
1731         final StringBuilder sb_failed = new StringBuilder();
1732         int counter = 0;
1733         int counter_failed = 0;
1734         if ( getCurrentTreePanel() != null ) {
1735             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1736             if ( ( phy != null ) && !phy.isEmpty() ) {
1737                 final PhylogenyNodeIterator it = phy.iteratorExternalForward();
1738                 while ( it.hasNext() ) {
1739                     final PhylogenyNode n = it.next();
1740                     final String name = n.getName().trim();
1741                     if ( !ForesterUtil.isEmpty( name ) ) {
1742                         final String nt = ParserUtils.extractTaxonomyDataFromNodeName( n,
1743                                                                                        TAXONOMY_EXTRACTION.AGGRESSIVE );
1744                         if ( !ForesterUtil.isEmpty( nt ) ) {
1745                             if ( counter < 15 ) {
1746                                 sb.append( name + ": " + nt + "\n" );
1747                             }
1748                             else if ( counter == 15 ) {
1749                                 sb.append( "...\n" );
1750                             }
1751                             counter++;
1752                         }
1753                         else {
1754                             if ( counter_failed < 15 ) {
1755                                 sb_failed.append( name + "\n" );
1756                             }
1757                             else if ( counter_failed == 15 ) {
1758                                 sb_failed.append( "...\n" );
1759                             }
1760                             counter_failed++;
1761                         }
1762                     }
1763                 }
1764                 if ( counter > 0 ) {
1765                     String failed = "";
1766                     String all = "all ";
1767                     if ( counter_failed > 0 ) {
1768                         all = "";
1769                         failed = "\nCould not extract taxonomic data for " + counter_failed
1770                                 + " named external nodes:\n" + sb_failed;
1771                     }
1772                     JOptionPane.showMessageDialog( this,
1773                                                    "Extracted taxonomic data from " + all + counter
1774                                                            + " named external nodes:\n" + sb.toString() + failed,
1775                                                    "Taxonomic Data Extraction Completed",
1776                                                    counter_failed > 0 ? JOptionPane.WARNING_MESSAGE
1777                                                            : JOptionPane.INFORMATION_MESSAGE );
1778                 }
1779                 else {
1780                     JOptionPane
1781                             .showMessageDialog( this,
1782                                                 "Could not extract any taxonomic data.\nMaybe node names are empty\n"
1783                                                         + "or not in the forms \"XYZ_CAEEL\", \"XYZ_6239\", or \"XYZ_Caenorhabditis_elegans\"\n"
1784                                                         + "or nodes already have taxonomic data?\n",
1785                                                 "No Taxonomic Data Extracted",
1786                                                 JOptionPane.ERROR_MESSAGE );
1787                 }
1788             }
1789         }
1790     }
1791
1792     private ControlPanel getControlPanel() {
1793         return getMainPanel().getControlPanel();
1794     }
1795
1796     private File getCurrentDir() {
1797         if ( ( _current_dir == null ) || !_current_dir.canRead() ) {
1798             if ( ForesterUtil.isWindows() ) {
1799                 try {
1800                     _current_dir = new File( WindowsUtils.getCurrentUserDesktopPath() );
1801                 }
1802                 catch ( final Exception e ) {
1803                     _current_dir = null;
1804                 }
1805             }
1806         }
1807         if ( ( _current_dir == null ) || !_current_dir.canRead() ) {
1808             if ( System.getProperty( "user.home" ) != null ) {
1809                 _current_dir = new File( System.getProperty( "user.home" ) );
1810             }
1811             else if ( System.getProperty( "user.dir" ) != null ) {
1812                 _current_dir = new File( System.getProperty( "user.dir" ) );
1813             }
1814         }
1815         return _current_dir;
1816     }
1817
1818     private double getMinNotCollapseConfidenceValue() {
1819         return _min_not_collapse;
1820     }
1821
1822     private PhylogeneticInferenceOptions getPhylogeneticInferenceOptions() {
1823         if ( _phylogenetic_inference_options == null ) {
1824             _phylogenetic_inference_options = new PhylogeneticInferenceOptions();
1825         }
1826         return _phylogenetic_inference_options;
1827     }
1828
1829     private boolean isUnsavedDataPresent() {
1830         final List<TreePanel> tps = getMainPanel().getTreePanels();
1831         for( final TreePanel tp : tps ) {
1832             if ( tp.isEdited() ) {
1833                 return true;
1834             }
1835         }
1836         return false;
1837     }
1838
1839     private void moveNodeNamesToSeqNames() throws PhyloXmlDataFormatException {
1840         if ( getCurrentTreePanel() != null ) {
1841             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1842             if ( ( phy != null ) && !phy.isEmpty() ) {
1843                 PhylogenyMethods
1844                         .transferNodeNameToField( phy, PhylogenyMethods.PhylogenyNodeField.SEQUENCE_NAME, false );
1845             }
1846         }
1847     }
1848
1849     private void moveNodeNamesToTaxSn() throws PhyloXmlDataFormatException {
1850         if ( getCurrentTreePanel() != null ) {
1851             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1852             if ( ( phy != null ) && !phy.isEmpty() ) {
1853                 PhylogenyMethods.transferNodeNameToField( phy,
1854                                                           PhylogenyMethods.PhylogenyNodeField.TAXONOMY_SCIENTIFIC_NAME,
1855                                                           false );
1856             }
1857         }
1858     }
1859
1860     private void newTree() {
1861         final Phylogeny[] phys = new Phylogeny[ 1 ];
1862         final Phylogeny phy = new Phylogeny();
1863         final PhylogenyNode node = new PhylogenyNode();
1864         phy.setRoot( node );
1865         phy.setRooted( true );
1866         phys[ 0 ] = phy;
1867         AptxUtil.addPhylogeniesToTabs( phys, "", "", getConfiguration(), getMainPanel() );
1868         _mainpanel.getControlPanel().showWhole();
1869         _mainpanel.getCurrentTreePanel().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1870         _mainpanel.getOptions().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1871         if ( getMainPanel().getMainFrame() == null ) {
1872             // Must be "E" applet version.
1873             ( ( ArchaeopteryxE ) ( ( MainPanelApplets ) getMainPanel() ).getApplet() )
1874                     .setSelectedTypeInTypeMenu( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1875         }
1876         else {
1877             getMainPanel().getMainFrame().setSelectedTypeInTypeMenu( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1878         }
1879         activateSaveAllIfNeeded();
1880         System.gc();
1881     }
1882
1883     private void obtainDetailedTaxonomicInformation() {
1884         if ( getCurrentTreePanel() != null ) {
1885             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1886             if ( ( phy != null ) && !phy.isEmpty() ) {
1887                 final TaxonomyDataManager t = new TaxonomyDataManager( this,
1888                                                                        _mainpanel.getCurrentTreePanel(),
1889                                                                        phy.copy(),
1890                                                                        false,
1891                                                                        true );
1892                 new Thread( t ).start();
1893             }
1894         }
1895     }
1896
1897     private void obtainDetailedTaxonomicInformationDelete() {
1898         if ( getCurrentTreePanel() != null ) {
1899             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1900             if ( ( phy != null ) && !phy.isEmpty() ) {
1901                 final TaxonomyDataManager t = new TaxonomyDataManager( this,
1902                                                                        _mainpanel.getCurrentTreePanel(),
1903                                                                        phy.copy(),
1904                                                                        true,
1905                                                                        true );
1906                 new Thread( t ).start();
1907             }
1908         }
1909     }
1910
1911     private void obtainSequenceInformation() {
1912         if ( getCurrentTreePanel() != null ) {
1913             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1914             if ( ( phy != null ) && !phy.isEmpty() ) {
1915                 final SequenceDataRetriver u = new SequenceDataRetriver( this,
1916                                                                          _mainpanel.getCurrentTreePanel(),
1917                                                                          phy.copy() );
1918                 new Thread( u ).start();
1919             }
1920         }
1921     }
1922
1923     private void print() {
1924         if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null )
1925                 || getCurrentTreePanel().getPhylogeny().isEmpty() ) {
1926             return;
1927         }
1928         if ( !getOptions().isPrintUsingActualSize() ) {
1929             getCurrentTreePanel().calcParametersForPainting( getOptions().getPrintSizeX() - 80,
1930                                                              getOptions().getPrintSizeY() - 140,
1931                                                              true );
1932             getCurrentTreePanel().resetPreferredSize();
1933             getCurrentTreePanel().repaint();
1934         }
1935         final String job_name = Constants.PRG_NAME;
1936         boolean error = false;
1937         String printer_name = null;
1938         try {
1939             printer_name = Printer.print( getCurrentTreePanel(), job_name );
1940         }
1941         catch ( final Exception e ) {
1942             error = true;
1943             JOptionPane.showMessageDialog( this, e.getMessage(), "Printing Error", JOptionPane.ERROR_MESSAGE );
1944         }
1945         if ( !error && ( printer_name != null ) ) {
1946             String msg = "Printing data sent to printer";
1947             if ( printer_name.length() > 1 ) {
1948                 msg += " [" + printer_name + "]";
1949             }
1950             JOptionPane.showMessageDialog( this, msg, "Printing...", JOptionPane.INFORMATION_MESSAGE );
1951         }
1952         if ( !getOptions().isPrintUsingActualSize() ) {
1953             getControlPanel().showWhole();
1954         }
1955     }
1956
1957     private void printPhylogenyToPdf( final String file_name ) {
1958         if ( !getOptions().isPrintUsingActualSize() ) {
1959             getCurrentTreePanel().calcParametersForPainting( getOptions().getPrintSizeX(),
1960                                                              getOptions().getPrintSizeY(),
1961                                                              true );
1962             getCurrentTreePanel().resetPreferredSize();
1963             getCurrentTreePanel().repaint();
1964         }
1965         String pdf_written_to = "";
1966         boolean error = false;
1967         try {
1968             if ( getOptions().isPrintUsingActualSize() ) {
1969                 pdf_written_to = PdfExporter.writePhylogenyToPdf( file_name,
1970                                                                   getCurrentTreePanel(),
1971                                                                   getCurrentTreePanel().getWidth(),
1972                                                                   getCurrentTreePanel().getHeight() );
1973             }
1974             else {
1975                 pdf_written_to = PdfExporter.writePhylogenyToPdf( file_name, getCurrentTreePanel(), getOptions()
1976                         .getPrintSizeX(), getOptions().getPrintSizeY() );
1977             }
1978         }
1979         catch ( final IOException e ) {
1980             error = true;
1981             JOptionPane.showMessageDialog( this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE );
1982         }
1983         if ( !error ) {
1984             if ( !ForesterUtil.isEmpty( pdf_written_to ) ) {
1985                 JOptionPane.showMessageDialog( this,
1986                                                "Wrote PDF to: " + pdf_written_to,
1987                                                "Information",
1988                                                JOptionPane.INFORMATION_MESSAGE );
1989             }
1990             else {
1991                 JOptionPane.showMessageDialog( this,
1992                                                "There was an unknown problem when attempting to write to PDF file: \""
1993                                                        + file_name + "\"",
1994                                                "Error",
1995                                                JOptionPane.ERROR_MESSAGE );
1996             }
1997         }
1998         if ( !getOptions().isPrintUsingActualSize() ) {
1999             getControlPanel().showWhole();
2000         }
2001     }
2002
2003     private void readPhylogeniesFromFile() {
2004         boolean exception = false;
2005         Phylogeny[] phys = null;
2006         // Set an initial directory if none set yet
2007         final File my_dir = getCurrentDir();
2008         _open_filechooser.setMultiSelectionEnabled( true );
2009         // Open file-open dialog and set current directory
2010         if ( my_dir != null ) {
2011             _open_filechooser.setCurrentDirectory( my_dir );
2012         }
2013         final int result = _open_filechooser.showOpenDialog( _contentpane );
2014         // All done: get the file
2015         final File[] files = _open_filechooser.getSelectedFiles();
2016         setCurrentDir( _open_filechooser.getCurrentDirectory() );
2017         boolean nhx_or_nexus = false;
2018         if ( ( files != null ) && ( files.length > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2019             for( final File file : files ) {
2020                 if ( ( file != null ) && !file.isDirectory() ) {
2021                     if ( _mainpanel.getCurrentTreePanel() != null ) {
2022                         _mainpanel.getCurrentTreePanel().setWaitCursor();
2023                     }
2024                     else {
2025                         _mainpanel.setWaitCursor();
2026                     }
2027                     if ( ( _open_filechooser.getFileFilter() == MainFrameApplication.nhfilter )
2028                             || ( _open_filechooser.getFileFilter() == MainFrameApplication.nhxfilter ) ) {
2029                         try {
2030                             final NHXParser nhx = new NHXParser();
2031                             setSpecialOptionsForNhxParser( nhx );
2032                             phys = PhylogenyMethods.readPhylogenies( nhx, file );
2033                             nhx_or_nexus = true;
2034                         }
2035                         catch ( final Exception e ) {
2036                             exception = true;
2037                             exceptionOccuredDuringOpenFile( e );
2038                         }
2039                     }
2040                     else if ( _open_filechooser.getFileFilter() == MainFrameApplication.xmlfilter ) {
2041                         warnIfNotPhyloXmlValidation( getConfiguration() );
2042                         try {
2043                             final PhyloXmlParser xml_parser = createPhyloXmlParser();
2044                             phys = PhylogenyMethods.readPhylogenies( xml_parser, file );
2045                         }
2046                         catch ( final Exception e ) {
2047                             exception = true;
2048                             exceptionOccuredDuringOpenFile( e );
2049                         }
2050                     }
2051                     else if ( _open_filechooser.getFileFilter() == MainFrameApplication.tolfilter ) {
2052                         try {
2053                             phys = PhylogenyMethods.readPhylogenies( new TolParser(), file );
2054                         }
2055                         catch ( final Exception e ) {
2056                             exception = true;
2057                             exceptionOccuredDuringOpenFile( e );
2058                         }
2059                     }
2060                     else if ( _open_filechooser.getFileFilter() == MainFrameApplication.nexusfilter ) {
2061                         try {
2062                             final NexusPhylogeniesParser nex = new NexusPhylogeniesParser();
2063                             setSpecialOptionsForNexParser( nex );
2064                             phys = PhylogenyMethods.readPhylogenies( nex, file );
2065                             nhx_or_nexus = true;
2066                         }
2067                         catch ( final Exception e ) {
2068                             exception = true;
2069                             exceptionOccuredDuringOpenFile( e );
2070                         }
2071                     }
2072                     // "*.*":
2073                     else {
2074                         try {
2075                             final PhylogenyParser parser = ParserUtils
2076                                     .createParserDependingOnFileType( file, getConfiguration()
2077                                             .isValidatePhyloXmlAgainstSchema() );
2078                             if ( parser instanceof NexusPhylogeniesParser ) {
2079                                 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
2080                                 setSpecialOptionsForNexParser( nex );
2081                                 nhx_or_nexus = true;
2082                             }
2083                             else if ( parser instanceof NHXParser ) {
2084                                 final NHXParser nhx = ( NHXParser ) parser;
2085                                 setSpecialOptionsForNhxParser( nhx );
2086                                 nhx_or_nexus = true;
2087                             }
2088                             else if ( parser instanceof PhyloXmlParser ) {
2089                                 warnIfNotPhyloXmlValidation( getConfiguration() );
2090                             }
2091                             phys = PhylogenyMethods.readPhylogenies( parser, file );
2092                         }
2093                         catch ( final Exception e ) {
2094                             exception = true;
2095                             exceptionOccuredDuringOpenFile( e );
2096                         }
2097                     }
2098                     if ( _mainpanel.getCurrentTreePanel() != null ) {
2099                         _mainpanel.getCurrentTreePanel().setArrowCursor();
2100                     }
2101                     else {
2102                         _mainpanel.setArrowCursor();
2103                     }
2104                     if ( !exception && ( phys != null ) && ( phys.length > 0 ) ) {
2105                         boolean one_desc = false;
2106                         if ( nhx_or_nexus ) {
2107                             for( final Phylogeny phy : phys ) {
2108                                 if ( getOptions().isInternalNumberAreConfidenceForNhParsing() ) {
2109                                     PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
2110                                 }
2111                                 if ( PhylogenyMethods.getMinimumDescendentsPerInternalNodes( phy ) == 1 ) {
2112                                     one_desc = true;
2113                                     break;
2114                                 }
2115                             }
2116                         }
2117                         AptxUtil.addPhylogeniesToTabs( phys,
2118                                                        file.getName(),
2119                                                        file.getAbsolutePath(),
2120                                                        getConfiguration(),
2121                                                        getMainPanel() );
2122                         _mainpanel.getControlPanel().showWhole();
2123                         if ( nhx_or_nexus && one_desc ) {
2124                             JOptionPane
2125                                     .showMessageDialog( this,
2126                                                         "One or more trees contain (a) node(s) with one descendant, "
2127                                                                 + ForesterUtil.LINE_SEPARATOR
2128                                                                 + "possibly indicating illegal parentheses within node names.",
2129                                                         "Warning: Possible Error in New Hampshire Formatted Data",
2130                                                         JOptionPane.WARNING_MESSAGE );
2131                         }
2132                     }
2133                 }
2134             }
2135         }
2136         activateSaveAllIfNeeded();
2137         System.gc();
2138     }
2139
2140     private void readSpeciesTreeFromFile() {
2141         Phylogeny t = null;
2142         boolean exception = false;
2143         final File my_dir = getCurrentDir();
2144         _open_filechooser_for_species_tree.setSelectedFile( new File( "" ) );
2145         if ( my_dir != null ) {
2146             _open_filechooser_for_species_tree.setCurrentDirectory( my_dir );
2147         }
2148         final int result = _open_filechooser_for_species_tree.showOpenDialog( _contentpane );
2149         final File file = _open_filechooser_for_species_tree.getSelectedFile();
2150         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2151             if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrameApplication.xmlfilter ) {
2152                 try {
2153                     final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( PhyloXmlParser
2154                             .createPhyloXmlParserXsdValidating(), file );
2155                     t = trees[ 0 ];
2156                 }
2157                 catch ( final Exception e ) {
2158                     exception = true;
2159                     exceptionOccuredDuringOpenFile( e );
2160                 }
2161             }
2162             else if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrameApplication.tolfilter ) {
2163                 try {
2164                     final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( new TolParser(), file );
2165                     t = trees[ 0 ];
2166                 }
2167                 catch ( final Exception e ) {
2168                     exception = true;
2169                     exceptionOccuredDuringOpenFile( e );
2170                 }
2171             }
2172             // "*.*":
2173             else {
2174                 try {
2175                     final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( PhyloXmlParser
2176                             .createPhyloXmlParserXsdValidating(), file );
2177                     t = trees[ 0 ];
2178                 }
2179                 catch ( final Exception e ) {
2180                     exception = true;
2181                     exceptionOccuredDuringOpenFile( e );
2182                 }
2183             }
2184             if ( !exception && ( t != null ) && !t.isRooted() ) {
2185                 exception = true;
2186                 t = null;
2187                 JOptionPane.showMessageDialog( this,
2188                                                "Species tree is not rooted",
2189                                                "Species tree not loaded",
2190                                                JOptionPane.ERROR_MESSAGE );
2191             }
2192             if ( !exception && ( t != null ) ) {
2193                 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
2194                 for( final PhylogenyNodeIterator it = t.iteratorExternalForward(); it.hasNext(); ) {
2195                     final PhylogenyNode node = it.next();
2196                     if ( !node.getNodeData().isHasTaxonomy() ) {
2197                         exception = true;
2198                         t = null;
2199                         JOptionPane
2200                                 .showMessageDialog( this,
2201                                                     "Species tree contains external node(s) without taxonomy information",
2202                                                     "Species tree not loaded",
2203                                                     JOptionPane.ERROR_MESSAGE );
2204                         break;
2205                     }
2206                     else {
2207                         if ( tax_set.contains( node.getNodeData().getTaxonomy() ) ) {
2208                             exception = true;
2209                             t = null;
2210                             JOptionPane.showMessageDialog( this,
2211                                                            "Taxonomy ["
2212                                                                    + node.getNodeData().getTaxonomy().asSimpleText()
2213                                                                    + "] is not unique in species tree",
2214                                                            "Species tree not loaded",
2215                                                            JOptionPane.ERROR_MESSAGE );
2216                             break;
2217                         }
2218                         else {
2219                             tax_set.add( node.getNodeData().getTaxonomy() );
2220                         }
2221                     }
2222                 }
2223             }
2224             if ( !exception && ( t != null ) ) {
2225                 setSpeciesTree( t );
2226                 JOptionPane.showMessageDialog( this,
2227                                                "Species tree successfully loaded",
2228                                                "Species tree loaded",
2229                                                JOptionPane.INFORMATION_MESSAGE );
2230             }
2231             _contentpane.repaint();
2232             System.gc();
2233         }
2234     }
2235
2236     private void setArrowCursor() {
2237         try {
2238             _mainpanel.getCurrentTreePanel().setArrowCursor();
2239         }
2240         catch ( final Exception ex ) {
2241             // Do nothing.
2242         }
2243     }
2244
2245     private void setCurrentDir( final File current_dir ) {
2246         _current_dir = current_dir;
2247     }
2248
2249     private void setMinNotCollapseConfidenceValue( final double min_not_collapse ) {
2250         _min_not_collapse = min_not_collapse;
2251     }
2252
2253     private void setPhylogeneticInferenceOptions( final PhylogeneticInferenceOptions phylogenetic_inference_options ) {
2254         _phylogenetic_inference_options = phylogenetic_inference_options;
2255     }
2256
2257     private void setSpecialOptionsForNexParser( final NexusPhylogeniesParser nex ) {
2258         nex.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() );
2259         nex.setTaxonomyExtraction( getOptions().getTaxonomyExtraction() );
2260     }
2261
2262     private void setSpecialOptionsForNhxParser( final NHXParser nhx ) {
2263         nhx.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() );
2264         nhx.setTaxonomyExtraction( getOptions().getTaxonomyExtraction() );
2265         nhx.setAllowErrorsInDistanceToParent( getOptions().isAllowErrorsInDistanceToParent() );
2266     }
2267
2268     private void writeAllToFile() {
2269         if ( ( getMainPanel().getTabbedPane() == null ) || ( getMainPanel().getTabbedPane().getTabCount() < 1 ) ) {
2270             return;
2271         }
2272         final File my_dir = getCurrentDir();
2273         if ( my_dir != null ) {
2274             _save_filechooser.setCurrentDirectory( my_dir );
2275         }
2276         _save_filechooser.setSelectedFile( new File( "" ) );
2277         final int result = _save_filechooser.showSaveDialog( _contentpane );
2278         final File file = _save_filechooser.getSelectedFile();
2279         setCurrentDir( _save_filechooser.getCurrentDirectory() );
2280         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2281             if ( file.exists() ) {
2282                 final int i = JOptionPane.showConfirmDialog( this,
2283                                                              file + " already exists. Overwrite?",
2284                                                              "Warning",
2285                                                              JOptionPane.OK_CANCEL_OPTION,
2286                                                              JOptionPane.WARNING_MESSAGE );
2287                 if ( i != JOptionPane.OK_OPTION ) {
2288                     return;
2289                 }
2290                 else {
2291                     try {
2292                         file.delete();
2293                     }
2294                     catch ( final Exception e ) {
2295                         JOptionPane.showMessageDialog( this,
2296                                                        "Failed to delete: " + file,
2297                                                        "Error",
2298                                                        JOptionPane.WARNING_MESSAGE );
2299                     }
2300                 }
2301             }
2302             final int count = getMainPanel().getTabbedPane().getTabCount();
2303             final List<Phylogeny> trees = new ArrayList<Phylogeny>();
2304             for( int i = 0; i < count; ++i ) {
2305                 final Phylogeny phy = getMainPanel().getPhylogeny( i );
2306                 if ( ForesterUtil.isEmpty( phy.getName() )
2307                         && !ForesterUtil.isEmpty( getMainPanel().getTabbedPane().getTitleAt( i ) ) ) {
2308                     phy.setName( getMainPanel().getTabbedPane().getTitleAt( i ) );
2309                 }
2310                 trees.add( phy );
2311                 getMainPanel().getTreePanels().get( i ).setEdited( false );
2312             }
2313             final PhylogenyWriter writer = new PhylogenyWriter();
2314             try {
2315                 writer.toPhyloXML( file, trees, 0, ForesterUtil.LINE_SEPARATOR );
2316             }
2317             catch ( final IOException e ) {
2318                 JOptionPane.showMessageDialog( this,
2319                                                "Failed to write to: " + file,
2320                                                "Error",
2321                                                JOptionPane.WARNING_MESSAGE );
2322             }
2323         }
2324     }
2325
2326     private boolean writeAsNewHampshire( final Phylogeny t, boolean exception, final File file ) {
2327         try {
2328             final PhylogenyWriter writer = new PhylogenyWriter();
2329             writer.toNewHampshire( t, false, true, getOptions().getNhConversionSupportValueStyle(), file );
2330         }
2331         catch ( final Exception e ) {
2332             exception = true;
2333             exceptionOccuredDuringSaveAs( e );
2334         }
2335         return exception;
2336     }
2337
2338     private boolean writeAsNexus( final Phylogeny t, boolean exception, final File file ) {
2339         try {
2340             final PhylogenyWriter writer = new PhylogenyWriter();
2341             writer.toNexus( file, t, getOptions().getNhConversionSupportValueStyle() );
2342         }
2343         catch ( final Exception e ) {
2344             exception = true;
2345             exceptionOccuredDuringSaveAs( e );
2346         }
2347         return exception;
2348     }
2349
2350     private boolean writeAsPhyloXml( final Phylogeny t, boolean exception, final File file ) {
2351         try {
2352             final PhylogenyWriter writer = new PhylogenyWriter();
2353             writer.toPhyloXML( file, t, 0 );
2354         }
2355         catch ( final Exception e ) {
2356             exception = true;
2357             exceptionOccuredDuringSaveAs( e );
2358         }
2359         return exception;
2360     }
2361
2362     private void writeToFile( final Phylogeny t ) {
2363         if ( t == null ) {
2364             return;
2365         }
2366         String initial_filename = null;
2367         if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) {
2368             try {
2369                 initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().getCanonicalPath();
2370             }
2371             catch ( final IOException e ) {
2372                 initial_filename = null;
2373             }
2374         }
2375         if ( !ForesterUtil.isEmpty( initial_filename ) ) {
2376             _save_filechooser.setSelectedFile( new File( initial_filename ) );
2377         }
2378         else {
2379             _save_filechooser.setSelectedFile( new File( "" ) );
2380         }
2381         final File my_dir = getCurrentDir();
2382         if ( my_dir != null ) {
2383             _save_filechooser.setCurrentDirectory( my_dir );
2384         }
2385         final int result = _save_filechooser.showSaveDialog( _contentpane );
2386         final File file = _save_filechooser.getSelectedFile();
2387         setCurrentDir( _save_filechooser.getCurrentDirectory() );
2388         boolean exception = false;
2389         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2390             if ( file.exists() ) {
2391                 final int i = JOptionPane.showConfirmDialog( this,
2392                                                              file + " already exists.\nOverwrite?",
2393                                                              "Overwrite?",
2394                                                              JOptionPane.OK_CANCEL_OPTION,
2395                                                              JOptionPane.QUESTION_MESSAGE );
2396                 if ( i != JOptionPane.OK_OPTION ) {
2397                     return;
2398                 }
2399                 else {
2400                     final File to = new File( file.getAbsoluteFile().toString() + Constants.BACKUP_FILE_SUFFIX );
2401                     try {
2402                         ForesterUtil.copyFile( file, to );
2403                     }
2404                     catch ( final Exception e ) {
2405                         JOptionPane.showMessageDialog( this,
2406                                                        "Failed to create backup copy " + to,
2407                                                        "Failed to Create Backup Copy",
2408                                                        JOptionPane.WARNING_MESSAGE );
2409                     }
2410                     try {
2411                         file.delete();
2412                     }
2413                     catch ( final Exception e ) {
2414                         JOptionPane.showMessageDialog( this,
2415                                                        "Failed to delete: " + file,
2416                                                        "Failed to Delete",
2417                                                        JOptionPane.WARNING_MESSAGE );
2418                     }
2419                 }
2420             }
2421             if ( _save_filechooser.getFileFilter() == MainFrameApplication.nhfilter ) {
2422                 exception = writeAsNewHampshire( t, exception, file );
2423             }
2424             else if ( _save_filechooser.getFileFilter() == MainFrameApplication.xmlfilter ) {
2425                 exception = writeAsPhyloXml( t, exception, file );
2426             }
2427             else if ( _save_filechooser.getFileFilter() == MainFrameApplication.nexusfilter ) {
2428                 exception = writeAsNexus( t, exception, file );
2429             }
2430             // "*.*":
2431             else {
2432                 final String file_name = file.getName().trim().toLowerCase();
2433                 if ( file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2434                         || file_name.endsWith( ".tree" ) ) {
2435                     exception = writeAsNewHampshire( t, exception, file );
2436                 }
2437                 else if ( file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) ) {
2438                     exception = writeAsNexus( t, exception, file );
2439                 }
2440                 // XML is default:
2441                 else {
2442                     exception = writeAsPhyloXml( t, exception, file );
2443                 }
2444             }
2445             if ( !exception ) {
2446                 getMainPanel().setTitleOfSelectedTab( file.getName() );
2447                 getMainPanel().getCurrentTreePanel().setTreeFile( file );
2448                 getMainPanel().getCurrentTreePanel().setEdited( false );
2449             }
2450         }
2451     }
2452
2453     private void writeToGraphicsFile( final Phylogeny t, final GraphicsExportType type ) {
2454         if ( ( t == null ) || t.isEmpty() ) {
2455             return;
2456         }
2457         String initial_filename = "";
2458         if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) {
2459             initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().toString();
2460         }
2461         if ( initial_filename.indexOf( '.' ) > 0 ) {
2462             initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) );
2463         }
2464         initial_filename = initial_filename + "." + type;
2465         _writetographics_filechooser.setSelectedFile( new File( initial_filename ) );
2466         final File my_dir = getCurrentDir();
2467         if ( my_dir != null ) {
2468             _writetographics_filechooser.setCurrentDirectory( my_dir );
2469         }
2470         final int result = _writetographics_filechooser.showSaveDialog( _contentpane );
2471         File file = _writetographics_filechooser.getSelectedFile();
2472         setCurrentDir( _writetographics_filechooser.getCurrentDirectory() );
2473         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2474             if ( !file.toString().toLowerCase().endsWith( type.toString() ) ) {
2475                 file = new File( file.toString() + "." + type );
2476             }
2477             if ( file.exists() ) {
2478                 final int i = JOptionPane.showConfirmDialog( this,
2479                                                              file + " already exists. Overwrite?",
2480                                                              "Warning",
2481                                                              JOptionPane.OK_CANCEL_OPTION,
2482                                                              JOptionPane.WARNING_MESSAGE );
2483                 if ( i != JOptionPane.OK_OPTION ) {
2484                     return;
2485                 }
2486                 else {
2487                     try {
2488                         file.delete();
2489                     }
2490                     catch ( final Exception e ) {
2491                         JOptionPane.showMessageDialog( this,
2492                                                        "Failed to delete: " + file,
2493                                                        "Error",
2494                                                        JOptionPane.WARNING_MESSAGE );
2495                     }
2496                 }
2497             }
2498             writePhylogenyToGraphicsFile( file.toString(), type );
2499         }
2500     }
2501
2502     private void writeToPdf( final Phylogeny t ) {
2503         if ( ( t == null ) || t.isEmpty() ) {
2504             return;
2505         }
2506         String initial_filename = "";
2507         if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) {
2508             initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().toString();
2509         }
2510         if ( initial_filename.indexOf( '.' ) > 0 ) {
2511             initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) );
2512         }
2513         initial_filename = initial_filename + ".pdf";
2514         _writetopdf_filechooser.setSelectedFile( new File( initial_filename ) );
2515         final File my_dir = getCurrentDir();
2516         if ( my_dir != null ) {
2517             _writetopdf_filechooser.setCurrentDirectory( my_dir );
2518         }
2519         final int result = _writetopdf_filechooser.showSaveDialog( _contentpane );
2520         File file = _writetopdf_filechooser.getSelectedFile();
2521         setCurrentDir( _writetopdf_filechooser.getCurrentDirectory() );
2522         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2523             if ( !file.toString().toLowerCase().endsWith( ".pdf" ) ) {
2524                 file = new File( file.toString() + ".pdf" );
2525             }
2526             if ( file.exists() ) {
2527                 final int i = JOptionPane.showConfirmDialog( this,
2528                                                              file + " already exists. Overwrite?",
2529                                                              "WARNING",
2530                                                              JOptionPane.OK_CANCEL_OPTION,
2531                                                              JOptionPane.WARNING_MESSAGE );
2532                 if ( i != JOptionPane.OK_OPTION ) {
2533                     return;
2534                 }
2535             }
2536             printPhylogenyToPdf( file.toString() );
2537         }
2538     }
2539
2540     public static MainFrameApplication createInstance( final Phylogeny[] phys, final Configuration config ) {
2541         return new MainFrameApplication( phys, config );
2542     }
2543
2544     public static MainFrame createInstance( final Phylogeny[] phys,
2545                                             final Configuration config,
2546                                             final String title,
2547                                             final File current_dir ) {
2548         return new MainFrameApplication( phys, config, title, current_dir );
2549     }
2550
2551     static MainFrame createInstance( final Phylogeny[] phys, final Configuration config, final String title ) {
2552         return new MainFrameApplication( phys, config, title );
2553     }
2554
2555     static MainFrame createInstance( final Phylogeny[] phys, final String config_file_name, final String title ) {
2556         return new MainFrameApplication( phys, config_file_name, title );
2557     }
2558
2559     static void setTextForGraphicsSizeChooserMenuItem( final JMenuItem mi, final Options o ) {
2560         mi.setText( "Enter Default Size for Graphics Export... (current: " + o.getPrintSizeX() + ", "
2561                 + o.getPrintSizeY() + ")" );
2562     }
2563
2564     static void setTextForPdfLineWidthChooserMenuItem( final JMenuItem mi, final Options o ) {
2565         mi.setText( "Enter Default Line Width for PDF Export... (current: " + o.getPrintLineWidth() + ")" );
2566     }
2567
2568     static void warnIfNotPhyloXmlValidation( final Configuration c ) {
2569         if ( !c.isValidatePhyloXmlAgainstSchema() ) {
2570             JOptionPane
2571                     .showMessageDialog( null,
2572                                         ForesterUtil
2573                                                 .wordWrap( "phyloXML XSD-based validation is turned off [enable with line 'validate_against_phyloxml_xsd_schem: true' in configuration file]",
2574                                                            80 ),
2575                                         "Warning",
2576                                         JOptionPane.WARNING_MESSAGE );
2577         }
2578     }
2579 } // MainFrameApplication.
2580
2581 class DefaultFilter extends FileFilter {
2582
2583     @Override
2584     public boolean accept( final File f ) {
2585         final String file_name = f.getName().trim().toLowerCase();
2586         return file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2587                 || file_name.endsWith( ".nwk" ) || file_name.endsWith( ".phb" ) || file_name.endsWith( ".ph" )
2588                 || file_name.endsWith( ".tr" ) || file_name.endsWith( ".dnd" ) || file_name.endsWith( ".tree" )
2589                 || file_name.endsWith( ".nhx" ) || file_name.endsWith( ".xml" ) || file_name.endsWith( ".phyloxml" )
2590                 || file_name.endsWith( "phylo.xml" ) || file_name.endsWith( ".pxml" ) || file_name.endsWith( ".nexus" )
2591                 || file_name.endsWith( ".nx" ) || file_name.endsWith( ".nex" ) || file_name.endsWith( ".tre" )
2592                 || file_name.endsWith( ".zip" ) || file_name.endsWith( ".tol" ) || file_name.endsWith( ".tolxml" )
2593                 || file_name.endsWith( ".con" ) || f.isDirectory();
2594     }
2595
2596     @Override
2597     public String getDescription() {
2598         return "All supported files (*.xml, *.phyloxml, *phylo.xml, *.nhx, *.nh, *.newick, *.nex, *.nexus, *.phy, *.tre, *.tree, *.tol, ...)";
2599     }
2600 }
2601
2602 class GraphicsFileFilter extends FileFilter {
2603
2604     @Override
2605     public boolean accept( final File f ) {
2606         final String file_name = f.getName().trim().toLowerCase();
2607         return file_name.endsWith( ".jpg" ) || file_name.endsWith( ".jpeg" ) || file_name.endsWith( ".png" )
2608                 || file_name.endsWith( ".gif" ) || file_name.endsWith( ".bmp" ) || f.isDirectory();
2609     }
2610
2611     @Override
2612     public String getDescription() {
2613         return "Image files (*.jpg, *.jpeg, *.png, *.gif, *.bmp)";
2614     }
2615 }
2616
2617 class MsaFileFilter extends FileFilter {
2618
2619     @Override
2620     public boolean accept( final File f ) {
2621         final String file_name = f.getName().trim().toLowerCase();
2622         return file_name.endsWith( ".msa" ) || file_name.endsWith( ".aln" ) || file_name.endsWith( ".fasta" )
2623                 || file_name.endsWith( ".fas" ) || file_name.endsWith( ".fa" ) || f.isDirectory();
2624     }
2625
2626     @Override
2627     public String getDescription() {
2628         return "Multiple sequence alignment files (*.msa, *.aln, *.fasta, *.fa, *.fas)";
2629     }
2630 }
2631
2632 class NexusFilter extends FileFilter {
2633
2634     @Override
2635     public boolean accept( final File f ) {
2636         final String file_name = f.getName().trim().toLowerCase();
2637         return file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) || file_name.endsWith( ".nx" )
2638                 || file_name.endsWith( ".tre" ) || f.isDirectory();
2639     }
2640
2641     @Override
2642     public String getDescription() {
2643         return "Nexus files (*.nex, *.nexus, *.nx, *.tre)";
2644     }
2645 } // NexusFilter
2646
2647 class NHFilter extends FileFilter {
2648
2649     @Override
2650     public boolean accept( final File f ) {
2651         final String file_name = f.getName().trim().toLowerCase();
2652         return file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2653                 || file_name.endsWith( ".tr" ) || file_name.endsWith( ".tree" ) || file_name.endsWith( ".dnd" )
2654                 || file_name.endsWith( ".ph" ) || file_name.endsWith( ".phb" ) || file_name.endsWith( ".nwk" )
2655                 || f.isDirectory();
2656     }
2657
2658     @Override
2659     public String getDescription() {
2660         return "New Hampshire - Newick files (*.nh, *.newick, *.phy, *.tree, *.dnd, *.tr, *.ph, *.phb, *.nwk)";
2661     }
2662 } // NHFilter
2663
2664 class NHXFilter extends FileFilter {
2665
2666     @Override
2667     public boolean accept( final File f ) {
2668         final String file_name = f.getName().trim().toLowerCase();
2669         return file_name.endsWith( ".nhx" ) || f.isDirectory();
2670     }
2671
2672     @Override
2673     public String getDescription() {
2674         return "NHX files (*.nhx) [deprecated]";
2675     }
2676 }
2677
2678 class PdfFilter extends FileFilter {
2679
2680     @Override
2681     public boolean accept( final File f ) {
2682         return f.getName().trim().toLowerCase().endsWith( ".pdf" ) || f.isDirectory();
2683     }
2684
2685     @Override
2686     public String getDescription() {
2687         return "PDF files (*.pdf)";
2688     }
2689 } // PdfFilter
2690
2691 class SequencesFileFilter extends FileFilter {
2692
2693     @Override
2694     public boolean accept( final File f ) {
2695         final String file_name = f.getName().trim().toLowerCase();
2696         return file_name.endsWith( ".fasta" ) || file_name.endsWith( ".fa" ) || file_name.endsWith( ".fas" )
2697                 || file_name.endsWith( ".seqs" ) || f.isDirectory();
2698     }
2699
2700     @Override
2701     public String getDescription() {
2702         return "Sequences files (*.fasta, *.fa, *.fas, *.seqs )";
2703     }
2704 }
2705
2706 class TolFilter extends FileFilter {
2707
2708     @Override
2709     public boolean accept( final File f ) {
2710         final String file_name = f.getName().trim().toLowerCase();
2711         return ( file_name.endsWith( ".tol" ) || file_name.endsWith( ".tolxml" ) || file_name.endsWith( ".zip" ) || f
2712                 .isDirectory() ) && ( !file_name.endsWith( ".xml.zip" ) );
2713     }
2714
2715     @Override
2716     public String getDescription() {
2717         return "Tree of Life files (*.tol, *.tolxml)";
2718     }
2719 } // TolFilter
2720
2721 class XMLFilter extends FileFilter {
2722
2723     @Override
2724     public boolean accept( final File f ) {
2725         final String file_name = f.getName().trim().toLowerCase();
2726         return file_name.endsWith( ".xml" ) || file_name.endsWith( ".phyloxml" ) || file_name.endsWith( "phylo.xml" )
2727                 || file_name.endsWith( ".pxml" ) || file_name.endsWith( ".zip" ) || f.isDirectory();
2728     }
2729
2730     @Override
2731     public String getDescription() {
2732         return "phyloXML files (*.xml, *.phyloxml, *phylo.xml, *.pxml, *.zip)";
2733     }
2734 } // XMLFilter