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.io.parsers.util.PhylogenyParserException;
61 import org.forester.phylogeny.Phylogeny;
62 import org.forester.phylogeny.PhylogenyMethods;
63 import org.forester.phylogeny.PhylogenyNode;
64 import org.forester.phylogeny.data.BranchColor;
65 import org.forester.phylogeny.data.Taxonomy;
66 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
67 import org.forester.phylogeny.factories.PhylogenyFactory;
68 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
69 import org.forester.phylogeny.iterators.PreorderTreeIterator;
70 import org.forester.util.ForesterUtil;
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( '.' ), my_name_for_file
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 ) {
303 desc.getBranchData().setBranchColor( new BranchColor( tree_panel
304 .calculateTaxonomyBasedColor( tax ) ) );
311 final static String createDescriptionForTab( final Phylogeny phy, final String full_path ) {
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( "external nodes: " );
331 desc.append( phy.getNumberOfExternalNodes() );
333 desc.append( "branches: " );
334 desc.append( phy.getNumberOfBranches() );
336 desc.append( "maximum descendants: " );
337 desc.append( PhylogenyMethods.calculateMaximumNumberOfDescendantsPerNode( phy ) );
338 if ( !ForesterUtil.isEmpty( full_path ) && ( full_path.length() <= 50 ) ) {
340 desc.append( "path: " );
341 desc.append( full_path );
344 return desc.toString();
352 * to message to be printed
354 final static void dieWithSystemError( final String message ) {
355 System.out.println();
356 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
357 System.out.println( "Please contact the authors." );
358 System.out.println( Constants.PRG_NAME + " needs to close." );
359 System.out.println();
363 final static String[] getAvailableFontFamiliesSorted() {
364 return AVAILABLE_FONT_FAMILIES_SORTED;
367 final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
368 boolean inferred = false;
369 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
370 final PhylogenyNode n = it.next();
371 if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
372 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
373 if ( !ForesterUtil.isEmpty( sn ) ) {
374 n.getNodeData().setTaxonomy( new Taxonomy() );
375 n.getNodeData().getTaxonomy().setScientificName( sn );
381 tree.setRerootable( false );
385 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
386 if ( !node.getNodeData().isHasEvent() ) {
389 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
395 final static boolean isJava15() {
397 final String s = ForesterUtil.JAVA_VERSION;
398 return s.startsWith( "1.5" );
400 catch ( final Exception e ) {
401 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
406 final static boolean isMac() {
408 final String s = ForesterUtil.OS_NAME.toLowerCase();
409 return s.startsWith( "mac" );
411 catch ( final Exception e ) {
412 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
417 final static boolean isUsOrCanada() {
419 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
423 catch ( final Exception e ) {
429 final static boolean isWindows() {
431 final String s = ForesterUtil.OS_NAME.toLowerCase();
432 return s.indexOf( "win" ) > -1;
434 catch ( final Exception e ) {
435 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
440 final static void launchWebBrowser( final URI uri,
441 final boolean is_applet,
442 final JApplet applet,
443 final String frame_name ) throws IOException {
445 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
448 // This requires Java 1.6:
449 // =======================
450 // boolean no_desktop = false;
452 // if ( Desktop.isDesktopSupported() ) {
453 // System.out.println( "desktop supported" );
454 // final Desktop dt = Desktop.getDesktop();
458 // no_desktop = true;
461 // catch ( final Exception ex ) {
462 // ex.printStackTrace();
463 // no_desktop = true;
465 // catch ( final Error er ) {
466 // er.printStackTrace();
467 // no_desktop = true;
469 // if ( no_desktop ) {
470 // System.out.println( "desktop not supported" );
472 openUrlInWebBrowser( uri.toString() );
474 catch ( final Exception e ) {
475 throw new IOException( e );
481 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
482 final ControlPanel atv_control,
483 final Configuration configuration ) {
484 if ( ( t != null ) && !t.isEmpty() ) {
485 if ( !ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
486 atv_control.setDrawPhylogram( false );
487 atv_control.setDrawPhylogramEnabled( false );
489 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
490 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
491 if ( ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
492 atv_control.setDrawPhylogram( true );
493 atv_control.setDrawPhylogramEnabled( true );
496 atv_control.setDrawPhylogram( false );
500 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
501 if ( atv_control.getWriteConfidenceCb() != null ) {
502 if ( ForesterUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
503 atv_control.setCheckbox( Configuration.write_confidence_values, true );
506 atv_control.setCheckbox( Configuration.write_confidence_values, false );
510 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
511 if ( atv_control.getShowEventsCb() != null ) {
512 if ( ForesterUtil.isHasAtLeastNodeWithEvent( t ) ) {
513 atv_control.setCheckbox( Configuration.write_events, true );
516 atv_control.setCheckbox( Configuration.write_events, false );
523 final private static char normalizeCharForRGB( char c ) {
526 c = c > 255 ? 255 : c;
531 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
532 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
533 InvocationTargetException, InterruptedException {
534 final String os = System.getProperty( "os.name" );
535 final Runtime runtime = Runtime.getRuntime();
536 if ( os.toLowerCase().startsWith( "win" ) ) {
537 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
539 else if ( isMac() ) {
540 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
541 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
542 open_url.invoke( null, new Object[] { url } );
545 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
546 String browser = null;
547 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
548 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
549 browser = browsers[ i ];
552 if ( browser == null ) {
553 throw new IOException( "could not find a web browser to open [" + url + "] in" );
556 runtime.exec( new String[] { browser, url } );
561 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
563 Util.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
565 catch ( final Exception e ) {
566 throw new IOException( e );
570 final static void printAppletMessage( final String applet_name, final String message ) {
571 System.out.println( "[" + applet_name + "] > " + message );
574 final static void printWarningMessage( final String name, final String message ) {
575 System.out.println( "[" + name + "] > " + message );
578 final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final File file ) throws IOException {
579 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
580 final Phylogeny[] trees = factory.create( file, parser );
581 if ( ( trees == null ) || ( trees.length == 0 ) ) {
582 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
587 final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
588 throws FileNotFoundException, IOException {
589 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
590 PhylogenyParser parser = null;
591 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
592 parser = new TolParser();
595 parser = ForesterUtil.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
597 return factory.create( url.openStream(), parser );
600 final static void removeBranchColors( final Phylogeny phy ) {
601 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
602 it.next().getBranchData().setBranchColor( null );
606 final static void showErrorMessage( final Component parent, final String error_msg ) {
607 printAppletMessage( Constants.PRG_NAME, error_msg );
608 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
609 + "] Error", JOptionPane.ERROR_MESSAGE );
612 final static void unexpectedError( final Error err ) {
613 err.printStackTrace();
614 final StringBuffer sb = new StringBuffer();
615 for( final StackTraceElement s : err.getStackTrace() ) {
616 sb.append( s + "\n" );
619 .showMessageDialog( null,
620 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
621 + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
622 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
623 JOptionPane.ERROR_MESSAGE );
627 final static void unexpectedException( final Exception ex ) {
628 ex.printStackTrace();
629 final StringBuffer sb = new StringBuffer();
630 for( final StackTraceElement s : ex.getStackTrace() ) {
631 sb.append( s + "\n" );
633 JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
634 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
635 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
638 final static String writePhylogenyToGraphicsFile( final String file_name,
641 final TreePanel tree_panel,
642 final ControlPanel ac,
643 final GraphicsExportType type,
644 final Options options ) throws IOException {
645 if ( !options.isGraphicsExportUsingActualSize() ) {
646 if ( options.isGraphicsExportVisibleOnly() ) {
647 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
649 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
650 tree_panel.resetPreferredSize();
651 tree_panel.repaint();
653 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
654 RenderingHints.VALUE_RENDER_QUALITY );
655 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
656 if ( options.isAntialiasPrint() ) {
657 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
658 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
661 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
662 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
664 final Phylogeny phylogeny = tree_panel.getPhylogeny();
665 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
668 final File file = new File( file_name );
669 if ( file.isDirectory() ) {
670 throw new IOException( "\"" + file_name + "\" is a directory" );
672 Rectangle visible = null;
673 if ( !options.isGraphicsExportUsingActualSize() ) {
674 width = options.getPrintSizeX();
675 height = options.getPrintSizeY();
677 else if ( options.isGraphicsExportVisibleOnly() ) {
678 visible = tree_panel.getVisibleRect();
679 width = visible.width;
680 height = visible.height;
682 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
683 Graphics2D g2d = buffered_img.createGraphics();
684 g2d.setRenderingHints( rendering_hints );
687 if ( options.isGraphicsExportVisibleOnly() ) {
688 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
693 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
694 if ( type == GraphicsExportType.TIFF ) {
695 writeToTiff( file, buffered_img );
698 ImageIO.write( buffered_img, type.toString(), file );
702 if ( !options.isGraphicsExportUsingActualSize() ) {
703 tree_panel.getMainPanel().getControlPanel().showWhole();
705 String msg = file.toString();
706 if ( ( width > 0 ) && ( height > 0 ) ) {
707 msg += " [size: " + width + ", " + height + "]";
712 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
713 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
714 ImageWriter writer = null;
715 ImageOutputStream ios = null;
716 // Find an appropriate writer:
717 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
718 if ( it.hasNext() ) {
722 throw new IOException( "failed to get TIFF image writer" );
725 ios = ImageIO.createImageOutputStream( file );
726 writer.setOutput( ios );
727 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
728 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
729 // see writeParam.getCompressionTypes() for available compression type
731 image_write_param.setCompressionType( "PackBits" );
732 final String t[] = image_write_param.getCompressionTypes();
733 for( final String string : t ) {
734 System.out.println( string );
736 // Convert to an IIOImage:
737 final IIOImage iio_image = new IIOImage( image, null, null );
738 writer.write( null, iio_image, image_write_param );
741 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
742 // static void openDDBJRest() throws IOException {
744 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
746 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
748 // URLConnection urlc = url.openConnection();
750 // urlc.setDoOutput( true );
751 // urlc.setAllowUserInteraction( false );
753 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
754 // ps.print( query );
757 // BufferedReader br = new BufferedReader( new InputStreamReader(
758 // urlc.getInputStream() ) );
760 // while ( ( l = br.readLine() ) != null ) {
761 // System.out.println( l );
765 static enum GraphicsExportType {
766 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
768 private final String _suffix;
770 private GraphicsExportType( final String suffix ) {
775 public String toString() {