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