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