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