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