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.HashMap;
45 import java.util.Iterator;
46 import java.util.List;
47 import java.util.Locale;
50 import java.util.SortedSet;
51 import java.util.TreeSet;
53 import javax.imageio.IIOImage;
54 import javax.imageio.ImageIO;
55 import javax.imageio.ImageWriteParam;
56 import javax.imageio.ImageWriter;
57 import javax.imageio.stream.ImageOutputStream;
58 import javax.swing.JApplet;
59 import javax.swing.JOptionPane;
60 import javax.swing.text.MaskFormatter;
62 import org.forester.io.parsers.PhylogenyParser;
63 import org.forester.io.parsers.tol.TolParser;
64 import org.forester.phylogeny.Phylogeny;
65 import org.forester.phylogeny.PhylogenyMethods;
66 import org.forester.phylogeny.PhylogenyNode;
67 import org.forester.phylogeny.data.BranchColor;
68 import org.forester.phylogeny.data.Taxonomy;
69 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
70 import org.forester.phylogeny.factories.PhylogenyFactory;
71 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
72 import org.forester.phylogeny.iterators.PreorderTreeIterator;
73 import org.forester.util.DescriptiveStatistics;
74 import org.forester.util.ForesterUtil;
76 public final class Util {
78 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
79 .getAvailableFontFamilyNames();
81 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
84 public static MaskFormatter createMaskFormatter( final String s ) {
85 MaskFormatter formatter = null;
87 formatter = new MaskFormatter( s );
89 catch ( final ParseException e ) {
90 throw new IllegalArgumentException( e );
95 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
96 final String default_name,
97 final String full_path,
98 final Configuration configuration,
99 final MainPanel main_panel ) {
100 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
101 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
102 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
103 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
106 for( final Phylogeny phy : phys ) {
107 if ( !phy.isEmpty() ) {
108 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
110 String my_name_for_file = "";
111 if ( phys.length > 1 ) {
112 if ( !ForesterUtil.isEmpty( default_name ) ) {
113 my_name = new String( default_name );
115 if ( !ForesterUtil.isEmpty( full_path ) ) {
116 my_name_for_file = new String( full_path );
118 else if ( !ForesterUtil.isEmpty( default_name ) ) {
119 my_name_for_file = new String( default_name );
122 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
123 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
124 my_name_for_file.length() );
125 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
127 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
128 my_name_for_file += "_";
130 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
131 my_name_for_file += phy.getName().replaceAll( " ", "_" );
133 else if ( phy.getIdentifier() != null ) {
134 final StringBuffer sb = new StringBuffer();
135 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
136 sb.append( phy.getIdentifier().getProvider() );
139 sb.append( phy.getIdentifier().getValue() );
140 my_name_for_file += sb;
143 my_name_for_file += i;
145 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
146 && ( phy.getIdentifier() == null ) ) {
147 my_name = my_name + " [" + i + "]";
149 if ( !ForesterUtil.isEmpty( suffix ) ) {
150 my_name_for_file += suffix;
154 if ( !ForesterUtil.isEmpty( default_name ) ) {
155 my_name = new String( default_name );
157 my_name_for_file = "";
158 if ( !ForesterUtil.isEmpty( full_path ) ) {
159 my_name_for_file = new String( full_path );
161 else if ( !ForesterUtil.isEmpty( default_name ) ) {
162 my_name_for_file = new String( default_name );
164 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
165 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
166 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
168 else if ( phy.getIdentifier() != null ) {
169 final StringBuffer sb = new StringBuffer();
170 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
171 sb.append( phy.getIdentifier().getProvider() );
174 sb.append( phy.getIdentifier().getValue() );
175 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
179 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
180 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
181 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
188 final static void addPhylogenyToPanel( final Phylogeny[] phys,
189 final Configuration configuration,
190 final MainPanel main_panel ) {
191 final Phylogeny phy = phys[ 0 ];
192 main_panel.addPhylogenyInPanel( phy, configuration );
193 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
196 final static Color calculateColorFromString( final String str ) {
197 final String species_uc = str.toUpperCase();
198 char first = species_uc.charAt( 0 );
201 if ( species_uc.length() > 1 ) {
202 second = species_uc.charAt( 1 );
203 if ( species_uc.length() > 2 ) {
204 if ( species_uc.indexOf( " " ) > 0 ) {
205 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
208 third = species_uc.charAt( 2 );
212 first = Util.normalizeCharForRGB( first );
213 second = Util.normalizeCharForRGB( second );
214 third = Util.normalizeCharForRGB( third );
215 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
218 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
221 return new Color( first, second, third );
224 // Returns true if the specified format name can be written
225 final static boolean canWriteFormat( final String format_name ) {
226 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
227 return iter.hasNext();
230 final public static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
231 boolean inferred = false;
232 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
233 final PhylogenyNode n = it.next();
234 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
235 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
236 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
237 Util.collapseSubtree( n, true );
238 if ( !n.getNodeData().isHasTaxonomy() ) {
239 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
240 .getTaxonomy().copy() );
245 n.setCollapse( false );
250 phy.setRerootable( false );
254 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
255 node.setCollapse( collapse );
256 if ( node.isExternal() ) {
259 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
260 while ( it.hasNext() ) {
261 it.next().setCollapse( collapse );
265 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
266 double max_conf = 0.0;
267 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
268 final PhylogenyNode n = it.next();
269 n.getBranchData().setBranchColor( null );
270 if ( n.getBranchData().isHasConfidences() ) {
271 final double conf = PhylogenyMethods.getConfidenceValue( n );
272 if ( conf > max_conf ) {
277 if ( max_conf > 0.0 ) {
278 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
279 final Color br = tree_panel.getTreeColorSet().getBranchColor();
280 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
281 final PhylogenyNode n = it.next();
282 if ( n.getBranchData().isHasConfidences() ) {
283 final double conf = PhylogenyMethods.getConfidenceValue( n );
284 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
285 n.getBranchData().setBranchColor( c );
286 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
287 for( final PhylogenyNode desc : descs ) {
288 desc.getBranchData().setBranchColor( c );
295 final static void colorPhylogenyAccordingToRanks( final Phylogeny tree,
297 final TreePanel tree_panel ) {
298 final Map<String, Color> m = new HashMap<String, Color>();
299 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
300 final PhylogenyNode n = it.next();
301 if ( n.getNodeData().isHasTaxonomy()
302 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
303 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
304 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
305 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
306 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
307 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
309 n.getBranchData().setBranchColor( c );
310 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
311 for( final PhylogenyNode desc : descs ) {
312 desc.getBranchData().setBranchColor( c );
314 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
315 m.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
320 if ( !m.isEmpty() ) {
321 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
322 final PhylogenyNode n = it.next();
323 if ( ( n.getBranchData().getBranchColor() == null ) && n.getNodeData().isHasTaxonomy()
324 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getLineage() ) ) {
325 for( final String lin : n.getNodeData().getTaxonomy().getLineage() ) {
326 if ( m.containsKey( lin ) ) {
327 final BranchColor c = new BranchColor( m.get( lin ) );
328 n.getBranchData().setBranchColor( c );
329 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
330 for( final PhylogenyNode desc : descs ) {
331 desc.getBranchData().setBranchColor( c );
340 final static String[] getAllRanks( final Phylogeny tree ) {
341 final SortedSet<String> ranks = new TreeSet<String>();
342 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
343 final PhylogenyNode n = it.next();
344 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
345 ranks.add( n.getNodeData().getTaxonomy().getRank() );
348 return ForesterUtil.stringSetToArray( ranks );
351 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
352 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
353 it.next().getBranchData().setBranchColor( null );
355 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
356 final PhylogenyNode n = it.next();
357 if ( !n.getBranchData().isHasBranchColor() ) {
358 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
360 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
361 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
362 for( final PhylogenyNode desc : descs ) {
364 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
371 final static String crateBasicInformation( final Phylogeny phy ) {
372 final StringBuilder desc = new StringBuilder();
373 if ( ( phy != null ) && !phy.isEmpty() ) {
374 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
375 desc.append( "Name: " );
376 desc.append( phy.getName() );
379 if ( phy.getIdentifier() != null ) {
380 desc.append( "Id: " );
381 desc.append( phy.getIdentifier() );
384 desc.append( "Rooted: " );
385 desc.append( phy.isRooted() );
387 desc.append( "Rerootable: " );
388 desc.append( phy.isRerootable() );
390 desc.append( "Node sum: " );
391 desc.append( phy.getNodeCount() );
393 desc.append( "External node sum: " );
394 desc.append( phy.getNumberOfExternalNodes() );
396 desc.append( "Internal node sum: " );
397 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
399 desc.append( "Branche sum: " );
400 desc.append( phy.getNumberOfBranches() );
402 desc.append( "Depth: " );
403 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
405 desc.append( "Maximum distance to root: " );
406 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
408 desc.append( "Descendants per node statistics: " );
409 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
411 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
413 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
415 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
417 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
419 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
421 final DescriptiveStatistics cs = PhylogenyMethods.calculatConfidenceStatistics( phy );
422 if ( cs.getN() > 1 ) {
423 desc.append( "Support statistics: " );
425 desc.append( " Branches with support: " + cs.getN() );
427 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
429 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
431 if ( cs.getN() > 2 ) {
432 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
435 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
437 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
440 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
441 if ( taxs != null ) {
442 desc.append( "Distinct external taxonomies: " );
443 desc.append( taxs.size() );
446 return desc.toString();
454 * to message to be printed
456 final static void dieWithSystemError( final String message ) {
457 System.out.println();
458 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
459 System.out.println( "Please contact the authors." );
460 System.out.println( Constants.PRG_NAME + " needs to close." );
461 System.out.println();
465 final static String[] getAvailableFontFamiliesSorted() {
466 return AVAILABLE_FONT_FAMILIES_SORTED;
469 final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
470 boolean inferred = false;
471 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
472 final PhylogenyNode n = it.next();
473 if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
474 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
475 if ( !ForesterUtil.isEmpty( sn ) ) {
476 n.getNodeData().setTaxonomy( new Taxonomy() );
477 n.getNodeData().getTaxonomy().setScientificName( sn );
483 tree.setRerootable( false );
487 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
488 if ( !node.getNodeData().isHasEvent() ) {
491 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
497 final static boolean isJava15() {
499 final String s = ForesterUtil.JAVA_VERSION;
500 return s.startsWith( "1.5" );
502 catch ( final Exception e ) {
503 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
508 final static boolean isMac() {
510 final String s = ForesterUtil.OS_NAME.toLowerCase();
511 return s.startsWith( "mac" );
513 catch ( final Exception e ) {
514 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
519 final static boolean isUsOrCanada() {
521 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
525 catch ( final Exception e ) {
531 final static boolean isWindows() {
533 final String s = ForesterUtil.OS_NAME.toLowerCase();
534 return s.indexOf( "win" ) > -1;
536 catch ( final Exception e ) {
537 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
542 final static void launchWebBrowser( final URI uri,
543 final boolean is_applet,
544 final JApplet applet,
545 final String frame_name ) throws IOException {
547 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
550 // This requires Java 1.6:
551 // =======================
552 // boolean no_desktop = false;
554 // if ( Desktop.isDesktopSupported() ) {
555 // System.out.println( "desktop supported" );
556 // final Desktop dt = Desktop.getDesktop();
560 // no_desktop = true;
563 // catch ( final Exception ex ) {
564 // ex.printStackTrace();
565 // no_desktop = true;
567 // catch ( final Error er ) {
568 // er.printStackTrace();
569 // no_desktop = true;
571 // if ( no_desktop ) {
572 // System.out.println( "desktop not supported" );
574 openUrlInWebBrowser( uri.toString() );
576 catch ( final Exception e ) {
577 throw new IOException( e );
583 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
584 final ControlPanel atv_control,
585 final Configuration configuration ) {
586 if ( ( t != null ) && !t.isEmpty() ) {
587 if ( !ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
588 atv_control.setDrawPhylogram( false );
589 atv_control.setDrawPhylogramEnabled( false );
591 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
592 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
593 if ( ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
594 atv_control.setDrawPhylogram( true );
595 atv_control.setDrawPhylogramEnabled( true );
598 atv_control.setDrawPhylogram( false );
602 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
603 if ( atv_control.getWriteConfidenceCb() != null ) {
604 if ( ForesterUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
605 atv_control.setCheckbox( Configuration.write_confidence_values, true );
608 atv_control.setCheckbox( Configuration.write_confidence_values, false );
612 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
613 if ( atv_control.getShowEventsCb() != null ) {
614 if ( ForesterUtil.isHasAtLeastNodeWithEvent( t ) ) {
615 atv_control.setCheckbox( Configuration.write_events, true );
618 atv_control.setCheckbox( Configuration.write_events, false );
625 final private static char normalizeCharForRGB( char c ) {
628 c = c > 255 ? 255 : c;
633 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
634 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
635 InvocationTargetException, InterruptedException {
636 final String os = System.getProperty( "os.name" );
637 final Runtime runtime = Runtime.getRuntime();
638 if ( os.toLowerCase().startsWith( "win" ) ) {
639 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
641 else if ( isMac() ) {
642 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
643 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
644 open_url.invoke( null, new Object[] { url } );
647 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
648 String browser = null;
649 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
650 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
651 browser = browsers[ i ];
654 if ( browser == null ) {
655 throw new IOException( "could not find a web browser to open [" + url + "] in" );
658 runtime.exec( new String[] { browser, url } );
663 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
665 Util.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
667 catch ( final Exception e ) {
668 throw new IOException( e );
672 final static void printAppletMessage( final String applet_name, final String message ) {
673 System.out.println( "[" + applet_name + "] > " + message );
676 public final static void printWarningMessage( final String name, final String message ) {
677 System.out.println( "[" + name + "] > " + message );
680 final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
681 throws FileNotFoundException, IOException {
682 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
683 PhylogenyParser parser = null;
684 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
685 parser = new TolParser();
688 parser = ForesterUtil.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
690 return factory.create( url.openStream(), parser );
693 final static void removeBranchColors( final Phylogeny phy ) {
694 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
695 it.next().getBranchData().setBranchColor( null );
699 final static void showErrorMessage( final Component parent, final String error_msg ) {
700 printAppletMessage( Constants.PRG_NAME, error_msg );
701 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
702 + "] Error", JOptionPane.ERROR_MESSAGE );
705 final static void unexpectedError( final Error err ) {
706 err.printStackTrace();
707 final StringBuffer sb = new StringBuffer();
708 for( final StackTraceElement s : err.getStackTrace() ) {
709 sb.append( s + "\n" );
712 .showMessageDialog( null,
713 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
714 + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
715 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
716 JOptionPane.ERROR_MESSAGE );
720 final static void unexpectedException( final Exception ex ) {
721 ex.printStackTrace();
722 final StringBuffer sb = new StringBuffer();
723 for( final StackTraceElement s : ex.getStackTrace() ) {
724 sb.append( s + "\n" );
726 JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
727 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
728 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
731 final static String writePhylogenyToGraphicsFile( final String file_name,
734 final TreePanel tree_panel,
735 final ControlPanel ac,
736 final GraphicsExportType type,
737 final Options options ) throws IOException {
738 if ( !options.isGraphicsExportUsingActualSize() ) {
739 if ( options.isGraphicsExportVisibleOnly() ) {
740 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
742 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
743 tree_panel.resetPreferredSize();
744 tree_panel.repaint();
746 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
747 RenderingHints.VALUE_RENDER_QUALITY );
748 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
749 if ( options.isAntialiasPrint() ) {
750 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
751 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
754 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
755 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
757 final Phylogeny phylogeny = tree_panel.getPhylogeny();
758 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
761 final File file = new File( file_name );
762 if ( file.isDirectory() ) {
763 throw new IOException( "\"" + file_name + "\" is a directory" );
765 Rectangle visible = null;
766 if ( !options.isGraphicsExportUsingActualSize() ) {
767 width = options.getPrintSizeX();
768 height = options.getPrintSizeY();
770 else if ( options.isGraphicsExportVisibleOnly() ) {
771 visible = tree_panel.getVisibleRect();
772 width = visible.width;
773 height = visible.height;
775 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
776 Graphics2D g2d = buffered_img.createGraphics();
777 g2d.setRenderingHints( rendering_hints );
780 if ( options.isGraphicsExportVisibleOnly() ) {
781 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
786 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
787 if ( type == GraphicsExportType.TIFF ) {
788 writeToTiff( file, buffered_img );
791 ImageIO.write( buffered_img, type.toString(), file );
795 if ( !options.isGraphicsExportUsingActualSize() ) {
796 tree_panel.getMainPanel().getControlPanel().showWhole();
798 String msg = file.toString();
799 if ( ( width > 0 ) && ( height > 0 ) ) {
800 msg += " [size: " + width + ", " + height + "]";
805 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
806 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
807 ImageWriter writer = null;
808 ImageOutputStream ios = null;
809 // Find an appropriate writer:
810 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
811 if ( it.hasNext() ) {
815 throw new IOException( "failed to get TIFF image writer" );
818 ios = ImageIO.createImageOutputStream( file );
819 writer.setOutput( ios );
820 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
821 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
822 // see writeParam.getCompressionTypes() for available compression type
824 image_write_param.setCompressionType( "PackBits" );
825 final String t[] = image_write_param.getCompressionTypes();
826 for( final String string : t ) {
827 System.out.println( string );
829 // Convert to an IIOImage:
830 final IIOImage iio_image = new IIOImage( image, null, null );
831 writer.write( null, iio_image, image_write_param );
834 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
835 // static void openDDBJRest() throws IOException {
837 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
839 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
841 // URLConnection urlc = url.openConnection();
843 // urlc.setDoOutput( true );
844 // urlc.setAllowUserInteraction( false );
846 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
847 // ps.print( query );
850 // BufferedReader br = new BufferedReader( new InputStreamReader(
851 // urlc.getInputStream() ) );
853 // while ( ( l = br.readLine() ) != null ) {
854 // System.out.println( l );
858 static enum GraphicsExportType {
859 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
861 private final String _suffix;
863 private GraphicsExportType( final String suffix ) {
868 public String toString() {