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.DescriptiveStatistics;
71 import org.forester.util.ForesterUtil;
75 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
76 .getAvailableFontFamilyNames();
78 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
81 public static MaskFormatter createMaskFormatter( final String s ) {
82 MaskFormatter formatter = null;
84 formatter = new MaskFormatter( s );
86 catch ( final ParseException e ) {
87 throw new IllegalArgumentException( e );
92 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
93 final String default_name,
94 final String full_path,
95 final Configuration configuration,
96 final MainPanel main_panel ) {
97 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
98 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
99 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
100 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
103 for( final Phylogeny phy : phys ) {
104 if ( !phy.isEmpty() ) {
105 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
107 String my_name_for_file = "";
108 if ( phys.length > 1 ) {
109 if ( !ForesterUtil.isEmpty( default_name ) ) {
110 my_name = new String( default_name );
112 if ( !ForesterUtil.isEmpty( full_path ) ) {
113 my_name_for_file = new String( full_path );
115 else if ( !ForesterUtil.isEmpty( default_name ) ) {
116 my_name_for_file = new String( default_name );
119 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
120 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
121 my_name_for_file.length() );
122 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
124 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
125 my_name_for_file += "_";
127 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
128 my_name_for_file += phy.getName().replaceAll( " ", "_" );
130 else if ( phy.getIdentifier() != null ) {
131 final StringBuffer sb = new StringBuffer();
132 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
133 sb.append( phy.getIdentifier().getProvider() );
136 sb.append( phy.getIdentifier().getValue() );
137 my_name_for_file += sb;
140 my_name_for_file += i;
142 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
143 && ( phy.getIdentifier() == null ) ) {
144 my_name = my_name + " [" + i + "]";
146 if ( !ForesterUtil.isEmpty( suffix ) ) {
147 my_name_for_file += suffix;
151 if ( !ForesterUtil.isEmpty( default_name ) ) {
152 my_name = new String( default_name );
154 my_name_for_file = "";
155 if ( !ForesterUtil.isEmpty( full_path ) ) {
156 my_name_for_file = new String( full_path );
158 else if ( !ForesterUtil.isEmpty( default_name ) ) {
159 my_name_for_file = new String( default_name );
161 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
162 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
163 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
165 else if ( phy.getIdentifier() != null ) {
166 final StringBuffer sb = new StringBuffer();
167 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
168 sb.append( phy.getIdentifier().getProvider() );
171 sb.append( phy.getIdentifier().getValue() );
172 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
176 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
177 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
178 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
185 final static void addPhylogenyToPanel( final Phylogeny[] phys,
186 final Configuration configuration,
187 final MainPanel main_panel ) {
188 final Phylogeny phy = phys[ 0 ];
189 main_panel.addPhylogenyInPanel( phy, configuration );
190 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
193 final static Color calculateColorFromString( final String str ) {
194 final String species_uc = str.toUpperCase();
195 char first = species_uc.charAt( 0 );
198 if ( species_uc.length() > 1 ) {
199 second = species_uc.charAt( 1 );
200 if ( species_uc.length() > 2 ) {
201 if ( species_uc.indexOf( " " ) > 0 ) {
202 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
205 third = species_uc.charAt( 2 );
209 first = Util.normalizeCharForRGB( first );
210 second = Util.normalizeCharForRGB( second );
211 third = Util.normalizeCharForRGB( third );
212 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
215 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
218 return new Color( first, second, third );
221 // Returns true if the specified format name can be written
222 final static boolean canWriteFormat( final String format_name ) {
223 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
224 return iter.hasNext();
227 final public static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
228 boolean inferred = false;
229 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
230 final PhylogenyNode n = it.next();
231 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
232 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
233 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
234 Util.collapseSubtree( n, true );
235 if ( !n.getNodeData().isHasTaxonomy() ) {
236 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
237 .getTaxonomy().copy() );
242 n.setCollapse( false );
247 phy.setRerootable( false );
251 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
252 node.setCollapse( collapse );
253 if ( node.isExternal() ) {
256 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
257 while ( it.hasNext() ) {
258 it.next().setCollapse( collapse );
262 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
263 double max_conf = 0.0;
264 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
265 final PhylogenyNode n = it.next();
266 n.getBranchData().setBranchColor( null );
267 if ( n.getBranchData().isHasConfidences() ) {
268 final double conf = PhylogenyMethods.getConfidenceValue( n );
269 if ( conf > max_conf ) {
274 if ( max_conf > 0.0 ) {
275 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
276 final Color br = tree_panel.getTreeColorSet().getBranchColor();
277 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
278 final PhylogenyNode n = it.next();
279 if ( n.getBranchData().isHasConfidences() ) {
280 final double conf = PhylogenyMethods.getConfidenceValue( n );
281 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
282 n.getBranchData().setBranchColor( c );
283 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
284 for( final PhylogenyNode desc : descs ) {
285 desc.getBranchData().setBranchColor( c );
292 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
293 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
294 it.next().getBranchData().setBranchColor( null );
296 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
297 final PhylogenyNode n = it.next();
298 if ( !n.getBranchData().isHasBranchColor() ) {
299 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
301 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
302 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
303 for( final PhylogenyNode desc : descs ) {
305 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
312 final static String crateBasicInformation( final Phylogeny phy ) {
313 final StringBuilder desc = new StringBuilder();
314 if ( ( phy != null ) && !phy.isEmpty() ) {
315 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
316 desc.append( "Name: " );
317 desc.append( phy.getName() );
320 if ( phy.getIdentifier() != null ) {
321 desc.append( "Id: " );
322 desc.append( phy.getIdentifier() );
325 desc.append( "Rooted: " );
326 desc.append( phy.isRooted() );
328 desc.append( "Rerootable: " );
329 desc.append( phy.isRerootable() );
331 desc.append( "Node sum: " );
332 desc.append( phy.getNodeCount() );
334 desc.append( "External node sum: " );
335 desc.append( phy.getNumberOfExternalNodes() );
337 desc.append( "Internal node sum: " );
338 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
340 desc.append( "Branche sum: " );
341 desc.append( phy.getNumberOfBranches() );
343 desc.append( "Depth: " );
344 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
346 desc.append( "Maximum distance to root: " );
347 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
349 desc.append( "Descendants per node statistics: " );
350 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
352 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
354 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
356 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
358 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
360 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
362 final DescriptiveStatistics cs = PhylogenyMethods.calculatConfidenceStatistics( phy );
363 if ( cs.getN() > 1 ) {
364 desc.append( "Support statistics: " );
366 desc.append( " Branches with support: " + cs.getN() );
368 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
370 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
372 if ( cs.getN() > 2 ) {
373 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
376 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
378 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
381 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
382 if ( taxs != null ) {
383 desc.append( "Distinct external taxonomies: " );
384 desc.append( taxs.size() );
387 return desc.toString();
395 * to message to be printed
397 final static void dieWithSystemError( final String message ) {
398 System.out.println();
399 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
400 System.out.println( "Please contact the authors." );
401 System.out.println( Constants.PRG_NAME + " needs to close." );
402 System.out.println();
406 final static String[] getAvailableFontFamiliesSorted() {
407 return AVAILABLE_FONT_FAMILIES_SORTED;
410 final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
411 boolean inferred = false;
412 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
413 final PhylogenyNode n = it.next();
414 if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
415 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
416 if ( !ForesterUtil.isEmpty( sn ) ) {
417 n.getNodeData().setTaxonomy( new Taxonomy() );
418 n.getNodeData().getTaxonomy().setScientificName( sn );
424 tree.setRerootable( false );
428 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
429 if ( !node.getNodeData().isHasEvent() ) {
432 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
438 final static boolean isJava15() {
440 final String s = ForesterUtil.JAVA_VERSION;
441 return s.startsWith( "1.5" );
443 catch ( final Exception e ) {
444 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
449 final static boolean isMac() {
451 final String s = ForesterUtil.OS_NAME.toLowerCase();
452 return s.startsWith( "mac" );
454 catch ( final Exception e ) {
455 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
460 final static boolean isUsOrCanada() {
462 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
466 catch ( final Exception e ) {
472 final static boolean isWindows() {
474 final String s = ForesterUtil.OS_NAME.toLowerCase();
475 return s.indexOf( "win" ) > -1;
477 catch ( final Exception e ) {
478 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
483 final static void launchWebBrowser( final URI uri,
484 final boolean is_applet,
485 final JApplet applet,
486 final String frame_name ) throws IOException {
488 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
491 // This requires Java 1.6:
492 // =======================
493 // boolean no_desktop = false;
495 // if ( Desktop.isDesktopSupported() ) {
496 // System.out.println( "desktop supported" );
497 // final Desktop dt = Desktop.getDesktop();
501 // no_desktop = true;
504 // catch ( final Exception ex ) {
505 // ex.printStackTrace();
506 // no_desktop = true;
508 // catch ( final Error er ) {
509 // er.printStackTrace();
510 // no_desktop = true;
512 // if ( no_desktop ) {
513 // System.out.println( "desktop not supported" );
515 openUrlInWebBrowser( uri.toString() );
517 catch ( final Exception e ) {
518 throw new IOException( e );
524 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
525 final ControlPanel atv_control,
526 final Configuration configuration ) {
527 if ( ( t != null ) && !t.isEmpty() ) {
528 if ( !ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
529 atv_control.setDrawPhylogram( false );
530 atv_control.setDrawPhylogramEnabled( false );
532 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
533 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
534 if ( ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
535 atv_control.setDrawPhylogram( true );
536 atv_control.setDrawPhylogramEnabled( true );
539 atv_control.setDrawPhylogram( false );
543 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
544 if ( atv_control.getWriteConfidenceCb() != null ) {
545 if ( ForesterUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
546 atv_control.setCheckbox( Configuration.write_confidence_values, true );
549 atv_control.setCheckbox( Configuration.write_confidence_values, false );
553 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
554 if ( atv_control.getShowEventsCb() != null ) {
555 if ( ForesterUtil.isHasAtLeastNodeWithEvent( t ) ) {
556 atv_control.setCheckbox( Configuration.write_events, true );
559 atv_control.setCheckbox( Configuration.write_events, false );
566 final private static char normalizeCharForRGB( char c ) {
569 c = c > 255 ? 255 : c;
574 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
575 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
576 InvocationTargetException, InterruptedException {
577 final String os = System.getProperty( "os.name" );
578 final Runtime runtime = Runtime.getRuntime();
579 if ( os.toLowerCase().startsWith( "win" ) ) {
580 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
582 else if ( isMac() ) {
583 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
584 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
585 open_url.invoke( null, new Object[] { url } );
588 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
589 String browser = null;
590 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
591 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
592 browser = browsers[ i ];
595 if ( browser == null ) {
596 throw new IOException( "could not find a web browser to open [" + url + "] in" );
599 runtime.exec( new String[] { browser, url } );
604 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
606 Util.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
608 catch ( final Exception e ) {
609 throw new IOException( e );
613 final static void printAppletMessage( final String applet_name, final String message ) {
614 System.out.println( "[" + applet_name + "] > " + message );
617 final static void printWarningMessage( final String name, final String message ) {
618 System.out.println( "[" + name + "] > " + message );
621 final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final File file ) throws IOException {
622 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
623 final Phylogeny[] trees = factory.create( file, parser );
624 if ( ( trees == null ) || ( trees.length == 0 ) ) {
625 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
630 final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
631 throws FileNotFoundException, IOException {
632 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
633 PhylogenyParser parser = null;
634 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
635 parser = new TolParser();
638 parser = ForesterUtil.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
640 return factory.create( url.openStream(), parser );
643 final static void removeBranchColors( final Phylogeny phy ) {
644 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
645 it.next().getBranchData().setBranchColor( null );
649 final static void showErrorMessage( final Component parent, final String error_msg ) {
650 printAppletMessage( Constants.PRG_NAME, error_msg );
651 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
652 + "] Error", JOptionPane.ERROR_MESSAGE );
655 final static void unexpectedError( final Error err ) {
656 err.printStackTrace();
657 final StringBuffer sb = new StringBuffer();
658 for( final StackTraceElement s : err.getStackTrace() ) {
659 sb.append( s + "\n" );
662 .showMessageDialog( null,
663 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
664 + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
665 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
666 JOptionPane.ERROR_MESSAGE );
670 final static void unexpectedException( final Exception ex ) {
671 ex.printStackTrace();
672 final StringBuffer sb = new StringBuffer();
673 for( final StackTraceElement s : ex.getStackTrace() ) {
674 sb.append( s + "\n" );
676 JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
677 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
678 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
681 final static String writePhylogenyToGraphicsFile( final String file_name,
684 final TreePanel tree_panel,
685 final ControlPanel ac,
686 final GraphicsExportType type,
687 final Options options ) throws IOException {
688 if ( !options.isGraphicsExportUsingActualSize() ) {
689 if ( options.isGraphicsExportVisibleOnly() ) {
690 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
692 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
693 tree_panel.resetPreferredSize();
694 tree_panel.repaint();
696 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
697 RenderingHints.VALUE_RENDER_QUALITY );
698 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
699 if ( options.isAntialiasPrint() ) {
700 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
701 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
704 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
705 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
707 final Phylogeny phylogeny = tree_panel.getPhylogeny();
708 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
711 final File file = new File( file_name );
712 if ( file.isDirectory() ) {
713 throw new IOException( "\"" + file_name + "\" is a directory" );
715 Rectangle visible = null;
716 if ( !options.isGraphicsExportUsingActualSize() ) {
717 width = options.getPrintSizeX();
718 height = options.getPrintSizeY();
720 else if ( options.isGraphicsExportVisibleOnly() ) {
721 visible = tree_panel.getVisibleRect();
722 width = visible.width;
723 height = visible.height;
725 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
726 Graphics2D g2d = buffered_img.createGraphics();
727 g2d.setRenderingHints( rendering_hints );
730 if ( options.isGraphicsExportVisibleOnly() ) {
731 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
736 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
737 if ( type == GraphicsExportType.TIFF ) {
738 writeToTiff( file, buffered_img );
741 ImageIO.write( buffered_img, type.toString(), file );
745 if ( !options.isGraphicsExportUsingActualSize() ) {
746 tree_panel.getMainPanel().getControlPanel().showWhole();
748 String msg = file.toString();
749 if ( ( width > 0 ) && ( height > 0 ) ) {
750 msg += " [size: " + width + ", " + height + "]";
755 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
756 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
757 ImageWriter writer = null;
758 ImageOutputStream ios = null;
759 // Find an appropriate writer:
760 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
761 if ( it.hasNext() ) {
765 throw new IOException( "failed to get TIFF image writer" );
768 ios = ImageIO.createImageOutputStream( file );
769 writer.setOutput( ios );
770 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
771 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
772 // see writeParam.getCompressionTypes() for available compression type
774 image_write_param.setCompressionType( "PackBits" );
775 final String t[] = image_write_param.getCompressionTypes();
776 for( final String string : t ) {
777 System.out.println( string );
779 // Convert to an IIOImage:
780 final IIOImage iio_image = new IIOImage( image, null, null );
781 writer.write( null, iio_image, image_write_param );
784 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
785 // static void openDDBJRest() throws IOException {
787 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
789 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
791 // URLConnection urlc = url.openConnection();
793 // urlc.setDoOutput( true );
794 // urlc.setAllowUserInteraction( false );
796 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
797 // ps.print( query );
800 // BufferedReader br = new BufferedReader( new InputStreamReader(
801 // urlc.getInputStream() ) );
803 // while ( ( l = br.readLine() ) != null ) {
804 // System.out.println( l );
808 static enum GraphicsExportType {
809 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
811 private final String _suffix;
813 private GraphicsExportType( final String suffix ) {
818 public String toString() {