e71eeefc9040a1d58054d8dca2bfe300ce6a8a56
[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.AncestralTaxonomyInference;
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.uniprot.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 = AncestralTaxonomyInference.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 crateBasicInformation( 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() > 2 ) {
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                 desc.append( "\n" );
601                 final AsciiHistogram histo = new AsciiHistogram( bs );
602                 desc.append( histo.toStringBuffer( 12, '#', 40, 7, "    " ) );
603             }
604             final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
605             if ( ds.getN() > 2 ) {
606                 desc.append( "\n" );
607                 desc.append( "Descendants per node statistics: " );
608                 desc.append( "\n" );
609                 desc.append( "    Median: " + ForesterUtil.round( ds.median(), 2 ) );
610                 desc.append( "\n" );
611                 desc.append( "    Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
612                 desc.append( "\n" );
613                 desc.append( "    SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
614                 desc.append( "\n" );
615                 desc.append( "    Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
616                 desc.append( "\n" );
617                 desc.append( "    Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
618                 desc.append( "\n" );
619             }
620             final List<DescriptiveStatistics> css = PhylogenyMethods.calculatConfidenceStatistics( phy );
621             if ( css.size() > 0 ) {
622                 desc.append( "\n" );
623                 for( int i = 0; i < css.size(); ++i ) {
624                     final DescriptiveStatistics cs = css.get( i );
625                     if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
626                         if ( css.size() > 1 ) {
627                             desc.append( "Support statistics " + ( i + 1 ) + ": " );
628                         }
629                         else {
630                             desc.append( "Support statistics: " );
631                         }
632                         if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
633                             desc.append( "\n" );
634                             desc.append( "    Type: " + cs.getDescription() );
635                         }
636                         desc.append( "\n" );
637                         desc.append( "    Branches with support: " + cs.getN() );
638                         desc.append( "\n" );
639                         desc.append( "    Median: " + ForesterUtil.round( cs.median(), 6 ) );
640                         desc.append( "\n" );
641                         desc.append( "    Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
642                         desc.append( "\n" );
643                         if ( cs.getN() > 2 ) {
644                             desc.append( "    SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
645                             desc.append( "\n" );
646                         }
647                         desc.append( "    Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
648                         desc.append( "\n" );
649                         desc.append( "    Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
650                         desc.append( "\n" );
651                     }
652                 }
653             }
654         }
655         return desc.toString();
656     }
657
658     /**
659      * Exits with -1.
660      * 
661      * 
662      * @param message
663      *            to message to be printed
664      */
665     final static void dieWithSystemError( final String message ) {
666         System.out.println();
667         System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
668         System.out.println( "Please contact the authors." );
669         System.out.println( Constants.PRG_NAME + " needs to close." );
670         System.out.println();
671         System.exit( -1 );
672     }
673
674     final static String[] getAvailableFontFamiliesSorted() {
675         return AVAILABLE_FONT_FAMILIES_SORTED;
676     }
677
678     final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
679         boolean inferred = false;
680         for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
681             final PhylogenyNode n = it.next();
682             if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
683                 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
684                 if ( !ForesterUtil.isEmpty( sn ) ) {
685                     n.getNodeData().setTaxonomy( new Taxonomy() );
686                     n.getNodeData().getTaxonomy().setScientificName( sn );
687                     inferred = true;
688                 }
689             }
690         }
691         if ( inferred ) {
692             tree.setRerootable( false );
693         }
694     }
695
696     final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
697         if ( !node.getNodeData().isHasEvent() ) {
698             return false;
699         }
700         if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
701             return false;
702         }
703         return true;
704     }
705
706     final static boolean isJava15() {
707         try {
708             final String s = ForesterUtil.JAVA_VERSION;
709             return s.startsWith( "1.5" );
710         }
711         catch ( final Exception e ) {
712             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
713             return false;
714         }
715     }
716
717     final static boolean isMac() {
718         try {
719             final String s = ForesterUtil.OS_NAME.toLowerCase();
720             return s.startsWith( "mac" );
721         }
722         catch ( final Exception e ) {
723             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
724             return false;
725         }
726     }
727
728     final static boolean isUsOrCanada() {
729         try {
730             if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
731                 return true;
732             }
733         }
734         catch ( final Exception e ) {
735             return false;
736         }
737         return false;
738     }
739
740     final static boolean isWindows() {
741         try {
742             final String s = ForesterUtil.OS_NAME.toLowerCase();
743             return s.indexOf( "win" ) > -1;
744         }
745         catch ( final Exception e ) {
746             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
747             return false;
748         }
749     }
750
751     final public static void launchWebBrowser( final URI uri,
752                                                final boolean is_applet,
753                                                final JApplet applet,
754                                                final String frame_name ) throws IOException {
755         if ( is_applet ) {
756             applet.getAppletContext().showDocument( uri.toURL(), frame_name );
757         }
758         else {
759             // This requires Java 1.6:
760             // =======================
761             // boolean no_desktop = false;
762             // try {
763             // if ( Desktop.isDesktopSupported() ) {
764             // System.out.println( "desktop supported" );
765             // final Desktop dt = Desktop.getDesktop();
766             // dt.browse( uri );
767             // }
768             // else {
769             // no_desktop = true;
770             // }
771             // }
772             // catch ( final Exception ex ) {
773             // ex.printStackTrace();
774             // no_desktop = true;
775             // }
776             // catch ( final Error er ) {
777             // er.printStackTrace();
778             // no_desktop = true;
779             // }
780             // if ( no_desktop ) {
781             // System.out.println( "desktop not supported" );
782             try {
783                 openUrlInWebBrowser( uri.toString() );
784             }
785             catch ( final Exception e ) {
786                 throw new IOException( e );
787             }
788             // }
789         }
790     }
791
792     final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
793                                                                       final ControlPanel atv_control,
794                                                                       final Configuration configuration ) {
795         if ( ( t != null ) && !t.isEmpty() ) {
796             if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
797                 atv_control.setDrawPhylogram( false );
798                 atv_control.setDrawPhylogramEnabled( false );
799             }
800             if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
801                 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
802                     if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
803                         atv_control.setDrawPhylogram( true );
804                         atv_control.setDrawPhylogramEnabled( true );
805                     }
806                     else {
807                         atv_control.setDrawPhylogram( false );
808                     }
809                 }
810             }
811             if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
812                 if ( atv_control.getWriteConfidenceCb() != null ) {
813                     if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
814                         atv_control.setCheckbox( Configuration.write_confidence_values, true );
815                     }
816                     else {
817                         atv_control.setCheckbox( Configuration.write_confidence_values, false );
818                     }
819                 }
820             }
821             if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
822                 if ( atv_control.getShowEventsCb() != null ) {
823                     if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
824                         atv_control.setCheckbox( Configuration.write_events, true );
825                     }
826                     else {
827                         atv_control.setCheckbox( Configuration.write_events, false );
828                     }
829                 }
830             }
831         }
832     }
833
834     final private static char normalizeCharForRGB( char c ) {
835         c -= 65;
836         c *= 10.2;
837         c = c > 255 ? 255 : c;
838         c = c < 0 ? 0 : c;
839         return c;
840     }
841
842     final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
843             SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
844             InvocationTargetException, InterruptedException {
845         final String os = System.getProperty( "os.name" );
846         final Runtime runtime = Runtime.getRuntime();
847         if ( os.toLowerCase().startsWith( "win" ) ) {
848             Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
849         }
850         else if ( isMac() ) {
851             final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
852             final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
853             open_url.invoke( null, new Object[] { url } );
854         }
855         else {
856             final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
857             String browser = null;
858             for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
859                 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
860                     browser = browsers[ i ];
861                 }
862             }
863             if ( browser == null ) {
864                 throw new IOException( "could not find a web browser to open [" + url + "] in" );
865             }
866             else {
867                 runtime.exec( new String[] { browser, url } );
868             }
869         }
870     }
871
872     final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
873         try {
874             AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
875         }
876         catch ( final Exception e ) {
877             throw new IOException( e );
878         }
879     }
880
881     final static void printAppletMessage( final String applet_name, final String message ) {
882         System.out.println( "[" + applet_name + "] > " + message );
883     }
884
885     public final static void printWarningMessage( final String name, final String message ) {
886         System.out.println( "[" + name + "] > " + message );
887     }
888
889     final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
890             throws FileNotFoundException, IOException {
891         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
892         PhylogenyParser parser = null;
893         if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
894             parser = new TolParser();
895         }
896         else {
897             parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
898         }
899         return factory.create( url.openStream(), parser );
900     }
901
902     final static void removeBranchColors( final Phylogeny phy ) {
903         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
904             it.next().getBranchData().setBranchColor( null );
905         }
906     }
907
908     final public static void showErrorMessage( final Component parent, final String error_msg ) {
909         printAppletMessage( Constants.PRG_NAME, error_msg );
910         JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
911                 + "] Error", JOptionPane.ERROR_MESSAGE );
912     }
913
914     final static void unexpectedError( final Error err ) {
915         err.printStackTrace();
916         final StringBuffer sb = new StringBuffer();
917         for( final StackTraceElement s : err.getStackTrace() ) {
918             sb.append( s + "\n" );
919         }
920         JOptionPane
921                 .showMessageDialog( null,
922                                     "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
923                                             + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
924                                     "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
925                                     JOptionPane.ERROR_MESSAGE );
926         System.exit( -1 );
927     }
928
929     final static void unexpectedException( final Exception ex ) {
930         ex.printStackTrace();
931         final StringBuffer sb = new StringBuffer();
932         for( final StackTraceElement s : ex.getStackTrace() ) {
933             sb.append( s + "\n" );
934         }
935         JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
936                 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
937                 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
938     }
939
940     final static String writePhylogenyToGraphicsFile( final String file_name,
941                                                       int width,
942                                                       int height,
943                                                       final TreePanel tree_panel,
944                                                       final ControlPanel ac,
945                                                       final GraphicsExportType type,
946                                                       final Options options ) throws IOException {
947         if ( !options.isGraphicsExportUsingActualSize() ) {
948             if ( options.isGraphicsExportVisibleOnly() ) {
949                 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
950             }
951             tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
952             tree_panel.resetPreferredSize();
953             tree_panel.repaint();
954         }
955         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
956                                                                    RenderingHints.VALUE_RENDER_QUALITY );
957         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
958         if ( options.isAntialiasPrint() ) {
959             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
960             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
961         }
962         else {
963             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
964             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
965         }
966         final Phylogeny phylogeny = tree_panel.getPhylogeny();
967         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
968             return "";
969         }
970         final File file = new File( file_name );
971         if ( file.isDirectory() ) {
972             throw new IOException( "\"" + file_name + "\" is a directory" );
973         }
974         Rectangle visible = null;
975         if ( !options.isGraphicsExportUsingActualSize() ) {
976             width = options.getPrintSizeX();
977             height = options.getPrintSizeY();
978         }
979         else if ( options.isGraphicsExportVisibleOnly() ) {
980             visible = tree_panel.getVisibleRect();
981             width = visible.width;
982             height = visible.height;
983         }
984         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
985         Graphics2D g2d = buffered_img.createGraphics();
986         g2d.setRenderingHints( rendering_hints );
987         int x = 0;
988         int y = 0;
989         if ( options.isGraphicsExportVisibleOnly() ) {
990             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
991             g2d.setClip( null );
992             x = visible.x;
993             y = visible.y;
994         }
995         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
996         if ( type == GraphicsExportType.TIFF ) {
997             writeToTiff( file, buffered_img );
998         }
999         else {
1000             ImageIO.write( buffered_img, type.toString(), file );
1001         }
1002         g2d.dispose();
1003         System.gc();
1004         if ( !options.isGraphicsExportUsingActualSize() ) {
1005             tree_panel.getMainPanel().getControlPanel().showWhole();
1006         }
1007         String msg = file.toString();
1008         if ( ( width > 0 ) && ( height > 0 ) ) {
1009             msg += " [size: " + width + ", " + height + "]";
1010         }
1011         return msg;
1012     }
1013
1014     public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
1015                                                                          final int width,
1016                                                                          final int height,
1017                                                                          final TreePanel tree_panel,
1018                                                                          final ControlPanel ac,
1019                                                                          final GraphicsExportType type,
1020                                                                          final Options options ) throws IOException {
1021         tree_panel.setParametersForPainting( width, height, true );
1022         tree_panel.resetPreferredSize();
1023         tree_panel.repaint();
1024         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1025                                                                    RenderingHints.VALUE_RENDER_QUALITY );
1026         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1027         if ( options.isAntialiasPrint() ) {
1028             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1029             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1030         }
1031         else {
1032             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1033             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1034         }
1035         final Phylogeny phylogeny = tree_panel.getPhylogeny();
1036         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1037             return;
1038         }
1039         if ( outfile.isDirectory() ) {
1040             throw new IOException( "\"" + outfile + "\" is a directory" );
1041         }
1042         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1043         final Graphics2D g2d = buffered_img.createGraphics();
1044         g2d.setRenderingHints( rendering_hints );
1045         tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
1046         if ( type == GraphicsExportType.TIFF ) {
1047             writeToTiff( outfile, buffered_img );
1048         }
1049         else {
1050             ImageIO.write( buffered_img, type.toString(), outfile );
1051         }
1052         g2d.dispose();
1053     }
1054
1055     final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
1056                                                                        int width,
1057                                                                        int height,
1058                                                                        final TreePanel tree_panel,
1059                                                                        final ControlPanel ac,
1060                                                                        final GraphicsExportType type,
1061                                                                        final Options options ) throws IOException {
1062         if ( !options.isGraphicsExportUsingActualSize() ) {
1063             if ( options.isGraphicsExportVisibleOnly() ) {
1064                 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1065             }
1066             tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1067             tree_panel.resetPreferredSize();
1068             tree_panel.repaint();
1069         }
1070         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1071                                                                    RenderingHints.VALUE_RENDER_QUALITY );
1072         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1073         if ( options.isAntialiasPrint() ) {
1074             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1075             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1076         }
1077         else {
1078             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1079             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1080         }
1081         final Phylogeny phylogeny = tree_panel.getPhylogeny();
1082         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1083             return "";
1084         }
1085         Rectangle visible = null;
1086         if ( !options.isGraphicsExportUsingActualSize() ) {
1087             width = options.getPrintSizeX();
1088             height = options.getPrintSizeY();
1089         }
1090         else if ( options.isGraphicsExportVisibleOnly() ) {
1091             visible = tree_panel.getVisibleRect();
1092             width = visible.width;
1093             height = visible.height;
1094         }
1095         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1096         Graphics2D g2d = buffered_img.createGraphics();
1097         g2d.setRenderingHints( rendering_hints );
1098         int x = 0;
1099         int y = 0;
1100         if ( options.isGraphicsExportVisibleOnly() ) {
1101             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1102             g2d.setClip( null );
1103             x = visible.x;
1104             y = visible.y;
1105         }
1106         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1107         ImageIO.write( buffered_img, type.toString(), baos );
1108         g2d.dispose();
1109         System.gc();
1110         if ( !options.isGraphicsExportUsingActualSize() ) {
1111             tree_panel.getMainPanel().getControlPanel().showWhole();
1112         }
1113         String msg = baos.toString();
1114         if ( ( width > 0 ) && ( height > 0 ) ) {
1115             msg += " [size: " + width + ", " + height + "]";
1116         }
1117         return msg;
1118     }
1119
1120     final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1121         // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1122         ImageWriter writer = null;
1123         ImageOutputStream ios = null;
1124         // Find an appropriate writer:
1125         final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1126         if ( it.hasNext() ) {
1127             writer = it.next();
1128         }
1129         else {
1130             throw new IOException( "failed to get TIFF image writer" );
1131         }
1132         // Setup writer:
1133         ios = ImageIO.createImageOutputStream( file );
1134         writer.setOutput( ios );
1135         final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1136         image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1137         // see writeParam.getCompressionTypes() for available compression type
1138         // strings.
1139         image_write_param.setCompressionType( "PackBits" );
1140         final String t[] = image_write_param.getCompressionTypes();
1141         for( final String string : t ) {
1142             System.out.println( string );
1143         }
1144         // Convert to an IIOImage:
1145         final IIOImage iio_image = new IIOImage( image, null, null );
1146         writer.write( null, iio_image, image_write_param );
1147     }
1148
1149     // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1150     // static void openDDBJRest() throws IOException {
1151     // //set URL
1152     // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1153     // //set parameter
1154     // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1155     // //make connection
1156     // URLConnection urlc = url.openConnection();
1157     // //use post mode
1158     // urlc.setDoOutput( true );
1159     // urlc.setAllowUserInteraction( false );
1160     // //send query
1161     // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1162     // ps.print( query );
1163     // ps.close();
1164     // //get result
1165     // BufferedReader br = new BufferedReader( new InputStreamReader(
1166     // urlc.getInputStream() ) );
1167     // String l = null;
1168     // while ( ( l = br.readLine() ) != null ) {
1169     // System.out.println( l );
1170     // }
1171     // br.close();
1172     // }
1173     public static enum GraphicsExportType {
1174         GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1175
1176         private final String _suffix;
1177
1178         private GraphicsExportType( final String suffix ) {
1179             _suffix = suffix;
1180         }
1181
1182         @Override
1183         public String toString() {
1184             return _suffix;
1185         }
1186     }
1187 }