6743505f586690b010f84127b648dea1903221af
[jalview.git] / forester / java / src / org / forester / archaeopteryx / ArchaeopteryxE.java
1
2 package org.forester.archaeopteryx;
3
4 import java.awt.BorderLayout;
5 import java.awt.Container;
6 import java.awt.event.ActionEvent;
7 import java.awt.event.ActionListener;
8 import java.awt.event.ComponentAdapter;
9 import java.awt.event.ComponentEvent;
10 import java.io.ByteArrayOutputStream;
11 import java.io.File;
12 import java.io.IOException;
13 import java.net.URL;
14 import java.util.LinkedList;
15 import java.util.List;
16 import java.util.NoSuchElementException;
17
18 import javax.swing.ButtonGroup;
19 import javax.swing.JApplet;
20 import javax.swing.JCheckBoxMenuItem;
21 import javax.swing.JFileChooser;
22 import javax.swing.JMenu;
23 import javax.swing.JMenuBar;
24 import javax.swing.JMenuItem;
25 import javax.swing.JOptionPane;
26 import javax.swing.JRadioButtonMenuItem;
27 import javax.swing.UIManager;
28 import javax.swing.UnsupportedLookAndFeelException;
29 import javax.swing.event.ChangeEvent;
30 import javax.swing.event.ChangeListener;
31
32 import org.apache.commons.codec.binary.Base64;
33 import org.forester.archaeopteryx.AptxUtil.GraphicsExportType;
34 import org.forester.archaeopteryx.Options.CLADOGRAM_TYPE;
35 import org.forester.archaeopteryx.Options.NODE_LABEL_DIRECTION;
36 import org.forester.archaeopteryx.Options.PHYLOGENY_GRAPHICS_TYPE;
37 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
38 import org.forester.phylogeny.Phylogeny;
39 import org.forester.phylogeny.PhylogenyMethods;
40 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
41 import org.forester.phylogeny.data.SequenceRelation;
42 import org.forester.sdi.GSDI;
43 import org.forester.sdi.GSDIR;
44 import org.forester.sdi.SDIException;
45 import org.forester.util.ForesterConstants;
46 import org.forester.util.ForesterUtil;
47 import org.forester.util.WindowsUtils;
48
49 // Use like this:
50 // <applet archive="forester.jar"
51 // code="org.forester.archaeopteryx.ArchaeopteryxE.class"
52 // codebase="http://www.myserver.org/path/to/forester"
53 // width="600"
54 // height="500"
55 // alt="ArchaeopteryxE is not working on your system (requires at least Sun Java 1.5)!">
56 // <param name="url_of_tree_to_load"
57 // value="http://www.myserver.org/examples/data/apaf.xml">
58 // <param name="config_file"
59 // value="http://www.myserver.org/examples/config/config_file.txt">
60 // </applet>
61 public class ArchaeopteryxE extends JApplet implements ActionListener {
62
63     private final static String         NAME             = "ArchaeopteryxE";
64     private static final long           serialVersionUID = -1220055577935759443L;
65     private Configuration               _configuration;
66     private MainPanel                   _mainpanel;
67     private JMenuBar                    _jmenubar;
68     private JMenu                       _options_jmenu;
69     private JMenu                       _font_size_menu;
70     private JMenuItem                   _super_tiny_fonts_mi;
71     private JMenuItem                   _tiny_fonts_mi;
72     private JMenuItem                   _small_fonts_mi;
73     private JMenuItem                   _medium_fonts_mi;
74     private JMenuItem                   _large_fonts_mi;
75     private JMenu                       _tools_menu;
76     private JMenuItem                   _taxcolor_item;
77     private JMenuItem                   _confcolor_item;
78     private JMenuItem                   _midpoint_root_item;
79     private JMenu                       _view_jmenu;
80     private JMenuItem                   _view_as_XML_item;
81     private JMenuItem                   _view_as_NH_item;
82     private JMenuItem                   _view_as_nexus_item;
83     private JMenuItem                   _display_basic_information_item;
84     private JMenu                       _type_menu;
85     private JCheckBoxMenuItem           _rectangular_type_cbmi;
86     private JCheckBoxMenuItem           _triangular_type_cbmi;
87     private JCheckBoxMenuItem           _curved_type_cbmi;
88     private JCheckBoxMenuItem           _convex_type_cbmi;
89     private JCheckBoxMenuItem           _euro_type_cbmi;
90     private JCheckBoxMenuItem           _rounded_type_cbmi;
91     private JCheckBoxMenuItem           _unrooted_type_cbmi;
92     private JCheckBoxMenuItem           _circular_type_cbmi;
93     private JMenuItem                   _help_item;
94     private JMenuItem                   _about_item;
95     private JMenu                       _help_jmenu;
96     private JMenuItem                   _website_item;
97     private JMenuItem                   _phyloxml_website_item;
98     private JMenuItem                   _phyloxml_ref_item;
99     private JMenuItem                   _aptx_ref_item;
100     private JMenuItem                   _remove_branch_color_item;
101     private JMenuItem                   _remove_visual_styles_item;
102     private JCheckBoxMenuItem           _show_domain_labels;
103     private JCheckBoxMenuItem           _show_annotation_ref_source;
104     private JCheckBoxMenuItem           _color_labels_same_as_parent_branch;
105     private JCheckBoxMenuItem           _abbreviate_scientific_names;
106     private JCheckBoxMenuItem           _screen_antialias_cbmi;
107     private JCheckBoxMenuItem           _background_gradient_cbmi;
108     private JCheckBoxMenuItem           _color_by_taxonomic_group_cbmi;
109     private JRadioButtonMenuItem        _non_lined_up_cladograms_rbmi;
110     private JRadioButtonMenuItem        _uniform_cladograms_rbmi;
111     private JRadioButtonMenuItem        _ext_node_dependent_cladogram_rbmi;
112     private Options                     _options;
113     private JMenuItem                   _choose_font_mi;
114     private JMenuItem                   _switch_colors_mi;
115     JCheckBoxMenuItem                   _label_direction_cbmi;
116     private JCheckBoxMenuItem           _show_scale_cbmi;
117     private JCheckBoxMenuItem           _search_case_senstive_cbmi;
118     private JCheckBoxMenuItem           _search_whole_words_only_cbmi;
119     private JCheckBoxMenuItem           _inverse_search_result_cbmi;
120     private JCheckBoxMenuItem           _search_with_regex_cbmi;
121     private JCheckBoxMenuItem           _show_overview_cbmi;
122     private JMenuItem                   _choose_minimal_confidence_mi;
123     private JMenuItem                   _collapse_species_specific_subtrees;
124     private JMenuItem                   _overview_placment_mi;
125     private ButtonGroup                 _radio_group_1;
126     private JCheckBoxMenuItem           _show_default_node_shapes_internal_cbmi;
127     private JCheckBoxMenuItem           _show_default_node_shapes_external_cbmi;
128     private JCheckBoxMenuItem           _show_default_node_shapes_for_marked_cbmi;
129     private JMenuItem                   _cycle_node_shape_mi;
130     private JMenuItem                   _cycle_node_fill_mi;
131     private JMenuItem                   _choose_node_size_mi;
132     private JCheckBoxMenuItem           _show_confidence_stddev_cbmi;
133     private final LinkedList<TextFrame> _textframes      = new LinkedList<TextFrame>();
134     private JMenu                       _analysis_menu;
135     private JMenuItem                   _gsdi_item;
136     private JMenuItem                   _gsdir_item;
137     private Phylogeny                   _species_tree;
138     private JCheckBoxMenuItem           _right_line_up_domains_cbmi;
139     private JCheckBoxMenuItem           _line_up_renderable_data_cbmi;
140     // file menu:
141     private JMenuItem                   _save_item;
142     private JMenuItem                   _print_item;
143     private JMenuItem                   _write_to_pdf_item;
144     private JMenuItem                   _write_to_jpg_item;
145     private JMenuItem                   _write_to_gif_item;
146     private JMenuItem                   _write_to_tif_item;
147     private JMenuItem                   _write_to_png_item;
148     private JMenuItem                   _write_to_bmp_item;
149     private JMenu                       _file_jmenu;
150     private JFileChooser                _writetopdf_filechooser;
151     private File                        _current_dir;
152     private JFileChooser                _save_filechooser;
153     private JFileChooser                _writetographics_filechooser;
154     private JCheckBoxMenuItem           _graphics_export_visible_only_cbmi;
155     private JCheckBoxMenuItem           _antialias_print_cbmi;
156     private JCheckBoxMenuItem           _print_black_and_white_cbmi;
157     private JCheckBoxMenuItem           _print_using_actual_size_cbmi;
158     private JCheckBoxMenuItem           _graphics_export_using_actual_size_cbmi;
159     private JMenuItem                   _print_size_mi;
160     private JMenuItem                   _choose_pdf_width_mi;
161
162     @Override
163     public void actionPerformed( final ActionEvent e ) {
164         final Object o = e.getSource();
165         if ( o == _midpoint_root_item ) {
166             getMainPanel().getCurrentTreePanel().midpointRoot();
167         }
168         else if ( o == _gsdi_item ) {
169             if ( isSubtreeDisplayed() ) {
170                 return;
171             }
172             executeGSDI();
173         }
174         else if ( o == _gsdir_item ) {
175             if ( isSubtreeDisplayed() ) {
176                 return;
177             }
178             executeGSDIR();
179         }
180         else if ( o == _taxcolor_item ) {
181             getMainPanel().getCurrentTreePanel().taxColor();
182         }
183         else if ( o == _confcolor_item ) {
184             getMainPanel().getCurrentTreePanel().confColor();
185         }
186         else if ( o == _collapse_species_specific_subtrees ) {
187             if ( getCurrentTreePanel() != null ) {
188                 getCurrentTreePanel().collapseSpeciesSpecificSubtrees();
189             }
190         }
191         else if ( o == _remove_branch_color_item ) {
192             removeBranchColors();
193         }
194         else if ( o == _remove_visual_styles_item ) {
195             removeVisualStyles();
196         }
197         else if ( o == _switch_colors_mi ) {
198             switchColors();
199         }
200         else if ( o == _display_basic_information_item ) {
201             displayBasicInformation();
202         }
203         else if ( o == _view_as_NH_item ) {
204             viewAsNH();
205         }
206         else if ( o == _view_as_XML_item ) {
207             viewAsXML();
208         }
209         else if ( o == _view_as_nexus_item ) {
210             viewAsNexus();
211         }
212         else if ( o == _super_tiny_fonts_mi ) {
213             if ( getCurrentTreePanel() != null ) {
214                 getCurrentTreePanel().setSuperTinyFonts();
215                 getCurrentTreePanel().repaint();
216             }
217         }
218         else if ( o == _tiny_fonts_mi ) {
219             if ( getCurrentTreePanel() != null ) {
220                 getCurrentTreePanel().setTinyFonts();
221                 getCurrentTreePanel().repaint();
222             }
223         }
224         else if ( o == _small_fonts_mi ) {
225             if ( getCurrentTreePanel() != null ) {
226                 getCurrentTreePanel().setSmallFonts();
227                 getCurrentTreePanel().repaint();
228             }
229         }
230         else if ( o == _medium_fonts_mi ) {
231             if ( getCurrentTreePanel() != null ) {
232                 getCurrentTreePanel().setMediumFonts();
233                 getCurrentTreePanel().repaint();
234             }
235         }
236         else if ( o == _large_fonts_mi ) {
237             if ( getCurrentTreePanel() != null ) {
238                 getCurrentTreePanel().setLargeFonts();
239                 getCurrentTreePanel().repaint();
240             }
241         }
242         else if ( o == _choose_font_mi ) {
243             chooseFont();
244         }
245         else if ( o == _choose_minimal_confidence_mi ) {
246             chooseMinimalConfidence();
247         }
248         else if ( o == _choose_node_size_mi ) {
249             MainFrame.chooseNodeSize( getOptions(), this );
250         }
251         else if ( o == _overview_placment_mi ) {
252             MainFrame.cycleOverview( getOptions(), getCurrentTreePanel() );
253         }
254         else if ( o == _cycle_node_fill_mi ) {
255             MainFrame.cycleNodeFill( getOptions() );
256         }
257         else if ( o == _cycle_node_shape_mi ) {
258             MainFrame.cycleNodeShape( getOptions() );
259         }
260         else if ( o == _non_lined_up_cladograms_rbmi ) {
261             updateOptions( getOptions() );
262             _mainpanel.getControlPanel().showWhole();
263         }
264         else if ( o == _uniform_cladograms_rbmi ) {
265             updateOptions( getOptions() );
266             _mainpanel.getControlPanel().showWhole();
267         }
268         else if ( o == _ext_node_dependent_cladogram_rbmi ) {
269             updateOptions( getOptions() );
270             _mainpanel.getControlPanel().showWhole();
271         }
272         else if ( o == _search_case_senstive_cbmi ) {
273             updateOptions( getOptions() );
274             getMainPanel().getControlPanel().search0();
275             getMainPanel().getControlPanel().search1();
276         }
277         else if ( o == _search_whole_words_only_cbmi ) {
278             if ( ( _search_with_regex_cbmi != null ) && _search_whole_words_only_cbmi.isSelected() ) {
279                 _search_with_regex_cbmi.setSelected( false );
280             }
281             updateOptions( getOptions() );
282             getMainPanel().getControlPanel().search0();
283             getMainPanel().getControlPanel().search1();
284         }
285         else if ( o == _inverse_search_result_cbmi ) {
286             updateOptions( getOptions() );
287             getMainPanel().getControlPanel().search0();
288             getMainPanel().getControlPanel().search1();
289         }
290         else if ( o == _search_with_regex_cbmi ) {
291             if ( ( _search_whole_words_only_cbmi != null ) && _search_with_regex_cbmi.isSelected() ) {
292                 _search_whole_words_only_cbmi.setSelected( false );
293             }
294             if ( ( _search_case_senstive_cbmi != null ) && _search_with_regex_cbmi.isSelected() ) {
295                 _search_case_senstive_cbmi.setSelected( true );
296             }
297             updateOptions( getOptions() );
298             getMainPanel().getControlPanel().search0();
299             getMainPanel().getControlPanel().search1();
300         }
301         else if ( o == _show_scale_cbmi ) {
302             updateOptions( getOptions() );
303         }
304         else if ( o == _show_confidence_stddev_cbmi ) {
305             updateOptions( getOptions() );
306         }
307         else if ( o == _label_direction_cbmi ) {
308             updateOptions( getOptions() );
309         }
310         else if ( o == _abbreviate_scientific_names ) {
311             updateOptions( getOptions() );
312         }
313         else if ( o == _show_overview_cbmi ) {
314             updateOptions( getOptions() );
315             if ( getCurrentTreePanel() != null ) {
316                 getCurrentTreePanel().updateOvSizes();
317             }
318         }
319         else if ( ( o == _rectangular_type_cbmi ) || ( o == _triangular_type_cbmi ) || ( o == _curved_type_cbmi )
320                 || ( o == _convex_type_cbmi ) || ( o == _rounded_type_cbmi ) || ( o == _euro_type_cbmi )
321                 || ( o == _unrooted_type_cbmi ) || ( o == _circular_type_cbmi ) ) {
322             typeChanged( o );
323         }
324         else if ( o == _screen_antialias_cbmi ) {
325             updateOptions( getOptions() );
326             setupScreenTextAntialias( getMainPanel().getTreePanels(), isScreenAntialias() );
327         }
328         else if ( o == _background_gradient_cbmi ) {
329             updateOptions( getOptions() );
330         }
331         else if ( o == _show_domain_labels ) {
332             updateOptions( getOptions() );
333         }
334         else if ( o == _color_labels_same_as_parent_branch ) {
335             updateOptions( getOptions() );
336         }
337         else if ( o == _show_default_node_shapes_internal_cbmi ) {
338             updateOptions( getOptions() );
339         }
340         else if ( o == _show_default_node_shapes_external_cbmi ) {
341             updateOptions( getOptions() );
342         }
343         else if ( o == _about_item ) {
344             MainFrame.about();
345         }
346         else if ( o == _help_item ) {
347             try {
348                 AptxUtil.openWebsite( AptxConstants.APTX_DOC_SITE, true, this );
349             }
350             catch ( final IOException e1 ) {
351                 ForesterUtil.printErrorMessage( AptxConstants.PRG_NAME, e1.toString() );
352             }
353         }
354         else if ( o == _website_item ) {
355             try {
356                 AptxUtil.openWebsite( AptxConstants.APTX_WEB_SITE, true, this );
357             }
358             catch ( final IOException e1 ) {
359                 ForesterUtil.printErrorMessage( AptxConstants.PRG_NAME, e1.toString() );
360             }
361         }
362         else if ( o == _phyloxml_website_item ) {
363             try {
364                 AptxUtil.openWebsite( AptxConstants.PHYLOXML_WEB_SITE, true, this );
365             }
366             catch ( final IOException e1 ) {
367                 ForesterUtil.printErrorMessage( AptxConstants.PRG_NAME, e1.toString() );
368             }
369         }
370         else if ( o == _aptx_ref_item ) {
371             try {
372                 AptxUtil.openWebsite( AptxConstants.APTX_REFERENCE_URL, true, this );
373             }
374             catch ( final IOException e1 ) {
375                 ForesterUtil.printErrorMessage( AptxConstants.PRG_NAME, e1.toString() );
376             }
377         }
378         else if ( o == _phyloxml_ref_item ) {
379             try {
380                 AptxUtil.openWebsite( AptxConstants.PHYLOXML_REFERENCE_URL, true, this );
381             }
382             catch ( final IOException e1 ) {
383                 ForesterUtil.printErrorMessage( AptxConstants.PRG_NAME, e1.toString() );
384             }
385         }
386         else if ( o == _color_by_taxonomic_group_cbmi ) {
387             updateOptions( getOptions() );
388         }
389         else if ( o == _line_up_renderable_data_cbmi ) {
390             if ( !_line_up_renderable_data_cbmi.isSelected() ) {
391                 _right_line_up_domains_cbmi.setSelected( false );
392             }
393             updateOptions( getOptions() );
394         }
395         else if ( o == _right_line_up_domains_cbmi ) {
396             if ( _right_line_up_domains_cbmi.isSelected() ) {
397                 _line_up_renderable_data_cbmi.setSelected( true );
398             }
399             updateOptions( getOptions() );
400         }
401         else if ( o == _write_to_pdf_item ) {
402             final File curr_dir = MainFrame.writeToPdf( _mainpanel.getCurrentPhylogeny(),
403                                                         getMainPanel(),
404                                                         _writetopdf_filechooser,
405                                                         _current_dir,
406                                                         getContentPane(),
407                                                         this );
408             if ( curr_dir != null ) {
409                 setCurrentDir( curr_dir );
410             }
411         }
412         else if ( o == _write_to_jpg_item ) {
413             final File curr_dir = MainFrame.writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(),
414                                                                  GraphicsExportType.JPG,
415                                                                  _mainpanel,
416                                                                  _writetographics_filechooser,
417                                                                  this,
418                                                                  getContentPane(),
419                                                                  _current_dir );
420             if ( curr_dir != null ) {
421                 setCurrentDir( curr_dir );
422             }
423         }
424         else if ( o == _write_to_gif_item ) {
425             final File curr_dir = MainFrame.writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(),
426                                                                  GraphicsExportType.GIF,
427                                                                  _mainpanel,
428                                                                  _writetographics_filechooser,
429                                                                  this,
430                                                                  getContentPane(),
431                                                                  _current_dir );
432             if ( curr_dir != null ) {
433                 setCurrentDir( curr_dir );
434             }
435         }
436         else if ( o == _write_to_tif_item ) {
437             final File curr_dir = MainFrame.writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(),
438                                                                  GraphicsExportType.TIFF,
439                                                                  _mainpanel,
440                                                                  _writetographics_filechooser,
441                                                                  this,
442                                                                  getContentPane(),
443                                                                  _current_dir );
444             if ( curr_dir != null ) {
445                 setCurrentDir( curr_dir );
446             }
447         }
448         else if ( o == _write_to_bmp_item ) {
449             final File curr_dir = MainFrame.writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(),
450                                                                  GraphicsExportType.BMP,
451                                                                  _mainpanel,
452                                                                  _writetographics_filechooser,
453                                                                  this,
454                                                                  getContentPane(),
455                                                                  _current_dir );
456             if ( curr_dir != null ) {
457                 setCurrentDir( curr_dir );
458             }
459         }
460         else if ( o == _write_to_png_item ) {
461             final File curr_dir = MainFrame.writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(),
462                                                                  GraphicsExportType.PNG,
463                                                                  _mainpanel,
464                                                                  _writetographics_filechooser,
465                                                                  this,
466                                                                  getContentPane(),
467                                                                  _current_dir );
468             if ( curr_dir != null ) {
469                 setCurrentDir( curr_dir );
470             }
471         }
472         else if ( o == _print_item ) {
473             MainFrame.print( getCurrentTreePanel(), getOptions(), this );
474         }
475         else if ( o == _save_item ) {
476             final File new_dir = MainFrame.writeToFile( _mainpanel.getCurrentPhylogeny(),
477                                                         getMainPanel(),
478                                                         _save_filechooser,
479                                                         _current_dir,
480                                                         getContentPane(),
481                                                         this );
482             if ( new_dir != null ) {
483                 setCurrentDir( new_dir );
484             }
485         }
486         else if ( o == _graphics_export_visible_only_cbmi ) {
487             updateOptions( getOptions() );
488         }
489         else if ( o == _antialias_print_cbmi ) {
490             updateOptions( getOptions() );
491         }
492         else if ( o == _print_black_and_white_cbmi ) {
493             updateOptions( getOptions() );
494         }
495         else if ( o == _print_using_actual_size_cbmi ) {
496             updateOptions( getOptions() );
497         }
498         else if ( o == _graphics_export_using_actual_size_cbmi ) {
499             updateOptions( getOptions() );
500         }
501         else if ( o == _print_size_mi ) {
502             choosePrintSize();
503         }
504         else if ( o == _choose_pdf_width_mi ) {
505             choosePdfWidth();
506         }
507         repaint();
508     }
509
510     @Override
511     public void destroy() {
512         AptxUtil.printAppletMessage( NAME, "going to be destroyed " );
513         removeAllTextFrames();
514         if ( getMainPanel() != null ) {
515             getMainPanel().terminate();
516         }
517     }
518
519     /**
520      * This method returns the current external node data which
521      * has been selected by the user by clicking the "Return ..."
522      * menu item. This method is expected to be called from Javascript or
523      * something like it.
524      *
525      * @return current external node data as String
526      */
527     public String getCurrentExternalNodesDataBuffer() {
528         return getCurrentTreePanel().getCurrentExternalNodesDataBufferAsString();
529     }
530
531     public int getCurrentExternalNodesDataBufferChangeCounter() {
532         return getCurrentTreePanel().getCurrentExternalNodesDataBufferChangeCounter();
533     }
534
535     public int getCurrentExternalNodesDataBufferLength() {
536         return getCurrentTreePanel().getCurrentExternalNodesDataBufferAsString().length();
537     }
538
539     /**
540      * This method returns the current phylogeny as a string in the chosen format
541      *
542      * @param format must be NH, NHX, NEXUS or PHYLOXML
543      * @return the phylogeny string
544      * @author Herve Menager
545      */
546     public String getCurrentPhylogeny( final String format ) {
547         removeAllTextFrames();
548         if ( ( getMainPanel().getCurrentPhylogeny() == null ) || getMainPanel().getCurrentPhylogeny().isEmpty()
549                 || ( getMainPanel().getCurrentPhylogeny().getNumberOfExternalNodes() > 10000 ) ) {
550             return new String();
551         }
552         switch ( ForesterConstants.PhylogeneticTreeFormats.valueOf( format ) ) {
553             case NH:
554                 return getMainPanel().getCurrentPhylogeny().toNewHampshire();
555             case NHX:
556                 return getMainPanel().getCurrentPhylogeny().toNewHampshireX();
557             case NEXUS:
558                 return getMainPanel().getCurrentPhylogeny().toNexus();
559             case PHYLOXML:
560                 return getMainPanel().getCurrentPhylogeny().toPhyloXML( -1 );
561             default:
562                 break;
563         }
564         return new String();
565     }
566
567     /**
568      * This method returns a view of the current phylogeny in a chosen
569      * graphics format, base64-encoded in a string so that in can be used
570      * from javascript.
571      *
572      * @param format must be GraphicsExportType (gif, jpg, pdf, png, tif, bmp)
573      * @return the phylogeny string
574      * @author Herve Menager
575      */
576     public String getCurrentPhylogenyGraphicsAsBase64EncodedString( final String format ) {
577         final ByteArrayOutputStream baos = new ByteArrayOutputStream();
578         try {
579             AptxUtil.writePhylogenyToGraphicsByteArrayOutputStream( baos,
580                                                                     _mainpanel.getWidth(),
581                                                                     _mainpanel.getHeight(),
582                                                                     getCurrentTreePanel(),
583                                                                     getCurrentTreePanel().getControlPanel(),
584                                                                     GraphicsExportType.valueOf( format ),
585                                                                     getOptions() );
586         }
587         catch ( final IOException ioe ) {
588             ForesterUtil.printErrorMessage( NAME, ioe.toString() );
589             ioe.printStackTrace();
590             JOptionPane.showMessageDialog( this,
591                                            NAME + ": Failed to generate graphics: " + "\nException: " + ioe,
592                                            "Failed to generate graphics",
593                                            JOptionPane.ERROR_MESSAGE );
594             return null;
595         }
596         final byte[] bytes = baos.toByteArray();
597         final String dataImg = Base64.encodeBase64String( bytes );
598         return dataImg;
599     }
600
601     public Options getOptions() {
602         return _options;
603     }
604
605     @Override
606     public void init() {
607         _writetopdf_filechooser = new JFileChooser();
608         _writetopdf_filechooser.setMultiSelectionEnabled( false );
609         _writetopdf_filechooser.addChoosableFileFilter( MainFrame.pdffilter );
610         _writetographics_filechooser = new JFileChooser();
611         _writetographics_filechooser.setMultiSelectionEnabled( false );
612         _writetographics_filechooser.addChoosableFileFilter( MainFrame.graphicsfilefilter );
613         _save_filechooser = new JFileChooser();
614         _save_filechooser.setMultiSelectionEnabled( false );
615         _save_filechooser.setFileFilter( MainFrame.xmlfilter );
616         _save_filechooser.addChoosableFileFilter( MainFrame.nhfilter );
617         _save_filechooser.addChoosableFileFilter( MainFrame.nexusfilter );
618         _save_filechooser.addChoosableFileFilter( _save_filechooser.getAcceptAllFileFilter() );
619         try {
620             final String home_dir = System.getProperty( "user.home" );
621             _save_filechooser.setCurrentDirectory( new File( home_dir ) );
622             _writetopdf_filechooser.setCurrentDirectory( new File( home_dir ) );
623             _writetographics_filechooser.setCurrentDirectory( new File( home_dir ) );
624         }
625         catch ( final Exception e ) {
626             e.printStackTrace();
627             // Do nothing. Not important.
628         }
629         final String config_filename = getParameter( AptxConstants.APPLET_PARAM_NAME_FOR_CONFIG_FILE_URL );
630         AptxUtil.printAppletMessage( NAME, "URL for configuration file is: " + config_filename );
631         final Configuration configuration = new Configuration( config_filename, true, true, true );
632         setConfiguration( configuration );
633         setOptions( Options.createInstance( configuration ) );
634         setupUI();
635         final String tree_url_str = getParameter( AptxConstants.APPLET_PARAM_NAME_FOR_URL_OF_TREE_TO_LOAD );
636         if ( ForesterUtil.isEmpty( tree_url_str ) ) {
637             ForesterUtil.printErrorMessage( NAME, "could not get tree URL from "
638                     + AptxConstants.APPLET_PARAM_NAME_FOR_URL_OF_TREE_TO_LOAD );
639             JOptionPane.showMessageDialog( this, NAME + ": could not get tree URL from "
640                     + AptxConstants.APPLET_PARAM_NAME_FOR_URL_OF_TREE_TO_LOAD, "Failed get URL", JOptionPane.ERROR_MESSAGE );
641             return;
642         }
643         AptxUtil.printAppletMessage( NAME, "URL for phylogenies is " + tree_url_str );
644         // Get URL to tree file
645         URL phys_url = null;
646         try {
647             phys_url = new URL( tree_url_str );
648         }
649         catch ( final Exception e ) {
650             ForesterUtil.printErrorMessage( NAME, "error: " + e );
651             e.printStackTrace();
652             JOptionPane.showMessageDialog( this, NAME + ": Could not create URL from: \"" + tree_url_str
653                     + "\"\nException: " + e, "Failed to create URL", JOptionPane.ERROR_MESSAGE );
654         }
655         if ( phys_url == null ) {
656             ForesterUtil.printErrorMessage( NAME, "failed to get tree URL from "
657                     + AptxConstants.APPLET_PARAM_NAME_FOR_URL_OF_TREE_TO_LOAD );
658             JOptionPane.showMessageDialog( this,
659                                            NAME + ": Could not create URL from: \"" + tree_url_str,
660                                            "Failed to create URL",
661                                            JOptionPane.ERROR_MESSAGE );
662             return;
663         }
664         // Load the tree from URL
665         Phylogeny[] phys = null;
666         try {
667             phys = AptxUtil.readPhylogeniesFromUrl( phys_url,
668                                                     getConfiguration().isValidatePhyloXmlAgainstSchema(),
669                                                     getConfiguration().isReplaceUnderscoresInNhParsing(),
670                                                     getConfiguration().isInternalNumberAreConfidenceForNhParsing(),
671                                                     getConfiguration().getTaxonomyExtraction(),
672                                                     getConfiguration().isMidpointReroot() );
673         }
674         catch ( final Exception e ) {
675             ForesterUtil.printErrorMessage( NAME, e.toString() );
676             e.printStackTrace();
677             JOptionPane.showMessageDialog( this,
678                                            NAME + ": Failed to read phylogenies: " + "\nException: " + e,
679                                            "Failed to read phylogenies",
680                                            JOptionPane.ERROR_MESSAGE );
681         }
682         if ( phys == null ) {
683             ForesterUtil.printErrorMessage( NAME, "phylogenies from [" + phys_url + "] are null" );
684             JOptionPane.showMessageDialog( this,
685                                            NAME + ": phylogenies from [" + phys_url + "] are null",
686                                            "Failed to read phylogenies",
687                                            JOptionPane.ERROR_MESSAGE );
688             return;
689         }
690         else if ( phys.length < 1 ) {
691             ForesterUtil.printErrorMessage( NAME, "phylogenies from [" + phys_url + "] are empty" );
692             JOptionPane.showMessageDialog( this,
693                                            NAME + ": phylogenies from [" + phys_url + "] are empty",
694                                            "Failed to read phylogenies",
695                                            JOptionPane.ERROR_MESSAGE );
696             return;
697         }
698         else {
699             AptxUtil.printAppletMessage( NAME, "loaded " + phys.length + " phylogenies from: " + phys_url );
700         }
701         //
702         final String species_tree_url_str = getParameter( AptxConstants.APPLET_PARAM_NAME_FOR_URL_OF_SPECIES_TREE_TO_LOAD );
703         if ( !ForesterUtil.isEmpty( species_tree_url_str ) ) {
704             AptxUtil.printAppletMessage( NAME, "URL of species tree to load: \"" + species_tree_url_str + "\"" );
705             Phylogeny[] species_trees = null;
706             try {
707                 final URL species_tree_url = new URL( species_tree_url_str );
708                 species_trees = AptxUtil.readPhylogeniesFromUrl( species_tree_url,
709                                                                  configuration.isValidatePhyloXmlAgainstSchema(),
710                                                                  configuration.isReplaceUnderscoresInNhParsing(),
711                                                                  false,
712                                                                  TAXONOMY_EXTRACTION.NO,
713                                                                  false );
714             }
715             catch ( final IOException e ) {
716                 ForesterUtil.printErrorMessage( NAME, "could not read species tree from  [" + species_tree_url_str
717                         + "]" );
718                 JOptionPane.showMessageDialog( this, NAME + ": could not read species tree from  ["
719                         + species_tree_url_str + "]", "Failed to read species tree", JOptionPane.ERROR_MESSAGE );
720             }
721             if ( ( species_trees != null ) && ( species_trees.length > 0 ) ) {
722                 AptxUtil.printAppletMessage( NAME, "successfully read species tree" );
723                 if ( species_trees[ 0 ].isEmpty() ) {
724                     ForesterUtil.printErrorMessage( NAME, "species tree is empty" );
725                 }
726                 else if ( !species_trees[ 0 ].isRooted() ) {
727                     ForesterUtil.printErrorMessage( NAME, "species tree is not rooted" );
728                 }
729                 else {
730                     setSpeciesTree( species_trees[ 0 ] );
731                     AptxUtil.printAppletMessage( NAME, "species tree OK" );
732                 }
733             }
734         }
735         try {
736             setVisible( false );
737             setMainPanel( new MainPanelApplets( getConfiguration(), this ) );
738             _jmenubar = new JMenuBar();
739             if ( !getConfiguration().isHideControlPanelAndMenubar() ) {
740                 buildFileMenu();
741                 if ( !getConfiguration().isUseNativeUI() ) {
742                     _jmenubar.setBackground( getConfiguration().getGuiMenuBackgroundColor() );
743                 }
744                 if ( getSpeciesTree() != null ) {
745                     buildAnalysisMenu();
746                 }
747                 buildToolsMenu();
748                 buildViewMenu();
749                 buildFontSizeMenu();
750                 buildOptionsMenu();
751                 buildTypeMenu();
752                 buildHelpMenu();
753                 setJMenuBar( _jmenubar );
754             }
755             final Container contentpane = getContentPane();
756             contentpane.setLayout( new BorderLayout() );
757             contentpane.add( getMainPanel(), BorderLayout.CENTER );
758             addComponentListener( new ComponentAdapter() {
759
760                 @Override
761                 public void componentResized( final ComponentEvent e ) {
762                     if ( getMainPanel().getCurrentTreePanel() != null ) {
763                         getMainPanel().getCurrentTreePanel().calcParametersForPainting( getMainPanel()
764                                                                                                 .getCurrentTreePanel()
765                                                                                                 .getWidth(),
766                                                                                         getMainPanel()
767                                                                                                 .getCurrentTreePanel()
768                                                                                                 .getHeight() );
769                     }
770                 }
771             } );
772             if ( getConfiguration().isUseTabbedDisplay() ) {
773                 try {
774                     AptxUtil.printAppletMessage( NAME, "using tabbed display" );
775                     AptxUtil.addPhylogeniesToTabs( phys,
776                                                    new File( phys_url.getFile() ).getName(),
777                                                    phys_url.toString(),
778                                                    getConfiguration(),
779                                                    getMainPanel() );
780                 }
781                 catch ( final Exception e ) {
782                     ForesterUtil.printErrorMessage( NAME, e.toString() );
783                     e.printStackTrace();
784                 }
785             }
786             else {
787                 AptxUtil.printAppletMessage( NAME, "not using tabbed display" );
788                 if ( getSpeciesTree() != null ) {
789                     AptxUtil.printAppletMessage( NAME,
790                                                  "Warning: gsdi (gene duplication inference) only available tabbed display" );
791                 }
792                 AptxUtil.addPhylogenyToPanel( phys, getConfiguration(), getMainPanel() );
793             }
794             validate();
795             setName( NAME );
796             getMainPanel().getControlPanel().showWholeAll();
797             getMainPanel().getControlPanel().showWhole();
798             /* GUILHEM_BEG */
799             getCurrentTreePanel().getControlPanel().getSequenceRelationTypeBox().removeAllItems();
800             for( final SequenceRelation.SEQUENCE_RELATION_TYPE type : getMainPanel().getCurrentPhylogeny()
801                     .getRelevantSequenceRelationTypes() ) {
802                 getCurrentTreePanel().getControlPanel().getSequenceRelationTypeBox().addItem( type );
803             }
804             final String default_relation = getParameter( AptxConstants.APPLET_PARAM_NAME_FOR_DEFAULT_SEQUENCE_RELATION_TYPE );
805             if ( default_relation != null ) {
806                 getCurrentTreePanel().getControlPanel().getSequenceRelationTypeBox().setSelectedItem( default_relation );
807             }
808             final String default_sequence = getParameter( AptxConstants.APPLET_PARAM_NAME_FOR_DEFAULT_QUERY_SEQUENCE );
809             if ( default_sequence != null ) {
810                 getCurrentTreePanel().getControlPanel().getSequenceRelationBox().setSelectedItem( default_sequence );
811             }
812             /* GUILHEM_END */
813             System.gc();
814             AptxUtil.printAppletMessage( NAME, "successfully initialized" );
815             setVisible( true );
816         }
817         catch ( final Exception e ) {
818             ForesterUtil.printErrorMessage( NAME, e.toString() );
819             e.printStackTrace();
820         }
821     }
822
823     public void showTextFrame( final String s, final String title ) {
824         checkTextFrames();
825         _textframes.addLast( TextFrame.instantiate( s, title, _textframes ) );
826     }
827
828     @Override
829     public void start() {
830         if ( getMainPanel() != null ) {
831             getMainPanel().validate();
832         }
833         requestFocus();
834         requestFocusInWindow();
835         requestFocus();
836         AptxUtil.printAppletMessage( NAME, "started" );
837     }
838
839     private void chooseFont() {
840         final FontChooser fc = new FontChooser();
841         fc.setFont( getMainPanel().getTreeFontSet().getLargeFont() );
842         fc.showDialog( this, "Select the Base Font" );
843         getMainPanel().getTreeFontSet().setBaseFont( fc.getFont() );
844     }
845
846     private void chooseMinimalConfidence() {
847         final String s = ( String ) JOptionPane
848                 .showInputDialog( this,
849                                   "Please the minimum for confidence values to be displayed.\n" + "[current value: "
850                                           + getOptions().getMinConfidenceValue() + "]\n",
851                                   "Minimal Confidence Value",
852                                   JOptionPane.QUESTION_MESSAGE,
853                                   null,
854                                   null,
855                                   getOptions().getMinConfidenceValue() );
856         if ( !ForesterUtil.isEmpty( s ) ) {
857             boolean success = true;
858             double m = 0.0;
859             final String m_str = s.trim();
860             if ( !ForesterUtil.isEmpty( m_str ) ) {
861                 try {
862                     m = Double.parseDouble( m_str );
863                 }
864                 catch ( final Exception ex ) {
865                     success = false;
866                 }
867             }
868             else {
869                 success = false;
870             }
871             if ( success && ( m >= 0.0 ) ) {
872                 getOptions().setMinConfidenceValue( m );
873             }
874         }
875     }
876
877     private void choosePdfWidth() {
878         final String s = ( String ) JOptionPane.showInputDialog( this,
879                                                                  "Please enter the default line width for PDF export.\n"
880                                                                          + "[current value: "
881                                                                          + getOptions().getPrintLineWidth() + "]\n",
882                                                                          "Line Width for PDF Export",
883                                                                          JOptionPane.QUESTION_MESSAGE,
884                                                                          null,
885                                                                          null,
886                                                                          getOptions().getPrintLineWidth() );
887         if ( !ForesterUtil.isEmpty( s ) ) {
888             boolean success = true;
889             float f = 0.0f;
890             final String m_str = s.trim();
891             if ( !ForesterUtil.isEmpty( m_str ) ) {
892                 try {
893                     f = Float.parseFloat( m_str );
894                 }
895                 catch ( final Exception ex ) {
896                     success = false;
897                 }
898             }
899             else {
900                 success = false;
901             }
902             if ( success && ( f > 0.0 ) ) {
903                 getOptions().setPrintLineWidth( f );
904             }
905         }
906     }
907
908     private void choosePrintSize() {
909         final String s = ( String ) JOptionPane.showInputDialog( this,
910                                                                  "Please enter values for width and height,\nseparated by a comma.\n"
911                                                                          + "[current values: "
912                                                                          + getOptions().getPrintSizeX() + ", "
913                                                                          + getOptions().getPrintSizeY() + "]\n"
914                                                                          + "[A4: " + AptxConstants.A4_SIZE_X + ", "
915                                                                          + AptxConstants.A4_SIZE_Y + "]\n" + "[US Letter: "
916                                                                          + AptxConstants.US_LETTER_SIZE_X + ", "
917                                                                          + AptxConstants.US_LETTER_SIZE_Y + "]",
918                                                                          "Default Size for Graphics Export",
919                                                                          JOptionPane.QUESTION_MESSAGE,
920                                                                          null,
921                                                                          null,
922                                                                          getOptions().getPrintSizeX() + ", "
923                                                                                  + getOptions().getPrintSizeY() );
924         if ( !ForesterUtil.isEmpty( s ) && ( s.indexOf( ',' ) > 0 ) ) {
925             boolean success = true;
926             int x = 0;
927             int y = 0;
928             final String[] str_ary = s.split( "," );
929             if ( str_ary.length == 2 ) {
930                 final String x_str = str_ary[ 0 ].trim();
931                 final String y_str = str_ary[ 1 ].trim();
932                 if ( !ForesterUtil.isEmpty( x_str ) && !ForesterUtil.isEmpty( y_str ) ) {
933                     try {
934                         x = Integer.parseInt( x_str );
935                         y = Integer.parseInt( y_str );
936                     }
937                     catch ( final Exception ex ) {
938                         success = false;
939                     }
940                 }
941                 else {
942                     success = false;
943                 }
944             }
945             else {
946                 success = false;
947             }
948             if ( success && ( x > 1 ) && ( y > 1 ) ) {
949                 getOptions().setPrintSizeX( x );
950                 getOptions().setPrintSizeY( y );
951             }
952         }
953     }
954
955     private void customizeRadioButtonMenuItem( final JRadioButtonMenuItem item, final boolean is_selected ) {
956         if ( item != null ) {
957             item.setFont( MainFrame.menu_font );
958             if ( !getConfiguration().isUseNativeUI() ) {
959                 item.setBackground( getConfiguration().getGuiMenuBackgroundColor() );
960                 item.setForeground( getConfiguration().getGuiMenuTextColor() );
961             }
962             item.setSelected( is_selected );
963             item.addActionListener( this );
964         }
965     }
966
967     private Phylogeny getSpeciesTree() {
968         return _species_tree;
969     }
970
971     private boolean isScreenAntialias() {
972         return true;
973     }
974
975     private void removeBranchColors() {
976         if ( getMainPanel().getCurrentPhylogeny() != null ) {
977             AptxUtil.removeBranchColors( getMainPanel().getCurrentPhylogeny() );
978         }
979     }
980
981     private void removeVisualStyles() {
982         if ( getMainPanel().getCurrentPhylogeny() != null ) {
983             AptxUtil.removeVisualStyles( getMainPanel().getCurrentPhylogeny() );
984         }
985     }
986
987     private void setMainPanel( final MainPanelApplets main_panel ) {
988         _mainpanel = main_panel;
989     }
990
991     private void setSpeciesTree( final Phylogeny species_tree ) {
992         _species_tree = species_tree;
993     }
994
995     private void setupUI() {
996         try {
997             if ( getConfiguration().isUseNativeUI() ) {
998                 UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
999             }
1000             else {
1001                 UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
1002             }
1003         }
1004         catch ( final UnsupportedLookAndFeelException e ) {
1005             AptxUtil.dieWithSystemError( "UnsupportedLookAndFeelException: " + e.toString() );
1006         }
1007         catch ( final ClassNotFoundException e ) {
1008             AptxUtil.dieWithSystemError( "ClassNotFoundException: " + e.toString() );
1009         }
1010         catch ( final InstantiationException e ) {
1011             AptxUtil.dieWithSystemError( "InstantiationException: " + e.toString() );
1012         }
1013         catch ( final IllegalAccessException e ) {
1014             AptxUtil.dieWithSystemError( "IllegalAccessException: " + e.toString() );
1015         }
1016         catch ( final Exception e ) {
1017             AptxUtil.dieWithSystemError( e.toString() );
1018         }
1019     }
1020
1021     void buildAnalysisMenu() {
1022         _analysis_menu = MainFrame.createMenu( "Analysis", getConfiguration() );
1023         _analysis_menu.add( _gsdi_item = new JMenuItem( "GSDI (Generalized Speciation Duplication Inference)" ) );
1024         _analysis_menu.add( _gsdir_item = new JMenuItem( "GSDIR (GSDI with re-rooting)" ) );
1025         customizeJMenuItem( _gsdi_item );
1026         customizeJMenuItem( _gsdir_item );
1027         _analysis_menu.addSeparator();
1028         _jmenubar.add( _analysis_menu );
1029     }
1030
1031     void buildFileMenu() {
1032         _file_jmenu = MainFrame.createMenu( "File", getConfiguration() );
1033         _file_jmenu.add( _save_item = new JMenuItem( "Save Tree As..." ) );
1034         _file_jmenu.addSeparator();
1035         _file_jmenu.add( _write_to_pdf_item = new JMenuItem( "Export to PDF file ..." ) );
1036         if ( AptxUtil.canWriteFormat( "tif" ) || AptxUtil.canWriteFormat( "tiff" ) || AptxUtil.canWriteFormat( "TIF" ) ) {
1037             _file_jmenu.add( _write_to_tif_item = new JMenuItem( "Export to TIFF file..." ) );
1038         }
1039         _file_jmenu.add( _write_to_png_item = new JMenuItem( "Export to PNG file..." ) );
1040         _file_jmenu.add( _write_to_jpg_item = new JMenuItem( "Export to JPG file..." ) );
1041         if ( AptxUtil.canWriteFormat( "gif" ) ) {
1042             _file_jmenu.add( _write_to_gif_item = new JMenuItem( "Export to GIF file..." ) );
1043         }
1044         if ( AptxUtil.canWriteFormat( "bmp" ) ) {
1045             _file_jmenu.add( _write_to_bmp_item = new JMenuItem( "Export to BMP file..." ) );
1046         }
1047         _file_jmenu.addSeparator();
1048         _file_jmenu.add( _print_item = new JMenuItem( "Print..." ) );
1049         customizeJMenuItem( _save_item );
1050         customizeJMenuItem( _write_to_pdf_item );
1051         customizeJMenuItem( _write_to_png_item );
1052         customizeJMenuItem( _write_to_jpg_item );
1053         customizeJMenuItem( _write_to_gif_item );
1054         customizeJMenuItem( _write_to_tif_item );
1055         customizeJMenuItem( _write_to_bmp_item );
1056         customizeJMenuItem( _print_item );
1057         _jmenubar.add( _file_jmenu );
1058     }
1059
1060     void buildFontSizeMenu() {
1061         _font_size_menu = MainFrame.createMenu( MainFrame.FONT_SIZE_MENU_LABEL, getConfiguration() );
1062         _font_size_menu.add( _super_tiny_fonts_mi = new JMenuItem( "Super tiny fonts" ) );
1063         _font_size_menu.add( _tiny_fonts_mi = new JMenuItem( "Tiny fonts" ) );
1064         _font_size_menu.add( _small_fonts_mi = new JMenuItem( "Small fonts" ) );
1065         _font_size_menu.add( _medium_fonts_mi = new JMenuItem( "Medium fonts" ) );
1066         _font_size_menu.add( _large_fonts_mi = new JMenuItem( "Large fonts" ) );
1067         customizeJMenuItem( _super_tiny_fonts_mi );
1068         customizeJMenuItem( _tiny_fonts_mi );
1069         customizeJMenuItem( _small_fonts_mi );
1070         customizeJMenuItem( _medium_fonts_mi );
1071         customizeJMenuItem( _large_fonts_mi );
1072         _jmenubar.add( _font_size_menu );
1073     }
1074
1075     void buildHelpMenu() {
1076         _help_jmenu = MainFrame.createMenu( "Help", getConfiguration() );
1077         _help_jmenu.add( _help_item = new JMenuItem( "Documentation" ) );
1078         _help_jmenu.addSeparator();
1079         _help_jmenu.add( _website_item = new JMenuItem( "Archaeopteryx Home" ) );
1080         _aptx_ref_item = new JMenuItem( "Archaeopteryx Reference" );
1081         _help_jmenu.add( _phyloxml_website_item = new JMenuItem( "phyloXML Home" ) );
1082         _help_jmenu.add( _phyloxml_ref_item = new JMenuItem( "phyloXML Reference" ) );
1083         _help_jmenu.addSeparator();
1084         _help_jmenu.add( _about_item = new JMenuItem( "About" ) );
1085         customizeJMenuItem( _help_item );
1086         customizeJMenuItem( _website_item );
1087         customizeJMenuItem( _phyloxml_website_item );
1088         customizeJMenuItem( _aptx_ref_item );
1089         customizeJMenuItem( _phyloxml_ref_item );
1090         customizeJMenuItem( _about_item );
1091         _phyloxml_ref_item.setToolTipText( MainFrame.PHYLOXML_REF_TOOL_TIP );
1092         _aptx_ref_item.setToolTipText( MainFrame.APTX_REF_TOOL_TIP );
1093         _jmenubar.add( _help_jmenu );
1094     }
1095
1096     void buildOptionsMenu() {
1097         _options_jmenu = MainFrame.createMenu( MainFrame.OPTIONS_HEADER, getConfiguration() );
1098         _options_jmenu.addChangeListener( new ChangeListener() {
1099
1100             @Override
1101             public void stateChanged( final ChangeEvent e ) {
1102                 MainFrame.setOvPlacementColorChooseMenuItem( _overview_placment_mi, getOptions() );
1103                 MainFrame.setTextColorChooseMenuItem( _switch_colors_mi, getCurrentTreePanel() );
1104                 MainFrame
1105                         .setTextMinSupportMenuItem( _choose_minimal_confidence_mi, getOptions(), getCurrentTreePanel() );
1106                 MainFrame.setTextForFontChooserMenuItem( _choose_font_mi, MainFrame
1107                         .createCurrentFontDesc( getMainPanel().getTreeFontSet() ) );
1108                 setTextForGraphicsSizeChooserMenuItem( _print_size_mi, getOptions() );
1109                 setTextForPdfLineWidthChooserMenuItem( _choose_pdf_width_mi, getOptions() );
1110                 MainFrame.setCycleNodeFillMenuItem( _cycle_node_fill_mi, getOptions() );
1111                 MainFrame.setCycleNodeShapeMenuItem( _cycle_node_shape_mi, getOptions() );
1112                 MainFrame.setTextNodeSizeMenuItem( _choose_node_size_mi, getOptions() );
1113                 try {
1114                     getMainPanel().getControlPanel().setVisibilityOfDomainStrucureCB();
1115                     getMainPanel().getControlPanel().setVisibilityOfX();
1116                 }
1117                 catch ( final Exception ignore ) {
1118                     // do nothing, not important.
1119                 }
1120             }
1121         } );
1122         _options_jmenu.add( MainFrame.customizeMenuItemAsLabel( new JMenuItem( MainFrame.DISPLAY_SUBHEADER ),
1123                                                                 getConfiguration() ) );
1124         _options_jmenu
1125                 .add( _ext_node_dependent_cladogram_rbmi = new JRadioButtonMenuItem( MainFrame.NONUNIFORM_CLADOGRAMS_LABEL ) );
1126         _options_jmenu.add( _uniform_cladograms_rbmi = new JRadioButtonMenuItem( MainFrame.UNIFORM_CLADOGRAMS_LABEL ) );
1127         _options_jmenu
1128                 .add( _non_lined_up_cladograms_rbmi = new JRadioButtonMenuItem( MainFrame.NON_LINED_UP_CLADOGRAMS_LABEL ) );
1129         _radio_group_1 = new ButtonGroup();
1130         _radio_group_1.add( _ext_node_dependent_cladogram_rbmi );
1131         _radio_group_1.add( _uniform_cladograms_rbmi );
1132         _radio_group_1.add( _non_lined_up_cladograms_rbmi );
1133         _options_jmenu.add( _show_overview_cbmi = new JCheckBoxMenuItem( MainFrame.SHOW_OVERVIEW_LABEL ) );
1134         _options_jmenu.add( _show_scale_cbmi = new JCheckBoxMenuItem( MainFrame.DISPLAY_SCALE_LABEL ) );
1135         _options_jmenu
1136                 .add( _show_default_node_shapes_internal_cbmi = new JCheckBoxMenuItem( MainFrame.DISPLAY_NODE_BOXES_LABEL_INT ) );
1137         _options_jmenu
1138                 .add( _show_default_node_shapes_external_cbmi = new JCheckBoxMenuItem( MainFrame.DISPLAY_NODE_BOXES_LABEL_EXT ) );
1139         _options_jmenu
1140                 .add( _show_default_node_shapes_for_marked_cbmi = new JCheckBoxMenuItem( MainFrame.DISPLAY_NODE_BOXES_LABEL_MARKED ) );
1141         _options_jmenu.add( _line_up_renderable_data_cbmi = new JCheckBoxMenuItem( MainFrame.LINE_UP_RENDERABLE_DATA ) );
1142         if ( getConfiguration().doDisplayOption( Configuration.show_domain_architectures ) ) {
1143             _options_jmenu.add( _right_line_up_domains_cbmi = new JCheckBoxMenuItem( MainFrame.RIGHT_LINE_UP_DOMAINS ) );
1144             _options_jmenu.add( _show_domain_labels = new JCheckBoxMenuItem( MainFrame.SHOW_DOMAIN_LABELS_LABEL ) );
1145         }
1146         _options_jmenu.add( _show_annotation_ref_source = new JCheckBoxMenuItem( MainFrame.SHOW_ANN_REF_SOURCE_LABEL ) );
1147         _options_jmenu.add( _show_confidence_stddev_cbmi = new JCheckBoxMenuItem( MainFrame.SHOW_CONF_STDDEV_LABEL ) );
1148         _options_jmenu
1149                 .add( _color_by_taxonomic_group_cbmi = new JCheckBoxMenuItem( MainFrame.COLOR_BY_TAXONOMIC_GROUP ) );
1150         _options_jmenu
1151                 .add( _color_labels_same_as_parent_branch = new JCheckBoxMenuItem( MainFrame.COLOR_LABELS_LABEL ) );
1152         _color_labels_same_as_parent_branch.setToolTipText( MainFrame.COLOR_LABELS_TIP );
1153         _options_jmenu.add( _abbreviate_scientific_names = new JCheckBoxMenuItem( MainFrame.ABBREV_SN_LABEL ) );
1154         _options_jmenu.add( _label_direction_cbmi = new JCheckBoxMenuItem( MainFrame.LABEL_DIRECTION_LABEL ) );
1155         _label_direction_cbmi.setToolTipText( MainFrame.LABEL_DIRECTION_TIP );
1156         _options_jmenu.add( _screen_antialias_cbmi = new JCheckBoxMenuItem( MainFrame.SCREEN_ANTIALIAS_LABEL ) );
1157         _options_jmenu.add( _background_gradient_cbmi = new JCheckBoxMenuItem( MainFrame.BG_GRAD_LABEL ) );
1158         _options_jmenu.add( _cycle_node_shape_mi = new JMenuItem( MainFrame.CYCLE_NODE_SHAPE_LABEL ) );
1159         _options_jmenu.add( _cycle_node_fill_mi = new JMenuItem( MainFrame.CYCLE_NODE_FILL_LABEL ) );
1160         _options_jmenu.add( _choose_node_size_mi = new JMenuItem( MainFrame.CHOOSE_NODE_SIZE_LABEL ) );
1161         _options_jmenu.add( _choose_minimal_confidence_mi = new JMenuItem( "" ) );
1162         _options_jmenu.add( _overview_placment_mi = new JMenuItem( "" ) );
1163         _options_jmenu.add( _switch_colors_mi = new JMenuItem( "" ) );
1164         _options_jmenu.add( _choose_font_mi = new JMenuItem( "" ) );
1165         _options_jmenu.addSeparator();
1166         _options_jmenu.add( MainFrame.customizeMenuItemAsLabel( new JMenuItem( MainFrame.SEARCH_SUBHEADER ),
1167                                                                 getConfiguration() ) );
1168         _options_jmenu
1169                 .add( _search_case_senstive_cbmi = new JCheckBoxMenuItem( MainFrame.SEARCH_CASE_SENSITIVE_LABEL ) );
1170         _options_jmenu.add( _search_whole_words_only_cbmi = new JCheckBoxMenuItem( MainFrame.SEARCH_TERMS_ONLY_LABEL ) );
1171         _options_jmenu.add( _search_with_regex_cbmi = new JCheckBoxMenuItem( MainFrame.SEARCH_REGEX_LABEL ) );
1172         _search_with_regex_cbmi.setToolTipText( MainFrame.SEARCH_WITH_REGEX_TIP );
1173         _options_jmenu
1174                 .add( _inverse_search_result_cbmi = new JCheckBoxMenuItem( MainFrame.INVERSE_SEARCH_RESULT_LABEL ) );
1175         //
1176         _options_jmenu.addSeparator();
1177         _options_jmenu.add( MainFrame.customizeMenuItemAsLabel( new JMenuItem( "Graphics Export & Printing:" ),
1178                                                                 getConfiguration() ) );
1179         _options_jmenu.add( _antialias_print_cbmi = new JCheckBoxMenuItem( "Antialias" ) );
1180         _options_jmenu.add( _print_black_and_white_cbmi = new JCheckBoxMenuItem( "Export in Black and White" ) );
1181         _options_jmenu
1182                 .add( _print_using_actual_size_cbmi = new JCheckBoxMenuItem( "Use Current Image Size for PDF export and Printing" ) );
1183         _options_jmenu
1184                 .add( _graphics_export_using_actual_size_cbmi = new JCheckBoxMenuItem( "Use Current Image Size for PNG, JPG, and GIF export" ) );
1185         _options_jmenu
1186                 .add( _graphics_export_visible_only_cbmi = new JCheckBoxMenuItem( "Limit to Visible ('Screenshot') for PNG, JPG, and GIF export" ) );
1187         _options_jmenu.add( _print_size_mi = new JMenuItem( "" ) );
1188         _options_jmenu.add( _choose_pdf_width_mi = new JMenuItem( "" ) );
1189         //
1190         customizeCheckBoxMenuItem( _antialias_print_cbmi, getOptions().isAntialiasPrint() );
1191         customizeCheckBoxMenuItem( _print_black_and_white_cbmi, getOptions().isPrintBlackAndWhite() );
1192         customizeCheckBoxMenuItem( _graphics_export_visible_only_cbmi, getOptions().isGraphicsExportVisibleOnly() );
1193         customizeCheckBoxMenuItem( _print_using_actual_size_cbmi, getOptions().isPrintUsingActualSize() );
1194         customizeCheckBoxMenuItem( _graphics_export_using_actual_size_cbmi, getOptions()
1195                 .isGraphicsExportUsingActualSize() );
1196         customizeJMenuItem( _print_size_mi );
1197         customizeJMenuItem( _choose_pdf_width_mi );
1198         //
1199         customizeJMenuItem( _choose_font_mi );
1200         customizeJMenuItem( _choose_minimal_confidence_mi );
1201         customizeJMenuItem( _switch_colors_mi );
1202         customizeJMenuItem( _overview_placment_mi );
1203         customizeCheckBoxMenuItem( _color_by_taxonomic_group_cbmi, getOptions().isColorByTaxonomicGroup() );
1204         customizeCheckBoxMenuItem( _label_direction_cbmi,
1205                                    getOptions().getNodeLabelDirection() == NODE_LABEL_DIRECTION.RADIAL );
1206         customizeCheckBoxMenuItem( _screen_antialias_cbmi, getOptions().isAntialiasScreen() );
1207         customizeCheckBoxMenuItem( _background_gradient_cbmi, getOptions().isBackgroundColorGradient() );
1208         customizeCheckBoxMenuItem( _show_domain_labels, getOptions().isShowDomainLabels() );
1209         customizeCheckBoxMenuItem( _show_annotation_ref_source, getOptions().isShowAnnotationRefSource() );
1210         customizeCheckBoxMenuItem( _abbreviate_scientific_names, getOptions().isAbbreviateScientificTaxonNames() );
1211         customizeCheckBoxMenuItem( _show_default_node_shapes_external_cbmi, getOptions()
1212                 .isShowDefaultNodeShapesExternal() );
1213         customizeCheckBoxMenuItem( _show_default_node_shapes_internal_cbmi, getOptions()
1214                 .isShowDefaultNodeShapesInternal() );
1215         customizeCheckBoxMenuItem( _show_default_node_shapes_for_marked_cbmi, getOptions()
1216                 .isShowDefaultNodeShapesForMarkedNodes() );
1217         customizeJMenuItem( _cycle_node_shape_mi );
1218         customizeJMenuItem( _cycle_node_fill_mi );
1219         customizeJMenuItem( _choose_node_size_mi );
1220         customizeCheckBoxMenuItem( _color_labels_same_as_parent_branch, getOptions().isColorLabelsSameAsParentBranch() );
1221         customizeCheckBoxMenuItem( _search_case_senstive_cbmi, getOptions().isSearchCaseSensitive() );
1222         customizeCheckBoxMenuItem( _show_scale_cbmi, getOptions().isShowScale() );
1223         customizeRadioButtonMenuItem( _non_lined_up_cladograms_rbmi,
1224                                       getOptions().getCladogramType() == CLADOGRAM_TYPE.NON_LINED_UP );
1225         customizeRadioButtonMenuItem( _uniform_cladograms_rbmi,
1226                                       getOptions().getCladogramType() == CLADOGRAM_TYPE.TOTAL_NODE_SUM_DEP );
1227         customizeRadioButtonMenuItem( _ext_node_dependent_cladogram_rbmi,
1228                                       getOptions().getCladogramType() == CLADOGRAM_TYPE.EXT_NODE_SUM_DEP );
1229         customizeCheckBoxMenuItem( _show_overview_cbmi, getOptions().isShowOverview() );
1230         customizeCheckBoxMenuItem( _search_with_regex_cbmi, getOptions().isSearchWithRegex() );
1231         customizeCheckBoxMenuItem( _search_whole_words_only_cbmi, getOptions().isMatchWholeTermsOnly() );
1232         customizeCheckBoxMenuItem( _inverse_search_result_cbmi, getOptions().isInverseSearchResult() );
1233         customizeCheckBoxMenuItem( _show_confidence_stddev_cbmi, getOptions().isShowConfidenceStddev() );
1234         customizeCheckBoxMenuItem( _line_up_renderable_data_cbmi, getOptions().isLineUpRendarableNodeData() );
1235         customizeCheckBoxMenuItem( _right_line_up_domains_cbmi, getOptions().isRightLineUpDomains() );
1236         _jmenubar.add( _options_jmenu );
1237     }
1238
1239     void buildToolsMenu() {
1240         _tools_menu = MainFrame.createMenu( "Tools", getConfiguration() );
1241         _tools_menu.add( _confcolor_item = new JMenuItem( "Colorize Branches Depending on Confidence" ) );
1242         customizeJMenuItem( _confcolor_item );
1243         _tools_menu.add( _taxcolor_item = new JMenuItem( "Taxonomy Colorize Branches" ) );
1244         customizeJMenuItem( _taxcolor_item );
1245         _tools_menu.addSeparator();
1246         _tools_menu.add( _remove_visual_styles_item = new JMenuItem( "Delete All Visual Styles From Nodes" ) );
1247         _remove_visual_styles_item
1248                 .setToolTipText( "To remove all node visual styles (fonts, colors) from the current phylogeny." );
1249         customizeJMenuItem( _remove_visual_styles_item );
1250         _tools_menu.add( _remove_branch_color_item = new JMenuItem( "Delete All Colors From Branches" ) );
1251         _remove_branch_color_item.setToolTipText( "To remove all branch color values from the current phylogeny." );
1252         customizeJMenuItem( _remove_branch_color_item );
1253         _tools_menu.addSeparator();
1254         _tools_menu.add( _midpoint_root_item = new JMenuItem( "Midpoint-Root" ) );
1255         customizeJMenuItem( _midpoint_root_item );
1256         _tools_menu.addSeparator();
1257         _tools_menu.add( _collapse_species_specific_subtrees = new JMenuItem( "Collapse Species-Specific Subtrees" ) );
1258         customizeJMenuItem( _collapse_species_specific_subtrees );
1259         _jmenubar.add( _tools_menu );
1260     }
1261
1262     void buildTypeMenu() {
1263         _type_menu = MainFrame.createMenu( MainFrame.TYPE_MENU_HEADER, getConfiguration() );
1264         _type_menu.add( _rectangular_type_cbmi = new JCheckBoxMenuItem( MainFrame.RECTANGULAR_TYPE_CBMI_LABEL ) );
1265         _type_menu.add( _euro_type_cbmi = new JCheckBoxMenuItem( MainFrame.EURO_TYPE_CBMI_LABEL ) );
1266         _type_menu.add( _rounded_type_cbmi = new JCheckBoxMenuItem( MainFrame.ROUNDED_TYPE_CBMI_LABEL ) );
1267         _type_menu.add( _curved_type_cbmi = new JCheckBoxMenuItem( MainFrame.CURVED_TYPE_CBMI_LABEL ) );
1268         _type_menu.add( _triangular_type_cbmi = new JCheckBoxMenuItem( MainFrame.TRIANGULAR_TYPE_CBMI_LABEL ) );
1269         _type_menu.add( _convex_type_cbmi = new JCheckBoxMenuItem( MainFrame.CONVEX_TYPE_CBMI_LABEL ) );
1270         _type_menu.add( _unrooted_type_cbmi = new JCheckBoxMenuItem( MainFrame.UNROOTED_TYPE_CBMI_LABEL ) );
1271         _type_menu.add( _circular_type_cbmi = new JCheckBoxMenuItem( MainFrame.CIRCULAR_TYPE_CBMI_LABEL ) );
1272         customizeCheckBoxMenuItem( _rectangular_type_cbmi, false );
1273         customizeCheckBoxMenuItem( _triangular_type_cbmi, false );
1274         customizeCheckBoxMenuItem( _euro_type_cbmi, false );
1275         customizeCheckBoxMenuItem( _rounded_type_cbmi, false );
1276         customizeCheckBoxMenuItem( _curved_type_cbmi, false );
1277         customizeCheckBoxMenuItem( _convex_type_cbmi, false );
1278         customizeCheckBoxMenuItem( _unrooted_type_cbmi, false );
1279         customizeCheckBoxMenuItem( _circular_type_cbmi, false );
1280         _unrooted_type_cbmi.setToolTipText( MainFrame.USE_MOUSEWHEEL_SHIFT_TO_ROTATE );
1281         _circular_type_cbmi.setToolTipText( MainFrame.USE_MOUSEWHEEL_SHIFT_TO_ROTATE );
1282         initializeTypeMenu( getOptions() );
1283         _jmenubar.add( _type_menu );
1284     }
1285
1286     void buildViewMenu() {
1287         _view_jmenu = MainFrame.createMenu( "View", getConfiguration() );
1288         _view_jmenu
1289                 .add( _display_basic_information_item = new JMenuItem( MainFrame.SHOW_BASIC_TREE_INFORMATION_LABEL ) );
1290         _view_jmenu.addSeparator();
1291         _view_jmenu.add( _view_as_XML_item = new JMenuItem( "as phyloXML" ) );
1292         _view_jmenu.add( _view_as_NH_item = new JMenuItem( "as Newick" ) );
1293         _view_jmenu.add( _view_as_nexus_item = new JMenuItem( "as Nexus" ) );
1294         customizeJMenuItem( _display_basic_information_item );
1295         customizeJMenuItem( _view_as_NH_item );
1296         customizeJMenuItem( _view_as_XML_item );
1297         customizeJMenuItem( _view_as_nexus_item );
1298         _jmenubar.add( _view_jmenu );
1299     }
1300
1301     void checkTextFrames() {
1302         if ( _textframes.size() > 5 ) {
1303             try {
1304                 if ( _textframes.getFirst() != null ) {
1305                     _textframes.getFirst().removeMe();
1306                 }
1307                 else {
1308                     _textframes.removeFirst();
1309                 }
1310             }
1311             catch ( final NoSuchElementException e ) {
1312                 // Ignore.
1313             }
1314         }
1315     }
1316
1317     void clearCurrentExternalNodesDataBuffer() {
1318         getCurrentTreePanel().clearCurrentExternalNodesDataBuffer();
1319     }
1320
1321     void customizeCheckBoxMenuItem( final JCheckBoxMenuItem item, final boolean is_selected ) {
1322         if ( item != null ) {
1323             item.setFont( MainFrame.menu_font );
1324             if ( !getConfiguration().isUseNativeUI() ) {
1325                 item.setBackground( getConfiguration().getGuiMenuBackgroundColor() );
1326                 item.setForeground( getConfiguration().getGuiMenuTextColor() );
1327             }
1328             item.setSelected( is_selected );
1329             item.addActionListener( this );
1330         }
1331     }
1332
1333     void customizeJMenuItem( final JMenuItem jmi ) {
1334         if ( jmi != null ) {
1335             jmi.setFont( MainFrame.menu_font );
1336             if ( !getConfiguration().isUseNativeUI() ) {
1337                 jmi.setBackground( getConfiguration().getGuiMenuBackgroundColor() );
1338                 jmi.setForeground( getConfiguration().getGuiMenuTextColor() );
1339             }
1340             jmi.addActionListener( this );
1341         }
1342     }
1343
1344     void displayBasicInformation() {
1345         if ( ( getMainPanel() != null ) && ( getMainPanel().getCurrentPhylogeny() != null )
1346                 && !getMainPanel().getCurrentPhylogeny().isEmpty() ) {
1347             String title = "Basic Information";
1348             if ( !ForesterUtil.isEmpty( getMainPanel().getCurrentPhylogeny().getName() ) ) {
1349                 title = title + " for \"" + _mainpanel.getCurrentPhylogeny().getName() + "\"";
1350             }
1351             showTextFrame( AptxUtil.createBasicInformation( getMainPanel().getCurrentPhylogeny(), null ), title );
1352         }
1353     }
1354
1355     void executeGSDI() {
1356         if ( !isOKforSDI( false, true ) ) {
1357             return;
1358         }
1359         if ( !_mainpanel.getCurrentPhylogeny().isRooted() ) {
1360             JOptionPane.showMessageDialog( this,
1361                                            "Gene tree is not rooted.",
1362                                            "Cannot execute GSDI",
1363                                            JOptionPane.ERROR_MESSAGE );
1364             return;
1365         }
1366         final Phylogeny gene_tree = _mainpanel.getCurrentPhylogeny().copy();
1367         gene_tree.setAllNodesToNotCollapse();
1368         gene_tree.recalculateNumberOfExternalDescendants( false );
1369         GSDI gsdi = null;
1370         final Phylogeny species_tree = _species_tree.copy();
1371         try {
1372             gsdi = new GSDI( gene_tree, species_tree, false, true, true, true );
1373         }
1374         catch ( final SDIException e ) {
1375             JOptionPane.showMessageDialog( this,
1376                                            e.getLocalizedMessage(),
1377                                            "Error during GSDI",
1378                                            JOptionPane.ERROR_MESSAGE );
1379             return;
1380         }
1381         catch ( final Exception e ) {
1382             AptxUtil.unexpectedException( e );
1383             return;
1384         }
1385         gene_tree.setRerootable( false );
1386         gene_tree.clearHashIdToNodeMap();
1387         gene_tree.recalculateNumberOfExternalDescendants( true );
1388         _mainpanel.addPhylogenyInNewTab( gene_tree, getConfiguration(), "gene tree", null );
1389         getMainPanel().getControlPanel().setShowEvents( true );
1390         showWhole();
1391         final int selected = _mainpanel.getTabbedPane().getSelectedIndex();
1392         _mainpanel.addPhylogenyInNewTab( species_tree, getConfiguration(), "species tree", null );
1393         showWhole();
1394         _mainpanel.getTabbedPane().setSelectedIndex( selected );
1395         showWhole();
1396         _mainpanel.getCurrentTreePanel().setEdited( true );
1397         final int poly = PhylogenyMethods.countNumberOfPolytomies( species_tree );
1398         if ( gsdi.getStrippedExternalGeneTreeNodes().size() > 0 ) {
1399             JOptionPane.showMessageDialog( this,
1400                                            "Duplications: " + gsdi.getDuplicationsSum() + "\n"
1401                                                    + "Potential duplications: "
1402                                                    + gsdi.getSpeciationOrDuplicationEventsSum() + "\n"
1403                                                    + "Speciations: " + gsdi.getSpeciationsSum() + "\n"
1404                                                    + "Stripped gene tree nodes: "
1405                                                    + gsdi.getStrippedExternalGeneTreeNodes().size() + "\n"
1406                                                    + "Taxonomy linkage based on: " + gsdi.getTaxCompBase() + "\n"
1407                                                    + "Number of polytomies in species tree used: " + poly + "\n",
1408                                            "GSDI successfully completed",
1409                                            JOptionPane.WARNING_MESSAGE );
1410         }
1411         else {
1412             JOptionPane.showMessageDialog( this,
1413                                            "Duplications: " + gsdi.getDuplicationsSum() + "\n"
1414                                                    + "Potential duplications: "
1415                                                    + gsdi.getSpeciationOrDuplicationEventsSum() + "\n"
1416                                                    + "Speciations: " + gsdi.getSpeciationsSum() + "\n"
1417                                                    + "Stripped gene tree nodes: "
1418                                                    + gsdi.getStrippedExternalGeneTreeNodes().size() + "\n"
1419                                                    + "Taxonomy linkage based on: " + gsdi.getTaxCompBase() + "\n"
1420                                                    + "Number of polytomies in species tree used: " + poly + "\n",
1421                                            "GSDI successfully completed",
1422                                            JOptionPane.INFORMATION_MESSAGE );
1423         }
1424     }
1425
1426     void executeGSDIR() {
1427         if ( !isOKforSDI( false, false ) ) {
1428             return;
1429         }
1430         final int p = PhylogenyMethods.countNumberOfPolytomies( _mainpanel.getCurrentPhylogeny() );
1431         if ( ( p > 0 )
1432                 && !( ( p == 1 ) && ( _mainpanel.getCurrentPhylogeny().getRoot().getNumberOfDescendants() == 3 ) ) ) {
1433             JOptionPane.showMessageDialog( this,
1434                                            "Gene tree is not completely binary",
1435                                            "Cannot execute GSDI",
1436                                            JOptionPane.ERROR_MESSAGE );
1437             return;
1438         }
1439         final Phylogeny gene_tree = _mainpanel.getCurrentPhylogeny().copy();
1440         gene_tree.setAllNodesToNotCollapse();
1441         gene_tree.recalculateNumberOfExternalDescendants( false );
1442         GSDIR gsdir = null;
1443         final Phylogeny species_tree = _species_tree.copy();
1444         try {
1445             gsdir = new GSDIR( gene_tree, species_tree, true, true, true );
1446         }
1447         catch ( final SDIException e ) {
1448             JOptionPane.showMessageDialog( this,
1449                                            e.getLocalizedMessage(),
1450                                            "Error during GSDIR",
1451                                            JOptionPane.ERROR_MESSAGE );
1452             return;
1453         }
1454         catch ( final Exception e ) {
1455             AptxUtil.unexpectedException( e );
1456             return;
1457         }
1458         final Phylogeny result_gene_tree = gsdir.getMinDuplicationsSumGeneTree();
1459         result_gene_tree.setRerootable( false );
1460         result_gene_tree.clearHashIdToNodeMap();
1461         result_gene_tree.recalculateNumberOfExternalDescendants( true );
1462         PhylogenyMethods.orderAppearance( result_gene_tree.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
1463         _mainpanel.addPhylogenyInNewTab( result_gene_tree, getConfiguration(), "gene tree", null );
1464         getMainPanel().getControlPanel().setShowEvents( true );
1465         showWhole();
1466         final int selected = _mainpanel.getTabbedPane().getSelectedIndex();
1467         _mainpanel.addPhylogenyInNewTab( species_tree, getConfiguration(), "species tree", null );
1468         showWhole();
1469         _mainpanel.getTabbedPane().setSelectedIndex( selected );
1470         showWhole();
1471         _mainpanel.getCurrentTreePanel().setEdited( true );
1472         final int poly = PhylogenyMethods.countNumberOfPolytomies( species_tree );
1473         if ( gsdir.getStrippedExternalGeneTreeNodes().size() > 0 ) {
1474             JOptionPane.showMessageDialog( this,
1475                                            "Minimal duplications: " + gsdir.getMinDuplicationsSum() + "\n"
1476                                                    + "Speciations: " + gsdir.getSpeciationsSum() + "\n"
1477                                                    + "Stripped gene tree nodes: "
1478                                                    + gsdir.getStrippedExternalGeneTreeNodes().size() + "\n"
1479                                                    + "Taxonomy linkage based on: " + gsdir.getTaxCompBase() + "\n"
1480                                                    + "Number of polytomies in species tree used: " + poly + "\n",
1481                                            "GSDIR successfully completed",
1482                                            JOptionPane.WARNING_MESSAGE );
1483         }
1484         else {
1485             JOptionPane.showMessageDialog( this,
1486                                            "Minimal duplications: " + gsdir.getMinDuplicationsSum() + "\n"
1487                                                    + "Speciations: " + gsdir.getSpeciationsSum() + "\n"
1488                                                    + "Stripped gene tree nodes: "
1489                                                    + gsdir.getStrippedExternalGeneTreeNodes().size() + "\n"
1490                                                    + "Taxonomy linkage based on: " + gsdir.getTaxCompBase() + "\n"
1491                                                    + "Number of polytomies in species tree used: " + poly + "\n",
1492                                            "GSDIR successfully completed",
1493                                            JOptionPane.INFORMATION_MESSAGE );
1494         }
1495     }
1496
1497     Configuration getConfiguration() {
1498         return _configuration;
1499     }
1500
1501     File getCurrentDir() {
1502         if ( ( _current_dir == null ) || !_current_dir.canRead() ) {
1503             if ( ForesterUtil.isWindows() ) {
1504                 try {
1505                     _current_dir = new File( WindowsUtils.getCurrentUserDesktopPath() );
1506                 }
1507                 catch ( final Exception e ) {
1508                     _current_dir = null;
1509                 }
1510             }
1511         }
1512         if ( ( _current_dir == null ) || !_current_dir.canRead() ) {
1513             if ( System.getProperty( "user.home" ) != null ) {
1514                 _current_dir = new File( System.getProperty( "user.home" ) );
1515             }
1516             else if ( System.getProperty( "user.dir" ) != null ) {
1517                 _current_dir = new File( System.getProperty( "user.dir" ) );
1518             }
1519         }
1520         return _current_dir;
1521     }
1522
1523     TreePanel getCurrentTreePanel() {
1524         return getMainPanel().getCurrentTreePanel();
1525     }
1526
1527     JCheckBoxMenuItem getlabelDirectionCbmi() {
1528         return _label_direction_cbmi;
1529     }
1530
1531     MainPanel getMainPanel() {
1532         return _mainpanel;
1533     }
1534
1535     Options getOtions() {
1536         return _options;
1537     }
1538
1539     void initializeTypeMenu( final Options options ) {
1540         setTypeMenuToAllUnselected();
1541         try {
1542             switch ( options.getPhylogenyGraphicsType() ) {
1543                 case CONVEX:
1544                     _convex_type_cbmi.setSelected( true );
1545                     break;
1546                 case CURVED:
1547                     _curved_type_cbmi.setSelected( true );
1548                     break;
1549                 case EURO_STYLE:
1550                     _euro_type_cbmi.setSelected( true );
1551                     break;
1552                 case ROUNDED:
1553                     _rounded_type_cbmi.setSelected( true );
1554                     break;
1555                 case TRIANGULAR:
1556                     _triangular_type_cbmi.setSelected( true );
1557                     break;
1558                 case UNROOTED:
1559                     _unrooted_type_cbmi.setSelected( true );
1560                     break;
1561                 case CIRCULAR:
1562                     _circular_type_cbmi.setSelected( true );
1563                     break;
1564                 default:
1565                     _rectangular_type_cbmi.setSelected( true );
1566                     break;
1567             }
1568         }
1569         catch ( final NullPointerException np ) {
1570             // In all likelihood, this is caused by menu-less display.
1571         }
1572     }
1573
1574     boolean isOKforSDI( final boolean species_tree_has_to_binary, final boolean gene_tree_has_to_binary ) {
1575         if ( ( _mainpanel.getCurrentPhylogeny() == null ) || _mainpanel.getCurrentPhylogeny().isEmpty() ) {
1576             return false;
1577         }
1578         else if ( ( _species_tree == null ) || _species_tree.isEmpty() ) {
1579             JOptionPane.showMessageDialog( this,
1580                                            "No species tree loaded",
1581                                            "Cannot execute GSDI",
1582                                            JOptionPane.ERROR_MESSAGE );
1583             return false;
1584         }
1585         else if ( species_tree_has_to_binary && !_species_tree.isCompletelyBinary() ) {
1586             JOptionPane.showMessageDialog( this,
1587                                            "Species tree is not completely binary",
1588                                            "Cannot execute GSDI",
1589                                            JOptionPane.ERROR_MESSAGE );
1590             return false;
1591         }
1592         else if ( gene_tree_has_to_binary && !_mainpanel.getCurrentPhylogeny().isCompletelyBinary() ) {
1593             JOptionPane.showMessageDialog( this,
1594                                            "Gene tree is not completely binary",
1595                                            "Cannot execute GSDI",
1596                                            JOptionPane.ERROR_MESSAGE );
1597             return false;
1598         }
1599         else {
1600             return true;
1601         }
1602     }
1603
1604     boolean isSubtreeDisplayed() {
1605         if ( getCurrentTreePanel() != null ) {
1606             if ( getCurrentTreePanel().isCurrentTreeIsSubtree() ) {
1607                 JOptionPane
1608                         .showMessageDialog( this,
1609                                             "This operation can only be performed on a complete tree, not on the currently displayed sub-tree only.",
1610                                             "Operation can not be exectuted on a sub-tree",
1611                                             JOptionPane.WARNING_MESSAGE );
1612                 return true;
1613             }
1614         }
1615         return false;
1616     }
1617
1618     void removeAllTextFrames() {
1619         for( final TextFrame tf : _textframes ) {
1620             if ( tf != null ) {
1621                 tf.close();
1622             }
1623         }
1624         _textframes.clear();
1625     }
1626
1627     void setConfiguration( final Configuration configuration ) {
1628         _configuration = configuration;
1629     }
1630
1631     void setCurrentDir( final File current_dir ) {
1632         _current_dir = current_dir;
1633     }
1634
1635     void setOptions( final Options options ) {
1636         _options = options;
1637     }
1638
1639     void setSelectedTypeInTypeMenu( final PHYLOGENY_GRAPHICS_TYPE type ) {
1640         setTypeMenuToAllUnselected();
1641         try {
1642             switch ( type ) {
1643                 case CIRCULAR:
1644                     _circular_type_cbmi.setSelected( true );
1645                     break;
1646                 case CONVEX:
1647                     _convex_type_cbmi.setSelected( true );
1648                     break;
1649                 case CURVED:
1650                     _curved_type_cbmi.setSelected( true );
1651                     break;
1652                 case EURO_STYLE:
1653                     _euro_type_cbmi.setSelected( true );
1654                     break;
1655                 case ROUNDED:
1656                     _rounded_type_cbmi.setSelected( true );
1657                     break;
1658                 case RECTANGULAR:
1659                     _rectangular_type_cbmi.setSelected( true );
1660                     break;
1661                 case TRIANGULAR:
1662                     _triangular_type_cbmi.setSelected( true );
1663                     break;
1664                 case UNROOTED:
1665                     _unrooted_type_cbmi.setSelected( true );
1666                     break;
1667                 default:
1668                     throw new IllegalArgumentException( "unknown type: " + type );
1669             }
1670         }
1671         catch ( final NullPointerException np ) {
1672             // In all likelihood, this is caused by menu-less display.
1673         }
1674     }
1675
1676     void setTypeMenuToAllUnselected() {
1677         if ( _convex_type_cbmi != null ) {
1678             _convex_type_cbmi.setSelected( false );
1679         }
1680         if ( _curved_type_cbmi != null ) {
1681             _curved_type_cbmi.setSelected( false );
1682         }
1683         if ( _euro_type_cbmi != null ) {
1684             _euro_type_cbmi.setSelected( false );
1685         }
1686         if ( _rounded_type_cbmi != null ) {
1687             _rounded_type_cbmi.setSelected( false );
1688         }
1689         if ( _triangular_type_cbmi != null ) {
1690             _triangular_type_cbmi.setSelected( false );
1691         }
1692         if ( _rectangular_type_cbmi != null ) {
1693             _rectangular_type_cbmi.setSelected( false );
1694         }
1695         if ( _unrooted_type_cbmi != null ) {
1696             _unrooted_type_cbmi.setSelected( false );
1697         }
1698         if ( _circular_type_cbmi != null ) {
1699             _circular_type_cbmi.setSelected( false );
1700         }
1701     }
1702
1703     void showWhole() {
1704         _mainpanel.getControlPanel().showWhole();
1705     }
1706
1707     void switchColors() {
1708         final TreeColorSet colorset = getMainPanel().getCurrentTreePanel().getTreeColorSet();
1709         final ColorSchemeChooser csc = new ColorSchemeChooser( getMainPanel(), colorset );
1710         csc.setVisible( true );
1711         getMainPanel().setTreeColorSet( colorset );
1712     }
1713
1714     void typeChanged( final Object o ) {
1715         updateTypeCheckboxes( getOptions(), o );
1716         updateOptions( getOptions() );
1717         if ( getCurrentTreePanel() != null ) {
1718             final PHYLOGENY_GRAPHICS_TYPE previous_type = getCurrentTreePanel().getPhylogenyGraphicsType();
1719             final PHYLOGENY_GRAPHICS_TYPE new_type = getOptions().getPhylogenyGraphicsType();
1720             if ( ( ( previous_type == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) && ( new_type != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) )
1721                     || ( ( previous_type == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) && ( new_type != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) )
1722                     || ( ( previous_type != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) && ( new_type == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) )
1723                     || ( ( previous_type != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) && ( new_type == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) ) {
1724                 getCurrentTreePanel().getControlPanel().showWhole();
1725             }
1726             if ( getCurrentTreePanel().isPhyHasBranchLengths() && ( new_type != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) {
1727                 getCurrentTreePanel().getControlPanel().setDrawPhylogramEnabled( true );
1728             }
1729             else {
1730                 getCurrentTreePanel().getControlPanel().setDrawPhylogramEnabled( false );
1731             }
1732             getCurrentTreePanel().setPhylogenyGraphicsType( getOptions().getPhylogenyGraphicsType() );
1733             MainFrame.updateScreenTextAntialias( getMainPanel().getTreePanels() );
1734         }
1735     }
1736
1737     void updateOptions( final Options options ) {
1738         options.setAntialiasScreen( ( _screen_antialias_cbmi != null ) && _screen_antialias_cbmi.isSelected() );
1739         options.setBackgroundColorGradient( ( _background_gradient_cbmi != null )
1740                 && _background_gradient_cbmi.isSelected() );
1741         options.setShowDomainLabels( ( _show_domain_labels != null ) && _show_domain_labels.isSelected() );
1742         options.setShowAnnotationRefSource( ( _show_annotation_ref_source != null )
1743                 && _show_annotation_ref_source.isSelected() );
1744         options.setAbbreviateScientificTaxonNames( ( _abbreviate_scientific_names != null )
1745                 && _abbreviate_scientific_names.isSelected() );
1746         options.setColorLabelsSameAsParentBranch( ( _color_labels_same_as_parent_branch != null )
1747                 && _color_labels_same_as_parent_branch.isSelected() );
1748         options.setShowDefaultNodeShapesInternal( ( _show_default_node_shapes_internal_cbmi != null )
1749                 && _show_default_node_shapes_internal_cbmi.isSelected() );
1750         options.setShowDefaultNodeShapesExternal( ( _show_default_node_shapes_external_cbmi != null )
1751                 && _show_default_node_shapes_external_cbmi.isSelected() );
1752         options.setShowDefaultNodeShapesForMarkedNodes( ( _show_default_node_shapes_for_marked_cbmi != null )
1753                 && _show_default_node_shapes_for_marked_cbmi.isSelected() );
1754         if ( ( _non_lined_up_cladograms_rbmi != null ) && ( _non_lined_up_cladograms_rbmi.isSelected() ) ) {
1755             options.setCladogramType( CLADOGRAM_TYPE.NON_LINED_UP );
1756         }
1757         else if ( ( _uniform_cladograms_rbmi != null ) && ( _uniform_cladograms_rbmi.isSelected() ) ) {
1758             options.setCladogramType( CLADOGRAM_TYPE.TOTAL_NODE_SUM_DEP );
1759         }
1760         else if ( ( _ext_node_dependent_cladogram_rbmi != null ) && ( _ext_node_dependent_cladogram_rbmi.isSelected() ) ) {
1761             options.setCladogramType( CLADOGRAM_TYPE.EXT_NODE_SUM_DEP );
1762         }
1763         options.setSearchCaseSensitive( ( _search_case_senstive_cbmi != null )
1764                 && _search_case_senstive_cbmi.isSelected() );
1765         if ( ( _show_scale_cbmi != null ) && _show_scale_cbmi.isEnabled() ) {
1766             options.setShowScale( _show_scale_cbmi.isSelected() );
1767         }
1768         if ( _label_direction_cbmi != null ) {
1769             if ( _label_direction_cbmi.isSelected() ) {
1770                 options.setNodeLabelDirection( NODE_LABEL_DIRECTION.RADIAL );
1771             }
1772             else {
1773                 options.setNodeLabelDirection( NODE_LABEL_DIRECTION.HORIZONTAL );
1774             }
1775         }
1776         options.setShowOverview( ( _show_overview_cbmi != null ) && _show_overview_cbmi.isSelected() );
1777         options.setShowConfidenceStddev( ( _show_confidence_stddev_cbmi != null )
1778                 && _show_confidence_stddev_cbmi.isSelected() );
1779         options.setMatchWholeTermsOnly( ( _search_whole_words_only_cbmi != null )
1780                 && _search_whole_words_only_cbmi.isSelected() );
1781         options.setSearchWithRegex( ( _search_with_regex_cbmi != null ) && _search_with_regex_cbmi.isSelected() );
1782         options.setInverseSearchResult( ( _inverse_search_result_cbmi != null )
1783                 && _inverse_search_result_cbmi.isSelected() );
1784         options.setPrintUsingActualSize( ( _print_using_actual_size_cbmi != null )
1785                                          && ( _print_using_actual_size_cbmi.isSelected() ) );
1786         options.setGraphicsExportUsingActualSize( ( _graphics_export_using_actual_size_cbmi != null )
1787                                                   && ( _graphics_export_using_actual_size_cbmi.isSelected() ) );
1788         options.setAntialiasPrint( ( _antialias_print_cbmi != null ) && _antialias_print_cbmi.isSelected() );
1789         options.setPrintBlackAndWhite( ( _print_black_and_white_cbmi != null )
1790                                        && _print_black_and_white_cbmi.isSelected() );
1791         if ( ( _rectangular_type_cbmi != null ) && _rectangular_type_cbmi.isSelected() ) {
1792             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
1793         }
1794         else if ( ( _triangular_type_cbmi != null ) && _triangular_type_cbmi.isSelected() ) {
1795             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.TRIANGULAR );
1796         }
1797         else if ( ( _curved_type_cbmi != null ) && _curved_type_cbmi.isSelected() ) {
1798             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CURVED );
1799         }
1800         else if ( ( _convex_type_cbmi != null ) && _convex_type_cbmi.isSelected() ) {
1801             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CONVEX );
1802         }
1803         else if ( ( _euro_type_cbmi != null ) && _euro_type_cbmi.isSelected() ) {
1804             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE );
1805         }
1806         else if ( ( _rounded_type_cbmi != null ) && _rounded_type_cbmi.isSelected() ) {
1807             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.ROUNDED );
1808         }
1809         else if ( ( _unrooted_type_cbmi != null ) && _unrooted_type_cbmi.isSelected() ) {
1810             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.UNROOTED );
1811         }
1812         else if ( ( _circular_type_cbmi != null ) && _circular_type_cbmi.isSelected() ) {
1813             options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CIRCULAR );
1814         }
1815         if ( ( _color_by_taxonomic_group_cbmi != null ) && _color_by_taxonomic_group_cbmi.isEnabled() ) {
1816             options.setColorByTaxonomicGroup( _color_by_taxonomic_group_cbmi.isSelected() );
1817         }
1818         if ( ( _right_line_up_domains_cbmi != null ) && _right_line_up_domains_cbmi.isEnabled() ) {
1819             options.setRightLineUpDomains( _right_line_up_domains_cbmi.isSelected() );
1820         }
1821         if ( ( _line_up_renderable_data_cbmi != null ) && _line_up_renderable_data_cbmi.isEnabled() ) {
1822             options.setLineUpRendarableNodeData( _line_up_renderable_data_cbmi.isSelected() );
1823         }
1824         if ( _graphics_export_visible_only_cbmi != null ) {
1825             options.setGraphicsExportVisibleOnly( _graphics_export_visible_only_cbmi.isSelected() );
1826             if ( _graphics_export_visible_only_cbmi.isSelected() && ( _graphics_export_using_actual_size_cbmi != null ) ) {
1827                 _graphics_export_using_actual_size_cbmi.setSelected( true );
1828                 _graphics_export_using_actual_size_cbmi.setEnabled( false );
1829             }
1830             else {
1831                 _graphics_export_using_actual_size_cbmi.setEnabled( true );
1832             }
1833         }
1834     }
1835
1836     void updateTypeCheckboxes( final Options options, final Object o ) {
1837         setTypeMenuToAllUnselected();
1838         ( ( JCheckBoxMenuItem ) o ).setSelected( true );
1839     }
1840
1841     void viewAsNexus() {
1842         if ( ( getMainPanel().getCurrentPhylogeny() != null ) && !getMainPanel().getCurrentPhylogeny().isEmpty() ) {
1843             String title = "Nexus";
1844             if ( !ForesterUtil.isEmpty( getMainPanel().getCurrentPhylogeny().getName() ) ) {
1845                 title = "\"" + getMainPanel().getCurrentPhylogeny().getName() + "\" in " + title;
1846             }
1847             showTextFrame( getMainPanel().getCurrentPhylogeny().toNexus( getOptions()
1848                                    .getNhConversionSupportValueStyle() ),
1849                            title );
1850         }
1851     }
1852
1853     void viewAsNH() {
1854         if ( ( getMainPanel().getCurrentPhylogeny() != null ) && !getMainPanel().getCurrentPhylogeny().isEmpty() ) {
1855             String title = "New Hampshire";
1856             if ( !ForesterUtil.isEmpty( getMainPanel().getCurrentPhylogeny().getName() ) ) {
1857                 title = "\"" + getMainPanel().getCurrentPhylogeny().getName() + "\" in " + title;
1858             }
1859             showTextFrame( getMainPanel().getCurrentPhylogeny().toNewHampshire( getOptions()
1860                                    .getNhConversionSupportValueStyle() ),
1861                            title );
1862         }
1863     }
1864
1865     void viewAsXML() {
1866         if ( ( getMainPanel().getCurrentPhylogeny() != null ) && !getMainPanel().getCurrentPhylogeny().isEmpty() ) {
1867             String title = "phyloXML";
1868             if ( !ForesterUtil.isEmpty( getMainPanel().getCurrentPhylogeny().getName() ) ) {
1869                 title = "\"" + getMainPanel().getCurrentPhylogeny().getName() + "\" in " + title;
1870             }
1871             showTextFrame( getMainPanel().getCurrentPhylogeny().toPhyloXML( 0 ), title );
1872         }
1873     }
1874
1875     static void setTextForGraphicsSizeChooserMenuItem( final JMenuItem mi, final Options o ) {
1876         mi.setText( "Enter Default Size for Graphics Export... (current: " + o.getPrintSizeX() + ", "
1877                 + o.getPrintSizeY() + ")" );
1878     }
1879
1880     static void setTextForPdfLineWidthChooserMenuItem( final JMenuItem mi, final Options o ) {
1881         mi.setText( "Enter Default Line Width for PDF Export... (current: " + o.getPrintLineWidth() + ")" );
1882     }
1883
1884     static void setupScreenTextAntialias( final List<TreePanel> treepanels, final boolean antialias ) {
1885         for( final TreePanel tree_panel : treepanels ) {
1886             tree_panel.setTextAntialias();
1887         }
1888     }
1889 }