in progress
[jalview.git] / forester / java / src / org / forester / archaeopteryx / MainFrame.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2008-2010 Christian M. Zmasek
6 // All rights reserved
7 //
8 // This library is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU Lesser General Public
10 // License as published by the Free Software Foundation; either
11 // version 2.1 of the License, or (at your option) any later version.
12 //
13 // This library is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // Lesser General Public License for more details.
17 //
18 // You should have received a copy of the GNU Lesser General Public
19 // License along with this library; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
21 //
22 // Contact: phylosoft @ gmail . com
23 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
24
25 package org.forester.archaeopteryx;
26
27 import java.awt.Color;
28 import java.awt.Component;
29 import java.awt.Container;
30 import java.awt.Font;
31 import java.awt.event.ActionEvent;
32 import java.awt.event.ActionListener;
33 import java.io.File;
34 import java.io.IOException;
35 import java.util.ArrayList;
36 import java.util.LinkedList;
37 import java.util.List;
38 import java.util.Locale;
39 import java.util.Map;
40 import java.util.NoSuchElementException;
41
42 import javax.swing.Box;
43 import javax.swing.JApplet;
44 import javax.swing.JCheckBoxMenuItem;
45 import javax.swing.JFileChooser;
46 import javax.swing.JFrame;
47 import javax.swing.JLabel;
48 import javax.swing.JMenu;
49 import javax.swing.JMenuBar;
50 import javax.swing.JMenuItem;
51 import javax.swing.JOptionPane;
52 import javax.swing.JPanel;
53 import javax.swing.JRadioButtonMenuItem;
54 import javax.swing.JTextField;
55 import javax.swing.SwingUtilities;
56 import javax.swing.filechooser.FileFilter;
57
58 import org.forester.archaeopteryx.AptxUtil.GraphicsExportType;
59 import org.forester.archaeopteryx.Options.CLADOGRAM_TYPE;
60 import org.forester.archaeopteryx.Options.NODE_LABEL_DIRECTION;
61 import org.forester.archaeopteryx.Options.PHYLOGENY_GRAPHICS_TYPE;
62 import org.forester.archaeopteryx.tools.AncestralTaxonomyInferrer;
63 import org.forester.archaeopteryx.tools.InferenceManager;
64 import org.forester.archaeopteryx.tools.ProcessPool;
65 import org.forester.archaeopteryx.tools.ProcessRunning;
66 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
67 import org.forester.io.writers.PhylogenyWriter;
68 import org.forester.phylogeny.Phylogeny;
69 import org.forester.phylogeny.PhylogenyMethods;
70 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
71 import org.forester.phylogeny.PhylogenyNode;
72 import org.forester.phylogeny.PhylogenyNode.NH_CONVERSION_SUPPORT_VALUE_STYLE;
73 import org.forester.phylogeny.data.Annotation;
74 import org.forester.phylogeny.data.NodeDataField;
75 import org.forester.phylogeny.data.NodeVisualData.NodeFill;
76 import org.forester.phylogeny.data.NodeVisualData.NodeShape;
77 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
78 import org.forester.sdi.GSDI;
79 import org.forester.sdi.GSDIR;
80 import org.forester.sdi.SDIException;
81 import org.forester.util.ForesterConstants;
82 import org.forester.util.ForesterUtil;
83 import org.forester.util.WindowsUtils;
84
85 public abstract class MainFrame extends JFrame implements ActionListener {
86
87     final static NHFilter            nhfilter                                = new NHFilter();
88     final static NHXFilter           nhxfilter                               = new NHXFilter();
89     final static XMLFilter           xmlfilter                               = new XMLFilter();
90     final static TolFilter           tolfilter                               = new TolFilter();
91     final static NexusFilter         nexusfilter                             = new NexusFilter();
92     final static PdfFilter           pdffilter                               = new PdfFilter();
93     final static GraphicsFileFilter  graphicsfilefilter                      = new GraphicsFileFilter();
94     final static MsaFileFilter       msafilter                               = new MsaFileFilter();
95     final static SequencesFileFilter seqsfilter                              = new SequencesFileFilter();
96     final static DefaultFilter       defaultfilter                           = new DefaultFilter();
97     static final String              USE_MOUSEWHEEL_SHIFT_TO_ROTATE          = "rotate with mousewheel + Shift (or A and S), D toggles between horizontal and radial labels";
98     static final String              PHYLOXML_REF_TOOL_TIP                   = AptxConstants.PHYLOXML_REFERENCE;                                                                                                                                                //TODO //FIXME
99     static final String              APTX_REF_TOOL_TIP                       = AptxConstants.APTX_REFERENCE;
100     private static final long        serialVersionUID                        = 3655000897845508358L;
101     final static Font                menu_font                               = new Font( Configuration.getDefaultFontFamilyName(),
102                                                                                          Font.PLAIN,
103                                                                                          10 );
104     static final String              TYPE_MENU_HEADER                        = "Type";
105     static final String              RECTANGULAR_TYPE_CBMI_LABEL             = "Rectangular";
106     static final String              EURO_TYPE_CBMI_LABEL                    = "Euro Type";
107     static final String              CURVED_TYPE_CBMI_LABEL                  = "Curved";
108     static final String              TRIANGULAR_TYPE_CBMI_LABEL              = "Triangular";
109     static final String              CONVEX_TYPE_CBMI_LABEL                  = "Convex";
110     static final String              ROUNDED_TYPE_CBMI_LABEL                 = "Rounded";
111     static final String              UNROOTED_TYPE_CBMI_LABEL                = "Unrooted (alpha)";                                                                                                                                                          //TODO
112     static final String              CIRCULAR_TYPE_CBMI_LABEL                = "Circular (alpha)";                                                                                                                                                          //TODO
113     static final String              OPTIONS_HEADER                          = "Options";
114     static final String              SEARCH_SUBHEADER                        = "Search:";
115     static final String              DISPLAY_SUBHEADER                       = "Display:";
116     static final String              SEARCH_TERMS_ONLY_LABEL                 = "Match Complete Terms Only";
117     static final String              SEARCH_REGEX_LABEL                      = "Search with Regular Expressions";
118     static final String              SEARCH_CASE_SENSITIVE_LABEL             = "Case Sensitive";
119     static final String              INVERSE_SEARCH_RESULT_LABEL             = "Negate Result";
120     static final String              COLOR_BY_TAXONOMIC_GROUP                = "Colorize by Taxonomic Group";
121     static final String              DISPLAY_SCALE_LABEL                     = "Scale";
122     static final String              NON_LINED_UP_CLADOGRAMS_LABEL           = "Non-Lined Up Cladogram";
123     static final String              LABEL_DIRECTION_LABEL                   = "Radial Labels";
124     static final String              LABEL_DIRECTION_TIP                     = "To use radial node labels in radial and unrooted display types";
125     static final String              SEARCH_WITH_REGEX_TIP                   = "To search using regular expressions (~Java/Perl syntax). For example, use \"^B.+\\d{2,}$\" to search for everything starting with a B and ending with at least two digits.";
126     static final String              SCREEN_ANTIALIAS_LABEL                  = "Antialias";
127     static final String              COLOR_LABELS_LABEL                      = "Colorize Labels Same as Parent Branch";
128     static final String              BG_GRAD_LABEL                           = "Background Color Gradient";
129     static final String              DISPLAY_NODE_BOXES_LABEL_EXT            = "Shapes for External Nodes";
130     static final String              DISPLAY_NODE_BOXES_LABEL_INT            = "Shapes for Internal Nodes";
131     static final String              DISPLAY_NODE_BOXES_LABEL_MARKED         = "Shapes for Nodes with Visual Data";
132     static final String              SHOW_OVERVIEW_LABEL                     = "Overview";
133     static final String              FONT_SIZE_MENU_LABEL                    = "Font Size";
134     static final String              NONUNIFORM_CLADOGRAMS_LABEL             = "Lined Up Cladogram";
135     static final String              SHOW_DOMAIN_LABELS_LABEL                = "Domain Labels";
136     static final String              SHOW_ANN_REF_SOURCE_LABEL               = "Seq Annotation Ref Sources";
137     static final String              COLOR_LABELS_TIP                        = "To use parent branch colors for node labels as well, need to turn off taxonomy dependent colorization and turn on branch colorization for this to become apparent";
138     static final String              ABBREV_SN_LABEL                         = "Abbreviate Scientific Taxonomic Names";
139     static final String              TAXONOMY_COLORIZE_NODE_SHAPES_LABEL     = "Colorize Node Shapes According to Taxonomy";
140     static final String              CYCLE_NODE_SHAPE_LABEL                  = "Cycle Node Shapes";
141     static final String              CYCLE_NODE_FILL_LABEL                   = "Cycle Node Fill Type";
142     static final String              CHOOSE_NODE_SIZE_LABEL                  = "Choose Node Shape Size";
143     static final String              SHOW_CONF_STDDEV_LABEL                  = "Confidence Standard Deviations";
144     static final String              USE_BRACKETS_FOR_CONF_IN_NH_LABEL       = "Use Brackets for Confidence Values";
145     static final String              USE_INTERNAL_NAMES_FOR_CONF_IN_NH_LABEL = "Use Internal Node Names for Confidence Values";
146     static final String              SHOW_BASIC_TREE_INFORMATION_LABEL       = "Basic Tree Information";
147     static final String              RIGHT_LINE_UP_DOMAINS                   = "Right-align Domain Architectures";
148     static final String              LINE_UP_RENDERABLE_DATA                 = "Line Up Diagrams (such as Domain Architectures)";
149     static final String              INFER_ANCESTOR_TAXONOMIES               = "Infer Ancestor Taxonomies";
150     static final String              OBTAIN_DETAILED_TAXONOMIC_INFORMATION   = "Obtain Detailed Taxonomic Information";
151     JMenuBar                         _jmenubar;
152     JMenu                            _file_jmenu;
153     JMenu                            _tools_menu;
154     JMenu                            _view_jmenu;
155     JMenu                            _options_jmenu;
156     JMenu                            _font_size_menu;
157     JMenu                            _help_jmenu;
158     JMenuItem[]                      _load_phylogeny_from_webservice_menu_items;
159     // Analysis menu
160     JMenu                            _analysis_menu;
161     JMenuItem                        _load_species_tree_item;
162     JMenuItem                        _gsdi_item;
163     JMenuItem                        _gsdir_item;
164     JMenuItem                        _lineage_inference;
165     // file menu:
166     JMenuItem                        _open_item;
167     JMenuItem                        _open_url_item;
168     JMenuItem                        _save_item;
169     JMenuItem                        _save_all_item;
170     JMenuItem                        _close_item;
171     JMenuItem                        _exit_item;
172     JMenuItem                        _new_item;
173     JMenuItem                        _print_item;
174     JMenuItem                        _write_to_pdf_item;
175     JMenuItem                        _write_to_jpg_item;
176     JMenuItem                        _write_to_gif_item;
177     JMenuItem                        _write_to_tif_item;
178     JMenuItem                        _write_to_png_item;
179     JMenuItem                        _write_to_bmp_item;
180     // tools menu:
181     JMenuItem                        _midpoint_root_item;
182     JMenuItem                        _taxcolor_item;
183     JMenuItem                        _confcolor_item;
184     JMenuItem                        _color_rank_jmi;
185     JMenuItem                        _collapse_species_specific_subtrees;
186     
187     JMenuItem                        _obtain_detailed_taxonomic_information_jmi;
188     JMenuItem                        _obtain_detailed_taxonomic_information_deleting_jmi;
189     JMenuItem                        _obtain_seq_information_jmi;
190     JMenuItem                        _move_node_names_to_tax_sn_jmi;
191     JMenuItem                        _move_node_names_to_seq_names_jmi;
192     JMenuItem                        _extract_tax_code_from_node_names_jmi;
193     JMenuItem                        _annotate_item;
194     JMenuItem                        _remove_branch_color_item;
195     JMenuItem                        _remove_visual_styles_item;
196     JMenuItem                        _delete_selected_nodes_item;
197     JMenuItem                        _delete_not_selected_nodes_item;
198     // font size menu:
199     JMenuItem                        _super_tiny_fonts_item;
200     JMenuItem                        _tiny_fonts_item;
201     JMenuItem                        _small_fonts_item;
202     JMenuItem                        _medium_fonts_item;
203     JMenuItem                        _large_fonts_item;
204     // options menu:
205     // _  screen and print
206     JMenuItem                        _choose_font_mi;
207     JMenuItem                        _switch_colors_mi;
208     JCheckBoxMenuItem                _label_direction_cbmi;
209     // _  screen display
210     JCheckBoxMenuItem                _screen_antialias_cbmi;
211     JCheckBoxMenuItem                _background_gradient_cbmi;
212     JRadioButtonMenuItem             _non_lined_up_cladograms_rbmi;
213     JRadioButtonMenuItem             _ext_node_dependent_cladogram_rbmi;
214     JCheckBoxMenuItem                _color_by_taxonomic_group_cbmi;
215     JCheckBoxMenuItem                _show_scale_cbmi;                                                                                                                                                                                                      //TODO fix me
216     JCheckBoxMenuItem                _show_overview_cbmi;
217     JCheckBoxMenuItem                _show_domain_labels;
218     JCheckBoxMenuItem                _show_annotation_ref_source;
219     JCheckBoxMenuItem                _abbreviate_scientific_names;
220     JCheckBoxMenuItem                _color_labels_same_as_parent_branch;
221     JMenuItem                        _overview_placment_mi;
222     JMenuItem                        _choose_minimal_confidence_mi;
223     JCheckBoxMenuItem                _show_default_node_shapes_internal_cbmi;
224     JCheckBoxMenuItem                _show_default_node_shapes_external_cbmi;
225     JCheckBoxMenuItem                _show_default_node_shapes_for_marked_cbmi;
226     JMenuItem                        _cycle_node_shape_mi;
227     JMenuItem                        _cycle_node_fill_mi;
228     JMenuItem                        _choose_node_size_mi;
229     JMenuItem                        _cycle_data_return;
230     JCheckBoxMenuItem                _show_confidence_stddev_cbmi;
231     JCheckBoxMenuItem                _right_line_up_domains_cbmi;
232     JCheckBoxMenuItem                _line_up_renderable_data_cbmi;
233     JCheckBoxMenuItem                _collapsed_with_average_height_cbmi;
234     // _  print
235     JCheckBoxMenuItem                _graphics_export_visible_only_cbmi;
236     JCheckBoxMenuItem                _antialias_print_cbmi;
237     JCheckBoxMenuItem                _print_black_and_white_cbmi;
238     //JMenuItem                        _print_size_mi;
239     JMenuItem                        _choose_pdf_width_mi;
240     // _  parsing
241     JCheckBoxMenuItem                _internal_number_are_confidence_for_nh_parsing_cbmi;
242     JRadioButtonMenuItem             _extract_taxonomy_no_rbmi;
243     JRadioButtonMenuItem             _extract_taxonomy_agressive_rbmi;
244     JRadioButtonMenuItem             _extract_taxonomy_pfam_strict_rbmi;
245     JRadioButtonMenuItem             _extract_taxonomy_pfam_relaxed_rbmi;
246     JCheckBoxMenuItem                _replace_underscores_cbmi;
247     JCheckBoxMenuItem                _allow_errors_in_distance_to_parent_cbmi;
248     JCheckBoxMenuItem                _use_brackets_for_conf_in_nh_export_cbmi;
249     JCheckBoxMenuItem                _use_internal_names_for_conf_in_nh_export_cbmi;
250     JCheckBoxMenuItem                _parse_beast_style_extended_nexus_tags_cbmi;
251     // _  search
252     JCheckBoxMenuItem                _search_case_senstive_cbmi;
253     JCheckBoxMenuItem                _search_whole_words_only_cbmi;
254     JCheckBoxMenuItem                _inverse_search_result_cbmi;
255     JCheckBoxMenuItem                _search_with_regex_cbmi;
256     JCheckBoxMenuItem                _color_all_found_nodes_when_coloring_subtree_cbmi;
257     // type menu:
258     JMenu                            _type_menu;
259     JCheckBoxMenuItem                _rectangular_type_cbmi;
260     JCheckBoxMenuItem                _triangular_type_cbmi;
261     JCheckBoxMenuItem                _curved_type_cbmi;
262     JCheckBoxMenuItem                _convex_type_cbmi;
263     JCheckBoxMenuItem                _euro_type_cbmi;
264     JCheckBoxMenuItem                _rounded_type_cbmi;
265     JCheckBoxMenuItem                _unrooted_type_cbmi;
266     JCheckBoxMenuItem                _circular_type_cbmi;
267     // view as text menu:
268     JMenuItem                        _view_as_NH_item;
269     JMenuItem                        _view_as_XML_item;
270     JMenuItem                        _view_as_nexus_item;
271     JMenuItem                        _display_basic_information_item;
272     // help menu:
273     JMenuItem                        _about_item;
274     JMenuItem                        _help_item;
275     JMenuItem                        _website_item;
276     JMenuItem                        _mailing_list_item;
277     JMenuItem                        _phyloxml_website_item;
278     JMenuItem                        _phyloxml_ref_item;
279     JMenuItem                        _aptx_ref_item;
280     //
281     File                             _current_dir;
282     JFileChooser                     _writetopdf_filechooser;
283     JFileChooser                     _save_filechooser;
284     JFileChooser                     _writetographics_filechooser;
285     // process menu:
286     JMenu                            _process_menu;
287     MainPanel                        _mainpanel;
288     Container                        _contentpane;
289     final LinkedList<TextFrame>      _textframes                             = new LinkedList<TextFrame>();                                                                                                                                                  ;
290     Configuration                    _configuration;
291     Options                          _options;
292     private Phylogeny                _species_tree;
293     InferenceManager                 _inference_manager;
294     final ProcessPool                _process_pool;
295     private String                   _previous_node_annotation_ref;
296
297     MainFrame() {
298         _process_pool = ProcessPool.createInstance();
299         _writetopdf_filechooser = new JFileChooser();
300         _writetopdf_filechooser.setMultiSelectionEnabled( false );
301         _writetopdf_filechooser.addChoosableFileFilter( pdffilter );
302         _writetographics_filechooser = new JFileChooser();
303         _writetographics_filechooser.setMultiSelectionEnabled( false );
304         _writetographics_filechooser.addChoosableFileFilter( graphicsfilefilter );
305         _save_filechooser = new JFileChooser();
306         _save_filechooser.setMultiSelectionEnabled( false );
307         _save_filechooser.setFileFilter( xmlfilter );
308         _save_filechooser.addChoosableFileFilter( nhfilter );
309         _save_filechooser.addChoosableFileFilter( nexusfilter );
310         _save_filechooser.addChoosableFileFilter( _save_filechooser.getAcceptAllFileFilter() );
311         try {
312             final String home_dir = System.getProperty( "user.home" );
313             _save_filechooser.setCurrentDirectory( new File( home_dir ) );
314             _writetopdf_filechooser.setCurrentDirectory( new File( home_dir ) );
315             _writetographics_filechooser.setCurrentDirectory( new File( home_dir ) );
316         }
317         catch ( final Exception e ) {
318             e.printStackTrace();
319             // Do nothing. Not important.
320         }
321     }
322
323     /**
324      * Action performed.
325      */
326     @Override
327     public void actionPerformed( final ActionEvent e ) {
328         final Object o = e.getSource();
329         boolean is_applet = false;
330         JApplet applet = null;
331         if ( getCurrentTreePanel() != null ) {
332             is_applet = getCurrentTreePanel().isApplet();
333             if ( is_applet ) {
334                 applet = getCurrentTreePanel().obtainApplet();
335             }
336         }
337         if ( o == _exit_item ) {
338             close();
339         }
340         else if ( o == _gsdi_item ) {
341             if ( isSubtreeDisplayed() ) {
342                 return;
343             }
344             executeGSDI();
345         }
346         else if ( o == _gsdir_item ) {
347             if ( isSubtreeDisplayed() ) {
348                 return;
349             }
350             executeGSDIR();
351         }
352         else if ( o == _taxcolor_item ) {
353             taxColor();
354         }
355         else if ( o == _confcolor_item ) {
356             confColor();
357         }
358         else if ( o == _color_rank_jmi ) {
359             colorRank();
360         }
361         else if ( o == _collapse_species_specific_subtrees ) {
362             if ( isSubtreeDisplayed() ) {
363                 return;
364             }
365             if ( getCurrentTreePanel() != null ) {
366                 getCurrentTreePanel().collapseSpeciesSpecificSubtrees();
367             }
368         }
369         else if ( o == _remove_branch_color_item ) {
370             if ( isSubtreeDisplayed() ) {
371                 return;
372             }
373             removeBranchColors();
374         }
375         else if ( o == _remove_visual_styles_item ) {
376             if ( isSubtreeDisplayed() ) {
377                 return;
378             }
379             removeVisualStyles();
380         }
381         else if ( o == _midpoint_root_item ) {
382             if ( isSubtreeDisplayed() ) {
383                 return;
384             }
385             midpointRoot();
386         }
387         else if ( o == _delete_selected_nodes_item ) {
388             if ( isSubtreeDisplayed() ) {
389                 return;
390             }
391             deleteSelectedNodes( true );
392         }
393         else if ( o == _delete_not_selected_nodes_item ) {
394             if ( isSubtreeDisplayed() ) {
395                 return;
396             }
397             deleteSelectedNodes( false );
398         }
399         else if ( o == _annotate_item ) {
400             annotateSequences();
401         }
402         else if ( o == _switch_colors_mi ) {
403             switchColors();
404         }
405         else if ( o == _display_basic_information_item ) {
406             if ( getCurrentTreePanel() != null ) {
407                 displayBasicInformation( getCurrentTreePanel().getTreeFile() );
408             }
409         }
410         else if ( o == _view_as_NH_item ) {
411             viewAsNH();
412         }
413         else if ( o == _view_as_XML_item ) {
414             viewAsXML();
415         }
416         else if ( o == _view_as_nexus_item ) {
417             viewAsNexus();
418         }
419         else if ( o == _super_tiny_fonts_item ) {
420             if ( getCurrentTreePanel() != null ) {
421                 getCurrentTreePanel().setSuperTinyFonts();
422                 getCurrentTreePanel().repaint();
423             }
424         }
425         else if ( o == _tiny_fonts_item ) {
426             if ( getCurrentTreePanel() != null ) {
427                 getCurrentTreePanel().setTinyFonts();
428                 getCurrentTreePanel().repaint();
429             }
430         }
431         else if ( o == _small_fonts_item ) {
432             if ( getCurrentTreePanel() != null ) {
433                 getCurrentTreePanel().setSmallFonts();
434                 getCurrentTreePanel().repaint();
435             }
436         }
437         else if ( o == _medium_fonts_item ) {
438             if ( getCurrentTreePanel() != null ) {
439                 getCurrentTreePanel().setMediumFonts();
440                 getCurrentTreePanel().repaint();
441             }
442         }
443         else if ( o == _large_fonts_item ) {
444             if ( getCurrentTreePanel() != null ) {
445                 getCurrentTreePanel().setLargeFonts();
446                 getCurrentTreePanel().repaint();
447             }
448         }
449         else if ( o == _choose_font_mi ) {
450             chooseFont();
451         }
452         else if ( o == _choose_minimal_confidence_mi ) {
453             chooseMinimalConfidence();
454         }
455         else if ( o == _choose_node_size_mi ) {
456             chooseNodeSize( getOptions(), this );
457         }
458         else if ( o == _overview_placment_mi ) {
459             MainFrame.cycleOverview( getOptions(), getCurrentTreePanel() );
460         }
461         else if ( o == _cycle_node_fill_mi ) {
462             MainFrame.cycleNodeFill( getOptions() );
463         }
464         else if ( o == _cycle_node_shape_mi ) {
465             MainFrame.cycleNodeShape( getOptions() );
466         }
467         else if ( o == _cycle_data_return ) {
468             MainFrame.cycleNodeDataReturn( getOptions(), getConfiguration() );
469         }
470         else if ( o == _screen_antialias_cbmi ) {
471             updateOptions( getOptions() );
472             updateScreenTextAntialias( getMainPanel().getTreePanels() );
473         }
474         else if ( o == _background_gradient_cbmi ) {
475             updateOptions( getOptions() );
476         }
477         else if ( o == _show_domain_labels ) {
478             updateOptions( getOptions() );
479         }
480         else if ( o == _show_annotation_ref_source ) {
481             updateOptions( getOptions() );
482         }
483         else if ( o == _abbreviate_scientific_names ) {
484             updateOptions( getOptions() );
485         }
486         else if ( o == _color_labels_same_as_parent_branch ) {
487             updateOptions( getOptions() );
488         }
489         else if ( o == _show_default_node_shapes_internal_cbmi ) {
490             updateOptions( getOptions() );
491         }
492         else if ( o == _show_default_node_shapes_external_cbmi ) {
493             updateOptions( getOptions() );
494         }
495         else if ( o == _show_default_node_shapes_for_marked_cbmi ) {
496             updateOptions( getOptions() );
497         }
498         else if ( o == _non_lined_up_cladograms_rbmi ) {
499             updateOptions( getOptions() );
500             showWhole();
501         }
502         else if ( o == _ext_node_dependent_cladogram_rbmi ) {
503             updateOptions( getOptions() );
504             showWhole();
505         }
506         else if ( o == _search_case_senstive_cbmi ) {
507             updateOptions( getOptions() );
508             getMainPanel().getControlPanel().search0();
509             getMainPanel().getControlPanel().search1();
510         }
511         else if ( o == _search_whole_words_only_cbmi ) {
512             if ( ( _search_with_regex_cbmi != null ) && _search_whole_words_only_cbmi.isSelected() ) {
513                 _search_with_regex_cbmi.setSelected( false );
514             }
515             updateOptions( getOptions() );
516             getMainPanel().getControlPanel().search0();
517             getMainPanel().getControlPanel().search1();
518         }
519         else if ( o == _inverse_search_result_cbmi ) {
520             updateOptions( getOptions() );
521             getMainPanel().getControlPanel().search0();
522             getMainPanel().getControlPanel().search1();
523         }
524         else if ( o == _search_with_regex_cbmi ) {
525             if ( ( _search_whole_words_only_cbmi != null ) && _search_with_regex_cbmi.isSelected() ) {
526                 _search_whole_words_only_cbmi.setSelected( false );
527             }
528             if ( ( _search_case_senstive_cbmi != null ) && _search_with_regex_cbmi.isSelected() ) {
529                 _search_case_senstive_cbmi.setSelected( true );
530             }
531             updateOptions( getOptions() );
532             getMainPanel().getControlPanel().search0();
533             getMainPanel().getControlPanel().search1();
534         }
535         else if ( o == _color_all_found_nodes_when_coloring_subtree_cbmi ) {
536             updateOptions( getOptions() );
537         }
538         else if ( o == _parse_beast_style_extended_nexus_tags_cbmi ) {
539             updateOptions( getOptions() );
540         }
541         else if ( o == _show_scale_cbmi ) {
542             updateOptions( getOptions() );
543         }
544         else if ( o == _color_by_taxonomic_group_cbmi ) {
545             updateOptions( getOptions() );
546         }
547         else if ( o == _show_confidence_stddev_cbmi ) {
548             updateOptions( getOptions() );
549         }
550         else if ( o == _use_brackets_for_conf_in_nh_export_cbmi ) {
551             if ( _use_brackets_for_conf_in_nh_export_cbmi.isSelected() ) {
552                 _use_internal_names_for_conf_in_nh_export_cbmi.setSelected( false );
553             }
554             updateOptions( getOptions() );
555         }
556         else if ( o == _use_internal_names_for_conf_in_nh_export_cbmi ) {
557             if ( _use_internal_names_for_conf_in_nh_export_cbmi.isSelected() ) {
558                 _use_brackets_for_conf_in_nh_export_cbmi.setSelected( false );
559             }
560             updateOptions( getOptions() );
561         }
562         else if ( o == _label_direction_cbmi ) {
563             updateOptions( getOptions() );
564         }
565         else if ( o == _show_overview_cbmi ) {
566             updateOptions( getOptions() );
567             if ( getCurrentTreePanel() != null ) {
568                 getCurrentTreePanel().updateOvSizes();
569             }
570         }
571         else if ( o == _line_up_renderable_data_cbmi ) {
572             if ( !_line_up_renderable_data_cbmi.isSelected() ) {
573                 _right_line_up_domains_cbmi.setSelected( false );
574             }
575             updateOptions( getOptions() );
576         }
577         
578         else if ( o == _collapsed_with_average_height_cbmi ) {
579             if ( _collapsed_with_average_height_cbmi.isSelected() ) {
580                 _collapsed_with_average_height_cbmi.setSelected( true );
581             }
582             updateOptions( getOptions() );
583         }
584         else if ( o == _right_line_up_domains_cbmi ) {
585             if ( _right_line_up_domains_cbmi.isSelected() ) {
586                 _line_up_renderable_data_cbmi.setSelected( true );
587             }
588             updateOptions( getOptions() );
589         }
590         else if ( ( o == _rectangular_type_cbmi ) || ( o == _triangular_type_cbmi ) || ( o == _curved_type_cbmi )
591                 || ( o == _convex_type_cbmi ) || ( o == _euro_type_cbmi ) || ( o == _rounded_type_cbmi )
592                 || ( o == _unrooted_type_cbmi ) || ( o == _circular_type_cbmi ) ) {
593             typeChanged( o );
594         }
595         else if ( o == _about_item ) {
596             about();
597         }
598         else if ( o == _help_item ) {
599             try {
600                 AptxUtil.openWebsite( AptxConstants.APTX_DOC_SITE, is_applet, applet );
601             }
602             catch ( final IOException e1 ) {
603                 ForesterUtil.printErrorMessage( AptxConstants.PRG_NAME, e1.toString() );
604             }
605         }
606         else if ( o == _website_item ) {
607             try {
608                 AptxUtil.openWebsite( AptxConstants.APTX_WEB_SITE, is_applet, applet );
609             }
610             catch ( final IOException e1 ) {
611                 ForesterUtil.printErrorMessage( AptxConstants.PRG_NAME, e1.toString() );
612             }
613         }
614         else if ( o == _mailing_list_item ) {
615             try {
616                 AptxUtil.openWebsite( AptxConstants.APTX_MAILING_LIST, is_applet, applet );
617             }
618             catch ( final IOException e1 ) {
619                 ForesterUtil.printErrorMessage( AptxConstants.PRG_NAME, e1.toString() );
620             }
621         }
622         else if ( o == _phyloxml_website_item ) {
623             try {
624                 AptxUtil.openWebsite( AptxConstants.PHYLOXML_WEB_SITE, is_applet, applet );
625             }
626             catch ( final IOException e1 ) {
627                 ForesterUtil.printErrorMessage( AptxConstants.PRG_NAME, e1.toString() );
628             }
629         }
630         else if ( o == _aptx_ref_item ) {
631             try {
632                 AptxUtil.openWebsite( AptxConstants.APTX_REFERENCE_URL, is_applet, applet );
633             }
634             catch ( final IOException e1 ) {
635                 ForesterUtil.printErrorMessage( AptxConstants.PRG_NAME, e1.toString() );
636             }
637         }
638         else if ( o == _phyloxml_ref_item ) {
639             try {
640                 AptxUtil.openWebsite( AptxConstants.PHYLOXML_REFERENCE_URL, is_applet, applet );
641             }
642             catch ( final IOException e1 ) {
643                 ForesterUtil.printErrorMessage( AptxConstants.PRG_NAME, e1.toString() );
644             }
645         }
646         else if ( o == _write_to_pdf_item ) {
647             final File curr_dir = writeToPdf( _mainpanel.getCurrentPhylogeny(),
648                                               getMainPanel(),
649                                               _writetopdf_filechooser,
650                                               _current_dir,
651                                               getContentPane(),
652                                               this );
653             if ( curr_dir != null ) {
654                 setCurrentDir( curr_dir );
655             }
656         }
657         else if ( o == _save_all_item ) {
658             writeAllToFile();
659         }
660         else if ( o == _write_to_jpg_item ) {
661             final File new_dir = writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(),
662                                                       GraphicsExportType.JPG,
663                                                       _mainpanel,
664                                                       _writetographics_filechooser,
665                                                       this,
666                                                       getContentPane(),
667                                                       _current_dir );
668             if ( new_dir != null ) {
669                 setCurrentDir( new_dir );
670             }
671         }
672         else if ( o == _write_to_gif_item ) {
673             final File new_dir = writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(),
674                                                       GraphicsExportType.GIF,
675                                                       _mainpanel,
676                                                       _writetographics_filechooser,
677                                                       this,
678                                                       getContentPane(),
679                                                       _current_dir );
680             if ( new_dir != null ) {
681                 setCurrentDir( new_dir );
682             }
683         }
684         else if ( o == _write_to_tif_item ) {
685             final File new_dir = writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(),
686                                                       GraphicsExportType.TIFF,
687                                                       _mainpanel,
688                                                       _writetographics_filechooser,
689                                                       this,
690                                                       getContentPane(),
691                                                       _current_dir );
692             if ( new_dir != null ) {
693                 setCurrentDir( new_dir );
694             }
695         }
696         else if ( o == _write_to_bmp_item ) {
697             final File new_dir = writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(),
698                                                       GraphicsExportType.BMP,
699                                                       _mainpanel,
700                                                       _writetographics_filechooser,
701                                                       this,
702                                                       getContentPane(),
703                                                       _current_dir );
704             if ( new_dir != null ) {
705                 setCurrentDir( new_dir );
706             }
707         }
708         else if ( o == _write_to_png_item ) {
709             final File new_dir = writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(),
710                                                       GraphicsExportType.PNG,
711                                                       _mainpanel,
712                                                       _writetographics_filechooser,
713                                                       this,
714                                                       getContentPane(),
715                                                       _current_dir );
716             if ( new_dir != null ) {
717                 setCurrentDir( new_dir );
718             }
719         }
720         else if ( o == _print_item ) {
721             print( getCurrentTreePanel(), getOptions(), this );
722         }
723         else if ( o == _save_item ) {
724             final File new_dir = writeToFile( _mainpanel.getCurrentPhylogeny(),
725                                               getMainPanel(),
726                                               _save_filechooser,
727                                               _current_dir,
728                                               getContentPane(),
729                                               this );
730             if ( new_dir != null ) {
731                 setCurrentDir( new_dir );
732             }
733         }
734         else if ( o == _graphics_export_visible_only_cbmi ) {
735             updateOptions( getOptions() );
736         }
737         else if ( o == _antialias_print_cbmi ) {
738             updateOptions( getOptions() );
739         }
740         else if ( o == _print_black_and_white_cbmi ) {
741             updateOptions( getOptions() );
742         }
743         else if ( o == _choose_pdf_width_mi ) {
744             choosePdfWidth();
745         }
746         else if ( o == _lineage_inference ) {
747             if ( isSubtreeDisplayed() ) {
748                 JOptionPane.showMessageDialog( this,
749                                                "Subtree is shown.",
750                                                "Cannot infer ancestral taxonomies",
751                                                JOptionPane.ERROR_MESSAGE );
752                 return;
753             }
754             executeLineageInference();
755         }
756         else {
757             if ( _load_phylogeny_from_webservice_menu_items != null ) {
758                 for( int i = 0; i < _load_phylogeny_from_webservice_menu_items.length; ++i ) {
759                     if ( o == _load_phylogeny_from_webservice_menu_items[ i ] ) {
760                         readPhylogeniesFromWebservice( i );
761                     }
762                 }
763             }
764         }
765         _contentpane.repaint();
766     }
767
768     public Configuration getConfiguration() {
769         return _configuration;
770     }
771
772     /**
773      * This method returns the current external node data which
774      * has been selected by the user by clicking the "Return ..."
775      * menu item. This method is expected to be called from Javascript or
776      * something like it.
777      *
778      * @return current external node data as String
779      */
780     public String getCurrentExternalNodesDataBuffer() {
781         return getCurrentTreePanel().getCurrentExternalNodesDataBufferAsString();
782     }
783
784     public int getCurrentExternalNodesDataBufferChangeCounter() {
785         return getCurrentTreePanel().getCurrentExternalNodesDataBufferChangeCounter();
786     }
787
788     public int getCurrentExternalNodesDataBufferLength() {
789         return getCurrentTreePanel().getCurrentExternalNodesDataBufferAsString().length();
790     }
791
792     public InferenceManager getInferenceManager() {
793         return _inference_manager;
794     }
795
796     public MainPanel getMainPanel() {
797         return _mainpanel;
798     }
799
800     public Options getOptions() {
801         return _options;
802     }
803
804     public ProcessPool getProcessPool() {
805         return _process_pool;
806     }
807
808     public void showTextFrame( final String s, final String title ) {
809         checkTextFrames();
810         _textframes.addLast( TextFrame.instantiate( s, title, _textframes ) );
811     }
812
813     public void showWhole() {
814         _mainpanel.getControlPanel().showWhole();
815     }
816
817     public void updateProcessMenu() {
818         // In general Swing is not thread safe.
819         // See "Swing's Threading Policy".
820         SwingUtilities.invokeLater( new Runnable() {
821
822             @Override
823             public void run() {
824                 doUpdateProcessMenu();
825             }
826         } );
827     }
828
829     private void annotateSequences() {
830         if ( getCurrentTreePanel() != null ) {
831             List<PhylogenyNode> nodes = null;
832             if ( ( getCurrentTreePanel().getFoundNodes0() != null )
833                     || ( getCurrentTreePanel().getFoundNodes1() != null ) ) {
834                 nodes = getCurrentTreePanel().getFoundNodesAsListOfPhylogenyNodes();
835             }
836             if ( ( nodes == null ) || nodes.isEmpty() ) {
837                 JOptionPane
838                         .showMessageDialog( this,
839                                             "Need to select nodes, either via direct selection or via the \"Search\" function",
840                                             "No nodes selected for annotation",
841                                             JOptionPane.ERROR_MESSAGE );
842                 return;
843             }
844             final Phylogeny phy = getMainPanel().getCurrentPhylogeny();
845             if ( ( phy != null ) && !phy.isEmpty() ) {
846                 final JTextField ref_field = new JTextField( 10 );
847                 final JTextField desc_filed = new JTextField( 20 );
848                 ref_field.setText( ForesterUtil.isEmpty( getPreviousNodeAnnotationReference() ) ? ""
849                         : getPreviousNodeAnnotationReference() );
850                 final JPanel my_panel = new JPanel();
851                 my_panel.add( new JLabel( "Reference " ) );
852                 my_panel.add( ref_field );
853                 my_panel.add( Box.createHorizontalStrut( 15 ) );
854                 my_panel.add( new JLabel( "Description " ) );
855                 my_panel.add( desc_filed );
856                 final int result = JOptionPane.showConfirmDialog( null,
857                                                                   my_panel,
858                                                                   "Enter the sequence annotation(s) for the "
859                                                                           + nodes.size() + " selected nodes",
860                                                                   JOptionPane.OK_CANCEL_OPTION );
861                 if ( result == JOptionPane.OK_OPTION ) {
862                     String ref = ref_field.getText();
863                     String desc = desc_filed.getText();
864                     if ( !ForesterUtil.isEmpty( ref ) ) {
865                         ref = ref.trim();
866                         ref = ref.replaceAll( "\\s+", " " );
867                         if ( ( ref.indexOf( ':' ) < 1 ) || ( ref.indexOf( ':' ) > ( ref.length() - 2 ) )
868                                 || ( ref.length() < 3 ) ) {
869                             JOptionPane.showMessageDialog( this,
870                                                            "Reference needs to be in the form of \"GO:1234567\"",
871                                                            "Illegal Format for Annotation Reference",
872                                                            JOptionPane.ERROR_MESSAGE );
873                             return;
874                         }
875                     }
876                     if ( ref != null ) {
877                         setPreviousNodeAnnotationReference( ref );
878                     }
879                     if ( desc != null ) {
880                         desc = desc.trim();
881                         desc = desc.replaceAll( "\\s+", " " );
882                     }
883                     if ( !ForesterUtil.isEmpty( ref ) || !ForesterUtil.isEmpty( desc ) ) {
884                         for( final PhylogenyNode n : nodes ) {
885                             ForesterUtil.ensurePresenceOfSequence( n );
886                             final Annotation ann = ForesterUtil.isEmpty( ref ) ? new Annotation()
887                                     : new Annotation( ref );
888                             if ( !ForesterUtil.isEmpty( desc ) ) {
889                                 ann.setDesc( desc );
890                             }
891                             n.getNodeData().getSequence().addAnnotation( ann );
892                         }
893                     }
894                     getMainPanel().getControlPanel().showAnnotations();
895                 }
896             }
897         }
898     }
899
900     private void chooseFont() {
901         final FontChooser fc = new FontChooser();
902         fc.setFont( getMainPanel().getTreeFontSet().getLargeFont() );
903         fc.showDialog( this, "Select the Base Font" );
904         getMainPanel().getTreeFontSet().setBaseFont( fc.getFont() );
905         getControlPanel().displayedPhylogenyMightHaveChanged( true );
906         if ( getMainPanel().getCurrentTreePanel() != null ) {
907             getMainPanel().getCurrentTreePanel().resetPreferredSize();
908             getMainPanel().getCurrentTreePanel().updateOvSizes();
909         }
910        
911         repaint();
912     }
913
914     private void chooseMinimalConfidence() {
915         final String s = ( String ) JOptionPane
916                 .showInputDialog( this,
917                                   "Please enter the minimum for confidence values to be displayed.\n"
918                                           + "[current value: " + getOptions().getMinConfidenceValue() + "]\n",
919                                   "Minimal Confidence Value",
920                                   JOptionPane.QUESTION_MESSAGE,
921                                   null,
922                                   null,
923                                   getOptions().getMinConfidenceValue() );
924         if ( !ForesterUtil.isEmpty( s ) ) {
925             boolean success = true;
926             double m = 0.0;
927             final String m_str = s.trim();
928             if ( !ForesterUtil.isEmpty( m_str ) ) {
929                 try {
930                     m = Double.parseDouble( m_str );
931                 }
932                 catch ( final Exception ex ) {
933                     success = false;
934                 }
935             }
936             else {
937                 success = false;
938             }
939             if ( success && ( m >= 0.0 ) ) {
940                 getOptions().setMinConfidenceValue( m );
941             }
942         }
943     }
944
945     private void deleteSelectedNodes( final boolean delete ) {
946         final Phylogeny phy = getMainPanel().getCurrentPhylogeny();
947         if ( ( phy == null ) || ( phy.getNumberOfExternalNodes() < 2 ) ) {
948             return;
949         }
950         final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
951         if ( ( getCurrentTreePanel().getFoundNodes0() != null ) || ( getCurrentTreePanel().getFoundNodes1() != null ) ) {
952             final List<PhylogenyNode> all_selected_nodes = getCurrentTreePanel().getFoundNodesAsListOfPhylogenyNodes();
953             for( final PhylogenyNode n : all_selected_nodes ) {
954                 if ( n.isExternal() ) {
955                     nodes.add( n );
956                 }
957             }
958         }
959         String function = "Retain";
960         if ( delete ) {
961             function = "Delete";
962         }
963         if ( ( nodes == null ) || nodes.isEmpty() ) {
964             JOptionPane
965                     .showMessageDialog( this,
966                                         "Need to select external nodes, either via direct selection or via the \"Search\" function",
967                                         "No external nodes selected to " + function.toLowerCase(),
968                                         JOptionPane.ERROR_MESSAGE );
969             return;
970         }
971         final int todo = nodes.size();
972         final int ext = phy.getNumberOfExternalNodes();
973         int res = todo;
974         if ( delete ) {
975             res = ext - todo;
976         }
977         if ( res < 1 ) {
978             JOptionPane.showMessageDialog( this,
979                                            "Cannot delete all nodes",
980                                            "Attempt to delete all nodes ",
981                                            JOptionPane.ERROR_MESSAGE );
982             return;
983         }
984         final int result = JOptionPane.showConfirmDialog( null, function + " " + todo
985                 + " external node(s), from a total of " + ext + " external nodes," + "\nresulting in tree with " + res
986                 + " nodes?", function + " external nodes", JOptionPane.OK_CANCEL_OPTION );
987         if ( result == JOptionPane.OK_OPTION ) {
988             if ( !delete ) {
989                 final List<PhylogenyNode> to_delete = new ArrayList<PhylogenyNode>();
990                 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
991                     final PhylogenyNode n = it.next();
992                     if ( !nodes.contains( n ) ) {
993                         to_delete.add( n );
994                     }
995                 }
996                 for( final PhylogenyNode n : to_delete ) {
997                     phy.deleteSubtree( n, true );
998                 }
999             }
1000             else {
1001                 for( final PhylogenyNode n : nodes ) {
1002                     phy.deleteSubtree( n, true );
1003                 }
1004             }
1005             resetSearch();
1006             getCurrentTreePanel().setNodeInPreorderToNull();
1007             phy.externalNodesHaveChanged();
1008             phy.clearHashIdToNodeMap();
1009             phy.recalculateNumberOfExternalDescendants( true );
1010             getCurrentTreePanel().resetNodeIdToDistToLeafMap();
1011             getCurrentTreePanel().setEdited( true );
1012             repaint();
1013         }
1014     }
1015
1016     private void doUpdateProcessMenu() {
1017         if ( _process_pool.size() > 0 ) {
1018             if ( _process_menu == null ) {
1019                 _process_menu = createMenu( "", getConfiguration() );
1020                 _process_menu.setForeground( Color.RED );
1021             }
1022             _process_menu.removeAll();
1023             final String text = "processes running: " + _process_pool.size();
1024             _process_menu.setText( text );
1025             _jmenubar.add( _process_menu );
1026             for( int i = 0; i < _process_pool.size(); ++i ) {
1027                 final ProcessRunning p = _process_pool.getProcessByIndex( i );
1028                 _process_menu.add( customizeJMenuItem( new JMenuItem( p.getName() + " [" + p.getStart() + "]" ) ) );
1029             }
1030         }
1031         else {
1032             if ( _process_menu != null ) {
1033                 _process_menu.removeAll();
1034                 _jmenubar.remove( _process_menu );
1035             }
1036         }
1037         _jmenubar.validate();
1038         _jmenubar.repaint();
1039         repaint();
1040     }
1041
1042     private String getPreviousNodeAnnotationReference() {
1043         return _previous_node_annotation_ref;
1044     }
1045
1046     private void removeBranchColors() {
1047         if ( getMainPanel().getCurrentPhylogeny() != null ) {
1048             AptxUtil.removeBranchColors( getMainPanel().getCurrentPhylogeny() );
1049         }
1050     }
1051
1052     private void removeVisualStyles() {
1053         if ( getMainPanel().getCurrentPhylogeny() != null ) {
1054             AptxUtil.removeVisualStyles( getMainPanel().getCurrentPhylogeny() );
1055         }
1056     }
1057
1058     private void setPreviousNodeAnnotationReference( final String previous_node_annotation_ref ) {
1059         _previous_node_annotation_ref = previous_node_annotation_ref;
1060     }
1061
1062     private void writeAllToFile() {
1063         if ( ( getMainPanel().getTabbedPane() == null ) || ( getMainPanel().getTabbedPane().getTabCount() < 1 ) ) {
1064             return;
1065         }
1066         final File my_dir = getCurrentDir();
1067         if ( my_dir != null ) {
1068             _save_filechooser.setCurrentDirectory( my_dir );
1069         }
1070         _save_filechooser.setSelectedFile( new File( "" ) );
1071         final int result = _save_filechooser.showSaveDialog( _contentpane );
1072         final File file = _save_filechooser.getSelectedFile();
1073         setCurrentDir( _save_filechooser.getCurrentDirectory() );
1074         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
1075             if ( file.exists() ) {
1076                 final int i = JOptionPane.showConfirmDialog( this,
1077                                                              file + " already exists. Overwrite?",
1078                                                              "Warning",
1079                                                              JOptionPane.OK_CANCEL_OPTION,
1080                                                              JOptionPane.WARNING_MESSAGE );
1081                 if ( i != JOptionPane.OK_OPTION ) {
1082                     return;
1083                 }
1084                 else {
1085                     try {
1086                         file.delete();
1087                     }
1088                     catch ( final Exception e ) {
1089                         JOptionPane.showMessageDialog( this,
1090                                                        "Failed to delete: " + file,
1091                                                        "Error",
1092                                                        JOptionPane.WARNING_MESSAGE );
1093                     }
1094                 }
1095             }
1096             final int count = getMainPanel().getTabbedPane().getTabCount();
1097             final List<Phylogeny> trees = new ArrayList<Phylogeny>();
1098             for( int i = 0; i < count; ++i ) {
1099                 final Phylogeny phy = getMainPanel().getPhylogeny( i );
1100                 if ( ForesterUtil.isEmpty( phy.getName() )
1101                         && !ForesterUtil.isEmpty( getMainPanel().getTabbedPane().getTitleAt( i ) ) ) {
1102                     phy.setName( getMainPanel().getTabbedPane().getTitleAt( i ) );
1103                 }
1104                 trees.add( phy );
1105                 getMainPanel().getTreePanels().get( i ).setEdited( false );
1106             }
1107             final PhylogenyWriter writer = new PhylogenyWriter();
1108             try {
1109                 writer.toPhyloXML( file, trees, 0, ForesterUtil.LINE_SEPARATOR );
1110             }
1111             catch ( final IOException e ) {
1112                 JOptionPane.showMessageDialog( this,
1113                                                "Failed to write to: " + file,
1114                                                "Error",
1115                                                JOptionPane.WARNING_MESSAGE );
1116             }
1117         }
1118     }
1119
1120     void activateSaveAllIfNeeded() {
1121         if ( ( getMainPanel().getTabbedPane() != null ) && ( getMainPanel().getTabbedPane().getTabCount() > 1 ) ) {
1122             _save_all_item.setEnabled( true );
1123         }
1124         else {
1125             _save_all_item.setEnabled( false );
1126         }
1127     }
1128
1129     void buildFileMenu() {
1130         _file_jmenu = MainFrame.createMenu( "File", getConfiguration() );
1131         _file_jmenu.add( _save_item = new JMenuItem( "Save Tree As..." ) );
1132         _file_jmenu.addSeparator();
1133         _file_jmenu.add( _write_to_pdf_item = new JMenuItem( "Export to PDF file ..." ) );
1134         if ( AptxUtil.canWriteFormat( "tif" ) || AptxUtil.canWriteFormat( "tiff" ) || AptxUtil.canWriteFormat( "TIF" ) ) {
1135             _file_jmenu.add( _write_to_tif_item = new JMenuItem( "Export to TIFF file..." ) );
1136         }
1137         _file_jmenu.add( _write_to_png_item = new JMenuItem( "Export to PNG file..." ) );
1138         _file_jmenu.add( _write_to_jpg_item = new JMenuItem( "Export to JPG file..." ) );
1139         if ( AptxUtil.canWriteFormat( "gif" ) ) {
1140             _file_jmenu.add( _write_to_gif_item = new JMenuItem( "Export to GIF file..." ) );
1141         }
1142         if ( AptxUtil.canWriteFormat( "bmp" ) ) {
1143             _file_jmenu.add( _write_to_bmp_item = new JMenuItem( "Export to BMP file..." ) );
1144         }
1145         _file_jmenu.addSeparator();
1146         _file_jmenu.add( _print_item = new JMenuItem( "Print..." ) );
1147         _file_jmenu.addSeparator();
1148         _file_jmenu.add( _exit_item = new JMenuItem( "Exit" ) );
1149         customizeJMenuItem( _save_item );
1150         customizeJMenuItem( _write_to_pdf_item );
1151         customizeJMenuItem( _write_to_png_item );
1152         customizeJMenuItem( _write_to_jpg_item );
1153         customizeJMenuItem( _write_to_gif_item );
1154         customizeJMenuItem( _write_to_tif_item );
1155         customizeJMenuItem( _write_to_bmp_item );
1156         customizeJMenuItem( _print_item );
1157         customizeJMenuItem( _exit_item );
1158         _jmenubar.add( _file_jmenu );
1159     }
1160
1161     void buildFontSizeMenu() {
1162         _font_size_menu = createMenu( FONT_SIZE_MENU_LABEL, getConfiguration() );
1163         _font_size_menu.add( _super_tiny_fonts_item = new JMenuItem( "Super Tiny Fonts" ) );
1164         _font_size_menu.add( _tiny_fonts_item = new JMenuItem( "Tiny Fonts" ) );
1165         _font_size_menu.add( _small_fonts_item = new JMenuItem( "Small Fonts" ) );
1166         _font_size_menu.add( _medium_fonts_item = new JMenuItem( "Medium Fonts" ) );
1167         _font_size_menu.add( _large_fonts_item = new JMenuItem( "Large Fonts" ) );
1168         customizeJMenuItem( _super_tiny_fonts_item );
1169         customizeJMenuItem( _tiny_fonts_item );
1170         customizeJMenuItem( _small_fonts_item );
1171         customizeJMenuItem( _medium_fonts_item );
1172         customizeJMenuItem( _large_fonts_item );
1173         _jmenubar.add( _font_size_menu );
1174     }
1175
1176     void buildHelpMenu() {
1177         _help_jmenu = createMenu( "Help", getConfiguration() );
1178         _help_jmenu.add( _help_item = new JMenuItem( "Documentation" ) );
1179         _help_jmenu.addSeparator();
1180         _help_jmenu.add( _website_item = new JMenuItem( "Archaeopteryx Home" ) );
1181         _help_jmenu.add( _mailing_list_item = new JMenuItem( "Mailing List" ) );
1182         _aptx_ref_item = new JMenuItem( "Archaeopteryx Reference" ); //TODO need to add this...
1183         _help_jmenu.add( _phyloxml_website_item = new JMenuItem( "phyloXML Home" ) );
1184         _help_jmenu.add( _phyloxml_ref_item = new JMenuItem( "phyloXML Reference" ) );
1185         _help_jmenu.addSeparator();
1186         _help_jmenu.add( _about_item = new JMenuItem( "About" ) );
1187         customizeJMenuItem( _help_item );
1188         customizeJMenuItem( _website_item );
1189         customizeJMenuItem( _mailing_list_item );
1190         customizeJMenuItem( _phyloxml_website_item );
1191         customizeJMenuItem( _aptx_ref_item );
1192         customizeJMenuItem( _phyloxml_ref_item );
1193         customizeJMenuItem( _about_item );
1194         _phyloxml_ref_item.setToolTipText( PHYLOXML_REF_TOOL_TIP );
1195         _aptx_ref_item.setToolTipText( APTX_REF_TOOL_TIP );
1196         _jmenubar.add( _help_jmenu );
1197     }
1198
1199     void buildTypeMenu() {
1200         _type_menu = createMenu( TYPE_MENU_HEADER, getConfiguration() );
1201         _type_menu.add( _rectangular_type_cbmi = new JCheckBoxMenuItem( MainFrame.RECTANGULAR_TYPE_CBMI_LABEL ) );
1202         _type_menu.add( _euro_type_cbmi = new JCheckBoxMenuItem( MainFrame.EURO_TYPE_CBMI_LABEL ) );
1203         _type_menu.add( _rounded_type_cbmi = new JCheckBoxMenuItem( MainFrame.ROUNDED_TYPE_CBMI_LABEL ) );
1204         _type_menu.add( _curved_type_cbmi = new JCheckBoxMenuItem( MainFrame.CURVED_TYPE_CBMI_LABEL ) );
1205         _type_menu.add( _triangular_type_cbmi = new JCheckBoxMenuItem( MainFrame.TRIANGULAR_TYPE_CBMI_LABEL ) );
1206         _type_menu.add( _convex_type_cbmi = new JCheckBoxMenuItem( MainFrame.CONVEX_TYPE_CBMI_LABEL ) );
1207         _type_menu.add( _unrooted_type_cbmi = new JCheckBoxMenuItem( MainFrame.UNROOTED_TYPE_CBMI_LABEL ) );
1208         _type_menu.add( _circular_type_cbmi = new JCheckBoxMenuItem( MainFrame.CIRCULAR_TYPE_CBMI_LABEL ) );
1209         customizeCheckBoxMenuItem( _rectangular_type_cbmi, false );
1210         customizeCheckBoxMenuItem( _triangular_type_cbmi, false );
1211         customizeCheckBoxMenuItem( _euro_type_cbmi, false );
1212         customizeCheckBoxMenuItem( _rounded_type_cbmi, false );
1213         customizeCheckBoxMenuItem( _curved_type_cbmi, false );
1214         customizeCheckBoxMenuItem( _convex_type_cbmi, false );
1215         customizeCheckBoxMenuItem( _unrooted_type_cbmi, false );
1216         customizeCheckBoxMenuItem( _circular_type_cbmi, false );
1217         _triangular_type_cbmi.setToolTipText( "not suitable for phylograms" );
1218         _curved_type_cbmi.setToolTipText( "not suitable for phylograms" );
1219         _unrooted_type_cbmi.setToolTipText( MainFrame.USE_MOUSEWHEEL_SHIFT_TO_ROTATE );
1220         _circular_type_cbmi.setToolTipText( MainFrame.USE_MOUSEWHEEL_SHIFT_TO_ROTATE );
1221         initializeTypeMenu( getOptions() );
1222         _jmenubar.add( _type_menu );
1223     }
1224
1225     void buildViewMenu() {
1226         _view_jmenu = createMenu( "View", getConfiguration() );
1227         _view_jmenu.add( _display_basic_information_item = new JMenuItem( SHOW_BASIC_TREE_INFORMATION_LABEL ) );
1228         _view_jmenu.addSeparator();
1229         _view_jmenu.add( _view_as_XML_item = new JMenuItem( "as phyloXML" ) );
1230         _view_jmenu.add( _view_as_NH_item = new JMenuItem( "as Newick" ) );
1231         _view_jmenu.add( _view_as_nexus_item = new JMenuItem( "as Nexus" ) );
1232         customizeJMenuItem( _display_basic_information_item );
1233         customizeJMenuItem( _view_as_NH_item );
1234         customizeJMenuItem( _view_as_XML_item );
1235         customizeJMenuItem( _view_as_nexus_item );
1236         _jmenubar.add( _view_jmenu );
1237     }
1238
1239     void checkTextFrames() {
1240         if ( _textframes.size() > 5 ) {
1241             try {
1242                 if ( _textframes.getFirst() != null ) {
1243                     _textframes.getFirst().removeMe();
1244                 }
1245                 else {
1246                     _textframes.removeFirst();
1247                 }
1248             }
1249             catch ( final NoSuchElementException e ) {
1250                 // Ignore.
1251             }
1252         }
1253     }
1254
1255     void choosePdfWidth() {
1256         final String s = ( String ) JOptionPane.showInputDialog( this,
1257                                                                  "Please enter the default line width for PDF export.\n"
1258                                                                          + "[current value: "
1259                                                                          + getOptions().getPrintLineWidth() + "]\n",
1260                                                                  "Line Width for PDF Export",
1261                                                                  JOptionPane.QUESTION_MESSAGE,
1262                                                                  null,
1263                                                                  null,
1264                                                                  getOptions().getPrintLineWidth() );
1265         if ( !ForesterUtil.isEmpty( s ) ) {
1266             boolean success = true;
1267             float f = 0.0f;
1268             final String m_str = s.trim();
1269             if ( !ForesterUtil.isEmpty( m_str ) ) {
1270                 try {
1271                     f = Float.parseFloat( m_str );
1272                 }
1273                 catch ( final Exception ex ) {
1274                     success = false;
1275                 }
1276             }
1277             else {
1278                 success = false;
1279             }
1280             if ( success && ( f > 0.0 ) ) {
1281                 getOptions().setPrintLineWidth( f );
1282             }
1283         }
1284     }
1285
1286     void close() {
1287         removeAllTextFrames();
1288         if ( _mainpanel != null ) {
1289             _mainpanel.terminate();
1290         }
1291         if ( _contentpane != null ) {
1292             _contentpane.removeAll();
1293         }
1294         setVisible( false );
1295         dispose();
1296     }
1297
1298     void colorRank() {
1299         if ( _mainpanel.getCurrentTreePanel() != null ) {
1300             final Map<String, Integer> present_ranks = AptxUtil.getRankCounts( _mainpanel.getCurrentTreePanel().getPhylogeny());
1301             final String[] ranks = AptxUtil.getAllPossibleRanks(present_ranks);
1302             String rank = ( String ) JOptionPane
1303                     .showInputDialog( this,
1304                                       "What rank should the colorization be based on",
1305                                       "Rank Selection",
1306                                       JOptionPane.QUESTION_MESSAGE,
1307                                       null,
1308                                       ranks,
1309                                       null );
1310             if ( !ForesterUtil.isEmpty( rank ) ) {
1311                 if ( rank.indexOf( '(' ) > 0 ) {
1312                     rank = rank.substring( 0, rank.indexOf( '(' ) ).trim();
1313                 }
1314                 _mainpanel.getCurrentTreePanel().colorRank( rank );
1315             }
1316         }
1317     }
1318
1319     void confColor() {
1320         if ( _mainpanel.getCurrentTreePanel() != null ) {
1321             _mainpanel.getCurrentTreePanel().confColor();
1322         }
1323     }
1324
1325     void customizeCheckBoxMenuItem( final JCheckBoxMenuItem item, final boolean is_selected ) {
1326         if ( item != null ) {
1327             item.setFont( MainFrame.menu_font );
1328             if ( !getConfiguration().isUseNativeUI() ) {
1329                 item.setBackground( getConfiguration().getGuiMenuBackgroundColor() );
1330                 item.setForeground( getConfiguration().getGuiMenuTextColor() );
1331             }
1332             item.setSelected( is_selected );
1333             item.addActionListener( this );
1334         }
1335     }
1336
1337     JMenuItem customizeJMenuItem( final JMenuItem jmi ) {
1338         if ( jmi != null ) {
1339             jmi.setFont( MainFrame.menu_font );
1340             if ( !getConfiguration().isUseNativeUI() ) {
1341                 jmi.setBackground( getConfiguration().getGuiMenuBackgroundColor() );
1342                 jmi.setForeground( getConfiguration().getGuiMenuTextColor() );
1343             }
1344             jmi.addActionListener( this );
1345         }
1346         return jmi;
1347     }
1348
1349     void customizeRadioButtonMenuItem( final JRadioButtonMenuItem item, final boolean is_selected ) {
1350         if ( item != null ) {
1351             item.setFont( MainFrame.menu_font );
1352             if ( !getConfiguration().isUseNativeUI() ) {
1353                 item.setBackground( getConfiguration().getGuiMenuBackgroundColor() );
1354                 item.setForeground( getConfiguration().getGuiMenuTextColor() );
1355             }
1356             item.setSelected( is_selected );
1357             item.addActionListener( this );
1358         }
1359     }
1360
1361     void displayBasicInformation( final File treefile ) {
1362         if ( ( _mainpanel.getCurrentPhylogeny() != null ) && !_mainpanel.getCurrentPhylogeny().isEmpty() ) {
1363             String title = "Basic Information";
1364             if ( !ForesterUtil.isEmpty( _mainpanel.getCurrentPhylogeny().getName() ) ) {
1365                 title = title + " for \"" + _mainpanel.getCurrentPhylogeny().getName() + "\"";
1366             }
1367             showTextFrame( AptxUtil.createBasicInformation( _mainpanel.getCurrentPhylogeny(), treefile ), title );
1368         }
1369     }
1370
1371     void exceptionOccuredDuringOpenFile( final Exception e ) {
1372         try {
1373             _mainpanel.getCurrentTreePanel().setArrowCursor();
1374         }
1375         catch ( final Exception ex ) {
1376             // Do nothing.
1377         }
1378         JOptionPane.showMessageDialog( this,
1379                                        ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ),
1380                                        "Error during File|Open",
1381                                        JOptionPane.ERROR_MESSAGE );
1382     }
1383
1384     void executeGSDI() {
1385         if ( !isOKforSDI( false, true ) ) {
1386             return;
1387         }
1388         if ( !_mainpanel.getCurrentPhylogeny().isRooted() ) {
1389             JOptionPane.showMessageDialog( this,
1390                                            "Gene tree is not rooted.",
1391                                            "Cannot execute GSDI",
1392                                            JOptionPane.ERROR_MESSAGE );
1393             return;
1394         }
1395         final Phylogeny gene_tree = _mainpanel.getCurrentPhylogeny().copy();
1396         gene_tree.setAllNodesToNotCollapse();
1397         gene_tree.recalculateNumberOfExternalDescendants( false );
1398         GSDI gsdi = null;
1399         final Phylogeny species_tree = getSpeciesTree().copy();
1400         try {
1401             gsdi = new GSDI( gene_tree, species_tree, false, true, true, true );
1402         }
1403         catch ( final SDIException e ) {
1404             JOptionPane.showMessageDialog( this,
1405                                            e.getLocalizedMessage(),
1406                                            "Error during GSDI",
1407                                            JOptionPane.ERROR_MESSAGE );
1408             return;
1409         }
1410         catch ( final Exception e ) {
1411             AptxUtil.unexpectedException( e );
1412             return;
1413         }
1414         gene_tree.setRerootable( false );
1415         gene_tree.clearHashIdToNodeMap();
1416         gene_tree.recalculateNumberOfExternalDescendants( true );
1417         _mainpanel.addPhylogenyInNewTab( gene_tree, getConfiguration(), "gene tree", null );
1418         getMainPanel().getControlPanel().setShowEvents( true );
1419         showWhole();
1420         final int selected = _mainpanel.getTabbedPane().getSelectedIndex();
1421         _mainpanel.addPhylogenyInNewTab( species_tree, getConfiguration(), "species tree", null );
1422         showWhole();
1423         _mainpanel.getTabbedPane().setSelectedIndex( selected );
1424         showWhole();
1425         _mainpanel.getCurrentTreePanel().setEdited( true );
1426         final int poly = PhylogenyMethods.countNumberOfPolytomies( species_tree );
1427         if ( gsdi.getStrippedExternalGeneTreeNodes().size() > 0 ) {
1428             JOptionPane.showMessageDialog( this,
1429                                            "Duplications: " + gsdi.getDuplicationsSum() + "\n"
1430                                                    + "Potential duplications: "
1431                                                    + gsdi.getSpeciationOrDuplicationEventsSum() + "\n"
1432                                                    + "Speciations: " + gsdi.getSpeciationsSum() + "\n"
1433                                                    + "Stripped gene tree nodes: "
1434                                                    + gsdi.getStrippedExternalGeneTreeNodes().size() + "\n"
1435                                                    + "Taxonomy linkage based on: " + gsdi.getTaxCompBase() + "\n"
1436                                                    + "Number of polytomies in species tree used: " + poly + "\n",
1437                                            "GSDI successfully completed",
1438                                            JOptionPane.WARNING_MESSAGE );
1439         }
1440         else {
1441             JOptionPane.showMessageDialog( this,
1442                                            "Duplications: " + gsdi.getDuplicationsSum() + "\n"
1443                                                    + "Potential duplications: "
1444                                                    + gsdi.getSpeciationOrDuplicationEventsSum() + "\n"
1445                                                    + "Speciations: " + gsdi.getSpeciationsSum() + "\n"
1446                                                    + "Stripped gene tree nodes: "
1447                                                    + gsdi.getStrippedExternalGeneTreeNodes().size() + "\n"
1448                                                    + "Taxonomy linkage based on: " + gsdi.getTaxCompBase() + "\n"
1449                                                    + "Number of polytomies in species tree used: " + poly + "\n",
1450                                            "GSDI successfully completed",
1451                                            JOptionPane.INFORMATION_MESSAGE );
1452         }
1453     }
1454
1455     void executeGSDIR() {
1456         if ( !isOKforSDI( false, false ) ) {
1457             return;
1458         }
1459         final int p = PhylogenyMethods.countNumberOfPolytomies( _mainpanel.getCurrentPhylogeny() );
1460         if ( ( p > 0 )
1461                 && !( ( p == 1 ) && ( _mainpanel.getCurrentPhylogeny().getRoot().getNumberOfDescendants() == 3 ) ) ) {
1462             JOptionPane.showMessageDialog( this,
1463                                            "Gene tree is not completely binary",
1464                                            "Cannot execute GSDI",
1465                                            JOptionPane.ERROR_MESSAGE );
1466             return;
1467         }
1468         final Phylogeny gene_tree = _mainpanel.getCurrentPhylogeny().copy();
1469         gene_tree.setAllNodesToNotCollapse();
1470         gene_tree.recalculateNumberOfExternalDescendants( false );
1471         GSDIR gsdir = null;
1472         final Phylogeny species_tree = getSpeciesTree().copy();
1473         try {
1474             gsdir = new GSDIR( gene_tree, species_tree, true, true, true );
1475         }
1476         catch ( final SDIException e ) {
1477             JOptionPane.showMessageDialog( this,
1478                                            e.getLocalizedMessage(),
1479                                            "Error during GSDIR",
1480                                            JOptionPane.ERROR_MESSAGE );
1481             return;
1482         }
1483         catch ( final Exception e ) {
1484             AptxUtil.unexpectedException( e );
1485             return;
1486         }
1487         final Phylogeny result_gene_tree = gsdir.getMinDuplicationsSumGeneTree();
1488         result_gene_tree.setRerootable( false );
1489         result_gene_tree.clearHashIdToNodeMap();
1490         result_gene_tree.recalculateNumberOfExternalDescendants( true );
1491         PhylogenyMethods.orderAppearance( result_gene_tree.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
1492         _mainpanel.addPhylogenyInNewTab( result_gene_tree, getConfiguration(), "gene tree", null );
1493         getMainPanel().getControlPanel().setShowEvents( true );
1494         showWhole();
1495         final int selected = _mainpanel.getTabbedPane().getSelectedIndex();
1496         _mainpanel.addPhylogenyInNewTab( species_tree, getConfiguration(), "species tree", null );
1497         showWhole();
1498         _mainpanel.getTabbedPane().setSelectedIndex( selected );
1499         showWhole();
1500         _mainpanel.getCurrentTreePanel().setEdited( true );
1501         final int poly = PhylogenyMethods.countNumberOfPolytomies( species_tree );
1502         if ( gsdir.getStrippedExternalGeneTreeNodes().size() > 0 ) {
1503             JOptionPane.showMessageDialog( this,
1504                                            "Minimal duplications: " + gsdir.getMinDuplicationsSum() + "\n"
1505                                                    + "Speciations: " + gsdir.getSpeciationsSum() + "\n"
1506                                                    + "Stripped gene tree nodes: "
1507                                                    + gsdir.getStrippedExternalGeneTreeNodes().size() + "\n"
1508                                                    + "Taxonomy linkage based on: " + gsdir.getTaxCompBase() + "\n"
1509                                                    + "Number of polytomies in species tree used: " + poly + "\n",
1510                                            "GSDIR successfully completed",
1511                                            JOptionPane.WARNING_MESSAGE );
1512         }
1513         else {
1514             JOptionPane.showMessageDialog( this,
1515                                            "Minimal duplications: " + gsdir.getMinDuplicationsSum() + "\n"
1516                                                    + "Speciations: " + gsdir.getSpeciationsSum() + "\n"
1517                                                    + "Stripped gene tree nodes: "
1518                                                    + gsdir.getStrippedExternalGeneTreeNodes().size() + "\n"
1519                                                    + "Taxonomy linkage based on: " + gsdir.getTaxCompBase() + "\n"
1520                                                    + "Number of polytomies in species tree used: " + poly + "\n",
1521                                            "GSDIR successfully completed",
1522                                            JOptionPane.INFORMATION_MESSAGE );
1523         }
1524     }
1525
1526     void executeLineageInference() {
1527         if ( ( _mainpanel.getCurrentPhylogeny() == null ) || ( _mainpanel.getCurrentPhylogeny().isEmpty() ) ) {
1528             return;
1529         }
1530         if ( !_mainpanel.getCurrentPhylogeny().isRooted() ) {
1531             JOptionPane.showMessageDialog( this,
1532                                            "Phylogeny is not rooted.",
1533                                            "Cannot infer ancestral taxonomies",
1534                                            JOptionPane.ERROR_MESSAGE );
1535             return;
1536         }
1537         final AncestralTaxonomyInferrer inferrer = new AncestralTaxonomyInferrer( this,
1538                                                                                   _mainpanel.getCurrentTreePanel(),
1539                                                                                   _mainpanel.getCurrentPhylogeny()
1540                                                                                           .copy() );
1541         new Thread( inferrer ).start();
1542     }
1543
1544     boolean GAndSDoHaveMoreThanOneSpeciesInComman( final Phylogeny gene_tree ) {
1545         if ( ( gene_tree == null ) || gene_tree.isEmpty() ) {
1546             JOptionPane.showMessageDialog( this,
1547                                            "Gene tree and species tree have no species in common.",
1548                                            "Error during SDI",
1549                                            JOptionPane.ERROR_MESSAGE );
1550             return false;
1551         }
1552         else if ( gene_tree.getNumberOfExternalNodes() < 2 ) {
1553             JOptionPane.showMessageDialog( this,
1554                                            "Gene tree and species tree have only one species in common.",
1555                                            "Error during SDI",
1556                                            JOptionPane.ERROR_MESSAGE );
1557             return false;
1558         }
1559         else {
1560             return true;
1561         }
1562     }
1563
1564     ControlPanel getControlPanel() {
1565         return getMainPanel().getControlPanel();
1566     }
1567
1568     File getCurrentDir() {
1569         if ( ( _current_dir == null ) || !_current_dir.canRead() ) {
1570             if ( ForesterUtil.isWindows() ) {
1571                 try {
1572                     _current_dir = new File( WindowsUtils.getCurrentUserDesktopPath() );
1573                 }
1574                 catch ( final Exception e ) {
1575                     _current_dir = null;
1576                 }
1577             }
1578         }
1579         if ( ( _current_dir == null ) || !_current_dir.canRead() ) {
1580             if ( System.getProperty( "user.home" ) != null ) {
1581                 _current_dir = new File( System.getProperty( "user.home" ) );
1582             }
1583             else if ( System.getProperty( "user.dir" ) != null ) {
1584                 _current_dir = new File( System.getProperty( "user.dir" ) );
1585             }
1586         }
1587         return _current_dir;
1588     }
1589
1590     TreePanel getCurrentTreePanel() {
1591         return getMainPanel().getCurrentTreePanel();
1592     }
1593
1594     JMenu getHelpMenu() {
1595         return _help_jmenu;
1596     }
1597
1598     JCheckBoxMenuItem getlabelDirectionCbmi() {
1599         return _label_direction_cbmi;
1600     }
1601
1602     JMenuBar getMenuBarOfMainFrame() {
1603         return _jmenubar;
1604     }
1605
1606     final Phylogeny getSpeciesTree() {
1607         return _species_tree;
1608     }
1609
1610     void initializeTypeMenu( final Options options ) {
1611         setTypeMenuToAllUnselected();
1612         switch ( options.getPhylogenyGraphicsType() ) {
1613             case CONVEX:
1614                 _convex_type_cbmi.setSelected( true );
1615                 break;
1616             case CURVED:
1617                 _curved_type_cbmi.setSelected( true );
1618                 break;
1619             case EURO_STYLE:
1620                 _euro_type_cbmi.setSelected( true );
1621                 break;
1622             case ROUNDED:
1623                 _rounded_type_cbmi.setSelected( true );
1624                 break;
1625             case TRIANGULAR:
1626                 _triangular_type_cbmi.setSelected( true );
1627                 break;
1628             case UNROOTED:
1629                 _unrooted_type_cbmi.setSelected( true );
1630                 break;
1631             case CIRCULAR:
1632                 _circular_type_cbmi.setSelected( true );
1633                 break;
1634             default:
1635                 _rectangular_type_cbmi.setSelected( true );
1636                 break;
1637         }
1638     }
1639
1640     boolean isOKforSDI( final boolean species_tree_has_to_binary, final boolean gene_tree_has_to_binary ) {
1641         if ( ( _mainpanel.getCurrentPhylogeny() == null ) || _mainpanel.getCurrentPhylogeny().isEmpty() ) {
1642             return false;
1643         }
1644         else if ( ( getSpeciesTree() == null ) || getSpeciesTree().isEmpty() ) {
1645             JOptionPane.showMessageDialog( this,
1646                                            "No species tree loaded",
1647                                            "Cannot execute GSDI",
1648                                            JOptionPane.ERROR_MESSAGE );
1649             return false;
1650         }
1651         else if ( species_tree_has_to_binary && !getSpeciesTree().isCompletelyBinary() ) {
1652             JOptionPane.showMessageDialog( this,
1653                                            "Species tree is not completely binary",
1654                                            "Cannot execute GSDI",
1655                                            JOptionPane.ERROR_MESSAGE );
1656             return false;
1657         }
1658         else if ( gene_tree_has_to_binary && !_mainpanel.getCurrentPhylogeny().isCompletelyBinary() ) {
1659             JOptionPane.showMessageDialog( this,
1660                                            "Gene tree is not completely binary",
1661                                            "Cannot execute GSDI",
1662                                            JOptionPane.ERROR_MESSAGE );
1663             return false;
1664         }
1665         else {
1666             return true;
1667         }
1668     }
1669
1670     boolean isSubtreeDisplayed() {
1671         if ( getCurrentTreePanel() != null ) {
1672             if ( getCurrentTreePanel().isCurrentTreeIsSubtree() ) {
1673                 JOptionPane
1674                         .showMessageDialog( this,
1675                                             "This operation can only be performed on a complete tree, not on the currently displayed sub-tree only.",
1676                                             "Operation can not be exectuted on a sub-tree",
1677                                             JOptionPane.WARNING_MESSAGE );
1678                 return true;
1679             }
1680         }
1681         return false;
1682     }
1683
1684     void midpointRoot() {
1685         if ( _mainpanel.getCurrentTreePanel() != null ) {
1686             _mainpanel.getCurrentTreePanel().midpointRoot();
1687         }
1688     }
1689
1690     void readPhylogeniesFromWebservice( final int i ) {
1691         final UrlTreeReader reader = new UrlTreeReader( this, i );
1692         new Thread( reader ).start();
1693     }
1694
1695     void removeAllTextFrames() {
1696         for( final TextFrame tf : _textframes ) {
1697             if ( tf != null ) {
1698                 tf.close();
1699             }
1700         }
1701         _textframes.clear();
1702     }
1703
1704     void resetSearch() {
1705         getMainPanel().getCurrentTreePanel().setFoundNodes0( null );
1706         getMainPanel().getCurrentTreePanel().setFoundNodes1( null );
1707         getMainPanel().getControlPanel().setSearchFoundCountsOnLabel0( 0 );
1708         getMainPanel().getControlPanel().getSearchFoundCountsLabel0().setVisible( false );
1709         getMainPanel().getControlPanel().getSearchTextField0().setText( "" );
1710         getMainPanel().getControlPanel().getSearchResetButton0().setEnabled( false );
1711         getMainPanel().getControlPanel().getSearchResetButton0().setVisible( false );
1712         getMainPanel().getControlPanel().setSearchFoundCountsOnLabel1( 0 );
1713         getMainPanel().getControlPanel().getSearchFoundCountsLabel1().setVisible( false );
1714         getMainPanel().getControlPanel().getSearchTextField1().setText( "" );
1715         getMainPanel().getControlPanel().getSearchResetButton1().setEnabled( false );
1716         getMainPanel().getControlPanel().getSearchResetButton1().setVisible( false );
1717     }
1718
1719     void setConfiguration( final Configuration configuration ) {
1720         _configuration = configuration;
1721     }
1722
1723     void setCurrentDir( final File current_dir ) {
1724         _current_dir = current_dir;
1725     }
1726
1727     void setInferenceManager( final InferenceManager i ) {
1728         _inference_manager = i;
1729     }
1730
1731     void setOptions( final Options options ) {
1732         _options = options;
1733     }
1734
1735     void setSelectedTypeInTypeMenu( final PHYLOGENY_GRAPHICS_TYPE type ) {
1736         setTypeMenuToAllUnselected();
1737         switch ( type ) {
1738             case CIRCULAR:
1739                 _circular_type_cbmi.setSelected( true );
1740                 break;
1741             case CONVEX:
1742                 _convex_type_cbmi.setSelected( true );
1743                 break;
1744             case CURVED:
1745                 _curved_type_cbmi.setSelected( true );
1746                 break;
1747             case EURO_STYLE:
1748                 _euro_type_cbmi.setSelected( true );
1749                 break;
1750             case ROUNDED:
1751                 _rounded_type_cbmi.setSelected( true );
1752                 break;
1753             case RECTANGULAR:
1754                 _rectangular_type_cbmi.setSelected( true );
1755                 break;
1756             case TRIANGULAR:
1757                 _triangular_type_cbmi.setSelected( true );
1758                 break;
1759             case UNROOTED:
1760                 _unrooted_type_cbmi.setSelected( true );
1761                 break;
1762             default:
1763                 throw new IllegalArgumentException( "unknown type: " + type );
1764         }
1765     }
1766
1767     final void setSpeciesTree( final Phylogeny species_tree ) {
1768         _species_tree = species_tree;
1769     }
1770
1771     void setTypeMenuToAllUnselected() {
1772         _convex_type_cbmi.setSelected( false );
1773         _curved_type_cbmi.setSelected( false );
1774         _euro_type_cbmi.setSelected( false );
1775         _rounded_type_cbmi.setSelected( false );
1776         _triangular_type_cbmi.setSelected( false );
1777         _rectangular_type_cbmi.setSelected( false );
1778         _unrooted_type_cbmi.setSelected( false );
1779         _circular_type_cbmi.setSelected( false );
1780     }
1781
1782     void switchColors() {
1783         final TreeColorSet colorset = _mainpanel.getTreeColorSet();
1784         final ColorSchemeChooser csc = new ColorSchemeChooser( getMainPanel(), colorset );
1785         csc.setVisible( true );
1786     }
1787
1788     void taxColor() {
1789         if ( _mainpanel.getCurrentTreePanel() != null ) {
1790             _mainpanel.getCurrentTreePanel().taxColor();
1791         }
1792     }
1793
1794     void typeChanged( final Object o ) {
1795         updateTypeCheckboxes( getOptions(), o );
1796         updateOptions( getOptions() );
1797         if ( getCurrentTreePanel() != null ) {
1798             final PHYLOGENY_GRAPHICS_TYPE previous_type = getCurrentTreePanel().getPhylogenyGraphicsType();
1799             final PHYLOGENY_GRAPHICS_TYPE new_type = getOptions().getPhylogenyGraphicsType();
1800             if ( ( ( previous_type == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) && ( new_type != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) )
1801                     || ( ( previous_type == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) && ( new_type != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) )
1802                     || ( ( previous_type != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) && ( new_type == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) )
1803                     || ( ( previous_type != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) && ( new_type == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) ) {
1804                 getCurrentTreePanel().getControlPanel().showWhole();
1805             }
1806             if ( getCurrentTreePanel().isPhyHasBranchLengths() && ( new_type != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) {
1807                 getCurrentTreePanel().getControlPanel().setDrawPhylogramEnabled( true );
1808             }
1809             else {
1810                 getCurrentTreePanel().getControlPanel().setDrawPhylogramEnabled( false );
1811             }
1812             getCurrentTreePanel().setPhylogenyGraphicsType( getOptions().getPhylogenyGraphicsType() );
1813             updateScreenTextAntialias( getMainPanel().getTreePanels() );
1814             if ( getCurrentTreePanel().getControlPanel().getDynamicallyHideData() != null ) {
1815                 if ( new_type == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) {
1816                     getCurrentTreePanel().getControlPanel().getDynamicallyHideData().setEnabled( false );
1817                 }
1818                 else {
1819                     getCurrentTreePanel().getControlPanel().getDynamicallyHideData().setEnabled( true );
1820                 }
1821             }
1822         }
1823     }
1824
1825     void updateOptions( final Options options ) {
1826         options.setAntialiasScreen( ( _screen_antialias_cbmi != null ) && _screen_antialias_cbmi.isSelected() );
1827         options.setBackgroundColorGradient( ( _background_gradient_cbmi != null )
1828                 && _background_gradient_cbmi.isSelected() );
1829         options.setShowDomainLabels( ( _show_domain_labels != null ) && _show_domain_labels.isSelected() );
1830         options.setShowAnnotationRefSource( ( _show_annotation_ref_source != null )
1831                 && _show_annotation_ref_source.isSelected() );
1832         options.setAbbreviateScientificTaxonNames( ( _abbreviate_scientific_names != null )
1833                 && _abbreviate_scientific_names.isSelected() );
1834         options.setColorLabelsSameAsParentBranch( ( _color_labels_same_as_parent_branch != null )
1835                 && _color_labels_same_as_parent_branch.isSelected() );
1836         options.setShowDefaultNodeShapesInternal( ( _show_default_node_shapes_internal_cbmi != null )
1837                 && _show_default_node_shapes_internal_cbmi.isSelected() );
1838         options.setShowDefaultNodeShapesExternal( ( _show_default_node_shapes_external_cbmi != null )
1839                 && _show_default_node_shapes_external_cbmi.isSelected() );
1840         options.setShowDefaultNodeShapesForMarkedNodes( ( _show_default_node_shapes_for_marked_cbmi != null )
1841                 && _show_default_node_shapes_for_marked_cbmi.isSelected() );
1842         if ( ( _non_lined_up_cladograms_rbmi != null ) && ( _non_lined_up_cladograms_rbmi.isSelected() ) ) {
1843             options.setCladogramType( CLADOGRAM_TYPE.NON_LINED_UP );
1844         }
1845         else if ( ( _ext_node_dependent_cladogram_rbmi != null ) && ( _ext_node_dependent_cladogram_rbmi.isSelected() ) ) {
1846             options.setCladogramType( CLADOGRAM_TYPE.LINED_UP );
1847         }
1848         options.setSearchCaseSensitive( ( _search_case_senstive_cbmi != null )
1849                 && _search_case_senstive_cbmi.isSelected() );
1850         if ( ( _show_scale_cbmi != null ) && _show_scale_cbmi.isEnabled() ) {
1851             options.setShowScale( _show_scale_cbmi.isSelected() );
1852         }
1853         if ( _label_direction_cbmi != null ) {
1854             if ( _label_direction_cbmi.isSelected() ) {
1855                 options.setNodeLabelDirection( NODE_LABEL_DIRECTION.RADIAL );
1856             }
1857             else {
1858                 options.setNodeLabelDirection( NODE_LABEL_DIRECTION.HORIZONTAL );
1859             }
1860         }
1861         options.setShowOverview( ( _show_overview_cbmi != null ) && _show_overview_cbmi.isSelected() );
1862         options.setShowConfidenceStddev( ( _show_confidence_stddev_cbmi != null )
1863                 && _show_confidence_stddev_cbmi.isSelected() );
1864         if ( ( _color_by_taxonomic_group_cbmi != null ) && _color_by_taxonomic_group_cbmi.isEnabled() ) {
1865             options.setColorByTaxonomicGroup( _color_by_taxonomic_group_cbmi.isSelected() );
1866         }
1867         options.setAntialiasPrint( ( _antialias_print_cbmi != null ) && _antialias_print_cbmi.isSelected() );
1868         if ( ( _use_brackets_for_conf_in_nh_export_cbmi != null )
1869                 && _use_brackets_for_conf_in_nh_export_cbmi.isSelected() ) {
1870             options.setNhConversionSupportValueStyle( NH_CONVERSION_SUPPORT_VALUE_STYLE.IN_SQUARE_BRACKETS );
1871         }
1872         else if ( ( _use_internal_names_for_conf_in_nh_export_cbmi != null )
1873                 && _use_internal_names_for_conf_in_nh_export_cbmi.isSelected() ) {
1874             options.setNhConversionSupportValueStyle( NH_CONVERSION_SUPPORT_VALUE_STYLE.AS_INTERNAL_NODE_NAMES );
1875         }
1876         else {
1877             options.setNhConversionSupportValueStyle( NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
1878         }
1879         options.setPrintBlackAndWhite( ( _print_black_and_white_cbmi != null )
1880                 && _print_black_and_white_cbmi.isSelected() );
1881         options.setInternalNumberAreConfidenceForNhParsing( ( _internal_number_are_confidence_for_nh_parsing_cbmi != null )
1882                 && _internal_number_are_confidence_for_nh_parsing_cbmi.isSelected() );
1883         if ( ( _extract_taxonomy_pfam_strict_rbmi != null ) && _extract_taxonomy_pfam_strict_rbmi.isSelected() ) {
1884             options.setTaxonomyExtraction( TAXONOMY_EXTRACTION.PFAM_STYLE_STRICT );
1885         }
1886         else if ( ( _extract_taxonomy_pfam_relaxed_rbmi != null ) && _extract_taxonomy_pfam_relaxed_rbmi.isSelected() ) {
1887             options.setTaxonomyExtraction( TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED );
1888         }
1889         else if ( ( _extract_taxonomy_agressive_rbmi != null ) && _extract_taxonomy_agressive_rbmi.isSelected() ) {
1890             options.setTaxonomyExtraction( TAXONOMY_EXTRACTION.AGGRESSIVE );
1891         }
1892         else if ( ( _extract_taxonomy_no_rbmi != null ) && _extract_taxonomy_no_rbmi.isSelected() ) {
1893             options.setTaxonomyExtraction( TAXONOMY_EXTRACTION.NO );
1894         }
1895         options.setReplaceUnderscoresInNhParsing( ( _replace_underscores_cbmi != null )
1896                 && _replace_underscores_cbmi.isSelected() );
1897         options.setAllowErrorsInDistanceToParent( ( _allow_errors_in_distance_to_parent_cbmi != null )
1898                 && _allow_errors_in_distance_to_parent_cbmi.isSelected() );
1899         options.setMatchWholeTermsOnly( ( _search_whole_words_only_cbmi != null )
1900                 && _search_whole_words_only_cbmi.isSelected() );
1901         options.setSearchWithRegex( ( _search_with_regex_cbmi != null ) && _search_with_regex_cbmi.isSelected() );
1902         options.setInverseSearchResult( ( _inverse_search_result_cbmi != null )
1903                 && _inverse_search_result_cbmi.isSelected() );
1904         if ( _graphics_export_visible_only_cbmi != null ) {
1905             options.setGraphicsExportVisibleOnly( _graphics_export_visible_only_cbmi.isSelected() );    
1906         }
1907         if ( ( _rectangular_type_cbmi != null ) && _rectangular_type_cbmi.isSelected() ) {
1908             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1909         }
1910         else if ( ( _triangular_type_cbmi != null ) && _triangular_type_cbmi.isSelected() ) {
1911             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.TRIANGULAR );
1912         }
1913         else if ( ( _curved_type_cbmi != null ) && _curved_type_cbmi.isSelected() ) {
1914             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CURVED );
1915         }
1916         else if ( ( _convex_type_cbmi != null ) && _convex_type_cbmi.isSelected() ) {
1917             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CONVEX );
1918         }
1919         else if ( ( _euro_type_cbmi != null ) && _euro_type_cbmi.isSelected() ) {
1920             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE );
1921         }
1922         else if ( ( _rounded_type_cbmi != null ) && _rounded_type_cbmi.isSelected() ) {
1923             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.ROUNDED );
1924         }
1925         else if ( ( _unrooted_type_cbmi != null ) && _unrooted_type_cbmi.isSelected() ) {
1926             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.UNROOTED );
1927         }
1928         else if ( ( _circular_type_cbmi != null ) && _circular_type_cbmi.isSelected() ) {
1929             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CIRCULAR );
1930         }
1931         if ( ( _right_line_up_domains_cbmi != null ) && _right_line_up_domains_cbmi.isEnabled() ) {
1932             options.setRightLineUpDomains( _right_line_up_domains_cbmi.isSelected() );
1933         }
1934         if ( ( _line_up_renderable_data_cbmi != null ) && _line_up_renderable_data_cbmi.isEnabled() ) {
1935             options.setLineUpRendarableNodeData( _line_up_renderable_data_cbmi.isSelected() );
1936         }
1937         if ( ( _color_all_found_nodes_when_coloring_subtree_cbmi != null ) && _color_all_found_nodes_when_coloring_subtree_cbmi.isEnabled() ) {
1938             options.setColorAllFoundNodesWhenColoringSubtree( _color_all_found_nodes_when_coloring_subtree_cbmi.isSelected() );
1939         }
1940         if ( ( _parse_beast_style_extended_nexus_tags_cbmi != null ) && _parse_beast_style_extended_nexus_tags_cbmi.isEnabled() ) {
1941             options.setParseBeastStyleExtendedNexusTags(_parse_beast_style_extended_nexus_tags_cbmi.isSelected() );
1942         }
1943         if ( ( _collapsed_with_average_height_cbmi != null ) && _collapsed_with_average_height_cbmi.isEnabled() ) {
1944             options.setCollapsedWithAverageHeigh(_collapsed_with_average_height_cbmi.isSelected() );
1945         }
1946         
1947     }
1948
1949     void updateTypeCheckboxes( final Options options, final Object o ) {
1950         setTypeMenuToAllUnselected();
1951         ( ( JCheckBoxMenuItem ) o ).setSelected( true );
1952     }
1953
1954     void viewAsNexus() {
1955         if ( ( _mainpanel.getCurrentPhylogeny() != null ) && !_mainpanel.getCurrentPhylogeny().isEmpty() ) {
1956             String title = "Nexus";
1957             if ( !ForesterUtil.isEmpty( _mainpanel.getCurrentPhylogeny().getName() ) ) {
1958                 title = "\"" + getMainPanel().getCurrentPhylogeny().getName() + "\" in " + title;
1959             }
1960             showTextFrame( _mainpanel.getCurrentPhylogeny().toNexus( getOptions().getNhConversionSupportValueStyle() ),
1961                            title );
1962         }
1963     }
1964
1965     void viewAsNH() {
1966         if ( ( _mainpanel.getCurrentPhylogeny() != null ) && !_mainpanel.getCurrentPhylogeny().isEmpty() ) {
1967             String title = "New Hampshire";
1968             if ( !ForesterUtil.isEmpty( _mainpanel.getCurrentPhylogeny().getName() ) ) {
1969                 title = "\"" + getMainPanel().getCurrentPhylogeny().getName() + "\" in " + title;
1970             }
1971             showTextFrame( _mainpanel.getCurrentPhylogeny().toNewHampshire( getOptions()
1972                                    .getNhConversionSupportValueStyle() ),
1973                            title );
1974         }
1975     }
1976
1977     void viewAsXML() {
1978         if ( ( _mainpanel.getCurrentPhylogeny() != null ) && !_mainpanel.getCurrentPhylogeny().isEmpty() ) {
1979             String title = "phyloXML";
1980             if ( !ForesterUtil.isEmpty( _mainpanel.getCurrentPhylogeny().getName() ) ) {
1981                 title = "\"" + getMainPanel().getCurrentPhylogeny().getName() + "\" in " + title;
1982             }
1983             showTextFrame( _mainpanel.getCurrentPhylogeny().toPhyloXML( 0 ), title );
1984         }
1985     }
1986
1987     private static void cycleNodeDataReturn( final Options op, final Configuration conf ) {
1988         switch ( op.getExtDescNodeDataToReturn() ) {
1989             case UNKNOWN:
1990                 op.setExtDescNodeDataToReturn( NodeDataField.DOMAINS_ALL );
1991                 break;
1992             case DOMAINS_ALL:
1993                 op.setExtDescNodeDataToReturn( NodeDataField.DOMAINS_COLLAPSED_PER_PROTEIN );
1994                 break;
1995             case DOMAINS_COLLAPSED_PER_PROTEIN:
1996                 op.setExtDescNodeDataToReturn( NodeDataField.SEQ_ANNOTATIONS );
1997                 break;
1998             case SEQ_ANNOTATIONS:
1999                 op.setExtDescNodeDataToReturn( NodeDataField.GO_TERM_IDS );
2000                 break;
2001             case GO_TERM_IDS:
2002                 op.setExtDescNodeDataToReturn( NodeDataField.SEQUENCE_MOL_SEQ_FASTA );
2003                 break;
2004             case SEQUENCE_MOL_SEQ_FASTA:
2005                 if ( ( conf != null ) && ( conf.getExtDescNodeDataToReturn() != null )
2006                         && ( conf.getExtDescNodeDataToReturn() != NodeDataField.DOMAINS_ALL )
2007                         && ( conf.getExtDescNodeDataToReturn() != NodeDataField.DOMAINS_COLLAPSED_PER_PROTEIN )
2008                         && ( conf.getExtDescNodeDataToReturn() != NodeDataField.SEQ_ANNOTATIONS )
2009                         && ( conf.getExtDescNodeDataToReturn() != NodeDataField.GO_TERM_IDS )
2010                         && ( conf.getExtDescNodeDataToReturn() != NodeDataField.SEQUENCE_MOL_SEQ_FASTA ) ) {
2011                     op.setExtDescNodeDataToReturn( conf.getExtDescNodeDataToReturn() );
2012                 }
2013                 else {
2014                     op.setExtDescNodeDataToReturn( NodeDataField.UNKNOWN );
2015                 }
2016                 break;
2017             default:
2018                 op.setExtDescNodeDataToReturn( NodeDataField.UNKNOWN );
2019         }
2020     }
2021
2022     /**
2023      * Display the about box.
2024      */
2025     void about() {
2026         final StringBuffer about = new StringBuffer( "Archaeopteryx\nVersion " + AptxConstants.VERSION + "\n" );
2027         about.append( "Copyright (C) 2016 Christian M Zmasek\n" );
2028         about.append( "All Rights Reserved\n" );
2029         about.append( "License: GNU Lesser General Public License (LGPL)\n" );
2030         about.append( "Last modified: " + AptxConstants.PRG_DATE + "\n" );
2031         about.append( "Based on: " + ForesterUtil.getForesterLibraryInformation() + "\n" );
2032         
2033         if  ( _configuration.isCouldReadConfigFile() ) {
2034             about.append( "Using configuration file: " + _configuration.config_filename + "\n" );
2035         }
2036         else {
2037             about.append( "Not using a configuration file\n" );
2038         }
2039         
2040         about.append( "phyloXML version : " + ForesterConstants.PHYLO_XML_VERSION + "\n" );
2041         about.append( "phyloXML location: " + ForesterConstants.PHYLO_XML_LOCATION + "\n" );
2042         if ( !ForesterUtil.isEmpty( ForesterUtil.JAVA_VERSION ) && !ForesterUtil.isEmpty( ForesterUtil.JAVA_VENDOR ) ) {
2043             about.append( "[your Java version: " + ForesterUtil.JAVA_VERSION + " " + ForesterUtil.JAVA_VENDOR + "]\n" );
2044         }
2045         if ( !ForesterUtil.isEmpty( ForesterUtil.OS_NAME ) && !ForesterUtil.isEmpty( ForesterUtil.OS_ARCH )
2046                 && !ForesterUtil.isEmpty( ForesterUtil.OS_VERSION ) ) {
2047             about.append( "[your OS: " + ForesterUtil.OS_NAME + " " + ForesterUtil.OS_ARCH + " "
2048                     + ForesterUtil.OS_VERSION + "]\n" );
2049         }
2050         final Runtime rt = java.lang.Runtime.getRuntime();
2051         final long free_memory = rt.freeMemory() / 1000000;
2052         final long total_memory = rt.totalMemory() / 1000000;
2053         about.append( "[free memory: " + free_memory + "MB, total memory: " + total_memory + "MB]\n" );
2054         about.append( "[locale: " + Locale.getDefault() + "]\n" );
2055         about.append( "References:\n" );
2056         about.append( AptxConstants.PHYLOXML_REFERENCE_SHORT + "\n" );
2057         about.append( "For more information & download:\n" );
2058         about.append( AptxConstants.APTX_WEB_SITE + "\n" );
2059         about.append( "Documentation:\n" );
2060         about.append( AptxConstants.APTX_DOC_SITE + "\n" );
2061         about.append( "Comments: " + AptxConstants.AUTHOR_EMAIL );
2062         JOptionPane.showMessageDialog( null, about, AptxConstants.PRG_NAME, JOptionPane.PLAIN_MESSAGE );
2063     }
2064
2065     static void chooseNodeSize( final Options options, final Component parent ) {
2066         final String s = ( String ) JOptionPane.showInputDialog( parent,
2067                                                                  "Please enter the default size for node shapes.\n"
2068                                                                          + "[current value: "
2069                                                                          + options.getDefaultNodeShapeSize() + "]\n",
2070                                                                  "Node Shape Size",
2071                                                                  JOptionPane.QUESTION_MESSAGE,
2072                                                                  null,
2073                                                                  null,
2074                                                                  options.getDefaultNodeShapeSize() );
2075         if ( !ForesterUtil.isEmpty( s ) ) {
2076             boolean success = true;
2077             double m = 0.0;
2078             final String m_str = s.trim();
2079             if ( !ForesterUtil.isEmpty( m_str ) ) {
2080                 try {
2081                     m = Double.parseDouble( m_str );
2082                 }
2083                 catch ( final Exception ex ) {
2084                     success = false;
2085                 }
2086             }
2087             else {
2088                 success = false;
2089             }
2090             if ( success && ( m >= 0.0 ) ) {
2091                 final short size = ForesterUtil.roundToShort( m );
2092                 if ( size >= 0.0 ) {
2093                     options.setDefaultNodeShapeSize( size );
2094                 }
2095             }
2096         }
2097     }
2098
2099     static String createCurrentFontDesc( final TreeFontSet tree_font_set ) {
2100         return tree_font_set.getLargeFont().getFamily() + " " + tree_font_set.getLargeFont().getSize();
2101     }
2102
2103     static JMenu createMenu( final String title, final Configuration conf ) {
2104         final JMenu jmenu = new JMenu( title );
2105         if ( !conf.isUseNativeUI() ) {
2106             jmenu.setFont( MainFrame.menu_font );
2107             jmenu.setBackground( conf.getGuiMenuBackgroundColor() );
2108             jmenu.setForeground( conf.getGuiMenuTextColor() );
2109         }
2110         return jmenu;
2111     }
2112
2113     static JMenuItem customizeMenuItemAsLabel( final JMenuItem label, final Configuration configuration ) {
2114         label.setFont( MainFrame.menu_font.deriveFont( Font.BOLD ) );
2115         if ( !configuration.isUseNativeUI() ) {
2116             label.setBackground( configuration.getGuiMenuBackgroundColor() );
2117             label.setForeground( configuration.getGuiMenuTextColor() );
2118             label.setOpaque( true );
2119         }
2120         label.setSelected( false );
2121         label.setEnabled( false );
2122         return label;
2123     }
2124
2125     static void cycleNodeFill( final Options op ) {
2126         switch ( op.getDefaultNodeFill() ) {
2127             case GRADIENT:
2128                 op.setDefaultNodeFill( NodeFill.SOLID );
2129                 break;
2130             case NONE:
2131                 op.setDefaultNodeFill( NodeFill.GRADIENT );
2132                 break;
2133             case SOLID:
2134                 op.setDefaultNodeFill( NodeFill.NONE );
2135                 break;
2136             default:
2137                 throw new RuntimeException( "unknown fill: " + op.getDefaultNodeFill() );
2138         }
2139     }
2140
2141     static void cycleNodeShape( final Options op ) {
2142         switch ( op.getDefaultNodeShape() ) {
2143             case CIRCLE:
2144                 op.setDefaultNodeShape( NodeShape.RECTANGLE );
2145                 break;
2146             case RECTANGLE:
2147                 op.setDefaultNodeShape( NodeShape.CIRCLE );
2148                 break;
2149             default:
2150                 throw new RuntimeException( "unknown shape: " + op.getDefaultNodeShape() );
2151         }
2152     }
2153
2154     static void cycleOverview( final Options op, final TreePanel tree_panel ) {
2155         switch ( op.getOvPlacement() ) {
2156             case LOWER_LEFT:
2157                 op.setOvPlacement( Options.OVERVIEW_PLACEMENT_TYPE.UPPER_LEFT );
2158                 break;
2159             case LOWER_RIGHT:
2160                 op.setOvPlacement( Options.OVERVIEW_PLACEMENT_TYPE.LOWER_LEFT );
2161                 break;
2162             case UPPER_LEFT:
2163                 op.setOvPlacement( Options.OVERVIEW_PLACEMENT_TYPE.UPPER_RIGHT );
2164                 break;
2165             case UPPER_RIGHT:
2166                 op.setOvPlacement( Options.OVERVIEW_PLACEMENT_TYPE.LOWER_RIGHT );
2167                 break;
2168             default:
2169                 throw new RuntimeException( "unknown placement: " + op.getOvPlacement() );
2170         }
2171         if ( tree_panel != null ) {
2172             tree_panel.updateOvSettings();
2173         }
2174     }
2175
2176     static void exceptionOccuredDuringSaveAs( final Exception e, final TreePanel tp, final Component comp ) {
2177         try {
2178             tp.setArrowCursor();
2179         }
2180         catch ( final Exception ex ) {
2181             // Do nothing.
2182         }
2183         JOptionPane.showMessageDialog( comp, "Exception" + e, "Error during File|SaveAs", JOptionPane.ERROR_MESSAGE );
2184     }
2185
2186     static void print( final TreePanel tp, final Options op, final Component c ) {
2187         if ( ( tp == null ) || ( tp.getPhylogeny() == null ) || tp.getPhylogeny().isEmpty() ) {
2188             return;
2189         }
2190         final String job_name = AptxConstants.PRG_NAME;
2191         boolean error = false;
2192         String printer_name = null;
2193         try {
2194             printer_name = Printer.print( tp, job_name );
2195         }
2196         catch ( final Exception e ) {
2197             error = true;
2198             JOptionPane.showMessageDialog( c, e.getMessage(), "Printing Error", JOptionPane.ERROR_MESSAGE );
2199         }
2200         if ( !error && ( printer_name != null ) ) {
2201             String msg = "Printing data sent to printer";
2202             if ( printer_name.length() > 1 ) {
2203                 msg += " [" + printer_name + "]";
2204             }
2205             JOptionPane.showMessageDialog( c, msg, "Printing...", JOptionPane.INFORMATION_MESSAGE );
2206         }
2207         if ( !op.isPrintUsingActualSize() ) {
2208             tp.getControlPanel().showWhole();
2209         }
2210     }
2211
2212     static void printPhylogenyToPdf( final String file_name,
2213                                      final Options opts,
2214                                      final TreePanel tp,
2215                                      final Component comp ) {
2216        
2217         String pdf_written_to = "";
2218         boolean error = false;
2219         try {
2220             if ( opts.isPrintUsingActualSize() ) {
2221                 pdf_written_to = PdfExporter.writePhylogenyToPdf( file_name, tp, tp.getWidth() , tp.getHeight()  );
2222             }
2223             else {
2224                 // Never false.
2225             }
2226         }
2227         catch ( final IOException e ) {
2228             error = true;
2229             JOptionPane.showMessageDialog( comp, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE );
2230         }
2231         if ( !error ) {
2232             if ( !ForesterUtil.isEmpty( pdf_written_to ) ) {
2233                 JOptionPane.showMessageDialog( comp,
2234                                                "Wrote PDF to: " + pdf_written_to,
2235                                                "Information",
2236                                                JOptionPane.INFORMATION_MESSAGE );
2237             }
2238             else {
2239                 JOptionPane.showMessageDialog( comp,
2240                                                "There was an unknown problem when attempting to write to PDF file: \""
2241                                                        + file_name + "\"",
2242                                                "Error",
2243                                                JOptionPane.ERROR_MESSAGE );
2244             }
2245         }
2246         if ( !opts.isPrintUsingActualSize() ) {
2247             tp.getControlPanel().showWhole();
2248         }
2249     }
2250
2251     static void setCycleDataReturnMenuItem( final JMenuItem mi, final Options options ) {
2252         if ( ( options != null ) && ( options.getExtDescNodeDataToReturn() != null ) ) {
2253             mi.setText( "Cycle Node Return Data... (current: " + options.getExtDescNodeDataToReturn().toString() + ")" );
2254         }
2255         else {
2256             mi.setText( "Cycle Node Return Data..." );
2257         }
2258     }
2259
2260     static void setCycleNodeFillMenuItem( final JMenuItem mi, final Options options ) {
2261         if ( ( options != null ) && ( options.getDefaultNodeFill() != null ) ) {
2262             mi.setText( "Cycle Node Shape Fill Type... (current: "
2263                     + options.getDefaultNodeFill().toString().toLowerCase() + ")" );
2264         }
2265         else {
2266             mi.setText( "Cycle Node Shape Fill Type..." );
2267         }
2268     }
2269
2270     static void setCycleNodeShapeMenuItem( final JMenuItem mi, final Options options ) {
2271         if ( ( options != null ) && ( options.getDefaultNodeShape() != null ) ) {
2272             mi.setText( "Cycle Node Shape Fill Type... (current: "
2273                     + options.getDefaultNodeShape().toString().toLowerCase() + ")" );
2274         }
2275         else {
2276             mi.setText( "Cycle Node Shape Fill Type..." );
2277         }
2278     }
2279
2280     static void setOvPlacementColorChooseMenuItem( final JMenuItem mi, final Options options ) {
2281         if ( ( options != null ) && ( options.getOvPlacement() != null ) ) {
2282             mi.setText( "Cycle Overview Placement... (current: " + options.getOvPlacement() + ")" );
2283         }
2284         else {
2285             mi.setText( "Cycle Overview Placement..." );
2286         }
2287     }
2288
2289     static void setTextColorChooseMenuItem( final JMenuItem mi, final TreePanel tree_panel ) {
2290         if ( ( tree_panel != null ) && ( tree_panel.getTreeColorSet() != null ) ) {
2291             mi.setText( "Select Color Scheme... (current: " + tree_panel.getTreeColorSet().getCurrentColorSchemeName()
2292                     + ")" );
2293         }
2294         else {
2295             mi.setText( "Select Color Scheme..." );
2296         }
2297     }
2298
2299     static void setTextForFontChooserMenuItem( final JMenuItem mi, final String font_desc ) {
2300         mi.setText( "Select Default Font... (current: " + font_desc + ")" );
2301     }
2302
2303     static void setTextForPdfLineWidthChooserMenuItem( final JMenuItem mi, final Options o ) {
2304         mi.setText( "Enter Default Line Width for PDF Export... (current: " + o.getPrintLineWidth() + ")" );
2305     }
2306
2307     static void setTextMinSupportMenuItem( final JMenuItem mi, final Options options, final TreePanel current_tree_panel ) {
2308         if ( ( current_tree_panel == null ) || ( current_tree_panel.getPhylogeny() == null ) ) {
2309             mi.setEnabled( true );
2310         }
2311         else if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( current_tree_panel.getPhylogeny() ) ) {
2312             mi.setEnabled( true );
2313         }
2314         else {
2315             mi.setEnabled( false );
2316         }
2317         mi.setText( "Enter Min Confidence Value... (current: " + options.getMinConfidenceValue() + ")" );
2318     }
2319
2320     static void setTextNodeSizeMenuItem( final JMenuItem mi, final Options options ) {
2321         mi.setText( "Enter Default Node Shape Size... (current: " + options.getDefaultNodeShapeSize() + ")" );
2322     }
2323
2324     static void updateScreenTextAntialias( final List<TreePanel> treepanels ) {
2325         for( final TreePanel tree_panel : treepanels ) {
2326             tree_panel.setTextAntialias();
2327         }
2328     }
2329
2330     static boolean writeAsNewHampshire( final TreePanel tp, final Options op, boolean exception, final File file ) {
2331         try {
2332             final PhylogenyWriter writer = new PhylogenyWriter();
2333             writer.toNewHampshire( tp.getPhylogeny(), true, op.getNhConversionSupportValueStyle(), file );
2334         }
2335         catch ( final Exception e ) {
2336             exception = true;
2337             exceptionOccuredDuringSaveAs( e, tp, tp );
2338         }
2339         return exception;
2340     }
2341
2342     static boolean writeAsNexus( final TreePanel tp, final Options op, boolean exception, final File file ) {
2343         try {
2344             final PhylogenyWriter writer = new PhylogenyWriter();
2345             writer.toNexus( file, tp.getPhylogeny(), op.getNhConversionSupportValueStyle() );
2346         }
2347         catch ( final Exception e ) {
2348             exception = true;
2349             exceptionOccuredDuringSaveAs( e, tp, tp );
2350         }
2351         return exception;
2352     }
2353
2354     static boolean writeAsPhyloXml( final TreePanel tp, final Options op, boolean exception, final File file ) {
2355         try {
2356             final PhylogenyWriter writer = new PhylogenyWriter();
2357             writer.toPhyloXML( file, tp.getPhylogeny(), 0 );
2358         }
2359         catch ( final Exception e ) {
2360             exception = true;
2361             exceptionOccuredDuringSaveAs( e, tp, tp );
2362         }
2363         return exception;
2364     }
2365
2366     static void writePhylogenyToGraphicsFile( final String file_name,
2367                                               final GraphicsExportType type,
2368                                               final MainPanel mp,
2369                                               final Component comp,
2370                                               final Container contentpane ) {
2371         mp.getCurrentTreePanel().calcParametersForPainting( mp.getCurrentTreePanel().getWidth(),
2372                                                             mp.getCurrentTreePanel().getHeight() );
2373         String file_written_to = "";
2374         boolean error = false;
2375         try {
2376             file_written_to = AptxUtil.writePhylogenyToGraphicsFile( file_name,
2377                                                                      mp.getCurrentTreePanel().getWidth(),
2378                                                                      mp.getCurrentTreePanel().getHeight(),
2379                                                                      mp.getCurrentTreePanel(),
2380                                                                      mp.getControlPanel(),
2381                                                                      type,
2382                                                                      mp.getOptions() );
2383         }
2384         catch ( final IOException e ) {
2385             error = true;
2386             JOptionPane.showMessageDialog( comp, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE );
2387         }
2388         if ( !error ) {
2389             if ( ( file_written_to != null ) && ( file_written_to.length() > 0 ) ) {
2390                 JOptionPane.showMessageDialog( comp,
2391                                                "Wrote image to: " + file_written_to,
2392                                                "Graphics Export",
2393                                                JOptionPane.INFORMATION_MESSAGE );
2394             }
2395             else {
2396                 JOptionPane.showMessageDialog( comp,
2397                                                "There was an unknown problem when attempting to write to an image file: \""
2398                                                        + file_name + "\"",
2399                                                "Error",
2400                                                JOptionPane.ERROR_MESSAGE );
2401             }
2402         }
2403         contentpane.repaint();
2404     }
2405
2406     static File writeToFile( final Phylogeny t,
2407                              final MainPanel mp,
2408                              final JFileChooser save_filechooser,
2409                              final File current_dir,
2410                              final Container contentpane,
2411                              final Component comp ) {
2412         File new_file = null;
2413         if ( t == null ) {
2414             return null;
2415         }
2416         String initial_filename = null;
2417         if ( mp.getCurrentTreePanel().getTreeFile() != null ) {
2418             try {
2419                 initial_filename = mp.getCurrentTreePanel().getTreeFile().getCanonicalPath();
2420             }
2421             catch ( final IOException e ) {
2422                 initial_filename = null;
2423             }
2424         }
2425         if ( !ForesterUtil.isEmpty( initial_filename ) ) {
2426             save_filechooser.setSelectedFile( new File( initial_filename ) );
2427         }
2428         else {
2429             save_filechooser.setSelectedFile( new File( "" ) );
2430         }
2431         final File my_dir = current_dir;
2432         if ( my_dir != null ) {
2433             save_filechooser.setCurrentDirectory( my_dir );
2434         }
2435         final int result = save_filechooser.showSaveDialog( contentpane );
2436         final File file = save_filechooser.getSelectedFile();
2437         new_file = save_filechooser.getCurrentDirectory();
2438         boolean exception = false;
2439         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2440             if ( file.exists() ) {
2441                 final int i = JOptionPane.showConfirmDialog( comp,
2442                                                              file + " already exists.\nOverwrite?",
2443                                                              "Overwrite?",
2444                                                              JOptionPane.OK_CANCEL_OPTION,
2445                                                              JOptionPane.QUESTION_MESSAGE );
2446                 if ( i != JOptionPane.OK_OPTION ) {
2447                     return null;
2448                 }
2449                 else {
2450                     final File to = new File( file.getAbsoluteFile().toString() + AptxConstants.BACKUP_FILE_SUFFIX );
2451                     try {
2452                         ForesterUtil.copyFile( file, to );
2453                     }
2454                     catch ( final Exception e ) {
2455                         JOptionPane.showMessageDialog( comp,
2456                                                        "Failed to create backup copy " + to,
2457                                                        "Failed to Create Backup Copy",
2458                                                        JOptionPane.WARNING_MESSAGE );
2459                     }
2460                     try {
2461                         file.delete();
2462                     }
2463                     catch ( final Exception e ) {
2464                         JOptionPane.showMessageDialog( comp,
2465                                                        "Failed to delete: " + file,
2466                                                        "Failed to Delete",
2467                                                        JOptionPane.WARNING_MESSAGE );
2468                     }
2469                 }
2470             }
2471             if ( save_filechooser.getFileFilter() == MainFrame.nhfilter ) {
2472                 exception = writeAsNewHampshire( mp.getCurrentTreePanel(), mp.getOptions(), exception, file );
2473             }
2474             else if ( save_filechooser.getFileFilter() == MainFrame.xmlfilter ) {
2475                 exception = writeAsPhyloXml( mp.getCurrentTreePanel(), mp.getOptions(), exception, file );
2476             }
2477             else if ( save_filechooser.getFileFilter() == MainFrame.nexusfilter ) {
2478                 exception = writeAsNexus( mp.getCurrentTreePanel(), mp.getOptions(), exception, file );
2479             }
2480             // "*.*":
2481             else {
2482                 final String file_name = file.getName().trim().toLowerCase();
2483                 if ( file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2484                         || file_name.endsWith( ".tree" ) ) {
2485                     exception = writeAsNewHampshire( mp.getCurrentTreePanel(), mp.getOptions(), exception, file );
2486                 }
2487                 else if ( file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) ) {
2488                     exception = writeAsNexus( mp.getCurrentTreePanel(), mp.getOptions(), exception, file );
2489                 }
2490                 // XML is default:
2491                 else {
2492                     exception = writeAsPhyloXml( mp.getCurrentTreePanel(), mp.getOptions(), exception, file );
2493                 }
2494             }
2495             if ( !exception ) {
2496                 mp.setTitleOfSelectedTab( file.getName() );
2497                 mp.getCurrentTreePanel().setTreeFile( file );
2498                 mp.getCurrentTreePanel().setEdited( false );
2499             }
2500         }
2501         return new_file;
2502     }
2503
2504     static File writeToGraphicsFile( final Phylogeny t,
2505                                      final GraphicsExportType type,
2506                                      final MainPanel mp,
2507                                      final JFileChooser writetographics_filechooser,
2508                                      final Component component,
2509                                      final Container contentpane,
2510                                      final File current_dir ) {
2511         File new_dir = null;
2512         if ( ( t == null ) || t.isEmpty() ) {
2513             return null;
2514         }
2515         String initial_filename = "";
2516         if ( mp.getCurrentTreePanel().getTreeFile() != null ) {
2517             initial_filename = mp.getCurrentTreePanel().getTreeFile().toString();
2518         }
2519         if ( initial_filename.indexOf( '.' ) > 0 ) {
2520             initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) );
2521         }
2522         initial_filename = initial_filename + "." + type;
2523         writetographics_filechooser.setSelectedFile( new File( initial_filename ) );
2524         final File my_dir = current_dir;
2525         if ( my_dir != null ) {
2526             writetographics_filechooser.setCurrentDirectory( my_dir );
2527         }
2528         final int result = writetographics_filechooser.showSaveDialog( contentpane );
2529         File file = writetographics_filechooser.getSelectedFile();
2530         //setCurrentDir( writetographics_filechooser.getCurrentDirectory() );
2531         new_dir = writetographics_filechooser.getCurrentDirectory();
2532         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2533             if ( !file.toString().toLowerCase().endsWith( type.toString() ) ) {
2534                 file = new File( file.toString() + "." + type );
2535             }
2536             if ( file.exists() ) {
2537                 final int i = JOptionPane.showConfirmDialog( component,
2538                                                              file + " already exists. Overwrite?",
2539                                                              "Warning",
2540                                                              JOptionPane.OK_CANCEL_OPTION,
2541                                                              JOptionPane.WARNING_MESSAGE );
2542                 if ( i != JOptionPane.OK_OPTION ) {
2543                     return null;
2544                 }
2545                 else {
2546                     try {
2547                         file.delete();
2548                     }
2549                     catch ( final Exception e ) {
2550                         JOptionPane.showMessageDialog( component,
2551                                                        "Failed to delete: " + file,
2552                                                        "Error",
2553                                                        JOptionPane.WARNING_MESSAGE );
2554                     }
2555                 }
2556             }
2557             writePhylogenyToGraphicsFile( file.toString(), type, mp, component, contentpane );
2558         }
2559         return new_dir;
2560     }
2561
2562     static File writeToPdf( final Phylogeny t,
2563                             final MainPanel mp,
2564                             final JFileChooser writetopdf_filechooser,
2565                             final File curr_dir,
2566                             final Container contentpane,
2567                             final Component component ) {
2568         if ( ( t == null ) || t.isEmpty() ) {
2569             return null;
2570         }
2571         String initial_filename = "";
2572         if ( mp.getCurrentTreePanel().getTreeFile() != null ) {
2573             initial_filename = mp.getCurrentTreePanel().getTreeFile().toString();
2574         }
2575         if ( initial_filename.indexOf( '.' ) > 0 ) {
2576             initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) );
2577         }
2578         initial_filename = initial_filename + ".pdf";
2579         writetopdf_filechooser.setSelectedFile( new File( initial_filename ) );
2580         final File my_dir = curr_dir;
2581         if ( my_dir != null ) {
2582             writetopdf_filechooser.setCurrentDirectory( my_dir );
2583         }
2584         final int result = writetopdf_filechooser.showSaveDialog( contentpane );
2585         File file = writetopdf_filechooser.getSelectedFile();
2586         // setCurrentDir( writetopdf_filechooser.getCurrentDirectory() );
2587         final File new_current_dir = writetopdf_filechooser.getCurrentDirectory();
2588         if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) {
2589             if ( !file.toString().toLowerCase().endsWith( ".pdf" ) ) {
2590                 file = new File( file.toString() + ".pdf" );
2591             }
2592             if ( file.exists() ) {
2593                 final int i = JOptionPane.showConfirmDialog( component,
2594                                                              file + " already exists. Overwrite?",
2595                                                              "WARNING",
2596                                                              JOptionPane.OK_CANCEL_OPTION,
2597                                                              JOptionPane.WARNING_MESSAGE );
2598                 if ( i != JOptionPane.OK_OPTION ) {
2599                     return null;
2600                 }
2601             }
2602             printPhylogenyToPdf( file.toString(), mp.getOptions(), mp.getCurrentTreePanel(), component );
2603         }
2604         return new_current_dir;
2605     }
2606 }
2607
2608 class DefaultFilter extends FileFilter {
2609
2610     @Override
2611     public boolean accept( final File f ) {
2612         final String file_name = f.getName().trim().toLowerCase();
2613         return file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2614                 || file_name.endsWith( ".nwk" ) || file_name.endsWith( ".phb" ) || file_name.endsWith( ".ph" )
2615                 || file_name.endsWith( ".tr" ) || file_name.endsWith( ".dnd" ) || file_name.endsWith( ".tree" )
2616                 || file_name.endsWith( ".nhx" ) || file_name.endsWith( ".xml" ) || file_name.endsWith( ".phyloxml" )
2617                 || file_name.endsWith( "phylo.xml" ) || file_name.endsWith( ".pxml" ) || file_name.endsWith( ".nexus" )
2618                 || file_name.endsWith( ".nx" ) || file_name.endsWith( ".nex" ) || file_name.endsWith( ".tre" )
2619                 || file_name.endsWith( ".zip" ) || file_name.endsWith( ".tol" ) || file_name.endsWith( ".tolxml" )
2620                 || file_name.endsWith( ".con" ) || f.isDirectory();
2621     }
2622
2623     @Override
2624     public String getDescription() {
2625         return "All supported files (*.xml, *.phyloxml, *phylo.xml, *.nhx, *.nh, *.newick, *.nex, *.nexus, *.phy, *.tre, *.tree, *.tol, ...)";
2626     }
2627 }
2628
2629 class GraphicsFileFilter extends FileFilter {
2630
2631     @Override
2632     public boolean accept( final File f ) {
2633         final String file_name = f.getName().trim().toLowerCase();
2634         return file_name.endsWith( ".jpg" ) || file_name.endsWith( ".jpeg" ) || file_name.endsWith( ".png" )
2635                 || file_name.endsWith( ".gif" ) || file_name.endsWith( ".bmp" ) || f.isDirectory();
2636     }
2637
2638     @Override
2639     public String getDescription() {
2640         return "Image files (*.jpg, *.jpeg, *.png, *.gif, *.bmp)";
2641     }
2642 }
2643
2644 class MsaFileFilter extends FileFilter {
2645
2646     @Override
2647     public boolean accept( final File f ) {
2648         final String file_name = f.getName().trim().toLowerCase();
2649         return file_name.endsWith( ".msa" ) || file_name.endsWith( ".aln" ) || file_name.endsWith( ".fasta" )
2650                 || file_name.endsWith( ".fas" ) || file_name.endsWith( ".fa" ) || f.isDirectory();
2651     }
2652
2653     @Override
2654     public String getDescription() {
2655         return "Multiple sequence alignment files (*.msa, *.aln, *.fasta, *.fa, *.fas)";
2656     }
2657 }
2658
2659 class NexusFilter extends FileFilter {
2660
2661     @Override
2662     public boolean accept( final File f ) {
2663         final String file_name = f.getName().trim().toLowerCase();
2664         return file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) || file_name.endsWith( ".nx" )
2665                 || file_name.endsWith( ".tre" ) || f.isDirectory();
2666     }
2667
2668     @Override
2669     public String getDescription() {
2670         return "Nexus files (*.nex, *.nexus, *.nx, *.tre)";
2671     }
2672 } // NexusFilter
2673
2674 class NHFilter extends FileFilter {
2675
2676     @Override
2677     public boolean accept( final File f ) {
2678         final String file_name = f.getName().trim().toLowerCase();
2679         return file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" )
2680                 || file_name.endsWith( ".tr" ) || file_name.endsWith( ".tree" ) || file_name.endsWith( ".dnd" )
2681                 || file_name.endsWith( ".ph" ) || file_name.endsWith( ".phb" ) || file_name.endsWith( ".nwk" )
2682                 || f.isDirectory();
2683     }
2684
2685     @Override
2686     public String getDescription() {
2687         return "New Hampshire - Newick files (*.nh, *.newick, *.phy, *.tree, *.dnd, *.tr, *.ph, *.phb, *.nwk)";
2688     }
2689 } // NHFilter
2690
2691 class NHXFilter extends FileFilter {
2692
2693     @Override
2694     public boolean accept( final File f ) {
2695         final String file_name = f.getName().trim().toLowerCase();
2696         return file_name.endsWith( ".nhx" ) || f.isDirectory();
2697     }
2698
2699     @Override
2700     public String getDescription() {
2701         return "NHX files (*.nhx) [deprecated]";
2702     }
2703 }
2704
2705 class PdfFilter extends FileFilter {
2706
2707     @Override
2708     public boolean accept( final File f ) {
2709         return f.getName().trim().toLowerCase().endsWith( ".pdf" ) || f.isDirectory();
2710     }
2711
2712     @Override
2713     public String getDescription() {
2714         return "PDF files (*.pdf)";
2715     }
2716 } // PdfFilter
2717
2718 class SequencesFileFilter extends FileFilter {
2719
2720     @Override
2721     public boolean accept( final File f ) {
2722         final String file_name = f.getName().trim().toLowerCase();
2723         return file_name.endsWith( ".fasta" ) || file_name.endsWith( ".fa" ) || file_name.endsWith( ".fas" )
2724                 || file_name.endsWith( ".seqs" ) || f.isDirectory();
2725     }
2726
2727     @Override
2728     public String getDescription() {
2729         return "Sequences files (*.fasta, *.fa, *.fas, *.seqs )";
2730     }
2731 }
2732
2733 class TolFilter extends FileFilter {
2734
2735     @Override
2736     public boolean accept( final File f ) {
2737         final String file_name = f.getName().trim().toLowerCase();
2738         return ( file_name.endsWith( ".tol" ) || file_name.endsWith( ".tolxml" ) || file_name.endsWith( ".zip" ) || f
2739                 .isDirectory() ) && ( !file_name.endsWith( ".xml.zip" ) );
2740     }
2741
2742     @Override
2743     public String getDescription() {
2744         return "Tree of Life files (*.tol, *.tolxml)";
2745     }
2746 } // TolFilter
2747
2748 class XMLFilter extends FileFilter {
2749
2750     @Override
2751     public boolean accept( final File f ) {
2752         final String file_name = f.getName().trim().toLowerCase();
2753         return file_name.endsWith( ".xml" ) || file_name.endsWith( ".phyloxml" ) || file_name.endsWith( "phylo.xml" )
2754                 || file_name.endsWith( ".pxml" ) || file_name.endsWith( ".zip" ) || f.isDirectory();
2755     }
2756
2757     @Override
2758     public String getDescription() {
2759         return "phyloXML files (*.xml, *.phyloxml, *phylo.xml, *.pxml, *.zip)";
2760     }
2761 } // XMLFilter