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