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.Component;
29 import java.awt.Graphics2D;
30 import java.awt.GraphicsEnvironment;
31 import java.awt.Rectangle;
32 import java.awt.RenderingHints;
33 import java.awt.image.BufferedImage;
34 import java.io.ByteArrayOutputStream;
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.HashSet;
45 import java.util.Iterator;
46 import java.util.List;
47 import java.util.Locale;
49 import java.util.SortedSet;
50 import java.util.TreeSet;
52 import javax.imageio.IIOImage;
53 import javax.imageio.ImageIO;
54 import javax.imageio.ImageWriteParam;
55 import javax.imageio.ImageWriter;
56 import javax.imageio.stream.ImageOutputStream;
57 import javax.swing.JApplet;
58 import javax.swing.JOptionPane;
59 import javax.swing.text.MaskFormatter;
61 import org.forester.io.parsers.PhylogenyParser;
62 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
63 import org.forester.io.parsers.nhx.NHXParser;
64 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
65 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
66 import org.forester.io.parsers.tol.TolParser;
67 import org.forester.io.parsers.util.ParserUtils;
68 import org.forester.phylogeny.Phylogeny;
69 import org.forester.phylogeny.PhylogenyMethods;
70 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
71 import org.forester.phylogeny.PhylogenyNode;
72 import org.forester.phylogeny.data.Taxonomy;
73 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
74 import org.forester.phylogeny.factories.PhylogenyFactory;
75 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
76 import org.forester.util.AsciiHistogram;
77 import org.forester.util.DescriptiveStatistics;
78 import org.forester.util.ForesterUtil;
80 public final class AptxUtil {
82 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
83 .getAvailableFontFamilyNames();
85 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
88 public static MaskFormatter createMaskFormatter( final String s ) {
89 MaskFormatter formatter = null;
91 formatter = new MaskFormatter( s );
93 catch ( final ParseException e ) {
94 throw new IllegalArgumentException( e );
99 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
100 final PhylogenyNodeIterator it = phy.iteratorPostorder();
101 while ( it.hasNext() ) {
102 if ( it.next().getNodeData().isHasEvent() ) {
110 * Returns true if at least one branch has a length larger than zero.
115 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
116 final PhylogenyNodeIterator it = phy.iteratorPostorder();
117 while ( it.hasNext() ) {
118 if ( it.next().getDistanceToParent() > 0.0 ) {
125 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
126 final PhylogenyNodeIterator it = phy.iteratorPostorder();
127 while ( it.hasNext() ) {
128 if ( it.next().getBranchData().isHasConfidences() ) {
135 final public static void launchWebBrowser( final URI uri,
136 final boolean is_applet,
137 final JApplet applet,
138 final String frame_name ) throws IOException {
140 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
143 // This requires Java 1.6:
144 // =======================
145 // boolean no_desktop = false;
147 // if ( Desktop.isDesktopSupported() ) {
148 // System.out.println( "desktop supported" );
149 // final Desktop dt = Desktop.getDesktop();
153 // no_desktop = true;
156 // catch ( final Exception ex ) {
157 // ex.printStackTrace();
158 // no_desktop = true;
160 // catch ( final Error er ) {
161 // er.printStackTrace();
162 // no_desktop = true;
164 // if ( no_desktop ) {
165 // System.out.println( "desktop not supported" );
167 openUrlInWebBrowser( uri.toString() );
169 catch ( final Exception e ) {
170 throw new IOException( e );
176 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
177 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
178 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
179 for( final PhylogenyNode n : descs ) {
180 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
181 tax_set.add( n.getNodeData().getTaxonomy() );
187 public final static void printWarningMessage( final String name, final String message ) {
188 System.out.println( "[" + name + "] > " + message );
191 final public static void showErrorMessage( final Component parent, final String error_msg ) {
192 printAppletMessage( Constants.PRG_NAME, error_msg );
193 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
194 + "] Error", JOptionPane.ERROR_MESSAGE );
197 public static void writePhylogenyToGraphicsFile( final File intree,
201 final GraphicsExportType type,
202 final Configuration config ) throws IOException {
203 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
204 Phylogeny[] phys = null;
205 phys = PhylogenyMethods.readPhylogenies( parser, intree );
206 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
209 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
213 final GraphicsExportType type,
214 final Configuration config ) throws IOException {
215 final Phylogeny[] phys = new Phylogeny[ 1 ];
217 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
218 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
219 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
223 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
226 final TreePanel tree_panel,
227 final ControlPanel ac,
228 final GraphicsExportType type,
229 final Options options ) throws IOException {
230 tree_panel.calcParametersForPainting( width, height, true );
231 tree_panel.resetPreferredSize();
232 tree_panel.repaint();
233 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
234 RenderingHints.VALUE_RENDER_QUALITY );
235 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
236 if ( options.isAntialiasPrint() ) {
237 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
238 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
241 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
242 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
244 final Phylogeny phylogeny = tree_panel.getPhylogeny();
245 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
248 if ( outfile.isDirectory() ) {
249 throw new IOException( "\"" + outfile + "\" is a directory" );
251 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
252 final Graphics2D g2d = buffered_img.createGraphics();
253 g2d.setRenderingHints( rendering_hints );
254 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
255 if ( type == GraphicsExportType.TIFF ) {
256 writeToTiff( outfile, buffered_img );
259 ImageIO.write( buffered_img, type.toString(), outfile );
264 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
265 final String default_name,
266 final String full_path,
267 final Configuration configuration,
268 final MainPanel main_panel ) {
269 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
270 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
271 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
272 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
275 for( final Phylogeny phy : phys ) {
276 if ( !phy.isEmpty() ) {
277 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
279 String my_name_for_file = "";
280 if ( phys.length > 1 ) {
281 if ( !ForesterUtil.isEmpty( default_name ) ) {
282 my_name = new String( default_name );
284 if ( !ForesterUtil.isEmpty( full_path ) ) {
285 my_name_for_file = new String( full_path );
287 else if ( !ForesterUtil.isEmpty( default_name ) ) {
288 my_name_for_file = new String( default_name );
291 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
292 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
293 my_name_for_file.length() );
294 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
296 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
297 my_name_for_file += "_";
299 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
300 my_name_for_file += phy.getName().replaceAll( " ", "_" );
302 else if ( phy.getIdentifier() != null ) {
303 final StringBuffer sb = new StringBuffer();
304 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
305 sb.append( phy.getIdentifier().getProvider() );
308 sb.append( phy.getIdentifier().getValue() );
309 my_name_for_file += sb;
312 my_name_for_file += i;
314 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
315 && ( phy.getIdentifier() == null ) ) {
316 my_name = my_name + " [" + i + "]";
318 if ( !ForesterUtil.isEmpty( suffix ) ) {
319 my_name_for_file += suffix;
323 if ( !ForesterUtil.isEmpty( default_name ) ) {
324 my_name = new String( default_name );
326 my_name_for_file = "";
327 if ( !ForesterUtil.isEmpty( full_path ) ) {
328 my_name_for_file = new String( full_path );
330 else if ( !ForesterUtil.isEmpty( default_name ) ) {
331 my_name_for_file = new String( default_name );
333 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
334 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
335 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
337 else if ( phy.getIdentifier() != null ) {
338 final StringBuffer sb = new StringBuffer();
339 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
340 sb.append( phy.getIdentifier().getProvider() );
343 sb.append( phy.getIdentifier().getValue() );
344 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
348 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
349 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
350 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
357 final static void addPhylogenyToPanel( final Phylogeny[] phys,
358 final Configuration configuration,
359 final MainPanel main_panel ) {
360 final Phylogeny phy = phys[ 0 ];
361 main_panel.addPhylogenyInPanel( phy, configuration );
362 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
365 // Returns true if the specified format name can be written
366 final static boolean canWriteFormat( final String format_name ) {
367 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
368 return iter.hasNext();
371 final static String createBasicInformation( final Phylogeny phy, final File treefile ) {
372 final StringBuilder desc = new StringBuilder();
373 if ( ( phy != null ) && !phy.isEmpty() ) {
375 if ( treefile != null ) {
377 f = treefile.getCanonicalPath();
379 catch ( final IOException e ) {
380 //Not important, ignore.
382 if ( !ForesterUtil.isEmpty( f ) ) {
383 desc.append( "Path: " );
388 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
389 desc.append( "Name: " );
390 desc.append( phy.getName() );
393 if ( phy.getIdentifier() != null ) {
394 desc.append( "Id: " );
395 desc.append( phy.getIdentifier().toString() );
398 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
399 desc.append( "Description: " );
400 desc.append( phy.getDescription() );
403 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
404 desc.append( "Distance Unit: " );
405 desc.append( phy.getDistanceUnit() );
408 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
409 desc.append( "Type: " );
410 desc.append( phy.getType() );
413 desc.append( "Rooted: " );
414 desc.append( phy.isRooted() );
416 desc.append( "Rerootable: " );
417 desc.append( phy.isRerootable() );
419 desc.append( "Nodes: " );
420 desc.append( phy.getNodeCount() );
422 desc.append( "External nodes: " );
423 desc.append( phy.getNumberOfExternalNodes() );
425 desc.append( "Internal nodes: " );
426 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
428 desc.append( "Internal nodes with polytomies: " );
429 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
431 desc.append( "Branches: " );
432 desc.append( phy.getNumberOfBranches() );
434 desc.append( "Depth: " );
435 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
437 desc.append( "Maximum distance to root: " );
438 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
440 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
441 if ( taxs != null ) {
442 desc.append( "Distinct external taxonomies: " );
443 desc.append( taxs.size() );
445 for( final Taxonomy t : taxs ) {
446 System.out.println( t.toString() );
449 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
450 if ( bs.getN() > 3 ) {
452 desc.append( "Branch-length statistics: " );
454 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
456 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
458 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
459 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
461 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
463 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
465 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
467 final AsciiHistogram histo = new AsciiHistogram( bs );
468 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
471 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
472 if ( ds.getN() > 2 ) {
474 desc.append( "Descendants per node statistics: " );
476 desc.append( " Median: " + ForesterUtil.round( ds.median(), 6 ) );
478 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 6 ) + " (stdev: "
479 + ForesterUtil.round( ds.sampleStandardDeviation(), 6 ) + ")" );
481 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
483 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
486 List<DescriptiveStatistics> css = null;
488 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
490 catch ( final IllegalArgumentException e ) {
491 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
493 if ( ( css != null ) && ( css.size() > 0 ) ) {
495 for( int i = 0; i < css.size(); ++i ) {
496 final DescriptiveStatistics cs = css.get( i );
497 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
498 if ( css.size() > 1 ) {
499 desc.append( "Support statistics " + ( i + 1 ) + ": " );
502 desc.append( "Support statistics: " );
504 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
506 desc.append( " Type: " + cs.getDescription() );
509 desc.append( " Branches with support: " + cs.getN() );
511 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
513 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
514 if ( cs.getN() > 2 ) {
515 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
518 desc.append( " Minimum: " + ForesterUtil.round( cs.getMin(), 6 ) );
520 desc.append( " Maximum: " + ForesterUtil.round( cs.getMax(), 6 ) );
526 return desc.toString();
534 * to message to be printed
536 final static void dieWithSystemError( final String message ) {
537 System.out.println();
538 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
539 System.out.println( "Please contact the authors." );
540 System.out.println( Constants.PRG_NAME + " needs to close." );
541 System.out.println();
545 final static String[] getAllPossibleRanks() {
546 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
548 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
549 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
550 str_array[ i++ ] = e;
556 final static String[] getAllRanks( final Phylogeny tree ) {
557 final SortedSet<String> ranks = new TreeSet<String>();
558 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
559 final PhylogenyNode n = it.next();
560 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
561 ranks.add( n.getNodeData().getTaxonomy().getRank() );
564 return ForesterUtil.stringSetToArray( ranks );
567 final static String[] getAvailableFontFamiliesSorted() {
568 return AVAILABLE_FONT_FAMILIES_SORTED;
571 final static boolean isUsOrCanada() {
573 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
577 catch ( final Exception 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 ( !AptxUtil.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 ( AptxUtil.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 ( AptxUtil.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 ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
615 atv_control.setCheckbox( Configuration.write_events, true );
618 atv_control.setCheckbox( Configuration.write_events, false );
625 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
627 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
629 catch ( final Exception e ) {
630 throw new IOException( e );
634 final static void outOfMemoryError( final OutOfMemoryError e ) {
635 System.err.println();
636 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
637 System.err.println();
639 System.err.println();
640 JOptionPane.showMessageDialog( null,
641 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
642 + "\n\nError: " + e.getLocalizedMessage(),
643 "Out of Memory Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
644 JOptionPane.ERROR_MESSAGE );
648 final static void printAppletMessage( final String applet_name, final String message ) {
649 System.out.println( "[" + applet_name + "] > " + message );
652 final static Phylogeny[] readPhylogeniesFromUrl( final URL url,
653 final boolean phyloxml_validate_against_xsd,
654 final boolean replace_underscores,
655 final boolean internal_numbers_are_confidences,
656 final TAXONOMY_EXTRACTION taxonomy_extraction,
657 final boolean midpoint_reroot ) throws FileNotFoundException,
659 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
660 final PhylogenyParser parser;
661 boolean nhx_or_nexus = false;
662 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
663 parser = new TolParser();
666 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
667 if ( parser instanceof NHXParser ) {
669 final NHXParser nhx = ( NHXParser ) parser;
670 nhx.setReplaceUnderscores( replace_underscores );
671 nhx.setIgnoreQuotes( false );
672 nhx.setTaxonomyExtraction( taxonomy_extraction );
674 else if ( parser instanceof NexusPhylogeniesParser ) {
676 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
677 nex.setReplaceUnderscores( replace_underscores );
678 nex.setIgnoreQuotes( false );
681 AptxUtil.printAppletMessage( "Archaeopteryx", "parser is " + parser.getName() );
682 final Phylogeny[] phys = factory.create( url.openStream(), parser );
683 if ( phys != null ) {
684 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
685 for( final Phylogeny phy : phys ) {
686 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
689 if ( midpoint_reroot ) {
690 for( final Phylogeny phy : phys ) {
691 PhylogenyMethods.midpointRoot( phy );
692 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
699 final static void removeBranchColors( final Phylogeny phy ) {
700 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
701 it.next().getBranchData().setBranchColor( null );
705 final static void removeVisualStyles( final Phylogeny phy ) {
706 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
707 it.next().getNodeData().setNodeVisualData( null );
711 final static void unexpectedError( final Error e ) {
712 System.err.println();
713 e.printStackTrace( System.err );
714 System.err.println();
715 final StringBuffer sb = new StringBuffer();
716 for( final StackTraceElement s : e.getStackTrace() ) {
717 sb.append( s + "\n" );
720 .showMessageDialog( null,
721 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
722 + Constants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
724 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
725 JOptionPane.ERROR_MESSAGE );
729 final static void unexpectedException( final Exception e ) {
730 System.err.println();
731 e.printStackTrace( System.err );
732 System.err.println();
733 final StringBuffer sb = new StringBuffer();
734 for( final StackTraceElement s : e.getStackTrace() ) {
735 sb.append( s + "\n" );
737 JOptionPane.showMessageDialog( null,
738 "An unexpected exception has occured. \nPlease contact: "
739 + Constants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
741 "Unexpected Exception [" + Constants.PRG_NAME + Constants.VERSION + "]",
742 JOptionPane.ERROR_MESSAGE );
745 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
748 final TreePanel tree_panel,
749 final ControlPanel ac,
750 final GraphicsExportType type,
751 final Options options ) throws IOException {
752 if ( !options.isGraphicsExportUsingActualSize() ) {
753 if ( options.isGraphicsExportVisibleOnly() ) {
754 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
756 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
757 tree_panel.resetPreferredSize();
758 tree_panel.repaint();
760 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
761 RenderingHints.VALUE_RENDER_QUALITY );
762 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
763 if ( options.isAntialiasPrint() ) {
764 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
765 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
768 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
769 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
771 final Phylogeny phylogeny = tree_panel.getPhylogeny();
772 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
775 Rectangle visible = null;
776 if ( !options.isGraphicsExportUsingActualSize() ) {
777 width = options.getPrintSizeX();
778 height = options.getPrintSizeY();
780 else if ( options.isGraphicsExportVisibleOnly() ) {
781 visible = tree_panel.getVisibleRect();
782 width = visible.width;
783 height = visible.height;
785 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
786 Graphics2D g2d = buffered_img.createGraphics();
787 g2d.setRenderingHints( rendering_hints );
790 if ( options.isGraphicsExportVisibleOnly() ) {
791 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
796 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
797 ImageIO.write( buffered_img, type.toString(), baos );
800 if ( !options.isGraphicsExportUsingActualSize() ) {
801 tree_panel.getMainPanel().getControlPanel().showWhole();
803 String msg = baos.toString();
804 if ( ( width > 0 ) && ( height > 0 ) ) {
805 msg += " [size: " + width + ", " + height + "]";
810 final static String writePhylogenyToGraphicsFile( final String file_name,
813 final TreePanel tree_panel,
814 final ControlPanel ac,
815 final GraphicsExportType type,
816 final Options options ) throws IOException {
817 if ( !options.isGraphicsExportUsingActualSize() ) {
818 if ( options.isGraphicsExportVisibleOnly() ) {
819 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
821 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
822 tree_panel.resetPreferredSize();
823 tree_panel.repaint();
825 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
826 RenderingHints.VALUE_RENDER_QUALITY );
827 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
828 if ( options.isAntialiasPrint() ) {
829 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
830 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
833 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
834 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
836 final Phylogeny phylogeny = tree_panel.getPhylogeny();
837 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
840 final File file = new File( file_name );
841 if ( file.isDirectory() ) {
842 throw new IOException( "\"" + file_name + "\" is a directory" );
844 Rectangle visible = null;
845 if ( !options.isGraphicsExportUsingActualSize() ) {
846 width = options.getPrintSizeX();
847 height = options.getPrintSizeY();
849 else if ( options.isGraphicsExportVisibleOnly() ) {
850 visible = tree_panel.getVisibleRect();
851 width = visible.width;
852 height = visible.height;
854 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
855 Graphics2D g2d = buffered_img.createGraphics();
856 g2d.setRenderingHints( rendering_hints );
859 if ( options.isGraphicsExportVisibleOnly() ) {
860 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
865 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
866 if ( type == GraphicsExportType.TIFF ) {
867 writeToTiff( file, buffered_img );
870 ImageIO.write( buffered_img, type.toString(), file );
874 if ( !options.isGraphicsExportUsingActualSize() ) {
875 tree_panel.getMainPanel().getControlPanel().showWhole();
877 String msg = file.toString();
878 if ( ( width > 0 ) && ( height > 0 ) ) {
879 msg += " [size: " + width + ", " + height + "]";
884 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
885 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
886 ImageWriter writer = null;
887 ImageOutputStream ios = null;
888 // Find an appropriate writer:
889 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
890 if ( it.hasNext() ) {
894 throw new IOException( "failed to get TIFF image writer" );
897 ios = ImageIO.createImageOutputStream( file );
898 writer.setOutput( ios );
899 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
900 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
901 // see writeParam.getCompressionTypes() for available compression type
903 image_write_param.setCompressionType( "PackBits" );
904 final String t[] = image_write_param.getCompressionTypes();
905 for( final String string : t ) {
906 System.out.println( string );
908 // Convert to an IIOImage:
909 final IIOImage iio_image = new IIOImage( image, null, null );
910 writer.write( null, iio_image, image_write_param );
913 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
914 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
915 InvocationTargetException, InterruptedException {
916 final String os = System.getProperty( "os.name" );
917 final Runtime runtime = Runtime.getRuntime();
918 if ( os.toLowerCase().startsWith( "win" ) ) {
919 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
921 else if ( ForesterUtil.isMac() ) {
922 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
923 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
924 open_url.invoke( null, new Object[] { url } );
927 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
928 String browser = null;
929 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
930 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
931 browser = browsers[ i ];
934 if ( browser == null ) {
935 throw new IOException( "could not find a web browser to open [" + url + "] in" );
938 runtime.exec( new String[] { browser, url } );
943 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
944 // static void openDDBJRest() throws IOException {
946 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
948 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
950 // URLConnection urlc = url.openConnection();
952 // urlc.setDoOutput( true );
953 // urlc.setAllowUserInteraction( false );
955 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
956 // ps.print( query );
959 // BufferedReader br = new BufferedReader( new InputStreamReader(
960 // urlc.getInputStream() ) );
962 // while ( ( l = br.readLine() ) != null ) {
963 // System.out.println( l );
967 public static enum GraphicsExportType {
968 BMP( "bmp" ), GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" );
970 private final String _suffix;
972 private GraphicsExportType( final String suffix ) {
977 public String toString() {