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