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