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.phylogeny.Phylogeny;
61 import org.forester.phylogeny.PhylogenyMethods;
62 import org.forester.phylogeny.PhylogenyNode;
63 import org.forester.phylogeny.data.BranchColor;
64 import org.forester.phylogeny.data.Taxonomy;
65 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
66 import org.forester.phylogeny.factories.PhylogenyFactory;
67 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
68 import org.forester.phylogeny.iterators.PreorderTreeIterator;
69 import org.forester.util.DescriptiveStatistics;
70 import org.forester.util.ForesterUtil;
71
72 public 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 crateBasicInformation( final Phylogeny phy ) {
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( "\n" );
318             }
319             if ( phy.getIdentifier() != null ) {
320                 desc.append( "Id: " );
321                 desc.append( phy.getIdentifier() );
322                 desc.append( "\n" );
323             }
324             desc.append( "Rooted: " );
325             desc.append( phy.isRooted() );
326             desc.append( "\n" );
327             desc.append( "Rerootable: " );
328             desc.append( phy.isRerootable() );
329             desc.append( "\n" );
330             desc.append( "Node sum: " );
331             desc.append( phy.getNodeCount() );
332             desc.append( "\n" );
333             desc.append( "External node sum: " );
334             desc.append( phy.getNumberOfExternalNodes() );
335             desc.append( "\n" );
336             desc.append( "Internal node sum: " );
337             desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
338             desc.append( "\n" );
339             desc.append( "Branche sum: " );
340             desc.append( phy.getNumberOfBranches() );
341             desc.append( "\n" );
342             desc.append( "Depth: " );
343             desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
344             desc.append( "\n" );
345             desc.append( "Maximum distance to root: " );
346             desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
347             desc.append( "\n" );
348             desc.append( "Descendants per node statistics: " );
349             final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
350             desc.append( "\n" );
351             desc.append( "    Median: " + ForesterUtil.round( ds.median(), 2 ) );
352             desc.append( "\n" );
353             desc.append( "    Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) );
354             desc.append( "\n" );
355             desc.append( "    SD: " + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) );
356             desc.append( "\n" );
357             desc.append( "    Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
358             desc.append( "\n" );
359             desc.append( "    Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
360             desc.append( "\n" );
361             final DescriptiveStatistics cs = PhylogenyMethods.calculatConfidenceStatistics( phy );
362             if ( cs.getN() > 1 ) {
363                 desc.append( "Support statistics: " );
364                 desc.append( "\n" );
365                 desc.append( "    Branches with support: " + cs.getN() );
366                 desc.append( "\n" );
367                 desc.append( "    Median: " + ForesterUtil.round( cs.median(), 6 ) );
368                 desc.append( "\n" );
369                 desc.append( "    Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
370                 desc.append( "\n" );
371                 if ( cs.getN() > 2 ) {
372                     desc.append( "    SD: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) );
373                     desc.append( "\n" );
374                 }
375                 desc.append( "    Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
376                 desc.append( "\n" );
377                 desc.append( "    Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
378                 desc.append( "\n" );
379             }
380             final Set<Taxonomy> taxs = PhylogenyMethods.obtainDistinctTaxonomies( phy.getRoot() );
381             if ( taxs != null ) {
382                 desc.append( "Distinct external taxonomies: " );
383                 desc.append( taxs.size() );
384             }
385         }
386         return desc.toString();
387     }
388
389     /**
390      * Exits with -1.
391      * 
392      * 
393      * @param message
394      *            to message to be printed
395      */
396     final static void dieWithSystemError( final String message ) {
397         System.out.println();
398         System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
399         System.out.println( "Please contact the authors." );
400         System.out.println( Constants.PRG_NAME + " needs to close." );
401         System.out.println();
402         System.exit( -1 );
403     }
404
405     final static String[] getAvailableFontFamiliesSorted() {
406         return AVAILABLE_FONT_FAMILIES_SORTED;
407     }
408
409     final static void inferCommonPartOfScientificNames( final Phylogeny tree ) {
410         boolean inferred = false;
411         for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
412             final PhylogenyNode n = it.next();
413             if ( !n.getNodeData().isHasTaxonomy() && !n.isExternal() ) {
414                 final String sn = PhylogenyMethods.inferCommonPartOfScientificNameOfDescendants( n );
415                 if ( !ForesterUtil.isEmpty( sn ) ) {
416                     n.getNodeData().setTaxonomy( new Taxonomy() );
417                     n.getNodeData().getTaxonomy().setScientificName( sn );
418                     inferred = true;
419                 }
420             }
421         }
422         if ( inferred ) {
423             tree.setRerootable( false );
424         }
425     }
426
427     final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
428         if ( !node.getNodeData().isHasEvent() ) {
429             return false;
430         }
431         if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
432             return false;
433         }
434         return true;
435     }
436
437     final static boolean isJava15() {
438         try {
439             final String s = ForesterUtil.JAVA_VERSION;
440             return s.startsWith( "1.5" );
441         }
442         catch ( final Exception e ) {
443             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
444             return false;
445         }
446     }
447
448     final static boolean isMac() {
449         try {
450             final String s = ForesterUtil.OS_NAME.toLowerCase();
451             return s.startsWith( "mac" );
452         }
453         catch ( final Exception e ) {
454             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
455             return false;
456         }
457     }
458
459     final static boolean isUsOrCanada() {
460         try {
461             if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
462                 return true;
463             }
464         }
465         catch ( final Exception e ) {
466             return false;
467         }
468         return false;
469     }
470
471     final static boolean isWindows() {
472         try {
473             final String s = ForesterUtil.OS_NAME.toLowerCase();
474             return s.indexOf( "win" ) > -1;
475         }
476         catch ( final Exception e ) {
477             ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
478             return false;
479         }
480     }
481
482     final static void launchWebBrowser( final URI uri,
483                                         final boolean is_applet,
484                                         final JApplet applet,
485                                         final String frame_name ) throws IOException {
486         if ( is_applet ) {
487             applet.getAppletContext().showDocument( uri.toURL(), frame_name );
488         }
489         else {
490             // This requires Java 1.6:
491             // =======================
492             // boolean no_desktop = false;
493             // try {
494             // if ( Desktop.isDesktopSupported() ) {
495             // System.out.println( "desktop supported" );
496             // final Desktop dt = Desktop.getDesktop();
497             // dt.browse( uri );
498             // }
499             // else {
500             // no_desktop = true;
501             // }
502             // }
503             // catch ( final Exception ex ) {
504             // ex.printStackTrace();
505             // no_desktop = true;
506             // }
507             // catch ( final Error er ) {
508             // er.printStackTrace();
509             // no_desktop = true;
510             // }
511             // if ( no_desktop ) {
512             // System.out.println( "desktop not supported" );
513             try {
514                 openUrlInWebBrowser( uri.toString() );
515             }
516             catch ( final Exception e ) {
517                 throw new IOException( e );
518             }
519             // }
520         }
521     }
522
523     final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
524                                                                       final ControlPanel atv_control,
525                                                                       final Configuration configuration ) {
526         if ( ( t != null ) && !t.isEmpty() ) {
527             if ( !ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
528                 atv_control.setDrawPhylogram( false );
529                 atv_control.setDrawPhylogramEnabled( false );
530             }
531             if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
532                 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
533                     if ( ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
534                         atv_control.setDrawPhylogram( true );
535                         atv_control.setDrawPhylogramEnabled( true );
536                     }
537                     else {
538                         atv_control.setDrawPhylogram( false );
539                     }
540                 }
541             }
542             if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
543                 if ( atv_control.getWriteConfidenceCb() != null ) {
544                     if ( ForesterUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
545                         atv_control.setCheckbox( Configuration.write_confidence_values, true );
546                     }
547                     else {
548                         atv_control.setCheckbox( Configuration.write_confidence_values, false );
549                     }
550                 }
551             }
552             if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
553                 if ( atv_control.getShowEventsCb() != null ) {
554                     if ( ForesterUtil.isHasAtLeastNodeWithEvent( t ) ) {
555                         atv_control.setCheckbox( Configuration.write_events, true );
556                     }
557                     else {
558                         atv_control.setCheckbox( Configuration.write_events, false );
559                     }
560                 }
561             }
562         }
563     }
564
565     final private static char normalizeCharForRGB( char c ) {
566         c -= 65;
567         c *= 10.2;
568         c = c > 255 ? 255 : c;
569         c = c < 0 ? 0 : c;
570         return c;
571     }
572
573     final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
574             SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
575             InvocationTargetException, InterruptedException {
576         final String os = System.getProperty( "os.name" );
577         final Runtime runtime = Runtime.getRuntime();
578         if ( os.toLowerCase().startsWith( "win" ) ) {
579             Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
580         }
581         else if ( isMac() ) {
582             final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
583             final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
584             open_url.invoke( null, new Object[] { url } );
585         }
586         else {
587             final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
588             String browser = null;
589             for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
590                 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
591                     browser = browsers[ i ];
592                 }
593             }
594             if ( browser == null ) {
595                 throw new IOException( "could not find a web browser to open [" + url + "] in" );
596             }
597             else {
598                 runtime.exec( new String[] { browser, url } );
599             }
600         }
601     }
602
603     final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
604         try {
605             Util.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
606         }
607         catch ( final Exception e ) {
608             throw new IOException( e );
609         }
610     }
611
612     final static void printAppletMessage( final String applet_name, final String message ) {
613         System.out.println( "[" + applet_name + "] > " + message );
614     }
615
616     public final static void printWarningMessage( final String name, final String message ) {
617         System.out.println( "[" + name + "] > " + message );
618     }
619
620     final static Phylogeny[] readPhylogeniesFromUrl( final URL url, final boolean phyloxml_validate_against_xsd )
621             throws FileNotFoundException, IOException {
622         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
623         PhylogenyParser parser = null;
624         if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
625             parser = new TolParser();
626         }
627         else {
628             parser = ForesterUtil.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
629         }
630         return factory.create( url.openStream(), parser );
631     }
632
633     final static void removeBranchColors( final Phylogeny phy ) {
634         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
635             it.next().getBranchData().setBranchColor( null );
636         }
637     }
638
639     final static void showErrorMessage( final Component parent, final String error_msg ) {
640         printAppletMessage( Constants.PRG_NAME, error_msg );
641         JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
642                 + "] Error", JOptionPane.ERROR_MESSAGE );
643     }
644
645     final static void unexpectedError( final Error err ) {
646         err.printStackTrace();
647         final StringBuffer sb = new StringBuffer();
648         for( final StackTraceElement s : err.getStackTrace() ) {
649             sb.append( s + "\n" );
650         }
651         JOptionPane
652                 .showMessageDialog( null,
653                                     "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
654                                             + Constants.AUTHOR_EMAIL + " \nError: " + err + "\n" + sb,
655                                     "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
656                                     JOptionPane.ERROR_MESSAGE );
657         System.exit( -1 );
658     }
659
660     final static void unexpectedException( final Exception ex ) {
661         ex.printStackTrace();
662         final StringBuffer sb = new StringBuffer();
663         for( final StackTraceElement s : ex.getStackTrace() ) {
664             sb.append( s + "\n" );
665         }
666         JOptionPane.showMessageDialog( null, "An unexpected exception has occured. \nPlease contact: "
667                 + Constants.AUTHOR_EMAIL + " \nException: " + ex + "\n" + sb, "Unexpected Exception ["
668                 + Constants.PRG_NAME + Constants.VERSION + "]", JOptionPane.ERROR_MESSAGE );
669     }
670
671     final static String writePhylogenyToGraphicsFile( final String file_name,
672                                                       int width,
673                                                       int height,
674                                                       final TreePanel tree_panel,
675                                                       final ControlPanel ac,
676                                                       final GraphicsExportType type,
677                                                       final Options options ) throws IOException {
678         if ( !options.isGraphicsExportUsingActualSize() ) {
679             if ( options.isGraphicsExportVisibleOnly() ) {
680                 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
681             }
682             tree_panel.setParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
683             tree_panel.resetPreferredSize();
684             tree_panel.repaint();
685         }
686         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
687                                                                    RenderingHints.VALUE_RENDER_QUALITY );
688         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
689         if ( options.isAntialiasPrint() ) {
690             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
691             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
692         }
693         else {
694             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
695             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
696         }
697         final Phylogeny phylogeny = tree_panel.getPhylogeny();
698         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
699             return "";
700         }
701         final File file = new File( file_name );
702         if ( file.isDirectory() ) {
703             throw new IOException( "\"" + file_name + "\" is a directory" );
704         }
705         Rectangle visible = null;
706         if ( !options.isGraphicsExportUsingActualSize() ) {
707             width = options.getPrintSizeX();
708             height = options.getPrintSizeY();
709         }
710         else if ( options.isGraphicsExportVisibleOnly() ) {
711             visible = tree_panel.getVisibleRect();
712             width = visible.width;
713             height = visible.height;
714         }
715         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
716         Graphics2D g2d = buffered_img.createGraphics();
717         g2d.setRenderingHints( rendering_hints );
718         int x = 0;
719         int y = 0;
720         if ( options.isGraphicsExportVisibleOnly() ) {
721             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
722             g2d.setClip( null );
723             x = visible.x;
724             y = visible.y;
725         }
726         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
727         if ( type == GraphicsExportType.TIFF ) {
728             writeToTiff( file, buffered_img );
729         }
730         else {
731             ImageIO.write( buffered_img, type.toString(), file );
732         }
733         g2d.dispose();
734         System.gc();
735         if ( !options.isGraphicsExportUsingActualSize() ) {
736             tree_panel.getMainPanel().getControlPanel().showWhole();
737         }
738         String msg = file.toString();
739         if ( ( width > 0 ) && ( height > 0 ) ) {
740             msg += " [size: " + width + ", " + height + "]";
741         }
742         return msg;
743     }
744
745     final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
746         // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
747         ImageWriter writer = null;
748         ImageOutputStream ios = null;
749         // Find an appropriate writer:
750         final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
751         if ( it.hasNext() ) {
752             writer = it.next();
753         }
754         else {
755             throw new IOException( "failed to get TIFF image writer" );
756         }
757         // Setup writer:
758         ios = ImageIO.createImageOutputStream( file );
759         writer.setOutput( ios );
760         final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
761         image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
762         // see writeParam.getCompressionTypes() for available compression type
763         // strings.
764         image_write_param.setCompressionType( "PackBits" );
765         final String t[] = image_write_param.getCompressionTypes();
766         for( final String string : t ) {
767             System.out.println( string );
768         }
769         // Convert to an IIOImage:
770         final IIOImage iio_image = new IIOImage( image, null, null );
771         writer.write( null, iio_image, image_write_param );
772     }
773
774     // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
775     // static void openDDBJRest() throws IOException {
776     // //set URL
777     // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
778     // //set parameter
779     // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
780     // //make connection
781     // URLConnection urlc = url.openConnection();
782     // //use post mode
783     // urlc.setDoOutput( true );
784     // urlc.setAllowUserInteraction( false );
785     // //send query
786     // PrintStream ps = new PrintStream( urlc.getOutputStream() );
787     // ps.print( query );
788     // ps.close();
789     // //get result
790     // BufferedReader br = new BufferedReader( new InputStreamReader(
791     // urlc.getInputStream() ) );
792     // String l = null;
793     // while ( ( l = br.readLine() ) != null ) {
794     // System.out.println( l );
795     // }
796     // br.close();
797     // }
798     static enum GraphicsExportType {
799         GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
800
801         private final String _suffix;
802
803         private GraphicsExportType( final String suffix ) {
804             _suffix = suffix;
805         }
806
807         @Override
808         public String toString() {
809             return _suffix;
810         }
811     }
812 }