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