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