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