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