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