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