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