a6e256971f04c21fcc64bde1bc89a8a2fdac5f24
[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.WindowsUtils;
98 import org.forester.util.ForesterUtil.PhylogenyNodeField;
99 import org.forester.util.ForesterUtil.TAXONOMY_EXTRACTION;
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, _mainpanel.getCurrentTreePanel(), _mainpanel
1102                 .getCurrentPhylogeny() );
1103         new Thread( a ).start();
1104     }
1105
1106     void executeLineageInference() {
1107         if ( ( _mainpanel.getCurrentPhylogeny() == null ) || ( _mainpanel.getCurrentPhylogeny().isEmpty() ) ) {
1108             return;
1109         }
1110         if ( !_mainpanel.getCurrentPhylogeny().isRooted() ) {
1111             JOptionPane.showMessageDialog( this,
1112                                            "Phylogeny is not rooted.",
1113                                            "Cannot infer ancestral taxonomies",
1114                                            JOptionPane.ERROR_MESSAGE );
1115             return;
1116         }
1117         final Phylogeny phy = _mainpanel.getCurrentPhylogeny().copy();
1118         final AncestralTaxonomyInferrer inferrer = new AncestralTaxonomyInferrer( this, _mainpanel
1119                 .getCurrentTreePanel(), phy );
1120         new Thread( inferrer ).start();
1121     }
1122
1123     private void executePhyleneticInference( final boolean from_unaligned_seqs ) {
1124         final PhyloInferenceDialog dialog = new PhyloInferenceDialog( this,
1125                                                                       getPhylogeneticInferenceOptions(),
1126                                                                       from_unaligned_seqs );
1127         dialog.activate();
1128         if ( dialog.getValue() == JOptionPane.OK_OPTION ) {
1129             if ( !from_unaligned_seqs ) {
1130                 if ( getMsa() != null ) {
1131                     final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getMsa(),
1132                                                                                     getPhylogeneticInferenceOptions()
1133                                                                                             .copy(),
1134                                                                                     this );
1135                     new Thread( inferrer ).start();
1136                 }
1137                 else {
1138                     JOptionPane.showMessageDialog( this,
1139                                                    "No multiple sequence alignment selected",
1140                                                    "Phylogenetic Inference Not Launched",
1141                                                    JOptionPane.WARNING_MESSAGE );
1142                 }
1143             }
1144             else {
1145                 if ( getSeqs() != null ) {
1146                     final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getSeqs(),
1147                                                                                     getPhylogeneticInferenceOptions()
1148                                                                                             .copy(),
1149                                                                                     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, _mainpanel.getCurrentTreePanel(), phy
1378                         .copy() );
1379                 new Thread( t ).start();
1380             }
1381         }
1382     }
1383
1384     private void print() {
1385         if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null )
1386                 || getCurrentTreePanel().getPhylogeny().isEmpty() ) {
1387             return;
1388         }
1389         if ( !getOptions().isPrintUsingActualSize() ) {
1390             getCurrentTreePanel().setParametersForPainting( getOptions().getPrintSizeX() - 80,
1391                                                             getOptions().getPrintSizeY() - 140,
1392                                                             true );
1393             getCurrentTreePanel().resetPreferredSize();
1394             getCurrentTreePanel().repaint();
1395         }
1396         final String job_name = Constants.PRG_NAME;
1397         boolean error = false;
1398         String printer_name = null;
1399         try {
1400             printer_name = Printer.print( getCurrentTreePanel(), job_name );
1401         }
1402         catch ( final Exception e ) {
1403             error = true;
1404             JOptionPane.showMessageDialog( this, e.getMessage(), "Printing Error", JOptionPane.ERROR_MESSAGE );
1405         }
1406         if ( !error && ( printer_name != null ) ) {
1407             String msg = "Printing data sent to printer";
1408             if ( printer_name.length() > 1 ) {
1409                 msg += " [" + printer_name + "]";
1410             }
1411             JOptionPane.showMessageDialog( this, msg, "Printing...", JOptionPane.INFORMATION_MESSAGE );
1412         }
1413         if ( !getOptions().isPrintUsingActualSize() ) {
1414             getControlPanel().showWhole();
1415         }
1416     }
1417
1418     private void printPhylogenyToPdf( final String file_name ) {
1419         if ( !getOptions().isPrintUsingActualSize() ) {
1420             getCurrentTreePanel().setParametersForPainting( getOptions().getPrintSizeX(),
1421                                                             getOptions().getPrintSizeY(),
1422                                                             true );
1423             getCurrentTreePanel().resetPreferredSize();
1424             getCurrentTreePanel().repaint();
1425         }
1426         String pdf_written_to = "";
1427         boolean error = false;
1428         try {
1429             if ( getOptions().isPrintUsingActualSize() ) {
1430                 pdf_written_to = PdfExporter.writePhylogenyToPdf( file_name,
1431                                                                   getCurrentTreePanel(),
1432                                                                   getCurrentTreePanel().getWidth(),
1433                                                                   getCurrentTreePanel().getHeight() );
1434             }
1435             else {
1436                 pdf_written_to = PdfExporter.writePhylogenyToPdf( file_name, getCurrentTreePanel(), getOptions()
1437                         .getPrintSizeX(), getOptions().getPrintSizeY() );
1438             }
1439         }
1440         catch ( final IOException e ) {
1441             error = true;
1442             JOptionPane.showMessageDialog( this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE );
1443         }
1444         if ( !error ) {
1445             if ( !ForesterUtil.isEmpty( pdf_written_to ) ) {
1446                 JOptionPane.showMessageDialog( this,
1447                                                "Wrote PDF to: " + pdf_written_to,
1448                                                "Information",
1449                                                JOptionPane.INFORMATION_MESSAGE );
1450             }
1451             else {
1452                 JOptionPane.showMessageDialog( this,
1453                                                "There was an unknown problem when attempting to write to PDF file: \""
1454                                                        + file_name + "\"",
1455                                                "Error",
1456                                                JOptionPane.ERROR_MESSAGE );
1457             }
1458         }
1459         if ( !getOptions().isPrintUsingActualSize() ) {
1460             getControlPanel().showWhole();
1461         }
1462     }
1463
1464     private void addExpressionValuesFromFile() {
1465         if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) ) {
1466             JOptionPane.showMessageDialog( this,
1467                                            "Need to load evolutionary tree first",
1468                                            "Can Not Read Expression Values",
1469                                            JOptionPane.WARNING_MESSAGE );
1470             return;
1471         }
1472         final File my_dir = getCurrentDir();
1473         if ( my_dir != null ) {
1474             _values_filechooser.setCurrentDirectory( my_dir );
1475         }
1476         final int result = _values_filechooser.showOpenDialog( _contentpane );
1477         final File file = _values_filechooser.getSelectedFile();
1478         if ( ( file != null ) && ( file.length() > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
1479             BasicTable<String> t = null;
1480             try {
1481                 t = BasicTableParser.parse( file, "\t" );
1482                 if ( t.getNumberOfColumns() < 2 ) {
1483                     t = BasicTableParser.parse( file, "," );
1484                 }
1485                 if ( t.getNumberOfColumns() < 2 ) {
1486                     t = BasicTableParser.parse( file, " " );
1487                 }
1488             }
1489             catch ( final IOException e ) {
1490                 JOptionPane.showMessageDialog( this,
1491                                                e.getMessage(),
1492                                                "Could Not Read Expression Value Table",
1493                                                JOptionPane.ERROR_MESSAGE );
1494                 return;
1495             }
1496             if ( t.getNumberOfColumns() < 2 ) {
1497                 JOptionPane.showMessageDialog( this,
1498                                                "Table contains " + t.getNumberOfColumns() + " column(s)",
1499                                                "Problem with Expression Value Table",
1500                                                JOptionPane.ERROR_MESSAGE );
1501                 return;
1502             }
1503             if ( t.getNumberOfRows() < 1 ) {
1504                 JOptionPane.showMessageDialog( this,
1505                                                "Table contains zero rows",
1506                                                "Problem with Expression Value Table",
1507                                                JOptionPane.ERROR_MESSAGE );
1508                 return;
1509             }
1510             final Phylogeny phy = getCurrentTreePanel().getPhylogeny();
1511             if ( t.getNumberOfRows() != phy.getNumberOfExternalNodes() ) {
1512                 JOptionPane.showMessageDialog( this,
1513                                                "Table contains " + t.getNumberOfRows() + " rows, but tree contains "
1514                                                        + phy.getNumberOfExternalNodes() + " external nodes",
1515                                                "Warning",
1516                                                JOptionPane.WARNING_MESSAGE );
1517             }
1518             final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
1519             int not_found = 0;
1520             for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1521                 final PhylogenyNode node = iter.next();
1522                 final String node_name = node.getName();
1523                 if ( !ForesterUtil.isEmpty( node_name ) ) {
1524                     int row = -1;
1525                     try {
1526                         row = t.findRow( node_name );
1527                     }
1528                     catch ( final IllegalArgumentException e ) {
1529                         JOptionPane
1530                                 .showMessageDialog( this,
1531                                                     e.getMessage(),
1532                                                     "Error Mapping Node Identifiers to Expression Value Identifiers",
1533                                                     JOptionPane.ERROR_MESSAGE );
1534                         return;
1535                     }
1536                     if ( row < 0 ) {
1537                         if ( node.isExternal() ) {
1538                             not_found++;
1539                         }
1540                         continue;
1541                     }
1542                     final List<Double> l = new ArrayList<Double>();
1543                     for( int col = 1; col < t.getNumberOfColumns(); ++col ) {
1544                         double d = -100;
1545                         try {
1546                             d = Double.parseDouble( t.getValueAsString( col, row ) );
1547                         }
1548                         catch ( final NumberFormatException e ) {
1549                             JOptionPane.showMessageDialog( this,
1550                                                            "Could not parse \"" + t.getValueAsString( col, row )
1551                                                                    + "\" into a decimal value",
1552                                                            "Issue with Expression Value Table",
1553                                                            JOptionPane.ERROR_MESSAGE );
1554                             return;
1555                         }
1556                         stats.addValue( d );
1557                         l.add( d );
1558                     }
1559                     if ( !l.isEmpty() ) {
1560                         if ( node.getNodeData().getProperties() != null ) {
1561                             node.getNodeData().getProperties()
1562                                     .removePropertiesWithGivenReferencePrefix( PhyloXmlUtil.VECTOR_PROPERTY_REF );
1563                         }
1564                         node.getNodeData().setVector( l );
1565                     }
1566                 }
1567             }
1568             if ( not_found > 0 ) {
1569                 JOptionPane.showMessageDialog( this, "Could not fine expression values for " + not_found
1570                         + " external node(s)", "Warning", JOptionPane.WARNING_MESSAGE );
1571             }
1572             getCurrentTreePanel().setStatisticsForExpressionValues( stats );
1573         }
1574     }
1575
1576     private void readPhylogeniesFromFile() {
1577         boolean exception = false;
1578         Phylogeny[] phys = null;
1579         // Set an initial directory if none set yet
1580         final File my_dir = getCurrentDir();
1581         _open_filechooser.setMultiSelectionEnabled( true );
1582         // Open file-open dialog and set current directory
1583         if ( my_dir != null ) {
1584             _open_filechooser.setCurrentDirectory( my_dir );
1585         }
1586         final int result = _open_filechooser.showOpenDialog( _contentpane );
1587         // All done: get the file
1588         final File[] files = _open_filechooser.getSelectedFiles();
1589         setCurrentDir( _open_filechooser.getCurrentDirectory() );
1590         boolean nhx_or_nexus = false;
1591         if ( ( files != null ) && ( files.length > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
1592             for( final File file : files ) {
1593                 if ( ( file != null ) && !file.isDirectory() ) {
1594                     if ( _mainpanel.getCurrentTreePanel() != null ) {
1595                         _mainpanel.getCurrentTreePanel().setWaitCursor();
1596                     }
1597                     else {
1598                         _mainpanel.setWaitCursor();
1599                     }
1600                     if ( ( _open_filechooser.getFileFilter() == MainFrameApplication.nhfilter )
1601                             || ( _open_filechooser.getFileFilter() == MainFrameApplication.nhxfilter ) ) {
1602                         try {
1603                             final NHXParser nhx = new NHXParser();
1604                             setSpecialOptionsForNhxParser( nhx );
1605                             phys = Util.readPhylogenies( nhx, file );
1606                             nhx_or_nexus = true;
1607                         }
1608                         catch ( final Exception e ) {
1609                             exception = true;
1610                             exceptionOccuredDuringOpenFile( e );
1611                         }
1612                     }
1613                     else if ( _open_filechooser.getFileFilter() == MainFrameApplication.xmlfilter ) {
1614                         warnIfNotPhyloXmlValidation( getConfiguration() );
1615                         try {
1616                             final PhyloXmlParser xml_parser = createPhyloXmlParser();
1617                             phys = Util.readPhylogenies( xml_parser, file );
1618                         }
1619                         catch ( final Exception e ) {
1620                             exception = true;
1621                             exceptionOccuredDuringOpenFile( e );
1622                         }
1623                     }
1624                     else if ( _open_filechooser.getFileFilter() == MainFrameApplication.tolfilter ) {
1625                         try {
1626                             phys = Util.readPhylogenies( new TolParser(), file );
1627                         }
1628                         catch ( final Exception e ) {
1629                             exception = true;
1630                             exceptionOccuredDuringOpenFile( e );
1631                         }
1632                     }
1633                     else if ( _open_filechooser.getFileFilter() == MainFrameApplication.nexusfilter ) {
1634                         try {
1635                             final NexusPhylogeniesParser nex = new NexusPhylogeniesParser();
1636                             setSpecialOptionsForNexParser( nex );
1637                             phys = Util.readPhylogenies( nex, file );
1638                             nhx_or_nexus = true;
1639                         }
1640                         catch ( final Exception e ) {
1641                             exception = true;
1642                             exceptionOccuredDuringOpenFile( e );
1643                         }
1644                     }
1645                     // "*.*":
1646                     else {
1647                         try {
1648                             final PhylogenyParser parser = ForesterUtil
1649                                     .createParserDependingOnFileType( file, getConfiguration()
1650                                             .isValidatePhyloXmlAgainstSchema() );
1651                             if ( parser instanceof NexusPhylogeniesParser ) {
1652                                 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
1653                                 setSpecialOptionsForNexParser( nex );
1654                                 nhx_or_nexus = true;
1655                             }
1656                             else if ( parser instanceof NHXParser ) {
1657                                 final NHXParser nhx = ( NHXParser ) parser;
1658                                 setSpecialOptionsForNhxParser( nhx );
1659                                 nhx_or_nexus = true;
1660                             }
1661                             else if ( parser instanceof PhyloXmlParser ) {
1662                                 warnIfNotPhyloXmlValidation( getConfiguration() );
1663                             }
1664                             phys = Util.readPhylogenies( parser, file );
1665                         }
1666                         catch ( final Exception e ) {
1667                             exception = true;
1668                             exceptionOccuredDuringOpenFile( e );
1669                         }
1670                     }
1671                     if ( _mainpanel.getCurrentTreePanel() != null ) {
1672                         _mainpanel.getCurrentTreePanel().setArrowCursor();
1673                     }
1674                     else {
1675                         _mainpanel.setArrowCursor();
1676                     }
1677                     if ( !exception && ( phys != null ) && ( phys.length > 0 ) ) {
1678                         boolean one_desc = false;
1679                         if ( nhx_or_nexus ) {
1680                             for( final Phylogeny phy : phys ) {
1681                                 if ( getOptions().isInternalNumberAreConfidenceForNhParsing() ) {
1682                                     ForesterUtil.transferInternalNodeNamesToConfidence( phy );
1683                                 }
1684                                 if ( PhylogenyMethods.getMinimumDescendentsPerInternalNodes( phy ) == 1 ) {
1685                                     one_desc = true;
1686                                     break;
1687                                 }
1688                             }
1689                         }
1690                         Util.addPhylogeniesToTabs( phys,
1691                                                    file.getName(),
1692                                                    file.getAbsolutePath(),
1693                                                    getConfiguration(),
1694                                                    getMainPanel() );
1695                         _mainpanel.getControlPanel().showWhole();
1696                         if ( nhx_or_nexus && one_desc ) {
1697                             JOptionPane
1698                                     .showMessageDialog( this,
1699                                                         "One or more trees contain (a) node(s) with one descendant, "
1700                                                                 + ForesterUtil.LINE_SEPARATOR
1701                                                                 + "possibly indicating illegal parentheses within node names.",
1702                                                         "Warning: Possible Error in New Hampshire Formatted Data",
1703                                                         JOptionPane.WARNING_MESSAGE );
1704                         }
1705                     }
1706                 }
1707             }
1708         }
1709         activateSaveAllIfNeeded();
1710         System.gc();
1711     }
1712
1713     void readSeqsFromFile() {
1714         // Set an initial directory if none set yet
1715         final File my_dir = getCurrentDir();
1716         _seqs_filechooser.setMultiSelectionEnabled( false );
1717         // Open file-open dialog and set current directory
1718         if ( my_dir != null ) {
1719             _seqs_filechooser.setCurrentDirectory( my_dir );
1720         }
1721         final int result = _seqs_filechooser.showOpenDialog( _contentpane );
1722         // All done: get the seqs
1723         final File file = _seqs_filechooser.getSelectedFile();
1724         setCurrentDir( _seqs_filechooser.getCurrentDirectory() );
1725         if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) {
1726             setSeqsFile( null );
1727             setSeqs( null );
1728             List<Sequence> seqs = null;
1729             try {
1730                 if ( FastaParser.isLikelyFasta( new FileInputStream( file ) ) ) {
1731                     seqs = FastaParser.parse( new FileInputStream( file ) );
1732                     for( final Sequence seq : seqs ) {
1733                         System.out.println( SequenceWriter.toFasta( seq, 60 ) );
1734                     }
1735                 }
1736                 else {
1737                     //TODO error
1738                 }
1739             }
1740             catch ( final MsaFormatException e ) {
1741                 try {
1742                     _mainpanel.getCurrentTreePanel().setArrowCursor();
1743                 }
1744                 catch ( final Exception ex ) {
1745                     // Do nothing.
1746                 }
1747                 JOptionPane.showMessageDialog( this,
1748                                                e.getLocalizedMessage(),
1749                                                "Multiple sequence file format error",
1750                                                JOptionPane.ERROR_MESSAGE );
1751                 return;
1752             }
1753             catch ( final IOException e ) {
1754                 try {
1755                     _mainpanel.getCurrentTreePanel().setArrowCursor();
1756                 }
1757                 catch ( final Exception ex ) {
1758                     // Do nothing.
1759                 }
1760                 JOptionPane.showMessageDialog( this,
1761                                                e.getLocalizedMessage(),
1762                                                "Failed to read multiple sequence file",
1763                                                JOptionPane.ERROR_MESSAGE );
1764                 return;
1765             }
1766             catch ( final IllegalArgumentException e ) {
1767                 try {
1768                     _mainpanel.getCurrentTreePanel().setArrowCursor();
1769                 }
1770                 catch ( final Exception ex ) {
1771                     // Do nothing.
1772                 }
1773                 JOptionPane.showMessageDialog( this,
1774                                                e.getLocalizedMessage(),
1775                                                "Unexpected error during reading of multiple sequence file",
1776                                                JOptionPane.ERROR_MESSAGE );
1777                 return;
1778             }
1779             catch ( final Exception e ) {
1780                 try {
1781                     _mainpanel.getCurrentTreePanel().setArrowCursor();
1782                 }
1783                 catch ( final Exception ex ) {
1784                     // Do nothing.
1785                 }
1786                 e.printStackTrace();
1787                 JOptionPane.showMessageDialog( this,
1788                                                e.getLocalizedMessage(),
1789                                                "Unexpected error during reading of multiple sequence file",
1790                                                JOptionPane.ERROR_MESSAGE );
1791                 return;
1792             }
1793             if ( ( seqs == null ) || ( seqs.size() < 1 ) ) {
1794                 JOptionPane.showMessageDialog( this,
1795                                                "Multiple sequence file is empty",
1796                                                "Illegal multiple sequence file",
1797                                                JOptionPane.ERROR_MESSAGE );
1798                 return;
1799             }
1800             if ( seqs.size() < 4 ) {
1801                 JOptionPane.showMessageDialog( this,
1802                                                "Multiple sequence file needs to contain at least 3 sequences",
1803                                                "Illegal multiple sequence file",
1804                                                JOptionPane.ERROR_MESSAGE );
1805                 return;
1806             }
1807             //  if ( msa.getLength() < 2 ) {
1808             //       JOptionPane.showMessageDialog( this,
1809             //                                      "Multiple sequence alignment needs to contain at least 2 residues",
1810             //                                      "Illegal multiple sequence file",
1811             //                                      JOptionPane.ERROR_MESSAGE );
1812             //       return;
1813             //   }
1814             System.gc();
1815             setSeqsFile( _seqs_filechooser.getSelectedFile() );
1816             setSeqs( seqs );
1817         }
1818     }
1819
1820     void readMsaFromFile() {
1821         // Set an initial directory if none set yet
1822         final File my_dir = getCurrentDir();
1823         _msa_filechooser.setMultiSelectionEnabled( false );
1824         // Open file-open dialog and set current directory
1825         if ( my_dir != null ) {
1826             _msa_filechooser.setCurrentDirectory( my_dir );
1827         }
1828         final int result = _msa_filechooser.showOpenDialog( _contentpane );
1829         // All done: get the msa
1830         final File file = _msa_filechooser.getSelectedFile();
1831         setCurrentDir( _msa_filechooser.getCurrentDirectory() );
1832         if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) {
1833             setMsaFile( null );
1834             setMsa( null );
1835             Msa msa = null;
1836             try {
1837                 if ( FastaParser.isLikelyFasta( new FileInputStream( file ) ) ) {
1838                     msa = FastaParser.parseMsa( new FileInputStream( file ) );
1839                     System.out.println( msa.toString() );
1840                 }
1841                 else {
1842                     msa = GeneralMsaParser.parse( new FileInputStream( file ) );
1843                 }
1844             }
1845             catch ( final MsaFormatException e ) {
1846                 try {
1847                     _mainpanel.getCurrentTreePanel().setArrowCursor();
1848                 }
1849                 catch ( final Exception ex ) {
1850                     // Do nothing.
1851                 }
1852                 JOptionPane.showMessageDialog( this,
1853                                                e.getLocalizedMessage(),
1854                                                "Multiple sequence alignment format error",
1855                                                JOptionPane.ERROR_MESSAGE );
1856                 return;
1857             }
1858             catch ( final IOException e ) {
1859                 try {
1860                     _mainpanel.getCurrentTreePanel().setArrowCursor();
1861                 }
1862                 catch ( final Exception ex ) {
1863                     // Do nothing.
1864                 }
1865                 JOptionPane.showMessageDialog( this,
1866                                                e.getLocalizedMessage(),
1867                                                "Failed to read multiple sequence alignment",
1868                                                JOptionPane.ERROR_MESSAGE );
1869                 return;
1870             }
1871             catch ( final IllegalArgumentException e ) {
1872                 try {
1873                     _mainpanel.getCurrentTreePanel().setArrowCursor();
1874                 }
1875                 catch ( final Exception ex ) {
1876                     // Do nothing.
1877                 }
1878                 JOptionPane.showMessageDialog( this,
1879                                                e.getLocalizedMessage(),
1880                                                "Unexpected error during reading of multiple sequence alignment",
1881                                                JOptionPane.ERROR_MESSAGE );
1882                 return;
1883             }
1884             catch ( final Exception e ) {
1885                 try {
1886                     _mainpanel.getCurrentTreePanel().setArrowCursor();
1887                 }
1888                 catch ( final Exception ex ) {
1889                     // Do nothing.
1890                 }
1891                 e.printStackTrace();
1892                 JOptionPane.showMessageDialog( this,
1893                                                e.getLocalizedMessage(),
1894                                                "Unexpected error during reading of multiple sequence alignment",
1895                                                JOptionPane.ERROR_MESSAGE );
1896                 return;
1897             }
1898             if ( ( msa == null ) || ( msa.getNumberOfSequences() < 1 ) ) {
1899                 JOptionPane.showMessageDialog( this,
1900                                                "Multiple sequence alignment is empty",
1901                                                "Illegal Multiple Sequence Alignment",
1902                                                JOptionPane.ERROR_MESSAGE );
1903                 return;
1904             }
1905             if ( msa.getNumberOfSequences() < 4 ) {
1906                 JOptionPane.showMessageDialog( this,
1907                                                "Multiple sequence alignment needs to contain at least 3 sequences",
1908                                                "Illegal multiple sequence alignment",
1909                                                JOptionPane.ERROR_MESSAGE );
1910                 return;
1911             }
1912             if ( msa.getLength() < 2 ) {
1913                 JOptionPane.showMessageDialog( this,
1914                                                "Multiple sequence alignment needs to contain at least 2 residues",
1915                                                "Illegal multiple sequence alignment",
1916                                                JOptionPane.ERROR_MESSAGE );
1917                 return;
1918             }
1919             System.gc();
1920             setMsaFile( _msa_filechooser.getSelectedFile() );
1921             setMsa( msa );
1922         }
1923     }
1924
1925     @Override
1926     void readPhylogeniesFromURL() {
1927         URL url = null;
1928         Phylogeny[] phys = null;
1929         final String message = "Please enter a complete URL, for example \"http://www.phyloxml.org/examples/apaf.xml\"";
1930         final String url_string = JOptionPane.showInputDialog( this,
1931                                                                message,
1932                                                                "Use URL/webservice to obtain a phylogeny",
1933                                                                JOptionPane.QUESTION_MESSAGE );
1934         boolean nhx_or_nexus = false;
1935         if ( ( url_string != null ) && ( url_string.length() > 0 ) ) {
1936             try {
1937                 url = new URL( url_string );
1938                 PhylogenyParser parser = null;
1939                 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
1940                     parser = new TolParser();
1941                 }
1942                 else {
1943                     parser = ForesterUtil.createParserDependingOnUrlContents( url, getConfiguration()
1944                             .isValidatePhyloXmlAgainstSchema() );
1945                 }
1946                 if ( parser instanceof NexusPhylogeniesParser ) {
1947                     nhx_or_nexus = true;
1948                 }
1949                 else if ( parser instanceof NHXParser ) {
1950                     nhx_or_nexus = true;
1951                 }
1952                 if ( _mainpanel.getCurrentTreePanel() != null ) {
1953                     _mainpanel.getCurrentTreePanel().setWaitCursor();
1954                 }
1955                 else {
1956                     _mainpanel.setWaitCursor();
1957                 }
1958                 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
1959                 phys = factory.create( url.openStream(), parser );
1960             }
1961             catch ( final MalformedURLException e ) {
1962                 JOptionPane.showMessageDialog( this,
1963                                                "Malformed URL: " + url + "\n" + e.getLocalizedMessage(),
1964                                                "Malformed URL",
1965                                                JOptionPane.ERROR_MESSAGE );
1966             }
1967             catch ( final IOException e ) {
1968                 JOptionPane.showMessageDialog( this,
1969                                                "Could not read from " + url + "\n"
1970                                                        + ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ),
1971                                                "Failed to read URL",
1972                                                JOptionPane.ERROR_MESSAGE );
1973             }
1974             catch ( final Exception e ) {
1975                 JOptionPane.showMessageDialog( this,
1976                                                ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ),
1977                                                "Unexpected Exception",
1978                                                JOptionPane.ERROR_MESSAGE );
1979             }
1980             finally {
1981                 if ( _mainpanel.getCurrentTreePanel() != null ) {
1982                     _mainpanel.getCurrentTreePanel().setArrowCursor();
1983                 }
1984                 else {
1985                     _mainpanel.setArrowCursor();
1986                 }
1987             }
1988             if ( ( phys != null ) && ( phys.length > 0 ) ) {
1989                 if ( nhx_or_nexus && getOptions().isInternalNumberAreConfidenceForNhParsing() ) {
1990                     for( final Phylogeny phy : phys ) {
1991                         ForesterUtil.transferInternalNodeNamesToConfidence( phy );
1992                     }
1993                 }
1994                 Util.addPhylogeniesToTabs( phys, new File( url.getFile() ).getName(), new File( url.getFile() )
1995                         .toString(), getConfiguration(), getMainPanel() );
1996                 _mainpanel.getControlPanel().showWhole();
1997             }
1998         }
1999         activateSaveAllIfNeeded();
2000         System.gc();
2001     }
2002
2003     private void readSpeciesTreeFromFile() {
2004         Phylogeny t = null;
2005         boolean exception = false;
2006         final File my_dir = getCurrentDir();
2007         _open_filechooser_for_species_tree.setSelectedFile( new File( "" ) );
2008         if ( my_dir != null ) {
2009             _open_filechooser_for_species_tree.setCurrentDirectory( my_dir );
2010         }
2011         final int result = _open_filechooser_for_species_tree.showOpenDialog( _contentpane );
2012         final File file = _open_filechooser_for_species_tree.getSelectedFile();
2013         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2014             if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrameApplication.xmlfilter ) {
2015                 try {
2016                     final Phylogeny[] trees = Util.readPhylogenies( new PhyloXmlParser(), file );
2017                     t = trees[ 0 ];
2018                 }
2019                 catch ( final Exception e ) {
2020                     exception = true;
2021                     exceptionOccuredDuringOpenFile( e );
2022                 }
2023             }
2024             else if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrameApplication.tolfilter ) {
2025                 try {
2026                     final Phylogeny[] trees = Util.readPhylogenies( new TolParser(), file );
2027                     t = trees[ 0 ];
2028                 }
2029                 catch ( final Exception e ) {
2030                     exception = true;
2031                     exceptionOccuredDuringOpenFile( e );
2032                 }
2033             }
2034             // "*.*":
2035             else {
2036                 try {
2037                     final Phylogeny[] trees = Util.readPhylogenies( new PhyloXmlParser(), file );
2038                     t = trees[ 0 ];
2039                 }
2040                 catch ( final Exception e ) {
2041                     exception = true;
2042                     exceptionOccuredDuringOpenFile( e );
2043                 }
2044             }
2045             if ( !exception && ( t != null ) && !t.isRooted() ) {
2046                 exception = true;
2047                 t = null;
2048                 JOptionPane.showMessageDialog( this,
2049                                                "Species tree is not rooted",
2050                                                "Species tree not loaded",
2051                                                JOptionPane.ERROR_MESSAGE );
2052             }
2053             if ( !exception && ( t != null ) ) {
2054                 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
2055                 for( final PhylogenyNodeIterator it = t.iteratorExternalForward(); it.hasNext(); ) {
2056                     final PhylogenyNode node = it.next();
2057                     if ( !node.getNodeData().isHasTaxonomy() ) {
2058                         exception = true;
2059                         t = null;
2060                         JOptionPane
2061                                 .showMessageDialog( this,
2062                                                     "Species tree contains external node(s) without taxonomy information",
2063                                                     "Species tree not loaded",
2064                                                     JOptionPane.ERROR_MESSAGE );
2065                         break;
2066                     }
2067                     else {
2068                         if ( tax_set.contains( node.getNodeData().getTaxonomy() ) ) {
2069                             exception = true;
2070                             t = null;
2071                             JOptionPane.showMessageDialog( this,
2072                                                            "Taxonomy ["
2073                                                                    + node.getNodeData().getTaxonomy().asSimpleText()
2074                                                                    + "] is not unique in species tree",
2075                                                            "Species tree not loaded",
2076                                                            JOptionPane.ERROR_MESSAGE );
2077                             break;
2078                         }
2079                         else {
2080                             tax_set.add( node.getNodeData().getTaxonomy() );
2081                         }
2082                     }
2083                 }
2084             }
2085             if ( !exception && ( t != null ) ) {
2086                 _species_tree = t;
2087                 JOptionPane.showMessageDialog( this,
2088                                                "Species tree successfully loaded",
2089                                                "Species tree loaded",
2090                                                JOptionPane.INFORMATION_MESSAGE );
2091             }
2092             _contentpane.repaint();
2093             System.gc();
2094         }
2095     }
2096
2097     private void setCurrentDir( final File current_dir ) {
2098         _current_dir = current_dir;
2099     }
2100
2101     private void setMinNotCollapseConfidenceValue( final double min_not_collapse ) {
2102         _min_not_collapse = min_not_collapse;
2103     }
2104
2105     private void setSpecialOptionsForNexParser( final NexusPhylogeniesParser nex ) {
2106         nex.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() );
2107     }
2108
2109     private void setSpecialOptionsForNhxParser( final NHXParser nhx ) {
2110         nhx.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() );
2111         ForesterUtil.TAXONOMY_EXTRACTION te = ForesterUtil.TAXONOMY_EXTRACTION.NO;
2112         if ( getOptions().isExtractPfamTaxonomyCodesInNhParsing() ) {
2113             te = ForesterUtil.TAXONOMY_EXTRACTION.YES;
2114         }
2115         nhx.setTaxonomyExtraction( te );
2116     }
2117
2118     private void writeAllToFile() {
2119         if ( ( getMainPanel().getTabbedPane() == null ) || ( getMainPanel().getTabbedPane().getTabCount() < 1 ) ) {
2120             return;
2121         }
2122         final File my_dir = getCurrentDir();
2123         if ( my_dir != null ) {
2124             _save_filechooser.setCurrentDirectory( my_dir );
2125         }
2126         _save_filechooser.setSelectedFile( new File( "" ) );
2127         final int result = _save_filechooser.showSaveDialog( _contentpane );
2128         final File file = _save_filechooser.getSelectedFile();
2129         setCurrentDir( _save_filechooser.getCurrentDirectory() );
2130         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2131             if ( file.exists() ) {
2132                 final int i = JOptionPane.showConfirmDialog( this,
2133                                                              file + " already exists. Overwrite?",
2134                                                              "Warning",
2135                                                              JOptionPane.OK_CANCEL_OPTION,
2136                                                              JOptionPane.WARNING_MESSAGE );
2137                 if ( i != JOptionPane.OK_OPTION ) {
2138                     return;
2139                 }
2140                 else {
2141                     try {
2142                         file.delete();
2143                     }
2144                     catch ( final Exception e ) {
2145                         JOptionPane.showMessageDialog( this,
2146                                                        "Failed to delete: " + file,
2147                                                        "Error",
2148                                                        JOptionPane.WARNING_MESSAGE );
2149                     }
2150                 }
2151             }
2152             final int count = getMainPanel().getTabbedPane().getTabCount();
2153             final List<Phylogeny> trees = new ArrayList<Phylogeny>();
2154             for( int i = 0; i < count; ++i ) {
2155                 trees.add( getMainPanel().getPhylogeny( i ) );
2156                 getMainPanel().getTreePanels().get( i ).setEdited( false );
2157             }
2158             final PhylogenyWriter writer = new PhylogenyWriter();
2159             try {
2160                 writer.toPhyloXML( file, trees, 0, ForesterUtil.LINE_SEPARATOR );
2161             }
2162             catch ( final IOException e ) {
2163                 JOptionPane.showMessageDialog( this,
2164                                                "Failed to write to: " + file,
2165                                                "Error",
2166                                                JOptionPane.WARNING_MESSAGE );
2167             }
2168         }
2169     }
2170
2171     private boolean writeAsNewHampshire( final Phylogeny t, boolean exception, final File file ) {
2172         try {
2173             final PhylogenyWriter writer = new PhylogenyWriter();
2174             writer.toNewHampshire( t, false, true, file );
2175         }
2176         catch ( final Exception e ) {
2177             exception = true;
2178             exceptionOccuredDuringSaveAs( e );
2179         }
2180         return exception;
2181     }
2182
2183     private boolean writeAsNexus( final Phylogeny t, boolean exception, final File file ) {
2184         try {
2185             final PhylogenyWriter writer = new PhylogenyWriter();
2186             writer.toNexus( file, t );
2187         }
2188         catch ( final Exception e ) {
2189             exception = true;
2190             exceptionOccuredDuringSaveAs( e );
2191         }
2192         return exception;
2193     }
2194
2195     private boolean writeAsNHX( final Phylogeny t, boolean exception, final File file ) {
2196         try {
2197             final PhylogenyWriter writer = new PhylogenyWriter();
2198             writer.toNewHampshireX( t, file );
2199         }
2200         catch ( final Exception e ) {
2201             exception = true;
2202             exceptionOccuredDuringSaveAs( e );
2203         }
2204         return exception;
2205     }
2206
2207     private boolean writeAsPhyloXml( final Phylogeny t, boolean exception, final File file ) {
2208         try {
2209             final PhylogenyWriter writer = new PhylogenyWriter();
2210             writer.toPhyloXML( file, t, 0 );
2211         }
2212         catch ( final Exception e ) {
2213             exception = true;
2214             exceptionOccuredDuringSaveAs( e );
2215         }
2216         return exception;
2217     }
2218
2219     private void writePhylogenyToGraphicsFile( final String file_name, final GraphicsExportType type ) {
2220         _mainpanel.getCurrentTreePanel().setParametersForPainting( _mainpanel.getCurrentTreePanel().getWidth(),
2221                                                                    _mainpanel.getCurrentTreePanel().getHeight(),
2222                                                                    true );
2223         String file_written_to = "";
2224         boolean error = false;
2225         try {
2226             file_written_to = Util.writePhylogenyToGraphicsFile( file_name,
2227                                                                  _mainpanel.getCurrentTreePanel().getWidth(),
2228                                                                  _mainpanel.getCurrentTreePanel().getHeight(),
2229                                                                  _mainpanel.getCurrentTreePanel(),
2230                                                                  _mainpanel.getControlPanel(),
2231                                                                  type,
2232                                                                  getOptions() );
2233         }
2234         catch ( final IOException e ) {
2235             error = true;
2236             JOptionPane.showMessageDialog( this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE );
2237         }
2238         if ( !error ) {
2239             if ( ( file_written_to != null ) && ( file_written_to.length() > 0 ) ) {
2240                 JOptionPane.showMessageDialog( this,
2241                                                "Wrote image to: " + file_written_to,
2242                                                "Graphics Export",
2243                                                JOptionPane.INFORMATION_MESSAGE );
2244             }
2245             else {
2246                 JOptionPane.showMessageDialog( this,
2247                                                "There was an unknown problem when attempting to write to an image file: \""
2248                                                        + file_name + "\"",
2249                                                "Error",
2250                                                JOptionPane.ERROR_MESSAGE );
2251             }
2252         }
2253         _contentpane.repaint();
2254     }
2255
2256     private void writeToFile( final Phylogeny t ) {
2257         if ( t == null ) {
2258             return;
2259         }
2260         String initial_filename = null;
2261         if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) {
2262             try {
2263                 initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().getCanonicalPath();
2264             }
2265             catch ( final IOException e ) {
2266                 initial_filename = null;
2267             }
2268         }
2269         if ( !ForesterUtil.isEmpty( initial_filename ) ) {
2270             _save_filechooser.setSelectedFile( new File( initial_filename ) );
2271         }
2272         else {
2273             _save_filechooser.setSelectedFile( new File( "" ) );
2274         }
2275         final File my_dir = getCurrentDir();
2276         if ( my_dir != null ) {
2277             _save_filechooser.setCurrentDirectory( my_dir );
2278         }
2279         final int result = _save_filechooser.showSaveDialog( _contentpane );
2280         final File file = _save_filechooser.getSelectedFile();
2281         setCurrentDir( _save_filechooser.getCurrentDirectory() );
2282         boolean exception = false;
2283         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2284             if ( file.exists() ) {
2285                 final int i = JOptionPane.showConfirmDialog( this,
2286                                                              file + " already exists.\nOverwrite?",
2287                                                              "Overwrite?",
2288                                                              JOptionPane.OK_CANCEL_OPTION,
2289                                                              JOptionPane.QUESTION_MESSAGE );
2290                 if ( i != JOptionPane.OK_OPTION ) {
2291                     return;
2292                 }
2293                 else {
2294                     final File to = new File( file.getAbsoluteFile().toString() + Constants.BACKUP_FILE_SUFFIX );
2295                     try {
2296                         ForesterUtil.copyFile( file, to );
2297                     }
2298                     catch ( final Exception e ) {
2299                         JOptionPane.showMessageDialog( this,
2300                                                        "Failed to create backup copy " + to,
2301                                                        "Failed to Create Backup Copy",
2302                                                        JOptionPane.WARNING_MESSAGE );
2303                     }
2304                     try {
2305                         file.delete();
2306                     }
2307                     catch ( final Exception e ) {
2308                         JOptionPane.showMessageDialog( this,
2309                                                        "Failed to delete: " + file,
2310                                                        "Failed to Delete",
2311                                                        JOptionPane.WARNING_MESSAGE );
2312                     }
2313                 }
2314             }
2315             if ( _save_filechooser.getFileFilter() == MainFrameApplication.nhfilter ) {
2316                 exception = writeAsNewHampshire( t, exception, file );
2317             }
2318             else if ( _save_filechooser.getFileFilter() == MainFrameApplication.nhxfilter ) {
2319                 exception = writeAsNHX( t, exception, file );
2320             }
2321             else if ( _save_filechooser.getFileFilter() == MainFrameApplication.xmlfilter ) {
2322                 exception = writeAsPhyloXml( t, exception, file );
2323             }
2324             else if ( _save_filechooser.getFileFilter() == MainFrameApplication.nexusfilter ) {
2325                 exception = writeAsNexus( t, exception, file );
2326             }
2327             // "*.*":
2328             else {
2329                 final String file_name = file.getName().trim().toLowerCase();
2330                 if ( file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2331                         || file_name.endsWith( ".tree" ) ) {
2332                     exception = writeAsNewHampshire( t, exception, file );
2333                 }
2334                 else if ( file_name.endsWith( ".nhx" ) ) {
2335                     exception = writeAsNHX( t, exception, file );
2336                 }
2337                 else if ( file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) ) {
2338                     exception = writeAsNexus( t, exception, file );
2339                 }
2340                 // XML is default:
2341                 else {
2342                     exception = writeAsPhyloXml( t, exception, file );
2343                 }
2344             }
2345             if ( !exception ) {
2346                 getMainPanel().getCurrentTreePanel().setTreeFile( file );
2347                 getMainPanel().getCurrentTreePanel().setEdited( false );
2348             }
2349         }
2350     }
2351
2352     private void writeToGraphicsFile( final Phylogeny t, final GraphicsExportType type ) {
2353         if ( ( t == null ) || t.isEmpty() ) {
2354             return;
2355         }
2356         String initial_filename = "";
2357         if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) {
2358             initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().toString();
2359         }
2360         if ( initial_filename.indexOf( '.' ) > 0 ) {
2361             initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) );
2362         }
2363         initial_filename = initial_filename + "." + type;
2364         _writetographics_filechooser.setSelectedFile( new File( initial_filename ) );
2365         final File my_dir = getCurrentDir();
2366         if ( my_dir != null ) {
2367             _writetographics_filechooser.setCurrentDirectory( my_dir );
2368         }
2369         final int result = _writetographics_filechooser.showSaveDialog( _contentpane );
2370         File file = _writetographics_filechooser.getSelectedFile();
2371         setCurrentDir( _writetographics_filechooser.getCurrentDirectory() );
2372         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2373             if ( !file.toString().toLowerCase().endsWith( type.toString() ) ) {
2374                 file = new File( file.toString() + "." + type );
2375             }
2376             if ( file.exists() ) {
2377                 final int i = JOptionPane.showConfirmDialog( this,
2378                                                              file + " already exists. Overwrite?",
2379                                                              "Warning",
2380                                                              JOptionPane.OK_CANCEL_OPTION,
2381                                                              JOptionPane.WARNING_MESSAGE );
2382                 if ( i != JOptionPane.OK_OPTION ) {
2383                     return;
2384                 }
2385                 else {
2386                     try {
2387                         file.delete();
2388                     }
2389                     catch ( final Exception e ) {
2390                         JOptionPane.showMessageDialog( this,
2391                                                        "Failed to delete: " + file,
2392                                                        "Error",
2393                                                        JOptionPane.WARNING_MESSAGE );
2394                     }
2395                 }
2396             }
2397             writePhylogenyToGraphicsFile( file.toString(), type );
2398         }
2399     }
2400
2401     private void writeToPdf( final Phylogeny t ) {
2402         if ( ( t == null ) || t.isEmpty() ) {
2403             return;
2404         }
2405         String initial_filename = "";
2406         if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) {
2407             initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().toString();
2408         }
2409         if ( initial_filename.indexOf( '.' ) > 0 ) {
2410             initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) );
2411         }
2412         initial_filename = initial_filename + ".pdf";
2413         _writetopdf_filechooser.setSelectedFile( new File( initial_filename ) );
2414         final File my_dir = getCurrentDir();
2415         if ( my_dir != null ) {
2416             _writetopdf_filechooser.setCurrentDirectory( my_dir );
2417         }
2418         final int result = _writetopdf_filechooser.showSaveDialog( _contentpane );
2419         File file = _writetopdf_filechooser.getSelectedFile();
2420         setCurrentDir( _writetopdf_filechooser.getCurrentDirectory() );
2421         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2422             if ( !file.toString().toLowerCase().endsWith( ".pdf" ) ) {
2423                 file = new File( file.toString() + ".pdf" );
2424             }
2425             if ( file.exists() ) {
2426                 final int i = JOptionPane.showConfirmDialog( this,
2427                                                              file + " already exists. Overwrite?",
2428                                                              "WARNING",
2429                                                              JOptionPane.OK_CANCEL_OPTION,
2430                                                              JOptionPane.WARNING_MESSAGE );
2431                 if ( i != JOptionPane.OK_OPTION ) {
2432                     return;
2433                 }
2434             }
2435             printPhylogenyToPdf( file.toString() );
2436         }
2437     }
2438
2439     static MainFrame createInstance( final Phylogeny[] phys, final Configuration config, final String title ) {
2440         return new MainFrameApplication( phys, config, title );
2441     }
2442
2443     static MainFrame createInstance( final Phylogeny[] phys, final String config_file_name, final String title ) {
2444         return new MainFrameApplication( phys, config_file_name, title );
2445     }
2446
2447     static void setTextForGraphicsSizeChooserMenuItem( final JMenuItem mi, final Options o ) {
2448         mi.setText( "Enter Default Size for Graphics Export... (current: " + o.getPrintSizeX() + ", "
2449                 + o.getPrintSizeY() + ")" );
2450     }
2451
2452     static void setTextForPdfLineWidthChooserMenuItem( final JMenuItem mi, final Options o ) {
2453         mi.setText( "Enter Default Line Width for PDF Export... (current: " + o.getPrintLineWidth() + ")" );
2454     }
2455
2456     static void warnIfNotPhyloXmlValidation( final Configuration c ) {
2457         if ( !c.isValidatePhyloXmlAgainstSchema() ) {
2458             JOptionPane
2459                     .showMessageDialog( null,
2460                                         ForesterUtil
2461                                                 .wordWrap( "phyloXML XSD-based validation is turned off [enable with line 'validate_against_phyloxml_xsd_schem: true' in configuration file]",
2462                                                            80 ),
2463                                         "Warning",
2464                                         JOptionPane.WARNING_MESSAGE );
2465         }
2466     }
2467
2468     private void setPhylogeneticInferenceOptions( final PhylogeneticInferenceOptions phylogenetic_inference_options ) {
2469         _phylogenetic_inference_options = phylogenetic_inference_options;
2470     }
2471
2472     private PhylogeneticInferenceOptions getPhylogeneticInferenceOptions() {
2473         if ( _phylogenetic_inference_options == null ) {
2474             _phylogenetic_inference_options = new PhylogeneticInferenceOptions();
2475         }
2476         return _phylogenetic_inference_options;
2477     }
2478
2479     Msa getMsa() {
2480         return _msa;
2481     }
2482
2483     void setMsa( final Msa msa ) {
2484         _msa = msa;
2485     }
2486
2487     void setMsaFile( final File msa_file ) {
2488         _msa_file = msa_file;
2489     }
2490
2491     File getMsaFile() {
2492         return _msa_file;
2493     }
2494
2495     List<Sequence> getSeqs() {
2496         return _seqs;
2497     }
2498
2499     void setSeqs( final List<Sequence> seqs ) {
2500         _seqs = seqs;
2501     }
2502
2503     void setSeqsFile( final File seqs_file ) {
2504         _seqs_file = seqs_file;
2505     }
2506
2507     File getSeqsFile() {
2508         return _seqs_file;
2509     }
2510 } // MainFrameApplication.
2511
2512 class NexusFilter extends FileFilter {
2513
2514     @Override
2515     public boolean accept( final File f ) {
2516         final String file_name = f.getName().trim().toLowerCase();
2517         return file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) || file_name.endsWith( ".nx" )
2518                 || file_name.endsWith( ".tre" ) || f.isDirectory();
2519     }
2520
2521     @Override
2522     public String getDescription() {
2523         return "Nexus files (*.nex, *.nexus, *.nx, *.tre)";
2524     }
2525 } // NexusFilter
2526
2527 class NHFilter extends FileFilter {
2528
2529     @Override
2530     public boolean accept( final File f ) {
2531         final String file_name = f.getName().trim().toLowerCase();
2532         return file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2533                 || file_name.endsWith( ".tr" ) || file_name.endsWith( ".tree" ) || file_name.endsWith( ".dnd" )
2534                 || file_name.endsWith( ".ph" ) || file_name.endsWith( ".phb" ) || file_name.endsWith( ".nwk" )
2535                 || f.isDirectory();
2536     }
2537
2538     @Override
2539     public String getDescription() {
2540         return "New Hampshire - Newick files (*.nh, *.newick, *.phy, *.tree, *.dnd, *.tr, *.ph, *.phb, *.nwk)";
2541     }
2542 } // NHFilter
2543
2544 class NHXFilter extends FileFilter {
2545
2546     @Override
2547     public boolean accept( final File f ) {
2548         final String file_name = f.getName().trim().toLowerCase();
2549         return file_name.endsWith( ".nhx" ) || f.isDirectory();
2550     }
2551
2552     @Override
2553     public String getDescription() {
2554         return "NHX files (*.nhx)";
2555     }
2556 }
2557
2558 class PdfFilter extends FileFilter {
2559
2560     @Override
2561     public boolean accept( final File f ) {
2562         return f.getName().trim().toLowerCase().endsWith( ".pdf" ) || f.isDirectory();
2563     }
2564
2565     @Override
2566     public String getDescription() {
2567         return "PDF files (*.pdf)";
2568     }
2569 } // PdfFilter
2570
2571 class TolFilter extends FileFilter {
2572
2573     @Override
2574     public boolean accept( final File f ) {
2575         final String file_name = f.getName().trim().toLowerCase();
2576         return ( file_name.endsWith( ".tol" ) || file_name.endsWith( ".tolxml" ) || file_name.endsWith( ".zip" ) || f
2577                 .isDirectory() )
2578                 && ( !file_name.endsWith( ".xml.zip" ) );
2579     }
2580
2581     @Override
2582     public String getDescription() {
2583         return "Tree of Life files (*.tol, *.tolxml)";
2584     }
2585 } // TolFilter
2586
2587 class XMLFilter extends FileFilter {
2588
2589     @Override
2590     public boolean accept( final File f ) {
2591         final String file_name = f.getName().trim().toLowerCase();
2592         return file_name.endsWith( ".xml" ) || file_name.endsWith( ".phyloxml" ) || file_name.endsWith( "phylo.xml" )
2593                 || file_name.endsWith( ".pxml" ) || file_name.endsWith( ".zip" ) || f.isDirectory();
2594     }
2595
2596     @Override
2597     public String getDescription() {
2598         return "phyloXML files (*.xml, *.phyloxml, *phylo.xml, *.pxml, *.zip)";
2599     }
2600 } // XMLFilter