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