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