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;
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.Iterator;
45 import java.util.List;
46 import java.util.Locale;
48 import java.util.SortedSet;
49 import java.util.TreeSet;
51 import javax.imageio.IIOImage;
52 import javax.imageio.ImageIO;
53 import javax.imageio.ImageWriteParam;
54 import javax.imageio.ImageWriter;
55 import javax.imageio.stream.ImageOutputStream;
56 import javax.swing.JApplet;
57 import javax.swing.JOptionPane;
58 import javax.swing.text.MaskFormatter;
60 import org.forester.io.parsers.PhylogenyParser;
61 import org.forester.io.parsers.tol.TolParser;
62 import org.forester.phylogeny.Phylogeny;
63 import org.forester.phylogeny.PhylogenyMethods;
64 import org.forester.phylogeny.PhylogenyNode;
65 import org.forester.phylogeny.data.BranchColor;
66 import org.forester.phylogeny.data.Taxonomy;
67 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
68 import org.forester.phylogeny.factories.PhylogenyFactory;
69 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
70 import org.forester.phylogeny.iterators.PreorderTreeIterator;
71 import org.forester.util.DescriptiveStatistics;
72 import org.forester.util.ForesterUtil;
74 public final class Util {
76 private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
77 .getAvailableFontFamilyNames();
79 Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
82 public static MaskFormatter createMaskFormatter( final String s ) {
83 MaskFormatter formatter = null;
85 formatter = new MaskFormatter( s );
87 catch ( final ParseException e ) {
88 throw new IllegalArgumentException( e );
93 final static void addPhylogeniesToTabs( final Phylogeny[] phys,
94 final String default_name,
95 final String full_path,
96 final Configuration configuration,
97 final MainPanel main_panel ) {
98 if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
99 JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
100 + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
101 + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
104 for( final Phylogeny phy : phys ) {
105 if ( !phy.isEmpty() ) {
106 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
108 String my_name_for_file = "";
109 if ( phys.length > 1 ) {
110 if ( !ForesterUtil.isEmpty( default_name ) ) {
111 my_name = new String( default_name );
113 if ( !ForesterUtil.isEmpty( full_path ) ) {
114 my_name_for_file = new String( full_path );
116 else if ( !ForesterUtil.isEmpty( default_name ) ) {
117 my_name_for_file = new String( default_name );
120 if ( my_name_for_file.indexOf( '.' ) > 0 ) {
121 suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
122 my_name_for_file.length() );
123 my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
125 if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
126 my_name_for_file += "_";
128 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
129 my_name_for_file += phy.getName().replaceAll( " ", "_" );
131 else if ( phy.getIdentifier() != null ) {
132 final StringBuffer sb = new StringBuffer();
133 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
134 sb.append( phy.getIdentifier().getProvider() );
137 sb.append( phy.getIdentifier().getValue() );
138 my_name_for_file += sb;
141 my_name_for_file += i;
143 if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
144 && ( phy.getIdentifier() == null ) ) {
145 my_name = my_name + " [" + i + "]";
147 if ( !ForesterUtil.isEmpty( suffix ) ) {
148 my_name_for_file += suffix;
152 if ( !ForesterUtil.isEmpty( default_name ) ) {
153 my_name = new String( default_name );
155 my_name_for_file = "";
156 if ( !ForesterUtil.isEmpty( full_path ) ) {
157 my_name_for_file = new String( full_path );
159 else if ( !ForesterUtil.isEmpty( default_name ) ) {
160 my_name_for_file = new String( default_name );
162 if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
163 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
164 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
166 else if ( phy.getIdentifier() != null ) {
167 final StringBuffer sb = new StringBuffer();
168 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
169 sb.append( phy.getIdentifier().getProvider() );
172 sb.append( phy.getIdentifier().getValue() );
173 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
177 main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
178 main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
179 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
186 final static void addPhylogenyToPanel( final Phylogeny[] phys,
187 final Configuration configuration,
188 final MainPanel main_panel ) {
189 final Phylogeny phy = phys[ 0 ];
190 main_panel.addPhylogenyInPanel( phy, configuration );
191 lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
194 final static Color calculateColorFromString( final String str ) {
195 final String species_uc = str.toUpperCase();
196 char first = species_uc.charAt( 0 );
199 if ( species_uc.length() > 1 ) {
200 second = species_uc.charAt( 1 );
201 if ( species_uc.length() > 2 ) {
202 if ( species_uc.indexOf( " " ) > 0 ) {
203 third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
206 third = species_uc.charAt( 2 );
210 first = Util.normalizeCharForRGB( first );
211 second = Util.normalizeCharForRGB( second );
212 third = Util.normalizeCharForRGB( third );
213 if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
216 else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
219 return new Color( first, second, third );
222 // Returns true if the specified format name can be written
223 final static boolean canWriteFormat( final String format_name ) {
224 final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
225 return iter.hasNext();
228 final public static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
229 boolean inferred = false;
230 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
231 final PhylogenyNode n = it.next();
232 if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
233 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
234 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
235 Util.collapseSubtree( n, true );
236 if ( !n.getNodeData().isHasTaxonomy() ) {
237 n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
238 .getTaxonomy().copy() );
243 n.setCollapse( false );
248 phy.setRerootable( false );
252 final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
253 node.setCollapse( collapse );
254 if ( node.isExternal() ) {
257 final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
258 while ( it.hasNext() ) {
259 it.next().setCollapse( collapse );
263 final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
264 double max_conf = 0.0;
265 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
266 final PhylogenyNode n = it.next();
267 n.getBranchData().setBranchColor( null );
268 if ( n.getBranchData().isHasConfidences() ) {
269 final double conf = PhylogenyMethods.getConfidenceValue( n );
270 if ( conf > max_conf ) {
275 if ( max_conf > 0.0 ) {
276 final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
277 final Color br = tree_panel.getTreeColorSet().getBranchColor();
278 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
279 final PhylogenyNode n = it.next();
280 if ( n.getBranchData().isHasConfidences() ) {
281 final double conf = PhylogenyMethods.getConfidenceValue( n );
282 final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
283 n.getBranchData().setBranchColor( c );
284 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
285 for( final PhylogenyNode desc : descs ) {
286 desc.getBranchData().setBranchColor( c );
293 final static void colorPhylogenyAccordingToRanks( final Phylogeny tree,
295 final TreePanel tree_panel ) {
296 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
297 final PhylogenyNode n = it.next();
298 if ( n.getNodeData().isHasTaxonomy()
299 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) && n.getNodeData()
300 .getTaxonomy().getRank().equalsIgnoreCase( rank ) )
301 && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
302 || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
303 .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
304 final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
306 n.getBranchData().setBranchColor( c );
307 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
308 for( final PhylogenyNode desc : descs ) {
309 desc.getBranchData().setBranchColor( c );
315 final static String[] getAllRanks( final Phylogeny tree ) {
316 final SortedSet<String> ranks = new TreeSet<String>();
317 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
318 final PhylogenyNode n = it.next();
319 if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
320 ranks.add( n.getNodeData().getTaxonomy().getRank() );
323 return ForesterUtil.stringSetToArray( ranks );
326 final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
327 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
328 it.next().getBranchData().setBranchColor( null );
330 for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
331 final PhylogenyNode n = it.next();
332 if ( !n.getBranchData().isHasBranchColor() ) {
333 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
335 n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
336 final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
337 for( final PhylogenyNode desc : descs ) {
339 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
346 final static String crateBasicInformation( final Phylogeny phy ) {
347 final StringBuilder desc = new StringBuilder();
348 if ( ( phy != null ) && !phy.isEmpty() ) {
349 if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
350 desc.append( "Name: " );
351 desc.append( phy.getName() );
354 if ( phy.getIdentifier() != null ) {
355 desc.append( "Id: " );
356 desc.append( phy.getIdentifier() );
359 desc.append( "Rooted: " );
360 desc.append( phy.isRooted() );
362 desc.append( "Rerootable: " );
363 desc.append( phy.isRerootable() );
365 desc.append( "Node sum: " );
366 desc.append( phy.getNodeCount() );
368 desc.append( "External node sum: " );
369 desc.append( phy.getNumberOfExternalNodes() );
371 desc.append( "Internal node sum: " );
372 desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
374 desc.append( "Branche sum: " );
375 desc.append( phy.getNumberOfBranches() );
377 desc.append( "Depth: " );
378 desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
380 desc.append( "Maximum distance to root: " );
381 desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
383 desc.append( "Descendants per node statistics: " );
384 final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
386 desc.append( " Median: " + ForesterUtil.round( ds.median(), 2 ) );
388 desc.append( " Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
390 desc.append( " SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
392 desc.append( " Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
394 desc.append( " Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
396 final DescriptiveStatistics cs = PhylogenyMethods.calculatConfidenceStatistics( phy );
397 if ( cs.getN() > 1 ) {
398 desc.append( "Support statistics: " );
400 desc.append( " Branches with support: " + cs.getN() );
402 desc.append( " Median: " + ForesterUtil.round( cs.median(), 6 ) );
404 desc.append( " Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
406 if ( cs.getN() > 2 ) {
407 desc.append( " SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
410 desc.append( " Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
412 desc.append( " Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
415 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
416 if ( taxs != null ) {
417 desc.append( "Distinct external taxonomies: " );
418 desc.append( taxs.size() );
421 return desc.toString();
429 * to message to be printed
431 final static void dieWithSystemError( final String message ) {
432 System.out.println();
433 System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
434 System.out.println( "Please contact the authors." );
435 System.out.println( Constants.PRG_NAME + " needs to close." );
436 System.out.println();
440 final static String[] getAvailableFontFamiliesSorted() {
441 return AVAILABLE_FONT_FAMILIES_SORTED;
444 final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
445 boolean inferred = false;
446 for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
447 final PhylogenyNode n = it.next();
448 if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
449 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
450 if ( !ForesterUtil.isEmpty( sn ) ) {
451 n.getNodeData().setTaxonomy( new Taxonomy() );
452 n.getNodeData().getTaxonomy().setScientificName( sn );
458 tree.setRerootable( false );
462 final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
463 if ( !node.getNodeData().isHasEvent() ) {
466 if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
472 final static boolean isJava15() {
474 final String s = ForesterUtil.JAVA_VERSION;
475 return s.startsWith( "1.5" );
477 catch ( final Exception e ) {
478 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
483 final static boolean isMac() {
485 final String s = ForesterUtil.OS_NAME.toLowerCase();
486 return s.startsWith( "mac" );
488 catch ( final Exception e ) {
489 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
494 final static boolean isUsOrCanada() {
496 if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
500 catch ( final Exception e ) {
506 final static boolean isWindows() {
508 final String s = ForesterUtil.OS_NAME.toLowerCase();
509 return s.indexOf( "win" ) > -1;
511 catch ( final Exception e ) {
512 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
517 final static void launchWebBrowser( final URI uri,
518 final boolean is_applet,
519 final JApplet applet,
520 final String frame_name ) throws IOException {
522 applet.getAppletContext().showDocument( uri.toURL(), frame_name );
525 // This requires Java 1.6:
526 // =======================
527 // boolean no_desktop = false;
529 // if ( Desktop.isDesktopSupported() ) {
530 // System.out.println( "desktop supported" );
531 // final Desktop dt = Desktop.getDesktop();
535 // no_desktop = true;
538 // catch ( final Exception ex ) {
539 // ex.printStackTrace();
540 // no_desktop = true;
542 // catch ( final Error er ) {
543 // er.printStackTrace();
544 // no_desktop = true;
546 // if ( no_desktop ) {
547 // System.out.println( "desktop not supported" );
549 openUrlInWebBrowser( uri.toString() );
551 catch ( final Exception e ) {
552 throw new IOException( e );
558 final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
559 final ControlPanel atv_control,
560 final Configuration configuration ) {
561 if ( ( t != null ) && !t.isEmpty() ) {
562 if ( !ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
563 atv_control.setDrawPhylogram( false );
564 atv_control.setDrawPhylogramEnabled( false );
566 if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
567 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
568 if ( ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
569 atv_control.setDrawPhylogram( true );
570 atv_control.setDrawPhylogramEnabled( true );
573 atv_control.setDrawPhylogram( false );
577 if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
578 if ( atv_control.getWriteConfidenceCb() != null ) {
579 if ( ForesterUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
580 atv_control.setCheckbox( Configuration.write_confidence_values, true );
583 atv_control.setCheckbox( Configuration.write_confidence_values, false );
587 if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
588 if ( atv_control.getShowEventsCb() != null ) {
589 if ( ForesterUtil.isHasAtLeastNodeWithEvent( t ) ) {
590 atv_control.setCheckbox( Configuration.write_events, true );
593 atv_control.setCheckbox( Configuration.write_events, false );
600 final private static char normalizeCharForRGB( char c ) {
603 c = c > 255 ? 255 : c;
608 final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
609 SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
610 InvocationTargetException, InterruptedException {
611 final String os = System.getProperty( "os.name" );
612 final Runtime runtime = Runtime.getRuntime();
613 if ( os.toLowerCase().startsWith( "win" ) ) {
614 Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
616 else if ( isMac() ) {
617 final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
618 final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
619 open_url.invoke( null, new Object[] { url } );
622 final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
623 String browser = null;
624 for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
625 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
626 browser = browsers[ i ];
629 if ( browser == null ) {
630 throw new IOException( "could not find a web browser to open [" + url + "] in" );
633 runtime.exec( new String[] { browser, url } );
638 final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
640 Util.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
642 catch ( final Exception e ) {
643 throw new IOException( e );
647 final static void printAppletMessage( final String applet_name, final String message ) {
648 System.out.println( "[" + applet_name + "] > " + message );
651 public final static void printWarningMessage( final String name, final String message ) {
652 System.out.println( "[" + name + "] > " + message );
655 final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
656 throws FileNotFoundException, IOException {
657 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
658 PhylogenyParser parser = null;
659 if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
660 parser = new TolParser();
663 parser = ForesterUtil.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
665 return factory.create( url.openStream(), parser );
668 final static void removeBranchColors( final Phylogeny phy ) {
669 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
670 it.next().getBranchData().setBranchColor( null );
674 final static void showErrorMessage( final Component parent, final String error_msg ) {
675 printAppletMessage( Constants.PRG_NAME, error_msg );
676 JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
677 + "] Error", JOptionPane.ERROR_MESSAGE );
680 final static void unexpectedError( final Error err ) {
681 err.printStackTrace();
682 final StringBuffer sb = new StringBuffer();
683 for( final StackTraceElement s : err.getStackTrace() ) {
684 sb.append( s + "\n" );
687 .showMessageDialog( null,
688 "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
689 + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
690 "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
691 JOptionPane.ERROR_MESSAGE );
695 final static void unexpectedException( final Exception ex ) {
696 ex.printStackTrace();
697 final StringBuffer sb = new StringBuffer();
698 for( final StackTraceElement s : ex.getStackTrace() ) {
699 sb.append( s + "\n" );
701 JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
702 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
703 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
706 final static String writePhylogenyToGraphicsFile( final String file_name,
709 final TreePanel tree_panel,
710 final ControlPanel ac,
711 final GraphicsExportType type,
712 final Options options ) throws IOException {
713 if ( !options.isGraphicsExportUsingActualSize() ) {
714 if ( options.isGraphicsExportVisibleOnly() ) {
715 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
717 tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
718 tree_panel.resetPreferredSize();
719 tree_panel.repaint();
721 final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
722 RenderingHints.VALUE_RENDER_QUALITY );
723 rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
724 if ( options.isAntialiasPrint() ) {
725 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
726 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
729 rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
730 rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
732 final Phylogeny phylogeny = tree_panel.getPhylogeny();
733 if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
736 final File file = new File( file_name );
737 if ( file.isDirectory() ) {
738 throw new IOException( "\"" + file_name + "\" is a directory" );
740 Rectangle visible = null;
741 if ( !options.isGraphicsExportUsingActualSize() ) {
742 width = options.getPrintSizeX();
743 height = options.getPrintSizeY();
745 else if ( options.isGraphicsExportVisibleOnly() ) {
746 visible = tree_panel.getVisibleRect();
747 width = visible.width;
748 height = visible.height;
750 final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
751 Graphics2D g2d = buffered_img.createGraphics();
752 g2d.setRenderingHints( rendering_hints );
755 if ( options.isGraphicsExportVisibleOnly() ) {
756 g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
761 tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
762 if ( type == GraphicsExportType.TIFF ) {
763 writeToTiff( file, buffered_img );
766 ImageIO.write( buffered_img, type.toString(), file );
770 if ( !options.isGraphicsExportUsingActualSize() ) {
771 tree_panel.getMainPanel().getControlPanel().showWhole();
773 String msg = file.toString();
774 if ( ( width > 0 ) && ( height > 0 ) ) {
775 msg += " [size: " + width + ", " + height + "]";
780 final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
781 // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
782 ImageWriter writer = null;
783 ImageOutputStream ios = null;
784 // Find an appropriate writer:
785 final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
786 if ( it.hasNext() ) {
790 throw new IOException( "failed to get TIFF image writer" );
793 ios = ImageIO.createImageOutputStream( file );
794 writer.setOutput( ios );
795 final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
796 image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
797 // see writeParam.getCompressionTypes() for available compression type
799 image_write_param.setCompressionType( "PackBits" );
800 final String t[] = image_write_param.getCompressionTypes();
801 for( final String string : t ) {
802 System.out.println( string );
804 // Convert to an IIOImage:
805 final IIOImage iio_image = new IIOImage( image, null, null );
806 writer.write( null, iio_image, image_write_param );
809 // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
810 // static void openDDBJRest() throws IOException {
812 // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
814 // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
816 // URLConnection urlc = url.openConnection();
818 // urlc.setDoOutput( true );
819 // urlc.setAllowUserInteraction( false );
821 // PrintStream ps = new PrintStream( urlc.getOutputStream() );
822 // ps.print( query );
825 // BufferedReader br = new BufferedReader( new InputStreamReader(
826 // urlc.getInputStream() ) );
828 // while ( ( l = br.readLine() ) != null ) {
829 // System.out.println( l );
833 static enum GraphicsExportType {
834 GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
836 private final String _suffix;
838 private GraphicsExportType( final String suffix ) {
843 public String toString() {