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