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