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