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