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