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