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