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