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;
51 import java.util.regex.Matcher;
52 import java.util.regex.Pattern;
54 import javax.imageio.IIOImage;
55 import javax.imageio.ImageIO;
56 import javax.imageio.ImageWriteParam;
57 import javax.imageio.ImageWriter;
58 import javax.imageio.stream.ImageOutputStream;
59 import javax.swing.JApplet;
60 import javax.swing.JOptionPane;
61 import javax.swing.text.MaskFormatter;
63 import org.forester.io.parsers.PhylogenyParser;
64 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
65 import org.forester.io.parsers.nhx.NHXParser;
66 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
67 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
68 import org.forester.io.parsers.tol.TolParser;
69 import org.forester.io.parsers.util.ParserUtils;
70 import org.forester.phylogeny.Phylogeny;
71 import org.forester.phylogeny.PhylogenyMethods;
72 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
73 import org.forester.phylogeny.PhylogenyNode;
74 import org.forester.phylogeny.data.Accession;
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();
87 private final static Pattern seq_identifier_pattern_1 = Pattern
88 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})\\s*$" );
89 private final static Pattern seq_identifier_pattern_2 = Pattern
90 .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})[|,; ].*$" );
92 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
95 public static MaskFormatter createMaskFormatter( final String s ) {
96 MaskFormatter formatter = null;
98 formatter = new MaskFormatter( s );
100 catch ( final ParseException e ) {
101 throw new IllegalArgumentException( e );
106 final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
107 final PhylogenyNodeIterator it = phy.iteratorPostorder();
108 while ( it.hasNext() ) {
109 if ( it.next().getNodeData().isHasEvent() ) {
117 * Returns true if at least one branch has a length larger than zero.
122 final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
123 final PhylogenyNodeIterator it = phy.iteratorPostorder();
124 while ( it.hasNext() ) {
125 if ( it.next().getDistanceToParent() > 0.0 ) {
132 final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
133 final PhylogenyNodeIterator it = phy.iteratorPostorder();
134 while ( it.hasNext() ) {
135 if ( it.next().getBranchData().isHasConfidences() ) {
142 final public static void launchWebBrowser( final URI uri,
143 final boolean is_applet,
144 final JApplet applet,
145 final String frame_name ) throws IOException {
147 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
150 // This requires Java 1.6:
151 // =======================
152 // boolean no_desktop = false;
154 // if ( Desktop.isDesktopSupported() ) {
155 // System.out.println( "desktop supported" );
156 // final Desktop dt = Desktop.getDesktop();
160 // no_desktop = true;
163 // catch ( final Exception ex ) {
164 // ex.printStackTrace();
165 // no_desktop = true;
167 // catch ( final Error er ) {
168 // er.printStackTrace();
169 // no_desktop = true;
171 // if ( no_desktop ) {
172 // System.out.println( "desktop not supported" );
174 openUrlInWebBrowser( uri.toString() );
176 catch ( final Exception e ) {
177 throw new IOException( e );
183 public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
184 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
185 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
186 for( final PhylogenyNode n : descs ) {
187 if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
188 tax_set.add( n.getNodeData().getTaxonomy() );
194 public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
195 final String n = sequence_name.trim();
196 final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
199 if ( matcher1.matches() ) {
200 group1 = matcher1.group( 1 );
201 group2 = matcher1.group( 2 );
204 final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
205 if ( matcher2.matches() ) {
206 group1 = matcher2.group( 1 );
207 group2 = matcher2.group( 2 );
210 if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
213 return new Accession( group2, group1 );
216 public final static void printWarningMessage( final String name, final String message ) {
217 System.out.println( "[" + name + "] > " + message );
220 final public static void showErrorMessage( final Component parent, final String error_msg ) {
221 printAppletMessage( Constants.PRG_NAME, error_msg );
222 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
223 + "] Error", JOptionPane.ERROR_MESSAGE );
226 public static void writePhylogenyToGraphicsFile( final File intree,
230 final GraphicsExportType type,
231 final Configuration config ) throws IOException {
232 final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
233 Phylogeny[] phys = null;
234 phys = PhylogenyMethods.readPhylogenies( parser, intree );
235 writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
238 public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
242 final GraphicsExportType type,
243 final Configuration config ) throws IOException {
244 final Phylogeny[] phys = new Phylogeny[ 1 ];
246 final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
247 AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
248 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
252 public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
255 final TreePanel tree_panel,
256 final ControlPanel ac,
257 final GraphicsExportType type,
258 final Options options ) throws IOException {
259 tree_panel.calcParametersForPainting( width, height, true );
260 tree_panel.resetPreferredSize();
261 tree_panel.repaint();
262 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
263 RenderingHints.VALUE_RENDER_QUALITY );
264 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
265 if ( options.isAntialiasPrint() ) {
266 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
267 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
270 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
271 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
273 final Phylogeny phylogeny = tree_panel.getPhylogeny();
274 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
277 if ( outfile.isDirectory() ) {
278 throw new IOException( "\"" + outfile + "\" is a directory" );
280 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
281 final Graphics2D g2d = buffered_img.createGraphics();
282 g2d.setRenderingHints( rendering_hints );
283 tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
284 if ( type == GraphicsExportType.TIFF ) {
285 writeToTiff( outfile, buffered_img );
288 ImageIO.write( buffered_img, type.toString(), outfile );
293 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
294 final String default_name,
295 final String full_path,
296 final Configuration configuration,
297 final MainPanel main_panel ) {
298 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
299 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
300 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
301 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
304 for( final Phylogeny phy : phys ) {
305 if ( !phy.isEmpty() ) {
306 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
308 String my_name_for_file = "";
309 if ( phys.length > 1 ) {
310 if ( !ForesterUtil.isEmpty( default_name ) ) {
311 my_name = new String( default_name );
313 if ( !ForesterUtil.isEmpty( full_path ) ) {
314 my_name_for_file = new String( full_path );
316 else if ( !ForesterUtil.isEmpty( default_name ) ) {
317 my_name_for_file = new String( default_name );
320 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
321 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
322 my_name_for_file.length() );
323 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
325 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
326 my_name_for_file += "_";
328 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
329 my_name_for_file += phy.getName().replaceAll( " ", "_" );
331 else if ( phy.getIdentifier() != null ) {
332 final StringBuffer sb = new StringBuffer();
333 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
334 sb.append( phy.getIdentifier().getProvider() );
337 sb.append( phy.getIdentifier().getValue() );
338 my_name_for_file += sb;
341 my_name_for_file += i;
343 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
344 && ( phy.getIdentifier() == null ) ) {
345 my_name = my_name + " [" + i + "]";
347 if ( !ForesterUtil.isEmpty( suffix ) ) {
348 my_name_for_file += suffix;
352 if ( !ForesterUtil.isEmpty( default_name ) ) {
353 my_name = new String( default_name );
355 my_name_for_file = "";
356 if ( !ForesterUtil.isEmpty( full_path ) ) {
357 my_name_for_file = new String( full_path );
359 else if ( !ForesterUtil.isEmpty( default_name ) ) {
360 my_name_for_file = new String( default_name );
362 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
363 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
364 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
366 else if ( phy.getIdentifier() != null ) {
367 final StringBuffer sb = new StringBuffer();
368 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
369 sb.append( phy.getIdentifier().getProvider() );
372 sb.append( phy.getIdentifier().getValue() );
373 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
377 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
378 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
379 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
386 final static void addPhylogenyToPanel( final Phylogeny[] phys,
387 final Configuration configuration,
388 final MainPanel main_panel ) {
389 final Phylogeny phy = phys[ 0 ];
390 main_panel.addPhylogenyInPanel( phy, configuration );
391 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
394 // Returns true if the specified format name can be written
395 final static boolean canWriteFormat( final String format_name ) {
396 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
397 return iter.hasNext();
400 final static String createBasicInformation( final Phylogeny phy ) {
401 final StringBuilder desc = new StringBuilder();
402 if ( ( phy != null ) && !phy.isEmpty() ) {
403 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
404 desc.append( "Name: " );
405 desc.append( phy.getName() );
408 if ( phy.getIdentifier() != null ) {
409 desc.append( "Id: " );
410 desc.append( phy.getIdentifier().toString() );
413 if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
414 desc.append( "Description: " );
415 desc.append( phy.getDescription() );
418 if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
419 desc.append( "Distance Unit: " );
420 desc.append( phy.getDistanceUnit() );
423 if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
424 desc.append( "Type: " );
425 desc.append( phy.getType() );
428 desc.append( "Rooted: " );
429 desc.append( phy.isRooted() );
431 desc.append( "Rerootable: " );
432 desc.append( phy.isRerootable() );
434 desc.append( "Nodes: " );
435 desc.append( phy.getNodeCount() );
437 desc.append( "External nodes: " );
438 desc.append( phy.getNumberOfExternalNodes() );
440 desc.append( "Internal nodes: " );
441 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
443 desc.append( "Internal nodes with polytomies: " );
444 desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
446 desc.append( "Branches: " );
447 desc.append( phy.getNumberOfBranches() );
449 desc.append( "Depth: " );
450 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
452 desc.append( "Maximum distance to root: " );
453 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
455 final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
456 if ( taxs != null ) {
457 desc.append( "Distinct external taxonomies: " );
458 desc.append( taxs.size() );
460 for( final Taxonomy t : taxs ) {
461 System.out.println( t.toString() );
464 final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
465 if ( bs.getN() > 3 ) {
467 desc.append( "Branch-length statistics: " );
469 desc.append( " Number of branches with non-negative branch-lengths: " + bs.getN() );
471 desc.append( " Median: " + ForesterUtil.round( bs.median(), 6 ) );
473 desc.append( " Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
474 + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
476 desc.append( " Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
478 desc.append( " Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
480 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
482 final AsciiHistogram histo = new AsciiHistogram( bs );
483 desc.append( histo.toStringBuffer( 12, '#', 40, 7, " " ) );
486 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
487 if ( ds.getN() > 2 ) {
489 desc.append( "Descendants per node statistics: " );
491 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
493 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) + " (stdev: "
494 + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) + ")" );
496 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
498 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
501 List<DescriptiveStatistics> css = null;
503 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
505 catch ( final IllegalArgumentException e ) {
506 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
508 if ( ( css != null ) && ( css.size() > 0 ) ) {
510 for( int i = 0; i < css.size(); ++i ) {
511 final DescriptiveStatistics cs = css.get( i );
512 if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
513 if ( css.size() > 1 ) {
514 desc.append( "Support statistics " + ( i + 1 ) + ": " );
517 desc.append( "Support statistics: " );
519 if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
521 desc.append( " Type: " + cs.getDescription() );
524 desc.append( " Branches with support: " + cs.getN() );
526 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
528 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
529 if ( cs.getN() > 2 ) {
530 desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
533 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
535 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
541 return desc.toString();
549 * to message to be printed
551 final static void dieWithSystemError( final String message ) {
552 System.out.println();
553 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
554 System.out.println( "Please contact the authors." );
555 System.out.println( Constants.PRG_NAME + " needs to close." );
556 System.out.println();
560 final static String[] getAllPossibleRanks() {
561 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
563 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
564 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
565 str_array[ i++ ] = e;
571 final static String[] getAllRanks( final Phylogeny tree ) {
572 final SortedSet<String> ranks = new TreeSet<String>();
573 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
574 final PhylogenyNode n = it.next();
575 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
576 ranks.add( n.getNodeData().getTaxonomy().getRank() );
579 return ForesterUtil.stringSetToArray( ranks );
582 final static String[] getAvailableFontFamiliesSorted() {
583 return AVAILABLE_FONT_FAMILIES_SORTED;
586 final static boolean isUsOrCanada() {
588 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
592 catch ( final Exception e ) {
598 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
599 final ControlPanel atv_control,
600 final Configuration configuration ) {
601 if ( ( t != null ) && !t.isEmpty() ) {
602 if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
603 atv_control.setDrawPhylogram( false );
604 atv_control.setDrawPhylogramEnabled( false );
606 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
607 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
608 if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
609 atv_control.setDrawPhylogram( true );
610 atv_control.setDrawPhylogramEnabled( true );
613 atv_control.setDrawPhylogram( false );
617 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
618 if ( atv_control.getWriteConfidenceCb() != null ) {
619 if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
620 atv_control.setCheckbox( Configuration.write_confidence_values, true );
623 atv_control.setCheckbox( Configuration.write_confidence_values, false );
627 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
628 if ( atv_control.getShowEventsCb() != null ) {
629 if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
630 atv_control.setCheckbox( Configuration.write_events, true );
633 atv_control.setCheckbox( Configuration.write_events, false );
640 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
642 AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
644 catch ( final Exception e ) {
645 throw new IOException( e );
649 final static void outOfMemoryError( final OutOfMemoryError e ) {
650 System.err.println();
651 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
652 System.err.println();
654 System.err.println();
655 JOptionPane.showMessageDialog( null,
656 "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
657 + "\n\nError: " + e.getLocalizedMessage(),
658 "Out of Memory Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
659 JOptionPane.ERROR_MESSAGE );
663 final static void printAppletMessage( final String applet_name, final String message ) {
664 System.out.println( "[" + applet_name + "] > " + message );
667 final static Phylogeny[] readPhylogeniesFromUrl( final URL url,
668 final boolean phyloxml_validate_against_xsd,
669 final boolean replace_underscores,
670 final boolean internal_numbers_are_confidences,
671 final TAXONOMY_EXTRACTION taxonomy_extraction,
672 final boolean midpoint_reroot ) throws FileNotFoundException,
674 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
675 final PhylogenyParser parser;
676 boolean nhx_or_nexus = false;
677 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
678 parser = new TolParser();
681 parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
682 if ( parser instanceof NHXParser ) {
684 final NHXParser nhx = ( NHXParser ) parser;
685 nhx.setReplaceUnderscores( replace_underscores );
686 nhx.setIgnoreQuotes( false );
687 nhx.setTaxonomyExtraction( taxonomy_extraction );
689 else if ( parser instanceof NexusPhylogeniesParser ) {
691 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
692 nex.setReplaceUnderscores( replace_underscores );
693 nex.setIgnoreQuotes( false );
696 final Phylogeny[] phys = factory.create( url.openStream(), parser );
697 if ( nhx_or_nexus && internal_numbers_are_confidences ) {
698 for( final Phylogeny phy : phys ) {
699 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
702 if ( midpoint_reroot ) {
703 for( final Phylogeny phy : phys ) {
704 PhylogenyMethods.midpointRoot( phy );
705 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
711 final static void removeBranchColors( final Phylogeny phy ) {
712 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
713 it.next().getBranchData().setBranchColor( null );
717 final static void unexpectedError( final Error e ) {
718 System.err.println();
719 e.printStackTrace( System.err );
720 System.err.println();
721 final StringBuffer sb = new StringBuffer();
722 for( final StackTraceElement s : e.getStackTrace() ) {
723 sb.append( s + "\n" );
726 .showMessageDialog( null,
727 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
728 + Constants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
730 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
731 JOptionPane.ERROR_MESSAGE );
735 final static void unexpectedException( final Exception e ) {
736 System.err.println();
737 e.printStackTrace( System.err );
738 System.err.println();
739 final StringBuffer sb = new StringBuffer();
740 for( final StackTraceElement s : e.getStackTrace() ) {
741 sb.append( s + "\n" );
743 JOptionPane.showMessageDialog( null,
744 "An unexpected exception has occured. \nPlease contact: "
745 + Constants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
747 "Unexpected Exception [" + Constants.PRG_NAME + Constants.VERSION + "]",
748 JOptionPane.ERROR_MESSAGE );
751 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
754 final TreePanel tree_panel,
755 final ControlPanel ac,
756 final GraphicsExportType type,
757 final Options options ) throws IOException {
758 if ( !options.isGraphicsExportUsingActualSize() ) {
759 if ( options.isGraphicsExportVisibleOnly() ) {
760 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
762 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
763 tree_panel.resetPreferredSize();
764 tree_panel.repaint();
766 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
767 RenderingHints.VALUE_RENDER_QUALITY );
768 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
769 if ( options.isAntialiasPrint() ) {
770 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
771 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
774 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
775 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
777 final Phylogeny phylogeny = tree_panel.getPhylogeny();
778 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
781 Rectangle visible = null;
782 if ( !options.isGraphicsExportUsingActualSize() ) {
783 width = options.getPrintSizeX();
784 height = options.getPrintSizeY();
786 else if ( options.isGraphicsExportVisibleOnly() ) {
787 visible = tree_panel.getVisibleRect();
788 width = visible.width;
789 height = visible.height;
791 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
792 Graphics2D g2d = buffered_img.createGraphics();
793 g2d.setRenderingHints( rendering_hints );
796 if ( options.isGraphicsExportVisibleOnly() ) {
797 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
802 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
803 ImageIO.write( buffered_img, type.toString(), baos );
806 if ( !options.isGraphicsExportUsingActualSize() ) {
807 tree_panel.getMainPanel().getControlPanel().showWhole();
809 String msg = baos.toString();
810 if ( ( width > 0 ) && ( height > 0 ) ) {
811 msg += " [size: " + width + ", " + height + "]";
816 final static String writePhylogenyToGraphicsFile( final String file_name,
819 final TreePanel tree_panel,
820 final ControlPanel ac,
821 final GraphicsExportType type,
822 final Options options ) throws IOException {
823 if ( !options.isGraphicsExportUsingActualSize() ) {
824 if ( options.isGraphicsExportVisibleOnly() ) {
825 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
827 tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
828 tree_panel.resetPreferredSize();
829 tree_panel.repaint();
831 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
832 RenderingHints.VALUE_RENDER_QUALITY );
833 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
834 if ( options.isAntialiasPrint() ) {
835 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
836 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
839 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
840 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
842 final Phylogeny phylogeny = tree_panel.getPhylogeny();
843 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
846 final File file = new File( file_name );
847 if ( file.isDirectory() ) {
848 throw new IOException( "\"" + file_name + "\" is a directory" );
850 Rectangle visible = null;
851 if ( !options.isGraphicsExportUsingActualSize() ) {
852 width = options.getPrintSizeX();
853 height = options.getPrintSizeY();
855 else if ( options.isGraphicsExportVisibleOnly() ) {
856 visible = tree_panel.getVisibleRect();
857 width = visible.width;
858 height = visible.height;
860 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
861 Graphics2D g2d = buffered_img.createGraphics();
862 g2d.setRenderingHints( rendering_hints );
865 if ( options.isGraphicsExportVisibleOnly() ) {
866 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
871 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
872 if ( type == GraphicsExportType.TIFF ) {
873 writeToTiff( file, buffered_img );
876 ImageIO.write( buffered_img, type.toString(), file );
880 if ( !options.isGraphicsExportUsingActualSize() ) {
881 tree_panel.getMainPanel().getControlPanel().showWhole();
883 String msg = file.toString();
884 if ( ( width > 0 ) && ( height > 0 ) ) {
885 msg += " [size: " + width + ", " + height + "]";
890 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
891 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
892 ImageWriter writer = null;
893 ImageOutputStream ios = null;
894 // Find an appropriate writer:
895 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
896 if ( it.hasNext() ) {
900 throw new IOException( "failed to get TIFF image writer" );
903 ios = ImageIO.createImageOutputStream( file );
904 writer.setOutput( ios );
905 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
906 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
907 // see writeParam.getCompressionTypes() for available compression type
909 image_write_param.setCompressionType( "PackBits" );
910 final String t[] = image_write_param.getCompressionTypes();
911 for( final String string : t ) {
912 System.out.println( string );
914 // Convert to an IIOImage:
915 final IIOImage iio_image = new IIOImage( image, null, null );
916 writer.write( null, iio_image, image_write_param );
919 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
920 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
921 InvocationTargetException, InterruptedException {
922 final String os = System.getProperty( "os.name" );
923 final Runtime runtime = Runtime.getRuntime();
924 if ( os.toLowerCase().startsWith( "win" ) ) {
925 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
927 else if ( ForesterUtil.isMac() ) {
928 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
929 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
930 open_url.invoke( null, new Object[] { url } );
933 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
934 String browser = null;
935 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
936 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
937 browser = browsers[ i ];
940 if ( browser == null ) {
941 throw new IOException( "could not find a web browser to open [" + url + "] in" );
944 runtime.exec( new String[] { browser, url } );
949 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
950 // static void openDDBJRest() throws IOException {
952 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
954 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
956 // URLConnection urlc = url.openConnection();
958 // urlc.setDoOutput( true );
959 // urlc.setAllowUserInteraction( false );
961 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
962 // ps.print( query );
965 // BufferedReader br = new BufferedReader( new InputStreamReader(
966 // urlc.getInputStream() ) );
968 // while ( ( l = br.readLine() ) != null ) {
969 // System.out.println( l );
973 public static enum GraphicsExportType {
974 BMP( "bmp" ), GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" );
976 private final String _suffix;
978 private GraphicsExportType( final String suffix ) {
983 public String toString() {