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