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