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