2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
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.
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.
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
23 // Contact: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
26 package org.forester.archaeopteryx;
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;
36 import java.io.FileNotFoundException;
37 import java.io.IOException;
38 import java.lang.reflect.InvocationTargetException;
39 import java.lang.reflect.Method;
42 import java.text.ParseException;
43 import java.util.Arrays;
44 import java.util.Iterator;
45 import java.util.List;
46 import java.util.Locale;
49 import javax.imageio.IIOImage;
50 import javax.imageio.ImageIO;
51 import javax.imageio.ImageWriteParam;
52 import javax.imageio.ImageWriter;
53 import javax.imageio.stream.ImageOutputStream;
54 import javax.swing.JApplet;
55 import javax.swing.JOptionPane;
56 import javax.swing.text.MaskFormatter;
58 import org.forester.io.parsers.PhylogenyParser;
59 import org.forester.io.parsers.tol.TolParser;
60 import org.forester.phylogeny.Phylogeny;
61 import org.forester.phylogeny.PhylogenyMethods;
62 import org.forester.phylogeny.PhylogenyNode;
63 import org.forester.phylogeny.data.BranchColor;
64 import org.forester.phylogeny.data.Taxonomy;
65 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
66 import org.forester.phylogeny.factories.PhylogenyFactory;
67 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
68 import org.forester.phylogeny.iterators.PreorderTreeIterator;
69 import org.forester.util.DescriptiveStatistics;
70 import org.forester.util.ForesterUtil;
72 public final class Util {
74 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
75 .getAvailableFontFamilyNames();
77 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
80 public static MaskFormatter createMaskFormatter( final String s ) {
81 MaskFormatter formatter = null;
83 formatter = new MaskFormatter( s );
85 catch ( final ParseException e ) {
86 throw new IllegalArgumentException( e );
91 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
92 final String default_name,
93 final String full_path,
94 final Configuration configuration,
95 final MainPanel main_panel ) {
96 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
97 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
98 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
99 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
102 for( final Phylogeny phy : phys ) {
103 if ( !phy.isEmpty() ) {
104 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
106 String my_name_for_file = "";
107 if ( phys.length > 1 ) {
108 if ( !ForesterUtil.isEmpty( default_name ) ) {
109 my_name = new String( default_name );
111 if ( !ForesterUtil.isEmpty( full_path ) ) {
112 my_name_for_file = new String( full_path );
114 else if ( !ForesterUtil.isEmpty( default_name ) ) {
115 my_name_for_file = new String( default_name );
118 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
119 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
120 my_name_for_file.length() );
121 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
123 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
124 my_name_for_file += "_";
126 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
127 my_name_for_file += phy.getName().replaceAll( " ", "_" );
129 else if ( phy.getIdentifier() != null ) {
130 final StringBuffer sb = new StringBuffer();
131 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
132 sb.append( phy.getIdentifier().getProvider() );
135 sb.append( phy.getIdentifier().getValue() );
136 my_name_for_file += sb;
139 my_name_for_file += i;
141 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
142 && ( phy.getIdentifier() == null ) ) {
143 my_name = my_name + " [" + i + "]";
145 if ( !ForesterUtil.isEmpty( suffix ) ) {
146 my_name_for_file += suffix;
150 if ( !ForesterUtil.isEmpty( default_name ) ) {
151 my_name = new String( default_name );
153 my_name_for_file = "";
154 if ( !ForesterUtil.isEmpty( full_path ) ) {
155 my_name_for_file = new String( full_path );
157 else if ( !ForesterUtil.isEmpty( default_name ) ) {
158 my_name_for_file = new String( default_name );
160 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
161 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
162 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
164 else if ( phy.getIdentifier() != null ) {
165 final StringBuffer sb = new StringBuffer();
166 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
167 sb.append( phy.getIdentifier().getProvider() );
170 sb.append( phy.getIdentifier().getValue() );
171 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
175 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
176 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
177 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
184 final static void addPhylogenyToPanel( final Phylogeny[] phys,
185 final Configuration configuration,
186 final MainPanel main_panel ) {
187 final Phylogeny phy = phys[ 0 ];
188 main_panel.addPhylogenyInPanel( phy, configuration );
189 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
192 final static Color calculateColorFromString( final String str ) {
193 final String species_uc = str.toUpperCase();
194 char first = species_uc.charAt( 0 );
197 if ( species_uc.length() > 1 ) {
198 second = species_uc.charAt( 1 );
199 if ( species_uc.length() > 2 ) {
200 if ( species_uc.indexOf( " " ) > 0 ) {
201 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
204 third = species_uc.charAt( 2 );
208 first = Util.normalizeCharForRGB( first );
209 second = Util.normalizeCharForRGB( second );
210 third = Util.normalizeCharForRGB( third );
211 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
214 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
217 return new Color( first, second, third );
220 // Returns true if the specified format name can be written
221 final static boolean canWriteFormat( final String format_name ) {
222 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
223 return iter.hasNext();
226 final public static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
227 boolean inferred = false;
228 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
229 final PhylogenyNode n = it.next();
230 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
231 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
232 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
233 Util.collapseSubtree( n, true );
234 if ( !n.getNodeData().isHasTaxonomy() ) {
235 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
236 .getTaxonomy().copy() );
241 n.setCollapse( false );
246 phy.setRerootable( false );
250 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
251 node.setCollapse( collapse );
252 if ( node.isExternal() ) {
255 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
256 while ( it.hasNext() ) {
257 it.next().setCollapse( collapse );
261 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
262 double max_conf = 0.0;
263 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
264 final PhylogenyNode n = it.next();
265 n.getBranchData().setBranchColor( null );
266 if ( n.getBranchData().isHasConfidences() ) {
267 final double conf = PhylogenyMethods.getConfidenceValue( n );
268 if ( conf > max_conf ) {
273 if ( max_conf > 0.0 ) {
274 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
275 final Color br = tree_panel.getTreeColorSet().getBranchColor();
276 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
277 final PhylogenyNode n = it.next();
278 if ( n.getBranchData().isHasConfidences() ) {
279 final double conf = PhylogenyMethods.getConfidenceValue( n );
280 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
281 n.getBranchData().setBranchColor( c );
282 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
283 for( final PhylogenyNode desc : descs ) {
284 desc.getBranchData().setBranchColor( c );
291 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
292 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
293 it.next().getBranchData().setBranchColor( null );
295 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
296 final PhylogenyNode n = it.next();
297 if ( !n.getBranchData().isHasBranchColor() ) {
298 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
300 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
301 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
302 for( final PhylogenyNode desc : descs ) {
304 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
311 final static String crateBasicInformation( final Phylogeny phy ) {
312 final StringBuilder desc = new StringBuilder();
313 if ( ( phy != null ) && !phy.isEmpty() ) {
314 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
315 desc.append( "Name: " );
316 desc.append( phy.getName() );
319 if ( phy.getIdentifier() != null ) {
320 desc.append( "Id: " );
321 desc.append( phy.getIdentifier() );
324 desc.append( "Rooted: " );
325 desc.append( phy.isRooted() );
327 desc.append( "Rerootable: " );
328 desc.append( phy.isRerootable() );
330 desc.append( "Node sum: " );
331 desc.append( phy.getNodeCount() );
333 desc.append( "External node sum: " );
334 desc.append( phy.getNumberOfExternalNodes() );
336 desc.append( "Internal node sum: " );
337 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
339 desc.append( "Branche sum: " );
340 desc.append( phy.getNumberOfBranches() );
342 desc.append( "Depth: " );
343 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
345 desc.append( "Maximum distance to root: " );
346 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
348 desc.append( "Descendants per node statistics: " );
349 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
351 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
353 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
355 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
357 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
359 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
361 final DescriptiveStatistics cs = PhylogenyMethods.calculatConfidenceStatistics( phy );
362 if ( cs.getN() > 1 ) {
363 desc.append( "Support statistics: " );
365 desc.append( " Branches with support: " + cs.getN() );
367 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
369 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
371 if ( cs.getN() > 2 ) {
372 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
375 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
377 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
380 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
381 if ( taxs != null ) {
382 desc.append( "Distinct external taxonomies: " );
383 desc.append( taxs.size() );
386 return desc.toString();
394 * to message to be printed
396 final static void dieWithSystemError( final String message ) {
397 System.out.println();
398 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
399 System.out.println( "Please contact the authors." );
400 System.out.println( Constants.PRG_NAME + " needs to close." );
401 System.out.println();
405 final static String[] getAvailableFontFamiliesSorted() {
406 return AVAILABLE_FONT_FAMILIES_SORTED;
409 final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
410 boolean inferred = false;
411 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
412 final PhylogenyNode n = it.next();
413 if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
414 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
415 if ( !ForesterUtil.isEmpty( sn ) ) {
416 n.getNodeData().setTaxonomy( new Taxonomy() );
417 n.getNodeData().getTaxonomy().setScientificName( sn );
423 tree.setRerootable( false );
427 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
428 if ( !node.getNodeData().isHasEvent() ) {
431 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
437 final static boolean isJava15() {
439 final String s = ForesterUtil.JAVA_VERSION;
440 return s.startsWith( "1.5" );
442 catch ( final Exception e ) {
443 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
448 final static boolean isMac() {
450 final String s = ForesterUtil.OS_NAME.toLowerCase();
451 return s.startsWith( "mac" );
453 catch ( final Exception e ) {
454 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
459 final static boolean isUsOrCanada() {
461 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
465 catch ( final Exception e ) {
471 final static boolean isWindows() {
473 final String s = ForesterUtil.OS_NAME.toLowerCase();
474 return s.indexOf( "win" ) > -1;
476 catch ( final Exception e ) {
477 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
482 final static void launchWebBrowser( final URI uri,
483 final boolean is_applet,
484 final JApplet applet,
485 final String frame_name ) throws IOException {
487 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
490 // This requires Java 1.6:
491 // =======================
492 // boolean no_desktop = false;
494 // if ( Desktop.isDesktopSupported() ) {
495 // System.out.println( "desktop supported" );
496 // final Desktop dt = Desktop.getDesktop();
500 // no_desktop = true;
503 // catch ( final Exception ex ) {
504 // ex.printStackTrace();
505 // no_desktop = true;
507 // catch ( final Error er ) {
508 // er.printStackTrace();
509 // no_desktop = true;
511 // if ( no_desktop ) {
512 // System.out.println( "desktop not supported" );
514 openUrlInWebBrowser( uri.toString() );
516 catch ( final Exception e ) {
517 throw new IOException( e );
523 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
524 final ControlPanel atv_control,
525 final Configuration configuration ) {
526 if ( ( t != null ) && !t.isEmpty() ) {
527 if ( !ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
528 atv_control.setDrawPhylogram( false );
529 atv_control.setDrawPhylogramEnabled( false );
531 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
532 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
533 if ( ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
534 atv_control.setDrawPhylogram( true );
535 atv_control.setDrawPhylogramEnabled( true );
538 atv_control.setDrawPhylogram( false );
542 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
543 if ( atv_control.getWriteConfidenceCb() != null ) {
544 if ( ForesterUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
545 atv_control.setCheckbox( Configuration.write_confidence_values, true );
548 atv_control.setCheckbox( Configuration.write_confidence_values, false );
552 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
553 if ( atv_control.getShowEventsCb() != null ) {
554 if ( ForesterUtil.isHasAtLeastNodeWithEvent( t ) ) {
555 atv_control.setCheckbox( Configuration.write_events, true );
558 atv_control.setCheckbox( Configuration.write_events, false );
565 final private static char normalizeCharForRGB( char c ) {
568 c = c > 255 ? 255 : c;
573 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
574 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
575 InvocationTargetException, InterruptedException {
576 final String os = System.getProperty( "os.name" );
577 final Runtime runtime = Runtime.getRuntime();
578 if ( os.toLowerCase().startsWith( "win" ) ) {
579 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
581 else if ( isMac() ) {
582 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
583 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
584 open_url.invoke( null, new Object[] { url } );
587 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
588 String browser = null;
589 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
590 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
591 browser = browsers[ i ];
594 if ( browser == null ) {
595 throw new IOException( "could not find a web browser to open [" + url + "] in" );
598 runtime.exec( new String[] { browser, url } );
603 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
605 Util.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
607 catch ( final Exception e ) {
608 throw new IOException( e );
612 final static void printAppletMessage( final String applet_name, final String message ) {
613 System.out.println( "[" + applet_name + "] > " + message );
616 public final static void printWarningMessage( final String name, final String message ) {
617 System.out.println( "[" + name + "] > " + message );
620 final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
621 throws FileNotFoundException, IOException {
622 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
623 PhylogenyParser parser = null;
624 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
625 parser = new TolParser();
628 parser = ForesterUtil.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
630 return factory.create( url.openStream(), parser );
633 final static void removeBranchColors( final Phylogeny phy ) {
634 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
635 it.next().getBranchData().setBranchColor( null );
639 final static void showErrorMessage( final Component parent, final String error_msg ) {
640 printAppletMessage( Constants.PRG_NAME, error_msg );
641 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
642 + "] Error", JOptionPane.ERROR_MESSAGE );
645 final static void unexpectedError( final Error err ) {
646 err.printStackTrace();
647 final StringBuffer sb = new StringBuffer();
648 for( final StackTraceElement s : err.getStackTrace() ) {
649 sb.append( s + "\n" );
652 .showMessageDialog( null,
653 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
654 + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
655 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
656 JOptionPane.ERROR_MESSAGE );
660 final static void unexpectedException( final Exception ex ) {
661 ex.printStackTrace();
662 final StringBuffer sb = new StringBuffer();
663 for( final StackTraceElement s : ex.getStackTrace() ) {
664 sb.append( s + "\n" );
666 JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
667 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
668 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
671 final static String writePhylogenyToGraphicsFile( final String file_name,
674 final TreePanel tree_panel,
675 final ControlPanel ac,
676 final GraphicsExportType type,
677 final Options options ) throws IOException {
678 if ( !options.isGraphicsExportUsingActualSize() ) {
679 if ( options.isGraphicsExportVisibleOnly() ) {
680 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
682 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
683 tree_panel.resetPreferredSize();
684 tree_panel.repaint();
686 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
687 RenderingHints.VALUE_RENDER_QUALITY );
688 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
689 if ( options.isAntialiasPrint() ) {
690 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
691 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
694 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
695 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
697 final Phylogeny phylogeny = tree_panel.getPhylogeny();
698 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
701 final File file = new File( file_name );
702 if ( file.isDirectory() ) {
703 throw new IOException( "\"" + file_name + "\" is a directory" );
705 Rectangle visible = null;
706 if ( !options.isGraphicsExportUsingActualSize() ) {
707 width = options.getPrintSizeX();
708 height = options.getPrintSizeY();
710 else if ( options.isGraphicsExportVisibleOnly() ) {
711 visible = tree_panel.getVisibleRect();
712 width = visible.width;
713 height = visible.height;
715 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
716 Graphics2D g2d = buffered_img.createGraphics();
717 g2d.setRenderingHints( rendering_hints );
720 if ( options.isGraphicsExportVisibleOnly() ) {
721 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
726 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
727 if ( type == GraphicsExportType.TIFF ) {
728 writeToTiff( file, buffered_img );
731 ImageIO.write( buffered_img, type.toString(), file );
735 if ( !options.isGraphicsExportUsingActualSize() ) {
736 tree_panel.getMainPanel().getControlPanel().showWhole();
738 String msg = file.toString();
739 if ( ( width > 0 ) && ( height > 0 ) ) {
740 msg += " [size: " + width + ", " + height + "]";
745 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
746 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
747 ImageWriter writer = null;
748 ImageOutputStream ios = null;
749 // Find an appropriate writer:
750 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
751 if ( it.hasNext() ) {
755 throw new IOException( "failed to get TIFF image writer" );
758 ios = ImageIO.createImageOutputStream( file );
759 writer.setOutput( ios );
760 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
761 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
762 // see writeParam.getCompressionTypes() for available compression type
764 image_write_param.setCompressionType( "PackBits" );
765 final String t[] = image_write_param.getCompressionTypes();
766 for( final String string : t ) {
767 System.out.println( string );
769 // Convert to an IIOImage:
770 final IIOImage iio_image = new IIOImage( image, null, null );
771 writer.write( null, iio_image, image_write_param );
774 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
775 // static void openDDBJRest() throws IOException {
777 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
779 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
781 // URLConnection urlc = url.openConnection();
783 // urlc.setDoOutput( true );
784 // urlc.setAllowUserInteraction( false );
786 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
787 // ps.print( query );
790 // BufferedReader br = new BufferedReader( new InputStreamReader(
791 // urlc.getInputStream() ) );
793 // while ( ( l = br.readLine() ) != null ) {
794 // System.out.println( l );
798 static enum GraphicsExportType {
799 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
801 private final String _suffix;
803 private GraphicsExportType( final String suffix ) {
808 public String toString() {