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: https://sites.google.com/site/cmzmasek/home/software/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;
35 import java.io.ByteArrayOutputStream;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.lang.reflect.InvocationTargetException;
41 import java.lang.reflect.Method;
44 import java.net.URLConnection;
45 import java.text.ParseException;
46 import java.util.Arrays;
47 import java.util.HashSet;
48 import java.util.Iterator;
49 import java.util.List;
50 import java.util.Locale;
52 import java.util.SortedSet;
53 import java.util.TreeSet;
55 import javax.imageio.IIOImage;
56 import javax.imageio.ImageIO;
57 import javax.imageio.ImageWriteParam;
58 import javax.imageio.ImageWriter;
59 import javax.imageio.stream.ImageOutputStream;
60 import javax.swing.JApplet;
61 import javax.swing.JOptionPane;
62 import javax.swing.text.MaskFormatter;
64 import org.forester.io.parsers.PhylogenyParser;
65 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
66 import org.forester.io.parsers.nhx.NHXParser;
67 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
68 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
69 import org.forester.io.parsers.tol.TolParser;
70 import org.forester.io.parsers.util.ParserUtils;
71 import org.forester.phylogeny.Phylogeny;
72 import org.forester.phylogeny.PhylogenyMethods;
73 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
74 import org.forester.phylogeny.PhylogenyNode;
75 import org.forester.phylogeny.data.Taxonomy;
76 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
77 import org.forester.phylogeny.factories.PhylogenyFactory;
78 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
79 import org.forester.util.AsciiHistogram;
80 import org.forester.util.DescriptiveStatistics;
81 import org.forester.util.ForesterUtil;
83 public final class AptxUtil {
85 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
86 .getAvailableFontFamilyNames();
88 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
91 public static MaskFormatter createMaskFormatter( final String s ) {
92 MaskFormatter formatter = null;
94 formatter = new MaskFormatter( s );
96 catch ( final ParseException e ) {
97 throw new IllegalArgumentException( e );
102 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
103 final PhylogenyNodeIterator it = phy.iteratorPostorder();
104 while ( it.hasNext() ) {
105 if ( it.next().getNodeData().isHasEvent() ) {
113 * Returns true if at least one branch has a length larger than zero.
118 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
119 final PhylogenyNodeIterator it = phy.iteratorPostorder();
120 while ( it.hasNext() ) {
121 if ( it.next().getDistanceToParent() > 0.0 ) {
128 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
129 final PhylogenyNodeIterator it = phy.iteratorPostorder();
130 while ( it.hasNext() ) {
131 if ( it.next().getBranchData().isHasConfidences() ) {
138 final public static void launchWebBrowser( final URI uri,
139 final boolean is_applet,
140 final JApplet applet,
141 final String frame_name ) throws IOException {
143 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
146 // This requires Java 1.6:
147 // =======================
148 // boolean no_desktop = false;
150 // if ( Desktop.isDesktopSupported() ) {
151 // System.out.println( "desktop supported" );
152 // final Desktop dt = Desktop.getDesktop();
156 // no_desktop = true;
159 // catch ( final Exception ex ) {
160 // ex.printStackTrace();
161 // no_desktop = true;
163 // catch ( final Error er ) {
164 // er.printStackTrace();
165 // no_desktop = true;
167 // if ( no_desktop ) {
168 // System.out.println( "desktop not supported" );
170 openUrlInWebBrowser( uri.toString() );
172 catch ( final Exception e ) {
173 throw new IOException( e );
179 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
180 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
181 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
182 for( final PhylogenyNode n : descs ) {
183 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
184 tax_set.add( n.getNodeData().getTaxonomy() );
190 public final static void printWarningMessage( final String name, final String message ) {
191 System.out.println( "[" + name + "] > " + message );
194 final public static void showErrorMessage( final Component parent, final String error_msg ) {
195 printAppletMessage( Constants.PRG_NAME, error_msg );
196 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
197 + "] Error", JOptionPane.ERROR_MESSAGE );
200 public static void writePhylogenyToGraphicsFile( final File intree,
204 final GraphicsExportType type,
205 final Configuration config ) throws IOException {
206 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
207 Phylogeny[] phys = null;
208 phys = PhylogenyMethods.readPhylogenies( parser, intree );
209 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
212 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
216 final GraphicsExportType type,
217 final Configuration config ) throws IOException {
218 final Phylogeny[] phys = new Phylogeny[ 1 ];
220 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
221 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
222 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
226 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
229 final TreePanel tree_panel,
230 final ControlPanel ac,
231 final GraphicsExportType type,
232 final Options options ) throws IOException {
233 tree_panel.calcParametersForPainting( width, height, true );
234 tree_panel.resetPreferredSize();
235 tree_panel.repaint();
236 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
237 RenderingHints.VALUE_RENDER_QUALITY );
238 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
239 if ( options.isAntialiasPrint() ) {
240 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
241 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
244 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
245 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
247 final Phylogeny phylogeny = tree_panel.getPhylogeny();
248 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
251 if ( outfile.isDirectory() ) {
252 throw new IOException( "\"" + outfile + "\" is a directory" );
254 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
255 final Graphics2D g2d = buffered_img.createGraphics();
256 g2d.setRenderingHints( rendering_hints );
257 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
258 if ( type == GraphicsExportType.TIFF ) {
259 writeToTiff( outfile, buffered_img );
262 ImageIO.write( buffered_img, type.toString(), outfile );
267 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
268 final String default_name,
269 final String full_path,
270 final Configuration configuration,
271 final MainPanel main_panel ) {
272 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
273 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
274 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
275 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
278 for( final Phylogeny phy : phys ) {
279 if ( !phy.isEmpty() ) {
280 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
282 String my_name_for_file = "";
283 if ( phys.length > 1 ) {
284 if ( !ForesterUtil.isEmpty( default_name ) ) {
285 my_name = new String( default_name );
287 if ( !ForesterUtil.isEmpty( full_path ) ) {
288 my_name_for_file = new String( full_path );
290 else if ( !ForesterUtil.isEmpty( default_name ) ) {
291 my_name_for_file = new String( default_name );
294 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
295 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
296 my_name_for_file.length() );
297 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
299 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
300 my_name_for_file += "_";
302 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
303 my_name_for_file += phy.getName().replaceAll( " ", "_" );
305 else if ( phy.getIdentifier() != null ) {
306 final StringBuffer sb = new StringBuffer();
307 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
308 sb.append( phy.getIdentifier().getProvider() );
311 sb.append( phy.getIdentifier().getValue() );
312 my_name_for_file += sb;
315 my_name_for_file += i;
317 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
318 && ( phy.getIdentifier() == null ) ) {
319 my_name = my_name + " [" + i + "]";
321 if ( !ForesterUtil.isEmpty( suffix ) ) {
322 my_name_for_file += suffix;
326 if ( !ForesterUtil.isEmpty( default_name ) ) {
327 my_name = new String( default_name );
329 my_name_for_file = "";
330 if ( !ForesterUtil.isEmpty( full_path ) ) {
331 my_name_for_file = new String( full_path );
333 else if ( !ForesterUtil.isEmpty( default_name ) ) {
334 my_name_for_file = new String( default_name );
336 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
337 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
338 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
340 else if ( phy.getIdentifier() != null ) {
341 final StringBuffer sb = new StringBuffer();
342 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
343 sb.append( phy.getIdentifier().getProvider() );
346 sb.append( phy.getIdentifier().getValue() );
347 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
351 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
352 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
353 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
360 final static void addPhylogenyToPanel( final Phylogeny[] phys,
361 final Configuration configuration,
362 final MainPanel main_panel ) {
363 final Phylogeny phy = phys[ 0 ];
364 main_panel.addPhylogenyInPanel( phy, configuration );
365 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
368 // Returns true if the specified format name can be written
369 final static boolean canWriteFormat( final String format_name ) {
370 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
371 return iter.hasNext();
374 final static String createBasicInformation( final Phylogeny phy, final File treefile ) {
375 final StringBuilder desc = new StringBuilder();
376 if ( ( phy != null ) && !phy.isEmpty() ) {
378 if ( treefile != null ) {
380 f = treefile.getCanonicalPath();
382 catch ( final IOException e ) {
383 //Not important, ignore.
385 if ( !ForesterUtil.isEmpty( f ) ) {
386 desc.append( "Path: " );
391 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
392 desc.append( "Name: " );
393 desc.append( phy.getName() );
396 if ( phy.getIdentifier() != null ) {
397 desc.append( "Id: " );
398 desc.append( phy.getIdentifier().toString() );
401 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
402 desc.append( "Description: " );
403 desc.append( phy.getDescription() );
406 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
407 desc.append( "Distance Unit: " );
408 desc.append( phy.getDistanceUnit() );
411 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
412 desc.append( "Type: " );
413 desc.append( phy.getType() );
416 desc.append( "Rooted: " );
417 desc.append( phy.isRooted() );
419 desc.append( "Rerootable: " );
420 desc.append( phy.isRerootable() );
422 desc.append( "Nodes: " );
423 desc.append( phy.getNodeCount() );
425 desc.append( "External nodes: " );
426 desc.append( phy.getNumberOfExternalNodes() );
428 desc.append( "Internal nodes: " );
429 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
431 desc.append( "Internal nodes with polytomies: " );
432 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
434 desc.append( "Branches: " );
435 desc.append( phy.getNumberOfBranches() );
437 desc.append( "Depth: " );
438 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
440 desc.append( "Maximum distance to root: " );
441 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
443 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
444 if ( taxs != null ) {
445 desc.append( "Distinct external taxonomies: " );
446 desc.append( taxs.size() );
448 for( final Taxonomy t : taxs ) {
449 System.out.println( t.toString() );
452 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
453 if ( bs.getN() > 3 ) {
455 desc.append( "Branch-length statistics: " );
457 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
459 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
461 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
462 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
464 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
466 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
468 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
470 final AsciiHistogram histo = new AsciiHistogram( bs );
471 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
474 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
475 if ( ds.getN() > 2 ) {
477 desc.append( "Descendants per node statistics: " );
479 desc.append( " Median: " + ForesterUtil.round( ds.median(), 6 ) );
481 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 6 ) + " (stdev: "
482 + ForesterUtil.round( ds.sampleStandardDeviation(), 6 ) + ")" );
484 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
486 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
489 List<DescriptiveStatistics> css = null;
491 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
493 catch ( final IllegalArgumentException e ) {
494 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
496 if ( ( css != null ) && ( css.size() > 0 ) ) {
498 for( int i = 0; i < css.size(); ++i ) {
499 final DescriptiveStatistics cs = css.get( i );
500 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
501 if ( css.size() > 1 ) {
502 desc.append( "Support statistics " + ( i + 1 ) + ": " );
505 desc.append( "Support statistics: " );
507 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
509 desc.append( " Type: " + cs.getDescription() );
512 desc.append( " Branches with support: " + cs.getN() );
514 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
516 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
517 if ( cs.getN() > 2 ) {
518 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
521 desc.append( " Minimum: " + ForesterUtil.round( cs.getMin(), 6 ) );
523 desc.append( " Maximum: " + ForesterUtil.round( cs.getMax(), 6 ) );
529 return desc.toString();
537 * to message to be printed
539 final static void dieWithSystemError( final String message ) {
540 System.out.println();
541 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
542 System.out.println( "Please contact the authors." );
543 System.out.println( Constants.PRG_NAME + " needs to close." );
544 System.out.println();
548 final static String[] getAllPossibleRanks() {
549 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
551 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
552 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
553 str_array[ i++ ] = e;
559 final static String[] getAllRanks( final Phylogeny tree ) {
560 final SortedSet<String> ranks = new TreeSet<String>();
561 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
562 final PhylogenyNode n = it.next();
563 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
564 ranks.add( n.getNodeData().getTaxonomy().getRank() );
567 return ForesterUtil.stringSetToArray( ranks );
570 final static String[] getAvailableFontFamiliesSorted() {
571 return AVAILABLE_FONT_FAMILIES_SORTED;
574 final static boolean isUsOrCanada() {
576 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
580 catch ( final Exception e ) {
586 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
587 final ControlPanel atv_control,
588 final Configuration configuration ) {
589 if ( ( t != null ) && !t.isEmpty() ) {
590 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
591 atv_control.setDrawPhylogram( false );
592 atv_control.setDrawPhylogramEnabled( false );
594 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
595 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
596 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
597 atv_control.setDrawPhylogram( true );
598 atv_control.setDrawPhylogramEnabled( true );
601 atv_control.setDrawPhylogram( false );
605 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
606 if ( atv_control.getWriteConfidenceCb() != null ) {
607 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
608 atv_control.setCheckbox( Configuration.write_confidence_values, true );
611 atv_control.setCheckbox( Configuration.write_confidence_values, false );
615 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
616 if ( atv_control.getShowEventsCb() != null ) {
617 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
618 atv_control.setCheckbox( Configuration.write_events, true );
621 atv_control.setCheckbox( Configuration.write_events, false );
628 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
630 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
632 catch ( final Exception e ) {
633 throw new IOException( e );
637 final static void outOfMemoryError( final OutOfMemoryError e ) {
638 System.err.println();
639 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
640 System.err.println();
642 System.err.println();
643 JOptionPane.showMessageDialog( null,
644 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
645 + "\n\nError: " + e.getLocalizedMessage(),
646 "Out of Memory Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
647 JOptionPane.ERROR_MESSAGE );
651 final static void printAppletMessage( final String applet_name, final String message ) {
652 System.out.println( "[" + applet_name + "] > " + message );
655 final public static Phylogeny[] readPhylogeniesFromUrl( final URL url,
656 final boolean phyloxml_validate_against_xsd,
657 final boolean replace_underscores,
658 final boolean internal_numbers_are_confidences,
659 final TAXONOMY_EXTRACTION taxonomy_extraction,
660 final boolean midpoint_reroot )
661 throws FileNotFoundException, IOException {
662 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
663 final PhylogenyParser parser;
664 boolean nhx_or_nexus = false;
665 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
666 parser = new TolParser();
669 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
670 if ( parser instanceof NHXParser ) {
672 final NHXParser nhx = ( NHXParser ) parser;
673 nhx.setReplaceUnderscores( replace_underscores );
674 nhx.setIgnoreQuotes( false );
675 nhx.setTaxonomyExtraction( taxonomy_extraction );
677 else if ( parser instanceof NexusPhylogeniesParser ) {
679 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
680 nex.setReplaceUnderscores( replace_underscores );
681 nex.setIgnoreQuotes( false );
684 AptxUtil.printAppletMessage( "Archaeopteryx", "parser is " + parser.getName() );
685 final URLConnection url_connection = url.openConnection();
686 url_connection.setDefaultUseCaches( false );
687 final InputStream i = url_connection.getInputStream();
688 final Phylogeny[] phys = factory.create( i, parser );
690 if ( phys != null ) {
691 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
692 for( final Phylogeny phy : phys ) {
693 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
696 if ( midpoint_reroot ) {
697 for( final Phylogeny phy : phys ) {
698 PhylogenyMethods.midpointRoot( phy );
699 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
706 final static void removeBranchColors( final Phylogeny phy ) {
707 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
708 it.next().getBranchData().setBranchColor( null );
712 final static void removeVisualStyles( final Phylogeny phy ) {
713 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
714 it.next().getNodeData().setNodeVisualData( null );
718 final static void unexpectedError( final Error e ) {
719 System.err.println();
720 e.printStackTrace( System.err );
721 System.err.println();
722 final StringBuffer sb = new StringBuffer();
723 for( final StackTraceElement s : e.getStackTrace() ) {
724 sb.append( s + "\n" );
727 .showMessageDialog( null,
728 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
729 + Constants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
731 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
732 JOptionPane.ERROR_MESSAGE );
736 final static void unexpectedException( final Exception e ) {
737 System.err.println();
738 e.printStackTrace( System.err );
739 System.err.println();
740 final StringBuffer sb = new StringBuffer();
741 for( final StackTraceElement s : e.getStackTrace() ) {
742 sb.append( s + "\n" );
744 JOptionPane.showMessageDialog( null,
745 "An unexpected exception has occured. \nPlease contact: "
746 + Constants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
748 "Unexpected Exception [" + Constants.PRG_NAME + Constants.VERSION + "]",
749 JOptionPane.ERROR_MESSAGE );
752 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
755 final TreePanel tree_panel,
756 final ControlPanel ac,
757 final GraphicsExportType type,
758 final Options options ) throws IOException {
759 if ( !options.isGraphicsExportUsingActualSize() ) {
760 if ( options.isGraphicsExportVisibleOnly() ) {
761 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
763 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
764 tree_panel.resetPreferredSize();
765 tree_panel.repaint();
767 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
768 RenderingHints.VALUE_RENDER_QUALITY );
769 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
770 if ( options.isAntialiasPrint() ) {
771 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
772 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
775 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
776 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
778 final Phylogeny phylogeny = tree_panel.getPhylogeny();
779 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
782 Rectangle visible = null;
783 if ( !options.isGraphicsExportUsingActualSize() ) {
784 width = options.getPrintSizeX();
785 height = options.getPrintSizeY();
787 else if ( options.isGraphicsExportVisibleOnly() ) {
788 visible = tree_panel.getVisibleRect();
789 width = visible.width;
790 height = visible.height;
792 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
793 Graphics2D g2d = buffered_img.createGraphics();
794 g2d.setRenderingHints( rendering_hints );
797 if ( options.isGraphicsExportVisibleOnly() ) {
798 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
803 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
804 ImageIO.write( buffered_img, type.toString(), baos );
807 if ( !options.isGraphicsExportUsingActualSize() ) {
808 tree_panel.getMainPanel().getControlPanel().showWhole();
810 String msg = baos.toString();
811 if ( ( width > 0 ) && ( height > 0 ) ) {
812 msg += " [size: " + width + ", " + height + "]";
817 final static String writePhylogenyToGraphicsFile( final String file_name,
820 final TreePanel tree_panel,
821 final ControlPanel ac,
822 final GraphicsExportType type,
823 final Options options ) throws IOException {
824 if ( !options.isGraphicsExportUsingActualSize() ) {
825 if ( options.isGraphicsExportVisibleOnly() ) {
826 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
828 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
829 tree_panel.resetPreferredSize();
830 tree_panel.repaint();
832 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
833 RenderingHints.VALUE_RENDER_QUALITY );
834 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
835 if ( options.isAntialiasPrint() ) {
836 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
837 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
840 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
841 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
843 final Phylogeny phylogeny = tree_panel.getPhylogeny();
844 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
847 final File file = new File( file_name );
848 if ( file.isDirectory() ) {
849 throw new IOException( "\"" + file_name + "\" is a directory" );
851 Rectangle visible = null;
852 if ( !options.isGraphicsExportUsingActualSize() ) {
853 width = options.getPrintSizeX();
854 height = options.getPrintSizeY();
856 else if ( options.isGraphicsExportVisibleOnly() ) {
857 visible = tree_panel.getVisibleRect();
858 width = visible.width;
859 height = visible.height;
861 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
862 Graphics2D g2d = buffered_img.createGraphics();
863 g2d.setRenderingHints( rendering_hints );
866 if ( options.isGraphicsExportVisibleOnly() ) {
867 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
872 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
873 if ( type == GraphicsExportType.TIFF ) {
874 writeToTiff( file, buffered_img );
877 ImageIO.write( buffered_img, type.toString(), file );
881 if ( !options.isGraphicsExportUsingActualSize() ) {
882 tree_panel.getMainPanel().getControlPanel().showWhole();
884 String msg = file.toString();
885 if ( ( width > 0 ) && ( height > 0 ) ) {
886 msg += " [size: " + width + ", " + height + "]";
891 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
892 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
893 ImageWriter writer = null;
894 ImageOutputStream ios = null;
895 // Find an appropriate writer:
896 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
897 if ( it.hasNext() ) {
901 throw new IOException( "failed to get TIFF image writer" );
904 ios = ImageIO.createImageOutputStream( file );
905 writer.setOutput( ios );
906 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
907 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
908 // see writeParam.getCompressionTypes() for available compression type
910 image_write_param.setCompressionType( "PackBits" );
911 final String t[] = image_write_param.getCompressionTypes();
912 for( final String string : t ) {
913 System.out.println( string );
915 // Convert to an IIOImage:
916 final IIOImage iio_image = new IIOImage( image, null, null );
917 writer.write( null, iio_image, image_write_param );
920 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
921 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
922 InvocationTargetException, InterruptedException {
923 final String os = System.getProperty( "os.name" );
924 final Runtime runtime = Runtime.getRuntime();
925 if ( os.toLowerCase().startsWith( "win" ) ) {
926 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
928 else if ( ForesterUtil.isMac() ) {
929 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
930 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
931 open_url.invoke( null, new Object[] { url } );
934 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
935 String browser = null;
936 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
937 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
938 browser = browsers[ i ];
941 if ( browser == null ) {
942 throw new IOException( "could not find a web browser to open [" + url + "] in" );
945 runtime.exec( new String[] { browser, url } );
951 public static enum GraphicsExportType {
952 BMP( "bmp" ), GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" );
954 private final String _suffix;
956 private GraphicsExportType( final String suffix ) {
961 public String toString() {
966 final public static Color calculateColorFromString( final String str, final boolean is_taxonomy ) {
967 final String my_str = str.toUpperCase();
968 char first = my_str.charAt( 0 );
971 if ( my_str.length() > 1 ) {
973 second = my_str.charAt( 1 );
976 second = my_str.charAt( my_str.length() - 1 );
979 if ( my_str.length() > 2 ) {
980 if ( my_str.indexOf( " " ) > 0 ) {
981 third = my_str.charAt( my_str.indexOf( " " ) + 1 );
984 third = my_str.charAt( 2 );
988 else if ( my_str.length() > 2 ) {
989 third = my_str.charAt( ( my_str.length() - 1 ) / 2 );
992 first = normalizeCharForRGB( first );
993 second = normalizeCharForRGB( second );
994 third = normalizeCharForRGB( third );
995 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
998 else if ( ( first < 60 ) && ( second < 60 ) && ( third < 60 ) ) {
1001 return new Color( first, second, third );
1004 final private static char normalizeCharForRGB( char c ) {
1007 c = c > 255 ? 255 : c;