inprogress
[jalview.git] / forester / java / src / org / forester / archaeopteryx / AptxUtil.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
7 // All rights reserved
8 //
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
13 //
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
18 //
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 //
23 // Contact: phylosoft @ gmail . com
24 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
25
26 package org.forester.archaeopteryx;
27
28 import java.awt.Color;
29 import java.awt.Component;
30 import java.awt.Graphics2D;
31 import java.awt.GraphicsEnvironment;
32 import java.awt.Rectangle;
33 import java.awt.RenderingHints;
34 import java.awt.image.BufferedImage;
35 import java.io.ByteArrayOutputStream;
36 import java.io.File;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.lang.reflect.InvocationTargetException;
40 import java.lang.reflect.Method;
41 import java.net.URI;
42 import java.net.URL;
43 import java.text.ParseException;
44 import java.util.Arrays;
45 import java.util.HashMap;
46 import java.util.Iterator;
47 import java.util.List;
48 import java.util.Locale;
49 import java.util.Map;
50 import java.util.Set;
51 import java.util.SortedSet;
52 import java.util.TreeSet;
53 import java.util.regex.Matcher;
54 import java.util.regex.Pattern;
55
56 import javax.imageio.IIOImage;
57 import javax.imageio.ImageIO;
58 import javax.imageio.ImageWriteParam;
59 import javax.imageio.ImageWriter;
60 import javax.imageio.stream.ImageOutputStream;
61 import javax.swing.JApplet;
62 import javax.swing.JOptionPane;
63 import javax.swing.text.MaskFormatter;
64
65 import org.forester.analysis.TaxonomyDataManager;
66 import org.forester.io.parsers.PhylogenyParser;
67 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
68 import org.forester.io.parsers.nhx.NHXParser;
69 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
70 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
71 import org.forester.io.parsers.tol.TolParser;
72 import org.forester.io.parsers.util.ParserUtils;
73 import org.forester.phylogeny.Phylogeny;
74 import org.forester.phylogeny.PhylogenyMethods;
75 import org.forester.phylogeny.PhylogenyNode;
76 import org.forester.phylogeny.data.Accession;
77 import org.forester.phylogeny.data.BranchColor;
78 import org.forester.phylogeny.data.Taxonomy;
79 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
80 import org.forester.phylogeny.factories.PhylogenyFactory;
81 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
82 import org.forester.phylogeny.iterators.PreorderTreeIterator;
83 import org.forester.util.AsciiHistogram;
84 import org.forester.util.DescriptiveStatistics;
85 import org.forester.util.ForesterUtil;
86 import org.forester.ws.seqdb.UniProtTaxonomy;
87
88 public final class AptxUtil {
89
90     private final static Pattern  seq_identifier_pattern_1       = Pattern
91                                                                          .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})\\s*$" );
92     private final static Pattern  seq_identifier_pattern_2       = Pattern
93                                                                          .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})[|,; ].*$" );
94     private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
95                                                                          .getAvailableFontFamilyNames();
96     static {
97         Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
98     }
99
100     public static MaskFormatter createMaskFormatter( final String s ) {
101         MaskFormatter formatter = null;
102         try {
103             formatter = new MaskFormatter( s );
104         }
105         catch ( final ParseException e ) {
106             throw new IllegalArgumentException( e );
107         }
108         return formatter;
109     }
110
111     final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
112         final PhylogenyNodeIterator it = phy.iteratorPostorder();
113         while ( it.hasNext() ) {
114             if ( it.next().getNodeData().isHasEvent() ) {
115                 return true;
116             }
117         }
118         return false;
119     }
120
121     /**
122      * Returns true if at least one branch has a length larger than zero.
123      * 
124      * 
125      * @param phy
126      */
127     final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
128         final PhylogenyNodeIterator it = phy.iteratorPostorder();
129         while ( it.hasNext() ) {
130             if ( it.next().getDistanceToParent() > 0.0 ) {
131                 return true;
132             }
133         }
134         return false;
135     }
136
137     final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
138         final PhylogenyNodeIterator it = phy.iteratorPostorder();
139         while ( it.hasNext() ) {
140             if ( it.next().getBranchData().isHasConfidences() ) {
141                 return true;
142             }
143         }
144         return false;
145     }
146
147     final public static void launchWebBrowser( final URI uri,
148                                                final boolean is_applet,
149                                                final JApplet applet,
150                                                final String frame_name ) throws IOException {
151         if ( is_applet ) {
152             applet.getAppletContext().showDocument( uri.toURL(), frame_name );
153         }
154         else {
155             // This requires Java 1.6:
156             // =======================
157             // boolean no_desktop = false;
158             // try {
159             // if ( Desktop.isDesktopSupported() ) {
160             // System.out.println( "desktop supported" );
161             // final Desktop dt = Desktop.getDesktop();
162             // dt.browse( uri );
163             // }
164             // else {
165             // no_desktop = true;
166             // }
167             // }
168             // catch ( final Exception ex ) {
169             // ex.printStackTrace();
170             // no_desktop = true;
171             // }
172             // catch ( final Error er ) {
173             // er.printStackTrace();
174             // no_desktop = true;
175             // }
176             // if ( no_desktop ) {
177             // System.out.println( "desktop not supported" );
178             try {
179                 openUrlInWebBrowser( uri.toString() );
180             }
181             catch ( final Exception e ) {
182                 throw new IOException( e );
183             }
184             // }
185         }
186     }
187
188     public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
189         final String n = sequence_name.trim();
190         final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
191         String group1 = "";
192         String group2 = "";
193         if ( matcher1.matches() ) {
194             group1 = matcher1.group( 1 );
195             group2 = matcher1.group( 2 );
196         }
197         else {
198             final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
199             if ( matcher2.matches() ) {
200                 group1 = matcher2.group( 1 );
201                 group2 = matcher2.group( 2 );
202             }
203         }
204         if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
205             return null;
206         }
207         return new Accession( group2, group1 );
208     }
209
210     public final static void printWarningMessage( final String name, final String message ) {
211         System.out.println( "[" + name + "] > " + message );
212     }
213
214     final public static void showErrorMessage( final Component parent, final String error_msg ) {
215         printAppletMessage( Constants.PRG_NAME, error_msg );
216         JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
217                 + "] Error", JOptionPane.ERROR_MESSAGE );
218     }
219
220     public final static void showExtDescNodeDataUserSelectedHelper( final ControlPanel cp,
221                                                                     final PhylogenyNode node,
222                                                                     final List<String> data ) {
223         final StringBuilder sb = new StringBuilder();
224         if ( cp.isShowNodeNames() && !ForesterUtil.isEmpty( node.getName() ) ) {
225             showExtDescNodeDataUserSelectedHelperHelper( node.getName(), sb );
226         }
227         if ( cp.isShowGeneNames() && node.getNodeData().isHasSequence()
228                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) ) {
229             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getName(), sb );
230         }
231         if ( cp.isShowGeneSymbols() && node.getNodeData().isHasSequence()
232                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getSymbol() ) ) {
233             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getSymbol(), sb );
234         }
235         if ( cp.isShowSequenceAcc() && node.getNodeData().isHasSequence()
236                 && ( node.getNodeData().getSequence().getAccession() != null )
237                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().toString() ) ) {
238             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getAccession().toString(), sb );
239         }
240         if ( cp.isShowTaxonomyCode() && node.getNodeData().isHasTaxonomy()
241                 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
242             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getTaxonomyCode(), sb );
243         }
244         if ( cp.isShowTaxonomyScientificNames() && node.getNodeData().isHasTaxonomy()
245                 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
246             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getScientificName(), sb );
247         }
248         if ( ( cp.isShowGeneNames() || cp.isShowGeneSymbols() || cp.isShowSequenceAcc() )
249                 && node.getNodeData().isHasSequence()
250                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getMolecularSequence() ) ) {
251             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getMolecularSequence(), sb );
252         }
253         final String s = sb.toString().trim();
254         if ( !ForesterUtil.isEmpty( s ) ) {
255             data.add( s );
256         }
257     }
258
259     public final static void showExtDescNodeDataUserSelectedHelperHelper( final String s, final StringBuilder sb ) {
260         if ( sb.length() > 0 ) {
261             sb.append( "\t" );
262         }
263         sb.append( s );
264     }
265
266     final public static void showInformationMessage( final Component parent, final String title, final String msg ) {
267         JOptionPane.showMessageDialog( parent, msg, title, JOptionPane.INFORMATION_MESSAGE );
268     }
269
270     public static void writePhylogenyToGraphicsFile( final File intree,
271                                                      final File outfile,
272                                                      final int width,
273                                                      final int height,
274                                                      final GraphicsExportType type,
275                                                      final Configuration config ) throws IOException {
276         final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
277         Phylogeny[] phys = null;
278         phys = PhylogenyMethods.readPhylogenies( parser, intree );
279         writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
280     }
281
282     public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
283                                                      final File outfile,
284                                                      final int width,
285                                                      final int height,
286                                                      final GraphicsExportType type,
287                                                      final Configuration config ) throws IOException {
288         final Phylogeny[] phys = new Phylogeny[ 1 ];
289         phys[ 0 ] = phy;
290         final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
291         AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
292                 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
293         mf.end();
294     }
295
296     public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
297                                                                          final int width,
298                                                                          final int height,
299                                                                          final TreePanel tree_panel,
300                                                                          final ControlPanel ac,
301                                                                          final GraphicsExportType type,
302                                                                          final Options options ) throws IOException {
303         tree_panel.setParametersForPainting( width, height, true );
304         tree_panel.resetPreferredSize();
305         tree_panel.repaint();
306         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
307                                                                    RenderingHints.VALUE_RENDER_QUALITY );
308         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
309         if ( options.isAntialiasPrint() ) {
310             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
311             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
312         }
313         else {
314             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
315             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
316         }
317         final Phylogeny phylogeny = tree_panel.getPhylogeny();
318         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
319             return;
320         }
321         if ( outfile.isDirectory() ) {
322             throw new IOException( "\"" + outfile + "\" is a directory" );
323         }
324         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
325         final Graphics2D g2d = buffered_img.createGraphics();
326         g2d.setRenderingHints( rendering_hints );
327         tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
328         if ( type == GraphicsExportType.TIFF ) {
329             writeToTiff( outfile, buffered_img );
330         }
331         else {
332             ImageIO.write( buffered_img, type.toString(), outfile );
333         }
334         g2d.dispose();
335     }
336
337     final static void addPhylogeniesToTabs( final Phylogeny[] phys,
338                                             final String default_name,
339                                             final String full_path,
340                                             final Configuration configuration,
341                                             final MainPanel main_panel ) {
342         if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
343             JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
344                     + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
345                     + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
346         }
347         int i = 1;
348         for( final Phylogeny phy : phys ) {
349             if ( !phy.isEmpty() ) {
350                 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
351                     String my_name = "";
352                     String my_name_for_file = "";
353                     if ( phys.length > 1 ) {
354                         if ( !ForesterUtil.isEmpty( default_name ) ) {
355                             my_name = new String( default_name );
356                         }
357                         if ( !ForesterUtil.isEmpty( full_path ) ) {
358                             my_name_for_file = new String( full_path );
359                         }
360                         else if ( !ForesterUtil.isEmpty( default_name ) ) {
361                             my_name_for_file = new String( default_name );
362                         }
363                         String suffix = "";
364                         if ( my_name_for_file.indexOf( '.' ) > 0 ) {
365                             suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
366                                                                  my_name_for_file.length() );
367                             my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
368                         }
369                         if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
370                             my_name_for_file += "_";
371                         }
372                         if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
373                             my_name_for_file += phy.getName().replaceAll( " ", "_" );
374                         }
375                         else if ( phy.getIdentifier() != null ) {
376                             final StringBuffer sb = new StringBuffer();
377                             if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
378                                 sb.append( phy.getIdentifier().getProvider() );
379                                 sb.append( "_" );
380                             }
381                             sb.append( phy.getIdentifier().getValue() );
382                             my_name_for_file += sb;
383                         }
384                         else {
385                             my_name_for_file += i;
386                         }
387                         if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
388                                 && ( phy.getIdentifier() == null ) ) {
389                             my_name = my_name + " [" + i + "]";
390                         }
391                         if ( !ForesterUtil.isEmpty( suffix ) ) {
392                             my_name_for_file += suffix;
393                         }
394                     }
395                     else {
396                         if ( !ForesterUtil.isEmpty( default_name ) ) {
397                             my_name = new String( default_name );
398                         }
399                         my_name_for_file = "";
400                         if ( !ForesterUtil.isEmpty( full_path ) ) {
401                             my_name_for_file = new String( full_path );
402                         }
403                         else if ( !ForesterUtil.isEmpty( default_name ) ) {
404                             my_name_for_file = new String( default_name );
405                         }
406                         if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
407                             if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
408                                 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
409                             }
410                             else if ( phy.getIdentifier() != null ) {
411                                 final StringBuffer sb = new StringBuffer();
412                                 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
413                                     sb.append( phy.getIdentifier().getProvider() );
414                                     sb.append( "_" );
415                                 }
416                                 sb.append( phy.getIdentifier().getValue() );
417                                 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
418                             }
419                         }
420                     }
421                     main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
422                     main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
423                     lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
424                     ++i;
425                 }
426             }
427         }
428     }
429
430     final static void addPhylogenyToPanel( final Phylogeny[] phys,
431                                            final Configuration configuration,
432                                            final MainPanel main_panel ) {
433         final Phylogeny phy = phys[ 0 ];
434         main_panel.addPhylogenyInPanel( phy, configuration );
435         lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
436     }
437
438     final static Color calculateColorFromString( final String str ) {
439         final String species_uc = str.toUpperCase();
440         char first = species_uc.charAt( 0 );
441         char second = ' ';
442         char third = ' ';
443         if ( species_uc.length() > 1 ) {
444             second = species_uc.charAt( 1 );
445             if ( species_uc.length() > 2 ) {
446                 if ( species_uc.indexOf( " " ) > 0 ) {
447                     third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
448                 }
449                 else {
450                     third = species_uc.charAt( 2 );
451                 }
452             }
453         }
454         first = AptxUtil.normalizeCharForRGB( first );
455         second = AptxUtil.normalizeCharForRGB( second );
456         third = AptxUtil.normalizeCharForRGB( third );
457         if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
458             first = 0;
459         }
460         else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
461             second = 255;
462         }
463         return new Color( first, second, third );
464     }
465
466     // Returns true if the specified format name can be written
467     final static boolean canWriteFormat( final String format_name ) {
468         final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
469         return iter.hasNext();
470     }
471
472     final static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
473         boolean inferred = false;
474         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
475             final PhylogenyNode n = it.next();
476             if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
477                 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
478                 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
479                     AptxUtil.collapseSubtree( n, true );
480                     if ( !n.getNodeData().isHasTaxonomy() ) {
481                         n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
482                                 .getTaxonomy().copy() );
483                     }
484                     inferred = true;
485                 }
486                 else {
487                     n.setCollapse( false );
488                 }
489             }
490         }
491         if ( inferred ) {
492             phy.setRerootable( false );
493         }
494     }
495
496     final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
497         node.setCollapse( collapse );
498         if ( node.isExternal() ) {
499             return;
500         }
501         final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
502         while ( it.hasNext() ) {
503             it.next().setCollapse( collapse );
504         }
505     }
506
507     final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
508         double max_conf = 0.0;
509         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
510             final PhylogenyNode n = it.next();
511             n.getBranchData().setBranchColor( null );
512             if ( n.getBranchData().isHasConfidences() ) {
513                 final double conf = PhylogenyMethods.getConfidenceValue( n );
514                 if ( conf > max_conf ) {
515                     max_conf = conf;
516                 }
517             }
518         }
519         if ( max_conf > 0.0 ) {
520             final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
521             final Color br = tree_panel.getTreeColorSet().getBranchColor();
522             for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
523                 final PhylogenyNode n = it.next();
524                 if ( n.getBranchData().isHasConfidences() ) {
525                     final double conf = PhylogenyMethods.getConfidenceValue( n );
526                     final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
527                     colorizeSubtree( n, c );
528                 }
529             }
530         }
531     }
532
533     final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
534         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
535             it.next().getBranchData().setBranchColor( null );
536         }
537         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
538             final PhylogenyNode n = it.next();
539             if ( !n.getBranchData().isHasBranchColor() ) {
540                 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
541                 if ( tax != null ) {
542                     n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
543                     final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
544                     for( final PhylogenyNode desc : descs ) {
545                         desc.getBranchData()
546                                 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
547                     }
548                 }
549             }
550         }
551     }
552
553     final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
554         final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
555         int colorizations = 0;
556         for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
557             final PhylogenyNode n = it.next();
558             if ( n.getNodeData().isHasTaxonomy()
559                     && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
560                             || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
561                             .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
562                 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
563                         && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
564                     final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
565                             .getTaxonomy() ) );
566                     colorizeSubtree( n, c );
567                     ++colorizations;
568                     if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
569                         true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
570                     }
571                 }
572             }
573         }
574         for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
575             final PhylogenyNode node = it.next();
576             if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
577                     && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
578                 boolean success = false;
579                 if ( !true_lineage_to_color_map.isEmpty() ) {
580                     for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
581                         if ( true_lineage_to_color_map.containsKey( lin ) ) {
582                             colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
583                             ++colorizations;
584                             success = true;
585                             break;
586                         }
587                     }
588                 }
589                 if ( !success ) {
590                     final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
591                     for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
592                         final Taxonomy temp_tax = new Taxonomy();
593                         temp_tax.setScientificName( lin );
594                         if ( lineage_to_rank_map.containsKey( lin )
595                                 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
596                                 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
597                             final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
598                             colorizeSubtree( node, c );
599                             ++colorizations;
600                             true_lineage_to_color_map.put( lin, c.getValue() );
601                             break;
602                         }
603                         else {
604                             UniProtTaxonomy up = null;
605                             try {
606                                 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
607                             }
608                             catch ( final Exception e ) {
609                                 e.printStackTrace();
610                             }
611                             if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
612                                 lineage_to_rank_map.put( lin, up.getRank() );
613                                 if ( up.getRank().equalsIgnoreCase( rank ) ) {
614                                     final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
615                                     colorizeSubtree( node, c );
616                                     ++colorizations;
617                                     true_lineage_to_color_map.put( lin, c.getValue() );
618                                     break;
619                                 }
620                             }
621                         }
622                     }
623                 }
624             }
625         }
626         return colorizations;
627     }
628
629     final static String createBasicInformation( final Phylogeny phy ) {
630         final StringBuilder desc = new StringBuilder();
631         if ( ( phy != null ) && !phy.isEmpty() ) {
632             if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
633                 desc.append( "Name: " );
634                 desc.append( phy.getName() );
635                 desc.append( "\n" );
636             }
637             if ( phy.getIdentifier() != null ) {
638                 desc.append( "Id: " );
639                 desc.append( phy.getIdentifier() );
640                 desc.append( "\n" );
641             }
642             desc.append( "Rooted: " );
643             desc.append( phy.isRooted() );
644             desc.append( "\n" );
645             desc.append( "Rerootable: " );
646             desc.append( phy.isRerootable() );
647             desc.append( "\n" );
648             desc.append( "Node sum: " );
649             desc.append( phy.getNodeCount() );
650             desc.append( "\n" );
651             desc.append( "External node sum: " );
652             desc.append( phy.getNumberOfExternalNodes() );
653             desc.append( "\n" );
654             desc.append( "Internal node sum: " );
655             desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
656             desc.append( "\n" );
657             desc.append( "Branche sum: " );
658             desc.append( phy.getNumberOfBranches() );
659             desc.append( "\n" );
660             desc.append( "Depth: " );
661             desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
662             desc.append( "\n" );
663             desc.append( "Maximum distance to root: " );
664             desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
665             desc.append( "\n" );
666             final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
667             if ( taxs != null ) {
668                 desc.append( "Distinct external taxonomies: " );
669                 desc.append( taxs.size() );
670             }
671             desc.append( "\n" );
672             final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
673             if ( bs.getN() > 3 ) {
674                 desc.append( "\n" );
675                 desc.append( "Branch-length statistics: " );
676                 desc.append( "\n" );
677                 desc.append( "    Number of branches with non-negative branch-lengths: " + bs.getN() );
678                 desc.append( "\n" );
679                 desc.append( "    Median: " + ForesterUtil.round( bs.median(), 6 ) );
680                 desc.append( "\n" );
681                 desc.append( "    Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) );
682                 desc.append( "\n" );
683                 desc.append( "    SD: " + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) );
684                 desc.append( "\n" );
685                 desc.append( "    Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
686                 desc.append( "\n" );
687                 desc.append( "    Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
688                 desc.append( "\n" );
689                 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
690                     desc.append( "\n" );
691                     final AsciiHistogram histo = new AsciiHistogram( bs );
692                     desc.append( histo.toStringBuffer( 12, '#', 40, 7, "    " ) );
693                 }
694             }
695             final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
696             if ( ds.getN() > 2 ) {
697                 desc.append( "\n" );
698                 desc.append( "Descendants per node statistics: " );
699                 desc.append( "\n" );
700                 desc.append( "    Median: " + ForesterUtil.round( ds.median(), 2 ) );
701                 desc.append( "\n" );
702                 desc.append( "    Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
703                 desc.append( "\n" );
704                 desc.append( "    SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
705                 desc.append( "\n" );
706                 desc.append( "    Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
707                 desc.append( "\n" );
708                 desc.append( "    Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
709                 desc.append( "\n" );
710             }
711             List<DescriptiveStatistics> css = null;
712             try {
713                 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
714             }
715             catch ( final IllegalArgumentException e ) {
716                 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
717             }
718             if ( ( css != null ) && ( css.size() > 0 ) ) {
719                 desc.append( "\n" );
720                 for( int i = 0; i < css.size(); ++i ) {
721                     final DescriptiveStatistics cs = css.get( i );
722                     if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
723                         if ( css.size() > 1 ) {
724                             desc.append( "Support statistics " + ( i + 1 ) + ": " );
725                         }
726                         else {
727                             desc.append( "Support statistics: " );
728                         }
729                         if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
730                             desc.append( "\n" );
731                             desc.append( "    Type: " + cs.getDescription() );
732                         }
733                         desc.append( "\n" );
734                         desc.append( "    Branches with support: " + cs.getN() );
735                         desc.append( "\n" );
736                         desc.append( "    Median: " + ForesterUtil.round( cs.median(), 6 ) );
737                         desc.append( "\n" );
738                         desc.append( "    Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
739                         desc.append( "\n" );
740                         if ( cs.getN() > 2 ) {
741                             desc.append( "    SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
742                             desc.append( "\n" );
743                         }
744                         desc.append( "    Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
745                         desc.append( "\n" );
746                         desc.append( "    Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
747                         desc.append( "\n" );
748                     }
749                 }
750             }
751         }
752         return desc.toString();
753     }
754
755     /**
756      * Exits with -1.
757      * 
758      * 
759      * @param message
760      *            to message to be printed
761      */
762     final static void dieWithSystemError( final String message ) {
763         System.out.println();
764         System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
765         System.out.println( "Please contact the authors." );
766         System.out.println( Constants.PRG_NAME + " needs to close." );
767         System.out.println();
768         System.exit( -1 );
769     }
770
771     final static String[] getAllPossibleRanks() {
772         final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
773         int i = 0;
774         for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
775             if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
776                 str_array[ i++ ] = e;
777             }
778         }
779         return str_array;
780     }
781
782     final static String[] getAllRanks( final Phylogeny tree ) {
783         final SortedSet<String> ranks = new TreeSet<String>();
784         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
785             final PhylogenyNode n = it.next();
786             if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
787                 ranks.add( n.getNodeData().getTaxonomy().getRank() );
788             }
789         }
790         return ForesterUtil.stringSetToArray( ranks );
791     }
792
793     final static String[] getAvailableFontFamiliesSorted() {
794         return AVAILABLE_FONT_FAMILIES_SORTED;
795     }
796
797     final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
798         if ( !node.getNodeData().isHasEvent() ) {
799             return false;
800         }
801         if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
802             return false;
803         }
804         return true;
805     }
806
807     final static boolean isJava15() {
808         try {
809             final String s = ForesterUtil.JAVA_VERSION;
810             return s.startsWith( "1.5" );
811         }
812         catch ( final Exception e ) {
813             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
814             return false;
815         }
816     }
817
818     final static boolean isMac() {
819         try {
820             final String s = ForesterUtil.OS_NAME.toLowerCase();
821             return s.startsWith( "mac" );
822         }
823         catch ( final Exception e ) {
824             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
825             return false;
826         }
827     }
828
829     final static boolean isUsOrCanada() {
830         try {
831             if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
832                 return true;
833             }
834         }
835         catch ( final Exception e ) {
836             return false;
837         }
838         return false;
839     }
840
841     final static boolean isWindows() {
842         try {
843             final String s = ForesterUtil.OS_NAME.toLowerCase();
844             return s.indexOf( "win" ) > -1;
845         }
846         catch ( final Exception e ) {
847             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
848             return false;
849         }
850     }
851
852     final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
853                                                                       final ControlPanel atv_control,
854                                                                       final Configuration configuration ) {
855         if ( ( t != null ) && !t.isEmpty() ) {
856             if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
857                 atv_control.setDrawPhylogram( false );
858                 atv_control.setDrawPhylogramEnabled( false );
859             }
860             if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
861                 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
862                     if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
863                         atv_control.setDrawPhylogram( true );
864                         atv_control.setDrawPhylogramEnabled( true );
865                     }
866                     else {
867                         atv_control.setDrawPhylogram( false );
868                     }
869                 }
870             }
871             if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
872                 if ( atv_control.getWriteConfidenceCb() != null ) {
873                     if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
874                         atv_control.setCheckbox( Configuration.write_confidence_values, true );
875                     }
876                     else {
877                         atv_control.setCheckbox( Configuration.write_confidence_values, false );
878                     }
879                 }
880             }
881             if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
882                 if ( atv_control.getShowEventsCb() != null ) {
883                     if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
884                         atv_control.setCheckbox( Configuration.write_events, true );
885                     }
886                     else {
887                         atv_control.setCheckbox( Configuration.write_events, false );
888                     }
889                 }
890             }
891         }
892     }
893
894     final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
895         try {
896             AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
897         }
898         catch ( final Exception e ) {
899             throw new IOException( e );
900         }
901     }
902
903     final static void printAppletMessage( final String applet_name, final String message ) {
904         System.out.println( "[" + applet_name + "] > " + message );
905     }
906
907     final static Phylogeny[] readPhylogeniesFromUrl( final URL url,
908                                                      final boolean phyloxml_validate_against_xsd,
909                                                      final boolean replace_underscores,
910                                                      final boolean internal_numbers_are_confidences,
911                                                      final TAXONOMY_EXTRACTION taxonomy_extraction )
912             throws FileNotFoundException, IOException {
913         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
914         final PhylogenyParser parser;
915         boolean nhx_or_nexus = false;
916         if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
917             parser = new TolParser();
918         }
919         else {
920             parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
921             if ( parser instanceof NHXParser ) {
922                 nhx_or_nexus = true;
923                 final NHXParser nhx = ( NHXParser ) parser;
924                 nhx.setReplaceUnderscores( replace_underscores );
925                 nhx.setIgnoreQuotes( false );
926                 nhx.setTaxonomyExtraction( taxonomy_extraction );
927             }
928             else if ( parser instanceof NexusPhylogeniesParser ) {
929                 nhx_or_nexus = true;
930                 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
931                 nex.setReplaceUnderscores( replace_underscores );
932                 nex.setIgnoreQuotes( false );
933             }
934         }
935         final Phylogeny[] phys = factory.create( url.openStream(), parser );
936         if ( nhx_or_nexus && internal_numbers_are_confidences ) {
937             for( final Phylogeny phy : phys ) {
938                 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
939             }
940         }
941         return phys;
942     }
943
944     final static void removeBranchColors( final Phylogeny phy ) {
945         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
946             it.next().getBranchData().setBranchColor( null );
947         }
948     }
949
950     final static void unexpectedError( final Error e ) {
951         System.err.println();
952         e.printStackTrace( System.err );
953         System.err.println();
954         final StringBuffer sb = new StringBuffer();
955         for( final StackTraceElement s : e.getStackTrace() ) {
956             sb.append( s + "\n" );
957         }
958         JOptionPane
959                 .showMessageDialog( null,
960                                     "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
961                                             + Constants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
962                                             + sb,
963                                     "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
964                                     JOptionPane.ERROR_MESSAGE );
965         System.exit( -1 );
966     }
967
968     final static void outOfMemoryError( final OutOfMemoryError e ) {
969         System.err.println();
970         System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
971         System.err.println();
972         e.printStackTrace();
973         System.err.println();
974         JOptionPane.showMessageDialog( null,
975                                        "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
976                                                + "\n\nError: " + e.getLocalizedMessage(),
977                                        "Out of Memory Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
978                                        JOptionPane.ERROR_MESSAGE );
979         System.exit( -1 );
980     }
981
982     final static void unexpectedException( final Exception e ) {
983         System.err.println();
984         e.printStackTrace( System.err );
985         System.err.println();
986         final StringBuffer sb = new StringBuffer();
987         for( final StackTraceElement s : e.getStackTrace() ) {
988             sb.append( s + "\n" );
989         }
990         JOptionPane.showMessageDialog( null,
991                                        "An unexpected exception has occured. \nPlease contact: "
992                                                + Constants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
993                                                + "\n" + sb,
994                                        "Unexpected Exception [" + Constants.PRG_NAME + Constants.VERSION + "]",
995                                        JOptionPane.ERROR_MESSAGE );
996     }
997
998     final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
999                                                                        int width,
1000                                                                        int height,
1001                                                                        final TreePanel tree_panel,
1002                                                                        final ControlPanel ac,
1003                                                                        final GraphicsExportType type,
1004                                                                        final Options options ) throws IOException {
1005         if ( !options.isGraphicsExportUsingActualSize() ) {
1006             if ( options.isGraphicsExportVisibleOnly() ) {
1007                 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1008             }
1009             tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1010             tree_panel.resetPreferredSize();
1011             tree_panel.repaint();
1012         }
1013         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1014                                                                    RenderingHints.VALUE_RENDER_QUALITY );
1015         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1016         if ( options.isAntialiasPrint() ) {
1017             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1018             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1019         }
1020         else {
1021             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1022             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1023         }
1024         final Phylogeny phylogeny = tree_panel.getPhylogeny();
1025         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1026             return "";
1027         }
1028         Rectangle visible = null;
1029         if ( !options.isGraphicsExportUsingActualSize() ) {
1030             width = options.getPrintSizeX();
1031             height = options.getPrintSizeY();
1032         }
1033         else if ( options.isGraphicsExportVisibleOnly() ) {
1034             visible = tree_panel.getVisibleRect();
1035             width = visible.width;
1036             height = visible.height;
1037         }
1038         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1039         Graphics2D g2d = buffered_img.createGraphics();
1040         g2d.setRenderingHints( rendering_hints );
1041         int x = 0;
1042         int y = 0;
1043         if ( options.isGraphicsExportVisibleOnly() ) {
1044             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1045             g2d.setClip( null );
1046             x = visible.x;
1047             y = visible.y;
1048         }
1049         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1050         ImageIO.write( buffered_img, type.toString(), baos );
1051         g2d.dispose();
1052         System.gc();
1053         if ( !options.isGraphicsExportUsingActualSize() ) {
1054             tree_panel.getMainPanel().getControlPanel().showWhole();
1055         }
1056         String msg = baos.toString();
1057         if ( ( width > 0 ) && ( height > 0 ) ) {
1058             msg += " [size: " + width + ", " + height + "]";
1059         }
1060         return msg;
1061     }
1062
1063     final static String writePhylogenyToGraphicsFile( final String file_name,
1064                                                       int width,
1065                                                       int height,
1066                                                       final TreePanel tree_panel,
1067                                                       final ControlPanel ac,
1068                                                       final GraphicsExportType type,
1069                                                       final Options options ) throws IOException {
1070         if ( !options.isGraphicsExportUsingActualSize() ) {
1071             if ( options.isGraphicsExportVisibleOnly() ) {
1072                 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1073             }
1074             tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1075             tree_panel.resetPreferredSize();
1076             tree_panel.repaint();
1077         }
1078         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1079                                                                    RenderingHints.VALUE_RENDER_QUALITY );
1080         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1081         if ( options.isAntialiasPrint() ) {
1082             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1083             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1084         }
1085         else {
1086             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1087             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1088         }
1089         final Phylogeny phylogeny = tree_panel.getPhylogeny();
1090         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1091             return "";
1092         }
1093         final File file = new File( file_name );
1094         if ( file.isDirectory() ) {
1095             throw new IOException( "\"" + file_name + "\" is a directory" );
1096         }
1097         Rectangle visible = null;
1098         if ( !options.isGraphicsExportUsingActualSize() ) {
1099             width = options.getPrintSizeX();
1100             height = options.getPrintSizeY();
1101         }
1102         else if ( options.isGraphicsExportVisibleOnly() ) {
1103             visible = tree_panel.getVisibleRect();
1104             width = visible.width;
1105             height = visible.height;
1106         }
1107         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1108         Graphics2D g2d = buffered_img.createGraphics();
1109         g2d.setRenderingHints( rendering_hints );
1110         int x = 0;
1111         int y = 0;
1112         if ( options.isGraphicsExportVisibleOnly() ) {
1113             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1114             g2d.setClip( null );
1115             x = visible.x;
1116             y = visible.y;
1117         }
1118         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1119         if ( type == GraphicsExportType.TIFF ) {
1120             writeToTiff( file, buffered_img );
1121         }
1122         else {
1123             ImageIO.write( buffered_img, type.toString(), file );
1124         }
1125         g2d.dispose();
1126         System.gc();
1127         if ( !options.isGraphicsExportUsingActualSize() ) {
1128             tree_panel.getMainPanel().getControlPanel().showWhole();
1129         }
1130         String msg = file.toString();
1131         if ( ( width > 0 ) && ( height > 0 ) ) {
1132             msg += " [size: " + width + ", " + height + "]";
1133         }
1134         return msg;
1135     }
1136
1137     final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1138         // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1139         ImageWriter writer = null;
1140         ImageOutputStream ios = null;
1141         // Find an appropriate writer:
1142         final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1143         if ( it.hasNext() ) {
1144             writer = it.next();
1145         }
1146         else {
1147             throw new IOException( "failed to get TIFF image writer" );
1148         }
1149         // Setup writer:
1150         ios = ImageIO.createImageOutputStream( file );
1151         writer.setOutput( ios );
1152         final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1153         image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1154         // see writeParam.getCompressionTypes() for available compression type
1155         // strings.
1156         image_write_param.setCompressionType( "PackBits" );
1157         final String t[] = image_write_param.getCompressionTypes();
1158         for( final String string : t ) {
1159             System.out.println( string );
1160         }
1161         // Convert to an IIOImage:
1162         final IIOImage iio_image = new IIOImage( image, null, null );
1163         writer.write( null, iio_image, image_write_param );
1164     }
1165
1166     private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
1167         node.getBranchData().setBranchColor( c );
1168         final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
1169         for( final PhylogenyNode desc : descs ) {
1170             desc.getBranchData().setBranchColor( c );
1171         }
1172     }
1173
1174     final private static char normalizeCharForRGB( char c ) {
1175         c -= 65;
1176         c *= 10.2;
1177         c = c > 255 ? 255 : c;
1178         c = c < 0 ? 0 : c;
1179         return c;
1180     }
1181
1182     final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
1183             SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
1184             InvocationTargetException, InterruptedException {
1185         final String os = System.getProperty( "os.name" );
1186         final Runtime runtime = Runtime.getRuntime();
1187         if ( os.toLowerCase().startsWith( "win" ) ) {
1188             Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
1189         }
1190         else if ( isMac() ) {
1191             final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
1192             final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
1193             open_url.invoke( null, new Object[] { url } );
1194         }
1195         else {
1196             final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
1197             String browser = null;
1198             for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
1199                 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
1200                     browser = browsers[ i ];
1201                 }
1202             }
1203             if ( browser == null ) {
1204                 throw new IOException( "could not find a web browser to open [" + url + "] in" );
1205             }
1206             else {
1207                 runtime.exec( new String[] { browser, url } );
1208             }
1209         }
1210     }
1211
1212     // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1213     // static void openDDBJRest() throws IOException {
1214     // //set URL
1215     // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1216     // //set parameter
1217     // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1218     // //make connection
1219     // URLConnection urlc = url.openConnection();
1220     // //use post mode
1221     // urlc.setDoOutput( true );
1222     // urlc.setAllowUserInteraction( false );
1223     // //send query
1224     // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1225     // ps.print( query );
1226     // ps.close();
1227     // //get result
1228     // BufferedReader br = new BufferedReader( new InputStreamReader(
1229     // urlc.getInputStream() ) );
1230     // String l = null;
1231     // while ( ( l = br.readLine() ) != null ) {
1232     // System.out.println( l );
1233     // }
1234     // br.close();
1235     // }
1236     public static enum GraphicsExportType {
1237         GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1238
1239         private final String _suffix;
1240
1241         private GraphicsExportType( final String suffix ) {
1242             _suffix = suffix;
1243         }
1244
1245         @Override
1246         public String toString() {
1247             return _suffix;
1248         }
1249     }
1250 }