in progress...
[jalview.git] / forester / java / src / org / forester / archaeopteryx / Util.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
7 // All rights reserved
8 //
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.
13 //
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.
18 //
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
22 //
23 // Contact: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
25
26 package org.forester.archaeopteryx;
27
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.File;
36 import java.io.FileNotFoundException;
37 import java.io.IOException;
38 import java.lang.reflect.InvocationTargetException;
39 import java.lang.reflect.Method;
40 import java.net.URI;
41 import java.net.URL;
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;
47 import java.util.Set;
48
49 import javax.imageio.IIOImage;
50 import javax.imageio.ImageIO;
51 import javax.imageio.ImageWriteParam;
52 import javax.imageio.ImageWriter;
53 import javax.imageio.stream.ImageOutputStream;
54 import javax.swing.JApplet;
55 import javax.swing.JOptionPane;
56 import javax.swing.text.MaskFormatter;
57
58 import org.forester.io.parsers.PhylogenyParser;
59 import org.forester.io.parsers.tol.TolParser;
60 import org.forester.io.parsers.util.PhylogenyParserException;
61 import org.forester.phylogeny.Phylogeny;
62 import org.forester.phylogeny.PhylogenyMethods;
63 import org.forester.phylogeny.PhylogenyNode;
64 import org.forester.phylogeny.data.BranchColor;
65 import org.forester.phylogeny.data.Taxonomy;
66 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
67 import org.forester.phylogeny.factories.PhylogenyFactory;
68 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
69 import org.forester.phylogeny.iterators.PreorderTreeIterator;
70 import org.forester.util.ForesterUtil;
71
72 final class Util {
73
74     private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
75                                                                          .getAvailableFontFamilyNames();
76     static {
77         Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
78     }
79
80     public static MaskFormatter createMaskFormatter( final String s ) {
81         MaskFormatter formatter = null;
82         try {
83             formatter = new MaskFormatter( s );
84         }
85         catch ( final ParseException e ) {
86             throw new IllegalArgumentException( e );
87         }
88         return formatter;
89     }
90
91     final static void addPhylogeniesToTabs( final Phylogeny[] phys,
92                                             final String default_name,
93                                             final String full_path,
94                                             final Configuration configuration,
95                                             final MainPanel main_panel ) {
96         if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
97             JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
98                     + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
99                     + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
100         }
101         int i = 1;
102         for( final Phylogeny phy : phys ) {
103             if ( !phy.isEmpty() ) {
104                 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
105                     String my_name = "";
106                     String my_name_for_file = "";
107                     if ( phys.length > 1 ) {
108                         if ( !ForesterUtil.isEmpty( default_name ) ) {
109                             my_name = new String( default_name );
110                         }
111                         if ( !ForesterUtil.isEmpty( full_path ) ) {
112                             my_name_for_file = new String( full_path );
113                         }
114                         else if ( !ForesterUtil.isEmpty( default_name ) ) {
115                             my_name_for_file = new String( default_name );
116                         }
117                         String suffix = "";
118                         if ( my_name_for_file.indexOf( '.' ) > 0 ) {
119                             suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
120                                                                  my_name_for_file.length() );
121                             my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
122                         }
123                         if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
124                             my_name_for_file += "_";
125                         }
126                         if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
127                             my_name_for_file += phy.getName().replaceAll( " ", "_" );
128                         }
129                         else if ( phy.getIdentifier() != null ) {
130                             final StringBuffer sb = new StringBuffer();
131                             if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
132                                 sb.append( phy.getIdentifier().getProvider() );
133                                 sb.append( "_" );
134                             }
135                             sb.append( phy.getIdentifier().getValue() );
136                             my_name_for_file += sb;
137                         }
138                         else {
139                             my_name_for_file += i;
140                         }
141                         if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
142                                 && ( phy.getIdentifier() == null ) ) {
143                             my_name = my_name + " [" + i + "]";
144                         }
145                         if ( !ForesterUtil.isEmpty( suffix ) ) {
146                             my_name_for_file += suffix;
147                         }
148                     }
149                     else {
150                         if ( !ForesterUtil.isEmpty( default_name ) ) {
151                             my_name = new String( default_name );
152                         }
153                         my_name_for_file = "";
154                         if ( !ForesterUtil.isEmpty( full_path ) ) {
155                             my_name_for_file = new String( full_path );
156                         }
157                         else if ( !ForesterUtil.isEmpty( default_name ) ) {
158                             my_name_for_file = new String( default_name );
159                         }
160                         if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
161                             if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
162                                 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
163                             }
164                             else if ( phy.getIdentifier() != null ) {
165                                 final StringBuffer sb = new StringBuffer();
166                                 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
167                                     sb.append( phy.getIdentifier().getProvider() );
168                                     sb.append( "_" );
169                                 }
170                                 sb.append( phy.getIdentifier().getValue() );
171                                 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
172                             }
173                         }
174                     }
175                     main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
176                     main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
177                     lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
178                     ++i;
179                 }
180             }
181         }
182     }
183
184     final static void addPhylogenyToPanel( final Phylogeny[] phys,
185                                            final Configuration configuration,
186                                            final MainPanel main_panel ) {
187         final Phylogeny phy = phys[ 0 ];
188         main_panel.addPhylogenyInPanel( phy, configuration );
189         lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
190     }
191
192     final static Color calculateColorFromString( final String str ) {
193         final String species_uc = str.toUpperCase();
194         char first = species_uc.charAt( 0 );
195         char second = ' ';
196         char third = ' ';
197         if ( species_uc.length() > 1 ) {
198             second = species_uc.charAt( 1 );
199             if ( species_uc.length() > 2 ) {
200                 if ( species_uc.indexOf( " " ) > 0 ) {
201                     third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
202                 }
203                 else {
204                     third = species_uc.charAt( 2 );
205                 }
206             }
207         }
208         first = Util.normalizeCharForRGB( first );
209         second = Util.normalizeCharForRGB( second );
210         third = Util.normalizeCharForRGB( third );
211         if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
212             first = 0;
213         }
214         else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
215             second = 255;
216         }
217         return new Color( first, second, third );
218     }
219
220     // Returns true if the specified format name can be written
221     final static boolean canWriteFormat( final String format_name ) {
222         final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
223         return iter.hasNext();
224     }
225
226     final public static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
227         boolean inferred = false;
228         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
229             final PhylogenyNode n = it.next();
230             if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
231                 final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( n );
232                 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
233                     Util.collapseSubtree( n, true );
234                     if ( !n.getNodeData().isHasTaxonomy() ) {
235                         n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
236                                 .getTaxonomy().copy() );
237                     }
238                     inferred = true;
239                 }
240                 else {
241                     n.setCollapse( false );
242                 }
243             }
244         }
245         if ( inferred ) {
246             phy.setRerootable( false );
247         }
248     }
249
250     final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
251         node.setCollapse( collapse );
252         if ( node.isExternal() ) {
253             return;
254         }
255         final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
256         while ( it.hasNext() ) {
257             it.next().setCollapse( collapse );
258         }
259     }
260
261     final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
262         double max_conf = 0.0;
263         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
264             final PhylogenyNode n = it.next();
265             n.getBranchData().setBranchColor( null );
266             if ( n.getBranchData().isHasConfidences() ) {
267                 final double conf = PhylogenyMethods.getConfidenceValue( n );
268                 if ( conf > max_conf ) {
269                     max_conf = conf;
270                 }
271             }
272         }
273         if ( max_conf > 0.0 ) {
274             final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
275             final Color br = tree_panel.getTreeColorSet().getBranchColor();
276             for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
277                 final PhylogenyNode n = it.next();
278                 if ( n.getBranchData().isHasConfidences() ) {
279                     final double conf = PhylogenyMethods.getConfidenceValue( n );
280                     final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
281                     n.getBranchData().setBranchColor( c );
282                     final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
283                     for( final PhylogenyNode desc : descs ) {
284                         desc.getBranchData().setBranchColor( c );
285                     }
286                 }
287             }
288         }
289     }
290
291     final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
292         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
293             it.next().getBranchData().setBranchColor( null );
294         }
295         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
296             final PhylogenyNode n = it.next();
297             if ( !n.getBranchData().isHasBranchColor() ) {
298                 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
299                 if ( tax != null ) {
300                     n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
301                     final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
302                     for( final PhylogenyNode desc : descs ) {
303                         desc.getBranchData()
304                                 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
305                     }
306                 }
307             }
308         }
309     }
310
311     final static String createDescriptionForTab( final Phylogeny phy, final String full_path ) {
312         final StringBuilder desc = new StringBuilder();
313         if ( ( phy != null ) && !phy.isEmpty() ) {
314             if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
315                 desc.append( "name: " );
316                 desc.append( phy.getName() );
317                 desc.append( "; " );
318             }
319             if ( phy.getIdentifier() != null ) {
320                 desc.append( "id: " );
321                 desc.append( phy.getIdentifier() );
322                 desc.append( "; " );
323             }
324             desc.append( "rooted: " );
325             desc.append( phy.isRooted() );
326             desc.append( "; " );
327             desc.append( "rerootable: " );
328             desc.append( phy.isRerootable() );
329             desc.append( "; " );
330             desc.append( "external nodes: " );
331             desc.append( phy.getNumberOfExternalNodes() );
332             desc.append( "; " );
333             desc.append( "branches: " );
334             desc.append( phy.getNumberOfBranches() );
335             desc.append( "; " );
336             desc.append( "maximum descendants: " );
337             desc.append( PhylogenyMethods.calculateMaximumNumberOfDescendantsPerNode( phy ) );
338             if ( !ForesterUtil.isEmpty( full_path ) && ( full_path.length() <= 50 ) ) {
339                 desc.append( "; " );
340                 desc.append( "path: " );
341                 desc.append( full_path );
342             }
343         }
344         return desc.toString();
345     }
346
347     /**
348      * Exits with -1.
349      * 
350      * 
351      * @param message
352      *            to message to be printed
353      */
354     final static void dieWithSystemError( final String message ) {
355         System.out.println();
356         System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
357         System.out.println( "Please contact the authors." );
358         System.out.println( Constants.PRG_NAME + " needs to close." );
359         System.out.println();
360         System.exit( -1 );
361     }
362
363     final static String[] getAvailableFontFamiliesSorted() {
364         return AVAILABLE_FONT_FAMILIES_SORTED;
365     }
366
367     final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
368         boolean inferred = false;
369         for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
370             final PhylogenyNode n = it.next();
371             if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
372                 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
373                 if ( !ForesterUtil.isEmpty( sn ) ) {
374                     n.getNodeData().setTaxonomy( new Taxonomy() );
375                     n.getNodeData().getTaxonomy().setScientificName( sn );
376                     inferred = true;
377                 }
378             }
379         }
380         if ( inferred ) {
381             tree.setRerootable( false );
382         }
383     }
384
385     final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
386         if ( !node.getNodeData().isHasEvent() ) {
387             return false;
388         }
389         if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
390             return false;
391         }
392         return true;
393     }
394
395     final static boolean isJava15() {
396         try {
397             final String s = ForesterUtil.JAVA_VERSION;
398             return s.startsWith( "1.5" );
399         }
400         catch ( final Exception e ) {
401             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
402             return false;
403         }
404     }
405
406     final static boolean isMac() {
407         try {
408             final String s = ForesterUtil.OS_NAME.toLowerCase();
409             return s.startsWith( "mac" );
410         }
411         catch ( final Exception e ) {
412             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
413             return false;
414         }
415     }
416
417     final static boolean isUsOrCanada() {
418         try {
419             if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
420                 return true;
421             }
422         }
423         catch ( final Exception e ) {
424             return false;
425         }
426         return false;
427     }
428
429     final static boolean isWindows() {
430         try {
431             final String s = ForesterUtil.OS_NAME.toLowerCase();
432             return s.indexOf( "win" ) > -1;
433         }
434         catch ( final Exception e ) {
435             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
436             return false;
437         }
438     }
439
440     final static void launchWebBrowser( final URI uri,
441                                         final boolean is_applet,
442                                         final JApplet applet,
443                                         final String frame_name ) throws IOException {
444         if ( is_applet ) {
445             applet.getAppletContext().showDocument( uri.toURL(), frame_name );
446         }
447         else {
448             // This requires Java 1.6:
449             // =======================
450             // boolean no_desktop = false;
451             // try {
452             // if ( Desktop.isDesktopSupported() ) {
453             // System.out.println( "desktop supported" );
454             // final Desktop dt = Desktop.getDesktop();
455             // dt.browse( uri );
456             // }
457             // else {
458             // no_desktop = true;
459             // }
460             // }
461             // catch ( final Exception ex ) {
462             // ex.printStackTrace();
463             // no_desktop = true;
464             // }
465             // catch ( final Error er ) {
466             // er.printStackTrace();
467             // no_desktop = true;
468             // }
469             // if ( no_desktop ) {
470             // System.out.println( "desktop not supported" );
471             try {
472                 openUrlInWebBrowser( uri.toString() );
473             }
474             catch ( final Exception e ) {
475                 throw new IOException( e );
476             }
477             // }
478         }
479     }
480
481     final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
482                                                                       final ControlPanel atv_control,
483                                                                       final Configuration configuration ) {
484         if ( ( t != null ) && !t.isEmpty() ) {
485             if ( !ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
486                 atv_control.setDrawPhylogram( false );
487                 atv_control.setDrawPhylogramEnabled( false );
488             }
489             if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
490                 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
491                     if ( ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
492                         atv_control.setDrawPhylogram( true );
493                         atv_control.setDrawPhylogramEnabled( true );
494                     }
495                     else {
496                         atv_control.setDrawPhylogram( false );
497                     }
498                 }
499             }
500             if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
501                 if ( atv_control.getWriteConfidenceCb() != null ) {
502                     if ( ForesterUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
503                         atv_control.setCheckbox( Configuration.write_confidence_values, true );
504                     }
505                     else {
506                         atv_control.setCheckbox( Configuration.write_confidence_values, false );
507                     }
508                 }
509             }
510             if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
511                 if ( atv_control.getShowEventsCb() != null ) {
512                     if ( ForesterUtil.isHasAtLeastNodeWithEvent( t ) ) {
513                         atv_control.setCheckbox( Configuration.write_events, true );
514                     }
515                     else {
516                         atv_control.setCheckbox( Configuration.write_events, false );
517                     }
518                 }
519             }
520         }
521     }
522
523     final private static char normalizeCharForRGB( char c ) {
524         c -= 65;
525         c *= 10.2;
526         c = c > 255 ? 255 : c;
527         c = c < 0 ? 0 : c;
528         return c;
529     }
530
531     final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
532             SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
533             InvocationTargetException, InterruptedException {
534         final String os = System.getProperty( "os.name" );
535         final Runtime runtime = Runtime.getRuntime();
536         if ( os.toLowerCase().startsWith( "win" ) ) {
537             Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
538         }
539         else if ( isMac() ) {
540             final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
541             final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
542             open_url.invoke( null, new Object[] { url } );
543         }
544         else {
545             final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
546             String browser = null;
547             for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
548                 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
549                     browser = browsers[ i ];
550                 }
551             }
552             if ( browser == null ) {
553                 throw new IOException( "could not find a web browser to open [" + url + "] in" );
554             }
555             else {
556                 runtime.exec( new String[] { browser, url } );
557             }
558         }
559     }
560
561     final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
562         try {
563             Util.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
564         }
565         catch ( final Exception e ) {
566             throw new IOException( e );
567         }
568     }
569
570     final static void printAppletMessage( final String applet_name, final String message ) {
571         System.out.println( "[" + applet_name + "] > " + message );
572     }
573
574     final static void printWarningMessage( final String name, final String message ) {
575         System.out.println( "[" + name + "] > " + message );
576     }
577
578     final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final File file ) throws IOException {
579         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
580         final Phylogeny[] trees = factory.create( file, parser );
581         if ( ( trees == null ) || ( trees.length == 0 ) ) {
582             throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
583         }
584         return trees;
585     }
586
587     final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
588             throws FileNotFoundException, IOException {
589         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
590         PhylogenyParser parser = null;
591         if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
592             parser = new TolParser();
593         }
594         else {
595             parser = ForesterUtil.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
596         }
597         return factory.create( url.openStream(), parser );
598     }
599
600     final static void removeBranchColors( final Phylogeny phy ) {
601         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
602             it.next().getBranchData().setBranchColor( null );
603         }
604     }
605
606     final static void showErrorMessage( final Component parent, final String error_msg ) {
607         printAppletMessage( Constants.PRG_NAME, error_msg );
608         JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
609                 + "] Error", JOptionPane.ERROR_MESSAGE );
610     }
611
612     final static void unexpectedError( final Error err ) {
613         err.printStackTrace();
614         final StringBuffer sb = new StringBuffer();
615         for( final StackTraceElement s : err.getStackTrace() ) {
616             sb.append( s + "\n" );
617         }
618         JOptionPane
619                 .showMessageDialog( null,
620                                     "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
621                                             + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
622                                     "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
623                                     JOptionPane.ERROR_MESSAGE );
624         System.exit( -1 );
625     }
626
627     final static void unexpectedException( final Exception ex ) {
628         ex.printStackTrace();
629         final StringBuffer sb = new StringBuffer();
630         for( final StackTraceElement s : ex.getStackTrace() ) {
631             sb.append( s + "\n" );
632         }
633         JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
634                 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
635                 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
636     }
637
638     final static String writePhylogenyToGraphicsFile( final String file_name,
639                                                       int width,
640                                                       int height,
641                                                       final TreePanel tree_panel,
642                                                       final ControlPanel ac,
643                                                       final GraphicsExportType type,
644                                                       final Options options ) throws IOException {
645         if ( !options.isGraphicsExportUsingActualSize() ) {
646             if ( options.isGraphicsExportVisibleOnly() ) {
647                 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
648             }
649             tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
650             tree_panel.resetPreferredSize();
651             tree_panel.repaint();
652         }
653         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
654                                                                    RenderingHints.VALUE_RENDER_QUALITY );
655         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
656         if ( options.isAntialiasPrint() ) {
657             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
658             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
659         }
660         else {
661             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
662             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
663         }
664         final Phylogeny phylogeny = tree_panel.getPhylogeny();
665         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
666             return "";
667         }
668         final File file = new File( file_name );
669         if ( file.isDirectory() ) {
670             throw new IOException( "\"" + file_name + "\" is a directory" );
671         }
672         Rectangle visible = null;
673         if ( !options.isGraphicsExportUsingActualSize() ) {
674             width = options.getPrintSizeX();
675             height = options.getPrintSizeY();
676         }
677         else if ( options.isGraphicsExportVisibleOnly() ) {
678             visible = tree_panel.getVisibleRect();
679             width = visible.width;
680             height = visible.height;
681         }
682         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
683         Graphics2D g2d = buffered_img.createGraphics();
684         g2d.setRenderingHints( rendering_hints );
685         int x = 0;
686         int y = 0;
687         if ( options.isGraphicsExportVisibleOnly() ) {
688             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
689             g2d.setClip( null );
690             x = visible.x;
691             y = visible.y;
692         }
693         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
694         if ( type == GraphicsExportType.TIFF ) {
695             writeToTiff( file, buffered_img );
696         }
697         else {
698             ImageIO.write( buffered_img, type.toString(), file );
699         }
700         g2d.dispose();
701         System.gc();
702         if ( !options.isGraphicsExportUsingActualSize() ) {
703             tree_panel.getMainPanel().getControlPanel().showWhole();
704         }
705         String msg = file.toString();
706         if ( ( width > 0 ) && ( height > 0 ) ) {
707             msg += " [size: " + width + ", " + height + "]";
708         }
709         return msg;
710     }
711
712     final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
713         // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
714         ImageWriter writer = null;
715         ImageOutputStream ios = null;
716         // Find an appropriate writer:
717         final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
718         if ( it.hasNext() ) {
719             writer = it.next();
720         }
721         else {
722             throw new IOException( "failed to get TIFF image writer" );
723         }
724         // Setup writer:
725         ios = ImageIO.createImageOutputStream( file );
726         writer.setOutput( ios );
727         final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
728         image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
729         // see writeParam.getCompressionTypes() for available compression type
730         // strings.
731         image_write_param.setCompressionType( "PackBits" );
732         final String t[] = image_write_param.getCompressionTypes();
733         for( final String string : t ) {
734             System.out.println( string );
735         }
736         // Convert to an IIOImage:
737         final IIOImage iio_image = new IIOImage( image, null, null );
738         writer.write( null, iio_image, image_write_param );
739     }
740
741     // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
742     // static void openDDBJRest() throws IOException {
743     // //set URL
744     // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
745     // //set parameter
746     // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
747     // //make connection
748     // URLConnection urlc = url.openConnection();
749     // //use post mode
750     // urlc.setDoOutput( true );
751     // urlc.setAllowUserInteraction( false );
752     // //send query
753     // PrintStream ps = new PrintStream( urlc.getOutputStream() );
754     // ps.print( query );
755     // ps.close();
756     // //get result
757     // BufferedReader br = new BufferedReader( new InputStreamReader(
758     // urlc.getInputStream() ) );
759     // String l = null;
760     // while ( ( l = br.readLine() ) != null ) {
761     // System.out.println( l );
762     // }
763     // br.close();
764     // }
765     static enum GraphicsExportType {
766         GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
767
768         private final String _suffix;
769
770         private GraphicsExportType( final String suffix ) {
771             _suffix = suffix;
772         }
773
774         @Override
775         public String toString() {
776             return _suffix;
777         }
778     }
779 }