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.io.InputStream;
39 import java.lang.reflect.InvocationTargetException;
40 import java.lang.reflect.Method;
43 import java.text.ParseException;
44 import java.util.Arrays;
45 import java.util.HashSet;
46 import java.util.Iterator;
47 import java.util.List;
48 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.nexus.NexusPhylogeniesParser;
64 import org.forester.io.parsers.nhx.NHXParser;
65 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
66 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
67 import org.forester.io.parsers.tol.TolParser;
68 import org.forester.io.parsers.util.ParserUtils;
69 import org.forester.phylogeny.Phylogeny;
70 import org.forester.phylogeny.PhylogenyMethods;
71 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
72 import org.forester.phylogeny.PhylogenyNode;
73 import org.forester.phylogeny.data.Taxonomy;
74 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
75 import org.forester.phylogeny.factories.PhylogenyFactory;
76 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
77 import org.forester.util.AsciiHistogram;
78 import org.forester.util.DescriptiveStatistics;
79 import org.forester.util.ForesterUtil;
81 public final class AptxUtil {
83 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
84 .getAvailableFontFamilyNames();
86 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
89 public static MaskFormatter createMaskFormatter( final String s ) {
90 MaskFormatter formatter = null;
92 formatter = new MaskFormatter( s );
94 catch ( final ParseException e ) {
95 throw new IllegalArgumentException( e );
100 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
101 final PhylogenyNodeIterator it = phy.iteratorPostorder();
102 while ( it.hasNext() ) {
103 if ( it.next().getNodeData().isHasEvent() ) {
111 * Returns true if at least one branch has a length larger than zero.
116 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
117 final PhylogenyNodeIterator it = phy.iteratorPostorder();
118 while ( it.hasNext() ) {
119 if ( it.next().getDistanceToParent() > 0.0 ) {
126 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
127 final PhylogenyNodeIterator it = phy.iteratorPostorder();
128 while ( it.hasNext() ) {
129 if ( it.next().getBranchData().isHasConfidences() ) {
136 final public static void launchWebBrowser( final URI uri,
137 final boolean is_applet,
138 final JApplet applet,
139 final String frame_name ) throws IOException {
141 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
144 // This requires Java 1.6:
145 // =======================
146 // boolean no_desktop = false;
148 // if ( Desktop.isDesktopSupported() ) {
149 // System.out.println( "desktop supported" );
150 // final Desktop dt = Desktop.getDesktop();
154 // no_desktop = true;
157 // catch ( final Exception ex ) {
158 // ex.printStackTrace();
159 // no_desktop = true;
161 // catch ( final Error er ) {
162 // er.printStackTrace();
163 // no_desktop = true;
165 // if ( no_desktop ) {
166 // System.out.println( "desktop not supported" );
168 openUrlInWebBrowser( uri.toString() );
170 catch ( final Exception e ) {
171 throw new IOException( e );
177 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
178 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
179 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
180 for( final PhylogenyNode n : descs ) {
181 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
182 tax_set.add( n.getNodeData().getTaxonomy() );
188 public final static void printWarningMessage( final String name, final String message ) {
189 System.out.println( "[" + name + "] > " + message );
192 final public static void showErrorMessage( final Component parent, final String error_msg ) {
193 printAppletMessage( Constants.PRG_NAME, error_msg );
194 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
195 + "] Error", JOptionPane.ERROR_MESSAGE );
198 public static void writePhylogenyToGraphicsFile( final File intree,
202 final GraphicsExportType type,
203 final Configuration config ) throws IOException {
204 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
205 Phylogeny[] phys = null;
206 phys = PhylogenyMethods.readPhylogenies( parser, intree );
207 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
210 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
214 final GraphicsExportType type,
215 final Configuration config ) throws IOException {
216 final Phylogeny[] phys = new Phylogeny[ 1 ];
218 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
219 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
220 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
224 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
227 final TreePanel tree_panel,
228 final ControlPanel ac,
229 final GraphicsExportType type,
230 final Options options ) throws IOException {
231 tree_panel.calcParametersForPainting( width, height, true );
232 tree_panel.resetPreferredSize();
233 tree_panel.repaint();
234 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
235 RenderingHints.VALUE_RENDER_QUALITY );
236 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
237 if ( options.isAntialiasPrint() ) {
238 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
239 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
242 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
243 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
245 final Phylogeny phylogeny = tree_panel.getPhylogeny();
246 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
249 if ( outfile.isDirectory() ) {
250 throw new IOException( "\"" + outfile + "\" is a directory" );
252 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
253 final Graphics2D g2d = buffered_img.createGraphics();
254 g2d.setRenderingHints( rendering_hints );
255 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
256 if ( type == GraphicsExportType.TIFF ) {
257 writeToTiff( outfile, buffered_img );
260 ImageIO.write( buffered_img, type.toString(), outfile );
265 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
266 final String default_name,
267 final String full_path,
268 final Configuration configuration,
269 final MainPanel main_panel ) {
270 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
271 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
272 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
273 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
276 for( final Phylogeny phy : phys ) {
277 if ( !phy.isEmpty() ) {
278 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
280 String my_name_for_file = "";
281 if ( phys.length > 1 ) {
282 if ( !ForesterUtil.isEmpty( default_name ) ) {
283 my_name = new String( default_name );
285 if ( !ForesterUtil.isEmpty( full_path ) ) {
286 my_name_for_file = new String( full_path );
288 else if ( !ForesterUtil.isEmpty( default_name ) ) {
289 my_name_for_file = new String( default_name );
292 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
293 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
294 my_name_for_file.length() );
295 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
297 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
298 my_name_for_file += "_";
300 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
301 my_name_for_file += phy.getName().replaceAll( " ", "_" );
303 else if ( phy.getIdentifier() != null ) {
304 final StringBuffer sb = new StringBuffer();
305 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
306 sb.append( phy.getIdentifier().getProvider() );
309 sb.append( phy.getIdentifier().getValue() );
310 my_name_for_file += sb;
313 my_name_for_file += i;
315 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
316 && ( phy.getIdentifier() == null ) ) {
317 my_name = my_name + " [" + i + "]";
319 if ( !ForesterUtil.isEmpty( suffix ) ) {
320 my_name_for_file += suffix;
324 if ( !ForesterUtil.isEmpty( default_name ) ) {
325 my_name = new String( default_name );
327 my_name_for_file = "";
328 if ( !ForesterUtil.isEmpty( full_path ) ) {
329 my_name_for_file = new String( full_path );
331 else if ( !ForesterUtil.isEmpty( default_name ) ) {
332 my_name_for_file = new String( default_name );
334 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
335 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
336 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
338 else if ( phy.getIdentifier() != null ) {
339 final StringBuffer sb = new StringBuffer();
340 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
341 sb.append( phy.getIdentifier().getProvider() );
344 sb.append( phy.getIdentifier().getValue() );
345 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
349 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
350 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
351 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
358 final static void addPhylogenyToPanel( final Phylogeny[] phys,
359 final Configuration configuration,
360 final MainPanel main_panel ) {
361 final Phylogeny phy = phys[ 0 ];
362 main_panel.addPhylogenyInPanel( phy, configuration );
363 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
366 // Returns true if the specified format name can be written
367 final static boolean canWriteFormat( final String format_name ) {
368 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
369 return iter.hasNext();
372 final static String createBasicInformation( final Phylogeny phy, final File treefile ) {
373 final StringBuilder desc = new StringBuilder();
374 if ( ( phy != null ) && !phy.isEmpty() ) {
376 if ( treefile != null ) {
378 f = treefile.getCanonicalPath();
380 catch ( final IOException e ) {
381 //Not important, ignore.
383 if ( !ForesterUtil.isEmpty( f ) ) {
384 desc.append( "Path: " );
389 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
390 desc.append( "Name: " );
391 desc.append( phy.getName() );
394 if ( phy.getIdentifier() != null ) {
395 desc.append( "Id: " );
396 desc.append( phy.getIdentifier().toString() );
399 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
400 desc.append( "Description: " );
401 desc.append( phy.getDescription() );
404 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
405 desc.append( "Distance Unit: " );
406 desc.append( phy.getDistanceUnit() );
409 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
410 desc.append( "Type: " );
411 desc.append( phy.getType() );
414 desc.append( "Rooted: " );
415 desc.append( phy.isRooted() );
417 desc.append( "Rerootable: " );
418 desc.append( phy.isRerootable() );
420 desc.append( "Nodes: " );
421 desc.append( phy.getNodeCount() );
423 desc.append( "External nodes: " );
424 desc.append( phy.getNumberOfExternalNodes() );
426 desc.append( "Internal nodes: " );
427 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
429 desc.append( "Internal nodes with polytomies: " );
430 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
432 desc.append( "Branches: " );
433 desc.append( phy.getNumberOfBranches() );
435 desc.append( "Depth: " );
436 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
438 desc.append( "Maximum distance to root: " );
439 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
441 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
442 if ( taxs != null ) {
443 desc.append( "Distinct external taxonomies: " );
444 desc.append( taxs.size() );
446 for( final Taxonomy t : taxs ) {
447 System.out.println( t.toString() );
450 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
451 if ( bs.getN() > 3 ) {
453 desc.append( "Branch-length statistics: " );
455 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
457 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
459 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
460 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
462 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
464 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
466 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
468 final AsciiHistogram histo = new AsciiHistogram( bs );
469 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
472 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
473 if ( ds.getN() > 2 ) {
475 desc.append( "Descendants per node statistics: " );
477 desc.append( " Median: " + ForesterUtil.round( ds.median(), 6 ) );
479 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 6 ) + " (stdev: "
480 + ForesterUtil.round( ds.sampleStandardDeviation(), 6 ) + ")" );
482 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
484 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
487 List<DescriptiveStatistics> css = null;
489 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
491 catch ( final IllegalArgumentException e ) {
492 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
494 if ( ( css != null ) && ( css.size() > 0 ) ) {
496 for( int i = 0; i < css.size(); ++i ) {
497 final DescriptiveStatistics cs = css.get( i );
498 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
499 if ( css.size() > 1 ) {
500 desc.append( "Support statistics " + ( i + 1 ) + ": " );
503 desc.append( "Support statistics: " );
505 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
507 desc.append( " Type: " + cs.getDescription() );
510 desc.append( " Branches with support: " + cs.getN() );
512 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
514 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
515 if ( cs.getN() > 2 ) {
516 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
519 desc.append( " Minimum: " + ForesterUtil.round( cs.getMin(), 6 ) );
521 desc.append( " Maximum: " + ForesterUtil.round( cs.getMax(), 6 ) );
527 return desc.toString();
535 * to message to be printed
537 final static void dieWithSystemError( final String message ) {
538 System.out.println();
539 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
540 System.out.println( "Please contact the authors." );
541 System.out.println( Constants.PRG_NAME + " needs to close." );
542 System.out.println();
546 final static String[] getAllPossibleRanks() {
547 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
549 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
550 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
551 str_array[ i++ ] = e;
557 final static String[] getAllRanks( final Phylogeny tree ) {
558 final SortedSet<String> ranks = new TreeSet<String>();
559 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
560 final PhylogenyNode n = it.next();
561 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
562 ranks.add( n.getNodeData().getTaxonomy().getRank() );
565 return ForesterUtil.stringSetToArray( ranks );
568 final static String[] getAvailableFontFamiliesSorted() {
569 return AVAILABLE_FONT_FAMILIES_SORTED;
572 final static boolean isUsOrCanada() {
574 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
578 catch ( final Exception e ) {
584 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
585 final ControlPanel atv_control,
586 final Configuration configuration ) {
587 if ( ( t != null ) && !t.isEmpty() ) {
588 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
589 atv_control.setDrawPhylogram( false );
590 atv_control.setDrawPhylogramEnabled( false );
592 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
593 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
594 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
595 atv_control.setDrawPhylogram( true );
596 atv_control.setDrawPhylogramEnabled( true );
599 atv_control.setDrawPhylogram( false );
603 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
604 if ( atv_control.getWriteConfidenceCb() != null ) {
605 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
606 atv_control.setCheckbox( Configuration.write_confidence_values, true );
609 atv_control.setCheckbox( Configuration.write_confidence_values, false );
613 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
614 if ( atv_control.getShowEventsCb() != null ) {
615 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
616 atv_control.setCheckbox( Configuration.write_events, true );
619 atv_control.setCheckbox( Configuration.write_events, false );
626 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
628 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
630 catch ( final Exception e ) {
631 throw new IOException( e );
635 final static void outOfMemoryError( final OutOfMemoryError e ) {
636 System.err.println();
637 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
638 System.err.println();
640 System.err.println();
641 JOptionPane.showMessageDialog( null,
642 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
643 + "\n\nError: " + e.getLocalizedMessage(),
644 "Out of Memory Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
645 JOptionPane.ERROR_MESSAGE );
649 final static void printAppletMessage( final String applet_name, final String message ) {
650 System.out.println( "[" + applet_name + "] > " + message );
653 final public static Phylogeny[] readPhylogeniesFromUrl( final URL url,
654 final boolean phyloxml_validate_against_xsd,
655 final boolean replace_underscores,
656 final boolean internal_numbers_are_confidences,
657 final TAXONOMY_EXTRACTION taxonomy_extraction,
658 final boolean midpoint_reroot )
659 throws FileNotFoundException, IOException {
660 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
661 final PhylogenyParser parser;
662 boolean nhx_or_nexus = false;
663 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
664 parser = new TolParser();
667 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
668 if ( parser instanceof NHXParser ) {
670 final NHXParser nhx = ( NHXParser ) parser;
671 nhx.setReplaceUnderscores( replace_underscores );
672 nhx.setIgnoreQuotes( false );
673 nhx.setTaxonomyExtraction( taxonomy_extraction );
675 else if ( parser instanceof NexusPhylogeniesParser ) {
677 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
678 nex.setReplaceUnderscores( replace_underscores );
679 nex.setIgnoreQuotes( false );
682 AptxUtil.printAppletMessage( "Archaeopteryx", "parser is " + parser.getName() );
683 final InputStream i = url.openStream();
684 final Phylogeny[] phys = factory.create( i, parser );
686 if ( phys != null ) {
687 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
688 for( final Phylogeny phy : phys ) {
689 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
692 if ( midpoint_reroot ) {
693 for( final Phylogeny phy : phys ) {
694 PhylogenyMethods.midpointRoot( phy );
695 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
702 final static void removeBranchColors( final Phylogeny phy ) {
703 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
704 it.next().getBranchData().setBranchColor( null );
708 final static void removeVisualStyles( final Phylogeny phy ) {
709 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
710 it.next().getNodeData().setNodeVisualData( null );
714 final static void unexpectedError( final Error e ) {
715 System.err.println();
716 e.printStackTrace( System.err );
717 System.err.println();
718 final StringBuffer sb = new StringBuffer();
719 for( final StackTraceElement s : e.getStackTrace() ) {
720 sb.append( s + "\n" );
723 .showMessageDialog( null,
724 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
725 + Constants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
727 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
728 JOptionPane.ERROR_MESSAGE );
732 final static void unexpectedException( final Exception e ) {
733 System.err.println();
734 e.printStackTrace( System.err );
735 System.err.println();
736 final StringBuffer sb = new StringBuffer();
737 for( final StackTraceElement s : e.getStackTrace() ) {
738 sb.append( s + "\n" );
740 JOptionPane.showMessageDialog( null,
741 "An unexpected exception has occured. \nPlease contact: "
742 + Constants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
744 "Unexpected Exception [" + Constants.PRG_NAME + Constants.VERSION + "]",
745 JOptionPane.ERROR_MESSAGE );
748 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
751 final TreePanel tree_panel,
752 final ControlPanel ac,
753 final GraphicsExportType type,
754 final Options options ) throws IOException {
755 if ( !options.isGraphicsExportUsingActualSize() ) {
756 if ( options.isGraphicsExportVisibleOnly() ) {
757 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
759 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
760 tree_panel.resetPreferredSize();
761 tree_panel.repaint();
763 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
764 RenderingHints.VALUE_RENDER_QUALITY );
765 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
766 if ( options.isAntialiasPrint() ) {
767 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
768 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
771 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
772 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
774 final Phylogeny phylogeny = tree_panel.getPhylogeny();
775 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
778 Rectangle visible = null;
779 if ( !options.isGraphicsExportUsingActualSize() ) {
780 width = options.getPrintSizeX();
781 height = options.getPrintSizeY();
783 else if ( options.isGraphicsExportVisibleOnly() ) {
784 visible = tree_panel.getVisibleRect();
785 width = visible.width;
786 height = visible.height;
788 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
789 Graphics2D g2d = buffered_img.createGraphics();
790 g2d.setRenderingHints( rendering_hints );
793 if ( options.isGraphicsExportVisibleOnly() ) {
794 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
799 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
800 ImageIO.write( buffered_img, type.toString(), baos );
803 if ( !options.isGraphicsExportUsingActualSize() ) {
804 tree_panel.getMainPanel().getControlPanel().showWhole();
806 String msg = baos.toString();
807 if ( ( width > 0 ) && ( height > 0 ) ) {
808 msg += " [size: " + width + ", " + height + "]";
813 final static String writePhylogenyToGraphicsFile( final String file_name,
816 final TreePanel tree_panel,
817 final ControlPanel ac,
818 final GraphicsExportType type,
819 final Options options ) throws IOException {
820 if ( !options.isGraphicsExportUsingActualSize() ) {
821 if ( options.isGraphicsExportVisibleOnly() ) {
822 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
824 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
825 tree_panel.resetPreferredSize();
826 tree_panel.repaint();
828 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
829 RenderingHints.VALUE_RENDER_QUALITY );
830 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
831 if ( options.isAntialiasPrint() ) {
832 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
833 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
836 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
837 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
839 final Phylogeny phylogeny = tree_panel.getPhylogeny();
840 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
843 final File file = new File( file_name );
844 if ( file.isDirectory() ) {
845 throw new IOException( "\"" + file_name + "\" is a directory" );
847 Rectangle visible = null;
848 if ( !options.isGraphicsExportUsingActualSize() ) {
849 width = options.getPrintSizeX();
850 height = options.getPrintSizeY();
852 else if ( options.isGraphicsExportVisibleOnly() ) {
853 visible = tree_panel.getVisibleRect();
854 width = visible.width;
855 height = visible.height;
857 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
858 Graphics2D g2d = buffered_img.createGraphics();
859 g2d.setRenderingHints( rendering_hints );
862 if ( options.isGraphicsExportVisibleOnly() ) {
863 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
868 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
869 if ( type == GraphicsExportType.TIFF ) {
870 writeToTiff( file, buffered_img );
873 ImageIO.write( buffered_img, type.toString(), file );
877 if ( !options.isGraphicsExportUsingActualSize() ) {
878 tree_panel.getMainPanel().getControlPanel().showWhole();
880 String msg = file.toString();
881 if ( ( width > 0 ) && ( height > 0 ) ) {
882 msg += " [size: " + width + ", " + height + "]";
887 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
888 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
889 ImageWriter writer = null;
890 ImageOutputStream ios = null;
891 // Find an appropriate writer:
892 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
893 if ( it.hasNext() ) {
897 throw new IOException( "failed to get TIFF image writer" );
900 ios = ImageIO.createImageOutputStream( file );
901 writer.setOutput( ios );
902 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
903 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
904 // see writeParam.getCompressionTypes() for available compression type
906 image_write_param.setCompressionType( "PackBits" );
907 final String t[] = image_write_param.getCompressionTypes();
908 for( final String string : t ) {
909 System.out.println( string );
911 // Convert to an IIOImage:
912 final IIOImage iio_image = new IIOImage( image, null, null );
913 writer.write( null, iio_image, image_write_param );
916 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
917 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
918 InvocationTargetException, InterruptedException {
919 final String os = System.getProperty( "os.name" );
920 final Runtime runtime = Runtime.getRuntime();
921 if ( os.toLowerCase().startsWith( "win" ) ) {
922 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
924 else if ( ForesterUtil.isMac() ) {
925 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
926 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
927 open_url.invoke( null, new Object[] { url } );
930 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
931 String browser = null;
932 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
933 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
934 browser = browsers[ i ];
937 if ( browser == null ) {
938 throw new IOException( "could not find a web browser to open [" + url + "] in" );
941 runtime.exec( new String[] { browser, url } );
946 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
947 // static void openDDBJRest() throws IOException {
949 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
951 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
953 // URLConnection urlc = url.openConnection();
955 // urlc.setDoOutput( true );
956 // urlc.setAllowUserInteraction( false );
958 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
959 // ps.print( query );
962 // BufferedReader br = new BufferedReader( new InputStreamReader(
963 // urlc.getInputStream() ) );
965 // while ( ( l = br.readLine() ) != null ) {
966 // System.out.println( l );
970 public static enum GraphicsExportType {
971 BMP( "bmp" ), GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" );
973 private final String _suffix;
975 private GraphicsExportType( final String suffix ) {
980 public String toString() {