2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 // Contact: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
26 package org.forester.archaeopteryx;
28 import java.awt.Color;
29 import java.awt.Component;
30 import java.awt.Graphics2D;
31 import java.awt.GraphicsEnvironment;
32 import java.awt.Rectangle;
33 import java.awt.RenderingHints;
34 import java.awt.image.BufferedImage;
35 import java.io.ByteArrayOutputStream;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
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.HashMap;
46 import java.util.Iterator;
47 import java.util.List;
48 import java.util.Locale;
51 import java.util.SortedSet;
52 import java.util.TreeSet;
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.analysis.AncestralTaxonomyInference;
64 import org.forester.io.parsers.PhylogenyParser;
65 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
66 import org.forester.io.parsers.tol.TolParser;
67 import org.forester.phylogeny.Phylogeny;
68 import org.forester.phylogeny.PhylogenyMethods;
69 import org.forester.phylogeny.PhylogenyNode;
70 import org.forester.phylogeny.data.BranchColor;
71 import org.forester.phylogeny.data.Taxonomy;
72 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
73 import org.forester.phylogeny.factories.PhylogenyFactory;
74 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
75 import org.forester.phylogeny.iterators.PreorderTreeIterator;
76 import org.forester.util.DescriptiveStatistics;
77 import org.forester.util.ForesterUtil;
78 import org.forester.ws.uniprot.UniProtTaxonomy;
80 public final class Util {
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 void addPhylogeniesToTabs( final Phylogeny[] phys,
100 final String default_name,
101 final String full_path,
102 final Configuration configuration,
103 final MainPanel main_panel ) {
104 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
105 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
106 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
107 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
110 for( final Phylogeny phy : phys ) {
111 if ( !phy.isEmpty() ) {
112 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
114 String my_name_for_file = "";
115 if ( phys.length > 1 ) {
116 if ( !ForesterUtil.isEmpty( default_name ) ) {
117 my_name = new String( default_name );
119 if ( !ForesterUtil.isEmpty( full_path ) ) {
120 my_name_for_file = new String( full_path );
122 else if ( !ForesterUtil.isEmpty( default_name ) ) {
123 my_name_for_file = new String( default_name );
126 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
127 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
128 my_name_for_file.length() );
129 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
131 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
132 my_name_for_file += "_";
134 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
135 my_name_for_file += phy.getName().replaceAll( " ", "_" );
137 else if ( phy.getIdentifier() != null ) {
138 final StringBuffer sb = new StringBuffer();
139 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
140 sb.append( phy.getIdentifier().getProvider() );
143 sb.append( phy.getIdentifier().getValue() );
144 my_name_for_file += sb;
147 my_name_for_file += i;
149 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
150 && ( phy.getIdentifier() == null ) ) {
151 my_name = my_name + " [" + i + "]";
153 if ( !ForesterUtil.isEmpty( suffix ) ) {
154 my_name_for_file += suffix;
158 if ( !ForesterUtil.isEmpty( default_name ) ) {
159 my_name = new String( default_name );
161 my_name_for_file = "";
162 if ( !ForesterUtil.isEmpty( full_path ) ) {
163 my_name_for_file = new String( full_path );
165 else if ( !ForesterUtil.isEmpty( default_name ) ) {
166 my_name_for_file = new String( default_name );
168 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
169 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
170 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
172 else if ( phy.getIdentifier() != null ) {
173 final StringBuffer sb = new StringBuffer();
174 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
175 sb.append( phy.getIdentifier().getProvider() );
178 sb.append( phy.getIdentifier().getValue() );
179 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
183 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
184 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
185 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
192 final static void addPhylogenyToPanel( final Phylogeny[] phys,
193 final Configuration configuration,
194 final MainPanel main_panel ) {
195 final Phylogeny phy = phys[ 0 ];
196 main_panel.addPhylogenyInPanel( phy, configuration );
197 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
200 final static Color calculateColorFromString( final String str ) {
201 final String species_uc = str.toUpperCase();
202 char first = species_uc.charAt( 0 );
205 if ( species_uc.length() > 1 ) {
206 second = species_uc.charAt( 1 );
207 if ( species_uc.length() > 2 ) {
208 if ( species_uc.indexOf( " " ) > 0 ) {
209 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
212 third = species_uc.charAt( 2 );
216 first = Util.normalizeCharForRGB( first );
217 second = Util.normalizeCharForRGB( second );
218 third = Util.normalizeCharForRGB( third );
219 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
222 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
225 return new Color( first, second, third );
228 // Returns true if the specified format name can be written
229 final static boolean canWriteFormat( final String format_name ) {
230 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
231 return iter.hasNext();
234 final public static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
235 boolean inferred = false;
236 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
237 final PhylogenyNode n = it.next();
238 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
239 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
240 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
241 Util.collapseSubtree( n, true );
242 if ( !n.getNodeData().isHasTaxonomy() ) {
243 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
244 .getTaxonomy().copy() );
249 n.setCollapse( false );
254 phy.setRerootable( false );
258 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
259 node.setCollapse( collapse );
260 if ( node.isExternal() ) {
263 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
264 while ( it.hasNext() ) {
265 it.next().setCollapse( collapse );
269 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
270 double max_conf = 0.0;
271 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
272 final PhylogenyNode n = it.next();
273 n.getBranchData().setBranchColor( null );
274 if ( n.getBranchData().isHasConfidences() ) {
275 final double conf = PhylogenyMethods.getConfidenceValue( n );
276 if ( conf > max_conf ) {
281 if ( max_conf > 0.0 ) {
282 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
283 final Color br = tree_panel.getTreeColorSet().getBranchColor();
284 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
285 final PhylogenyNode n = it.next();
286 if ( n.getBranchData().isHasConfidences() ) {
287 final double conf = PhylogenyMethods.getConfidenceValue( n );
288 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
289 colorizeSubtree( n, c );
295 final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
296 final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
297 int colorizations = 0;
298 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
299 final PhylogenyNode n = it.next();
300 if ( n.getNodeData().isHasTaxonomy()
301 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
302 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
303 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
304 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
305 && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
306 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
308 colorizeSubtree( n, c );
310 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
311 true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
316 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
317 final PhylogenyNode node = it.next();
318 if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
319 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
320 boolean success = false;
321 if ( !true_lineage_to_color_map.isEmpty() ) {
322 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
323 if ( true_lineage_to_color_map.containsKey( lin ) ) {
324 colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
332 final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
333 for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
334 final Taxonomy temp_tax = new Taxonomy();
335 temp_tax.setScientificName( lin );
336 if ( lineage_to_rank_map.containsKey( lin )
337 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
338 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
339 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
340 colorizeSubtree( node, c );
342 true_lineage_to_color_map.put( lin, c.getValue() );
346 UniProtTaxonomy up = null;
348 up = AncestralTaxonomyInference.obtainUniProtTaxonomy( temp_tax, null, null );
350 catch ( final Exception e ) {
353 if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
354 lineage_to_rank_map.put( lin, up.getRank() );
355 if ( up.getRank().equalsIgnoreCase( rank ) ) {
356 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
357 colorizeSubtree( node, c );
359 true_lineage_to_color_map.put( lin, c.getValue() );
368 return colorizations;
371 private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
372 node.getBranchData().setBranchColor( c );
373 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
374 for( final PhylogenyNode desc : descs ) {
375 desc.getBranchData().setBranchColor( c );
379 final static String[] getAllRanks( final Phylogeny tree ) {
380 final SortedSet<String> ranks = new TreeSet<String>();
381 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
382 final PhylogenyNode n = it.next();
383 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
384 ranks.add( n.getNodeData().getTaxonomy().getRank() );
387 return ForesterUtil.stringSetToArray( ranks );
390 public static String[] getAllPossibleRanks() {
391 final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
393 for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
394 if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
395 str_array[ i++ ] = e;
401 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
402 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
403 it.next().getBranchData().setBranchColor( null );
405 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
406 final PhylogenyNode n = it.next();
407 if ( !n.getBranchData().isHasBranchColor() ) {
408 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
410 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
411 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
412 for( final PhylogenyNode desc : descs ) {
414 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
421 final static String crateBasicInformation( final Phylogeny phy ) {
422 final StringBuilder desc = new StringBuilder();
423 if ( ( phy != null ) && !phy.isEmpty() ) {
424 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
425 desc.append( "Name: " );
426 desc.append( phy.getName() );
429 if ( phy.getIdentifier() != null ) {
430 desc.append( "Id: " );
431 desc.append( phy.getIdentifier() );
434 desc.append( "Rooted: " );
435 desc.append( phy.isRooted() );
437 desc.append( "Rerootable: " );
438 desc.append( phy.isRerootable() );
440 desc.append( "Node sum: " );
441 desc.append( phy.getNodeCount() );
443 desc.append( "External node sum: " );
444 desc.append( phy.getNumberOfExternalNodes() );
446 desc.append( "Internal node sum: " );
447 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
449 desc.append( "Branche sum: " );
450 desc.append( phy.getNumberOfBranches() );
452 desc.append( "Depth: " );
453 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
455 desc.append( "Maximum distance to root: " );
456 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
458 desc.append( "Descendants per node statistics: " );
459 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
461 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
463 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
465 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
467 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
469 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
471 final DescriptiveStatistics cs = PhylogenyMethods.calculatConfidenceStatistics( phy );
472 if ( cs.getN() > 1 ) {
473 desc.append( "Support statistics: " );
475 desc.append( " Branches with support: " + cs.getN() );
477 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
479 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
481 if ( cs.getN() > 2 ) {
482 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
485 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
487 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
490 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
491 if ( taxs != null ) {
492 desc.append( "Distinct external taxonomies: " );
493 desc.append( taxs.size() );
496 return desc.toString();
504 * to message to be printed
506 final static void dieWithSystemError( final String message ) {
507 System.out.println();
508 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
509 System.out.println( "Please contact the authors." );
510 System.out.println( Constants.PRG_NAME + " needs to close." );
511 System.out.println();
515 final static String[] getAvailableFontFamiliesSorted() {
516 return AVAILABLE_FONT_FAMILIES_SORTED;
519 final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
520 boolean inferred = false;
521 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
522 final PhylogenyNode n = it.next();
523 if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
524 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
525 if ( !ForesterUtil.isEmpty( sn ) ) {
526 n.getNodeData().setTaxonomy( new Taxonomy() );
527 n.getNodeData().getTaxonomy().setScientificName( sn );
533 tree.setRerootable( false );
537 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
538 if ( !node.getNodeData().isHasEvent() ) {
541 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
547 final static boolean isJava15() {
549 final String s = ForesterUtil.JAVA_VERSION;
550 return s.startsWith( "1.5" );
552 catch ( final Exception e ) {
553 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
558 final static boolean isMac() {
560 final String s = ForesterUtil.OS_NAME.toLowerCase();
561 return s.startsWith( "mac" );
563 catch ( final Exception e ) {
564 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
569 final static boolean isUsOrCanada() {
571 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
575 catch ( final Exception e ) {
581 final static boolean isWindows() {
583 final String s = ForesterUtil.OS_NAME.toLowerCase();
584 return s.indexOf( "win" ) > -1;
586 catch ( final Exception e ) {
587 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
592 final static void launchWebBrowser( final URI uri,
593 final boolean is_applet,
594 final JApplet applet,
595 final String frame_name ) throws IOException {
597 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
600 // This requires Java 1.6:
601 // =======================
602 // boolean no_desktop = false;
604 // if ( Desktop.isDesktopSupported() ) {
605 // System.out.println( "desktop supported" );
606 // final Desktop dt = Desktop.getDesktop();
610 // no_desktop = true;
613 // catch ( final Exception ex ) {
614 // ex.printStackTrace();
615 // no_desktop = true;
617 // catch ( final Error er ) {
618 // er.printStackTrace();
619 // no_desktop = true;
621 // if ( no_desktop ) {
622 // System.out.println( "desktop not supported" );
624 openUrlInWebBrowser( uri.toString() );
626 catch ( final Exception e ) {
627 throw new IOException( e );
633 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
634 final ControlPanel atv_control,
635 final Configuration configuration ) {
636 if ( ( t != null ) && !t.isEmpty() ) {
637 if ( !ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
638 atv_control.setDrawPhylogram( false );
639 atv_control.setDrawPhylogramEnabled( false );
641 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
642 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
643 if ( ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
644 atv_control.setDrawPhylogram( true );
645 atv_control.setDrawPhylogramEnabled( true );
648 atv_control.setDrawPhylogram( false );
652 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
653 if ( atv_control.getWriteConfidenceCb() != null ) {
654 if ( ForesterUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
655 atv_control.setCheckbox( Configuration.write_confidence_values, true );
658 atv_control.setCheckbox( Configuration.write_confidence_values, false );
662 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
663 if ( atv_control.getShowEventsCb() != null ) {
664 if ( ForesterUtil.isHasAtLeastNodeWithEvent( t ) ) {
665 atv_control.setCheckbox( Configuration.write_events, true );
668 atv_control.setCheckbox( Configuration.write_events, false );
675 final private static char normalizeCharForRGB( char c ) {
678 c = c > 255 ? 255 : c;
683 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
684 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
685 InvocationTargetException, InterruptedException {
686 final String os = System.getProperty( "os.name" );
687 final Runtime runtime = Runtime.getRuntime();
688 if ( os.toLowerCase().startsWith( "win" ) ) {
689 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
691 else if ( isMac() ) {
692 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
693 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
694 open_url.invoke( null, new Object[] { url } );
697 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
698 String browser = null;
699 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
700 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
701 browser = browsers[ i ];
704 if ( browser == null ) {
705 throw new IOException( "could not find a web browser to open [" + url + "] in" );
708 runtime.exec( new String[] { browser, url } );
713 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
715 Util.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
717 catch ( final Exception e ) {
718 throw new IOException( e );
722 final static void printAppletMessage( final String applet_name, final String message ) {
723 System.out.println( "[" + applet_name + "] > " + message );
726 public final static void printWarningMessage( final String name, final String message ) {
727 System.out.println( "[" + name + "] > " + message );
730 final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
731 throws FileNotFoundException, IOException {
732 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
733 PhylogenyParser parser = null;
734 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
735 parser = new TolParser();
738 parser = ForesterUtil.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
740 return factory.create( url.openStream(), parser );
743 final static void removeBranchColors( final Phylogeny phy ) {
744 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
745 it.next().getBranchData().setBranchColor( null );
749 final static void showErrorMessage( final Component parent, final String error_msg ) {
750 printAppletMessage( Constants.PRG_NAME, error_msg );
751 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
752 + "] Error", JOptionPane.ERROR_MESSAGE );
755 final static void unexpectedError( final Error err ) {
756 err.printStackTrace();
757 final StringBuffer sb = new StringBuffer();
758 for( final StackTraceElement s : err.getStackTrace() ) {
759 sb.append( s + "\n" );
762 .showMessageDialog( null,
763 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
764 + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
765 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
766 JOptionPane.ERROR_MESSAGE );
770 final static void unexpectedException( final Exception ex ) {
771 ex.printStackTrace();
772 final StringBuffer sb = new StringBuffer();
773 for( final StackTraceElement s : ex.getStackTrace() ) {
774 sb.append( s + "\n" );
776 JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
777 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
778 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
781 final static String writePhylogenyToGraphicsFile( final String file_name,
784 final TreePanel tree_panel,
785 final ControlPanel ac,
786 final GraphicsExportType type,
787 final Options options ) throws IOException {
788 if ( !options.isGraphicsExportUsingActualSize() ) {
789 if ( options.isGraphicsExportVisibleOnly() ) {
790 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
792 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
793 tree_panel.resetPreferredSize();
794 tree_panel.repaint();
796 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
797 RenderingHints.VALUE_RENDER_QUALITY );
798 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
799 if ( options.isAntialiasPrint() ) {
800 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
801 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
804 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
805 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
807 final Phylogeny phylogeny = tree_panel.getPhylogeny();
808 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
811 final File file = new File( file_name );
812 if ( file.isDirectory() ) {
813 throw new IOException( "\"" + file_name + "\" is a directory" );
815 Rectangle visible = null;
816 if ( !options.isGraphicsExportUsingActualSize() ) {
817 width = options.getPrintSizeX();
818 height = options.getPrintSizeY();
820 else if ( options.isGraphicsExportVisibleOnly() ) {
821 visible = tree_panel.getVisibleRect();
822 width = visible.width;
823 height = visible.height;
825 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
826 Graphics2D g2d = buffered_img.createGraphics();
827 g2d.setRenderingHints( rendering_hints );
830 if ( options.isGraphicsExportVisibleOnly() ) {
831 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
836 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
837 if ( type == GraphicsExportType.TIFF ) {
838 writeToTiff( file, buffered_img );
841 ImageIO.write( buffered_img, type.toString(), file );
845 if ( !options.isGraphicsExportUsingActualSize() ) {
846 tree_panel.getMainPanel().getControlPanel().showWhole();
848 String msg = file.toString();
849 if ( ( width > 0 ) && ( height > 0 ) ) {
850 msg += " [size: " + width + ", " + height + "]";
855 final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
858 final TreePanel tree_panel,
859 final ControlPanel ac,
860 final GraphicsExportType type,
861 final Options options ) throws IOException{
862 if ( !options.isGraphicsExportUsingActualSize() ) {
863 if ( options.isGraphicsExportVisibleOnly() ) {
864 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
866 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
867 tree_panel.resetPreferredSize();
868 tree_panel.repaint();
870 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
871 RenderingHints.VALUE_RENDER_QUALITY );
872 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
873 if ( options.isAntialiasPrint() ) {
874 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
875 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
878 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
879 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
881 final Phylogeny phylogeny = tree_panel.getPhylogeny();
882 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
885 Rectangle visible = null;
886 if ( !options.isGraphicsExportUsingActualSize() ) {
887 width = options.getPrintSizeX();
888 height = options.getPrintSizeY();
890 else if ( options.isGraphicsExportVisibleOnly() ) {
891 visible = tree_panel.getVisibleRect();
892 width = visible.width;
893 height = visible.height;
895 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
896 Graphics2D g2d = buffered_img.createGraphics();
897 g2d.setRenderingHints( rendering_hints );
900 if ( options.isGraphicsExportVisibleOnly() ) {
901 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
906 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
907 ImageIO.write( buffered_img, type.toString(), baos );
910 if ( !options.isGraphicsExportUsingActualSize() ) {
911 tree_panel.getMainPanel().getControlPanel().showWhole();
913 String msg = baos.toString();
914 if ( ( width > 0 ) && ( height > 0 ) ) {
915 msg += " [size: " + width + ", " + height + "]";
920 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
921 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
922 ImageWriter writer = null;
923 ImageOutputStream ios = null;
924 // Find an appropriate writer:
925 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
926 if ( it.hasNext() ) {
930 throw new IOException( "failed to get TIFF image writer" );
933 ios = ImageIO.createImageOutputStream( file );
934 writer.setOutput( ios );
935 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
936 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
937 // see writeParam.getCompressionTypes() for available compression type
939 image_write_param.setCompressionType( "PackBits" );
940 final String t[] = image_write_param.getCompressionTypes();
941 for( final String string : t ) {
942 System.out.println( string );
944 // Convert to an IIOImage:
945 final IIOImage iio_image = new IIOImage( image, null, null );
946 writer.write( null, iio_image, image_write_param );
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 static enum GraphicsExportType {
974 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
976 private final String _suffix;
978 private GraphicsExportType( final String suffix ) {
983 public String toString() {