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