1078656bd7ab1308f9819783c9bc82302df49b23
[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 void inferCommonPartOfScientificNames( final Phylogeny tree ) {
795         boolean inferred = false;
796         for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
797             final PhylogenyNode n = it.next();
798             if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
799                 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
800                 if ( !ForesterUtil.isEmpty( sn ) ) {
801                     n.getNodeData().setTaxonomy( new Taxonomy() );
802                     n.getNodeData().getTaxonomy().setScientificName( sn );
803                     inferred = true;
804                 }
805             }
806         }
807         if ( inferred ) {
808             tree.setRerootable( false );
809         }
810     }
811
812     final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
813         if ( !node.getNodeData().isHasEvent() ) {
814             return false;
815         }
816         if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
817             return false;
818         }
819         return true;
820     }
821
822     final static boolean isJava15() {
823         try {
824             final String s = ForesterUtil.JAVA_VERSION;
825             return s.startsWith( "1.5" );
826         }
827         catch ( final Exception e ) {
828             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
829             return false;
830         }
831     }
832
833     final static boolean isMac() {
834         try {
835             final String s = ForesterUtil.OS_NAME.toLowerCase();
836             return s.startsWith( "mac" );
837         }
838         catch ( final Exception e ) {
839             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
840             return false;
841         }
842     }
843
844     final static boolean isUsOrCanada() {
845         try {
846             if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
847                 return true;
848             }
849         }
850         catch ( final Exception e ) {
851             return false;
852         }
853         return false;
854     }
855
856     final static boolean isWindows() {
857         try {
858             final String s = ForesterUtil.OS_NAME.toLowerCase();
859             return s.indexOf( "win" ) > -1;
860         }
861         catch ( final Exception e ) {
862             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
863             return false;
864         }
865     }
866
867     final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
868                                                                       final ControlPanel atv_control,
869                                                                       final Configuration configuration ) {
870         if ( ( t != null ) && !t.isEmpty() ) {
871             if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
872                 atv_control.setDrawPhylogram( false );
873                 atv_control.setDrawPhylogramEnabled( false );
874             }
875             if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
876                 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
877                     if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
878                         atv_control.setDrawPhylogram( true );
879                         atv_control.setDrawPhylogramEnabled( true );
880                     }
881                     else {
882                         atv_control.setDrawPhylogram( false );
883                     }
884                 }
885             }
886             if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
887                 if ( atv_control.getWriteConfidenceCb() != null ) {
888                     if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
889                         atv_control.setCheckbox( Configuration.write_confidence_values, true );
890                     }
891                     else {
892                         atv_control.setCheckbox( Configuration.write_confidence_values, false );
893                     }
894                 }
895             }
896             if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
897                 if ( atv_control.getShowEventsCb() != null ) {
898                     if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
899                         atv_control.setCheckbox( Configuration.write_events, true );
900                     }
901                     else {
902                         atv_control.setCheckbox( Configuration.write_events, false );
903                     }
904                 }
905             }
906         }
907     }
908
909     final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
910         try {
911             AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
912         }
913         catch ( final Exception e ) {
914             throw new IOException( e );
915         }
916     }
917
918     final static void printAppletMessage( final String applet_name, final String message ) {
919         System.out.println( "[" + applet_name + "] > " + message );
920     }
921
922     final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
923             throws FileNotFoundException, IOException {
924         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
925         PhylogenyParser parser = null;
926         if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
927             parser = new TolParser();
928         }
929         else {
930             parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
931         }
932         return factory.create( url.openStream(), parser );
933     }
934
935     final static void removeBranchColors( final Phylogeny phy ) {
936         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
937             it.next().getBranchData().setBranchColor( null );
938         }
939     }
940
941     final static void unexpectedError( final Error err ) {
942         err.printStackTrace();
943         final StringBuffer sb = new StringBuffer();
944         for( final StackTraceElement s : err.getStackTrace() ) {
945             sb.append( s + "\n" );
946         }
947         JOptionPane
948                 .showMessageDialog( null,
949                                     "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
950                                             + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
951                                     "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
952                                     JOptionPane.ERROR_MESSAGE );
953         System.exit( -1 );
954     }
955
956     final static void unexpectedException( final Exception ex ) {
957         ex.printStackTrace();
958         final StringBuffer sb = new StringBuffer();
959         for( final StackTraceElement s : ex.getStackTrace() ) {
960             sb.append( s + "\n" );
961         }
962         JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
963                 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
964                 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
965     }
966
967     final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
968                                                                        int width,
969                                                                        int height,
970                                                                        final TreePanel tree_panel,
971                                                                        final ControlPanel ac,
972                                                                        final GraphicsExportType type,
973                                                                        final Options options ) throws IOException {
974         if ( !options.isGraphicsExportUsingActualSize() ) {
975             if ( options.isGraphicsExportVisibleOnly() ) {
976                 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
977             }
978             tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
979             tree_panel.resetPreferredSize();
980             tree_panel.repaint();
981         }
982         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
983                                                                    RenderingHints.VALUE_RENDER_QUALITY );
984         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
985         if ( options.isAntialiasPrint() ) {
986             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
987             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
988         }
989         else {
990             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
991             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
992         }
993         final Phylogeny phylogeny = tree_panel.getPhylogeny();
994         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
995             return "";
996         }
997         Rectangle visible = null;
998         if ( !options.isGraphicsExportUsingActualSize() ) {
999             width = options.getPrintSizeX();
1000             height = options.getPrintSizeY();
1001         }
1002         else if ( options.isGraphicsExportVisibleOnly() ) {
1003             visible = tree_panel.getVisibleRect();
1004             width = visible.width;
1005             height = visible.height;
1006         }
1007         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1008         Graphics2D g2d = buffered_img.createGraphics();
1009         g2d.setRenderingHints( rendering_hints );
1010         int x = 0;
1011         int y = 0;
1012         if ( options.isGraphicsExportVisibleOnly() ) {
1013             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1014             g2d.setClip( null );
1015             x = visible.x;
1016             y = visible.y;
1017         }
1018         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1019         ImageIO.write( buffered_img, type.toString(), baos );
1020         g2d.dispose();
1021         System.gc();
1022         if ( !options.isGraphicsExportUsingActualSize() ) {
1023             tree_panel.getMainPanel().getControlPanel().showWhole();
1024         }
1025         String msg = baos.toString();
1026         if ( ( width > 0 ) && ( height > 0 ) ) {
1027             msg += " [size: " + width + ", " + height + "]";
1028         }
1029         return msg;
1030     }
1031
1032     final static String writePhylogenyToGraphicsFile( final String file_name,
1033                                                       int width,
1034                                                       int height,
1035                                                       final TreePanel tree_panel,
1036                                                       final ControlPanel ac,
1037                                                       final GraphicsExportType type,
1038                                                       final Options options ) throws IOException {
1039         if ( !options.isGraphicsExportUsingActualSize() ) {
1040             if ( options.isGraphicsExportVisibleOnly() ) {
1041                 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1042             }
1043             tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1044             tree_panel.resetPreferredSize();
1045             tree_panel.repaint();
1046         }
1047         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1048                                                                    RenderingHints.VALUE_RENDER_QUALITY );
1049         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1050         if ( options.isAntialiasPrint() ) {
1051             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1052             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1053         }
1054         else {
1055             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1056             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1057         }
1058         final Phylogeny phylogeny = tree_panel.getPhylogeny();
1059         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1060             return "";
1061         }
1062         final File file = new File( file_name );
1063         if ( file.isDirectory() ) {
1064             throw new IOException( "\"" + file_name + "\" is a directory" );
1065         }
1066         Rectangle visible = null;
1067         if ( !options.isGraphicsExportUsingActualSize() ) {
1068             width = options.getPrintSizeX();
1069             height = options.getPrintSizeY();
1070         }
1071         else if ( options.isGraphicsExportVisibleOnly() ) {
1072             visible = tree_panel.getVisibleRect();
1073             width = visible.width;
1074             height = visible.height;
1075         }
1076         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1077         Graphics2D g2d = buffered_img.createGraphics();
1078         g2d.setRenderingHints( rendering_hints );
1079         int x = 0;
1080         int y = 0;
1081         if ( options.isGraphicsExportVisibleOnly() ) {
1082             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1083             g2d.setClip( null );
1084             x = visible.x;
1085             y = visible.y;
1086         }
1087         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1088         if ( type == GraphicsExportType.TIFF ) {
1089             writeToTiff( file, buffered_img );
1090         }
1091         else {
1092             ImageIO.write( buffered_img, type.toString(), file );
1093         }
1094         g2d.dispose();
1095         System.gc();
1096         if ( !options.isGraphicsExportUsingActualSize() ) {
1097             tree_panel.getMainPanel().getControlPanel().showWhole();
1098         }
1099         String msg = file.toString();
1100         if ( ( width > 0 ) && ( height > 0 ) ) {
1101             msg += " [size: " + width + ", " + height + "]";
1102         }
1103         return msg;
1104     }
1105
1106     final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1107         // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1108         ImageWriter writer = null;
1109         ImageOutputStream ios = null;
1110         // Find an appropriate writer:
1111         final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1112         if ( it.hasNext() ) {
1113             writer = it.next();
1114         }
1115         else {
1116             throw new IOException( "failed to get TIFF image writer" );
1117         }
1118         // Setup writer:
1119         ios = ImageIO.createImageOutputStream( file );
1120         writer.setOutput( ios );
1121         final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1122         image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1123         // see writeParam.getCompressionTypes() for available compression type
1124         // strings.
1125         image_write_param.setCompressionType( "PackBits" );
1126         final String t[] = image_write_param.getCompressionTypes();
1127         for( final String string : t ) {
1128             System.out.println( string );
1129         }
1130         // Convert to an IIOImage:
1131         final IIOImage iio_image = new IIOImage( image, null, null );
1132         writer.write( null, iio_image, image_write_param );
1133     }
1134
1135     private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
1136         node.getBranchData().setBranchColor( c );
1137         final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
1138         for( final PhylogenyNode desc : descs ) {
1139             desc.getBranchData().setBranchColor( c );
1140         }
1141     }
1142
1143     final private static char normalizeCharForRGB( char c ) {
1144         c -= 65;
1145         c *= 10.2;
1146         c = c > 255 ? 255 : c;
1147         c = c < 0 ? 0 : c;
1148         return c;
1149     }
1150
1151     final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
1152             SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
1153             InvocationTargetException, InterruptedException {
1154         final String os = System.getProperty( "os.name" );
1155         final Runtime runtime = Runtime.getRuntime();
1156         if ( os.toLowerCase().startsWith( "win" ) ) {
1157             Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
1158         }
1159         else if ( isMac() ) {
1160             final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
1161             final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
1162             open_url.invoke( null, new Object[] { url } );
1163         }
1164         else {
1165             final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
1166             String browser = null;
1167             for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
1168                 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
1169                     browser = browsers[ i ];
1170                 }
1171             }
1172             if ( browser == null ) {
1173                 throw new IOException( "could not find a web browser to open [" + url + "] in" );
1174             }
1175             else {
1176                 runtime.exec( new String[] { browser, url } );
1177             }
1178         }
1179     }
1180
1181     // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1182     // static void openDDBJRest() throws IOException {
1183     // //set URL
1184     // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1185     // //set parameter
1186     // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1187     // //make connection
1188     // URLConnection urlc = url.openConnection();
1189     // //use post mode
1190     // urlc.setDoOutput( true );
1191     // urlc.setAllowUserInteraction( false );
1192     // //send query
1193     // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1194     // ps.print( query );
1195     // ps.close();
1196     // //get result
1197     // BufferedReader br = new BufferedReader( new InputStreamReader(
1198     // urlc.getInputStream() ) );
1199     // String l = null;
1200     // while ( ( l = br.readLine() ) != null ) {
1201     // System.out.println( l );
1202     // }
1203     // br.close();
1204     // }
1205     public static enum GraphicsExportType {
1206         GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1207
1208         private final String _suffix;
1209
1210         private GraphicsExportType( final String suffix ) {
1211             _suffix = suffix;
1212         }
1213
1214         @Override
1215         public String toString() {
1216             return _suffix;
1217         }
1218     }
1219 }