3ba5102d0b42735bb8fe6b1d5be524e15a59b818
[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.Color;
29 import java.awt.Component;
30 import java.awt.Graphics2D;
31 import java.awt.GraphicsEnvironment;
32 import java.awt.Rectangle;
33 import java.awt.RenderingHints;
34 import java.awt.image.BufferedImage;
35 import java.io.ByteArrayOutputStream;
36 import java.io.File;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.io.UnsupportedEncodingException;
40 import java.lang.reflect.InvocationTargetException;
41 import java.lang.reflect.Method;
42 import java.net.URI;
43 import java.net.URL;
44 import java.net.URLEncoder;
45 import java.text.ParseException;
46 import java.util.Arrays;
47 import java.util.HashMap;
48 import java.util.HashSet;
49 import java.util.Iterator;
50 import java.util.List;
51 import java.util.Locale;
52 import java.util.Map;
53 import java.util.Set;
54 import java.util.SortedSet;
55 import java.util.TreeSet;
56 import java.util.regex.Matcher;
57 import java.util.regex.Pattern;
58
59 import javax.imageio.IIOImage;
60 import javax.imageio.ImageIO;
61 import javax.imageio.ImageWriteParam;
62 import javax.imageio.ImageWriter;
63 import javax.imageio.stream.ImageOutputStream;
64 import javax.swing.JApplet;
65 import javax.swing.JOptionPane;
66 import javax.swing.text.MaskFormatter;
67
68 import org.forester.analysis.TaxonomyDataManager;
69 import org.forester.io.parsers.PhylogenyParser;
70 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
71 import org.forester.io.parsers.nhx.NHXParser;
72 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
73 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
74 import org.forester.io.parsers.tol.TolParser;
75 import org.forester.io.parsers.util.ParserUtils;
76 import org.forester.phylogeny.Phylogeny;
77 import org.forester.phylogeny.PhylogenyMethods;
78 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
79 import org.forester.phylogeny.PhylogenyNode;
80 import org.forester.phylogeny.data.Accession;
81 import org.forester.phylogeny.data.BranchColor;
82 import org.forester.phylogeny.data.Taxonomy;
83 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
84 import org.forester.phylogeny.factories.PhylogenyFactory;
85 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
86 import org.forester.phylogeny.iterators.PreorderTreeIterator;
87 import org.forester.util.AsciiHistogram;
88 import org.forester.util.DescriptiveStatistics;
89 import org.forester.util.ForesterConstants;
90 import org.forester.util.ForesterUtil;
91 import org.forester.util.SequenceIdParser;
92 import org.forester.ws.seqdb.UniProtTaxonomy;
93
94 public final class AptxUtil {
95
96     private final static Pattern  seq_identifier_pattern_1       = Pattern
97                                                                          .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})\\s*$" );
98     private final static Pattern  seq_identifier_pattern_2       = Pattern
99                                                                          .compile( "^([A-Za-z]{2,5})[|=:]([0-9A-Za-z_\\.]{5,40})[|,; ].*$" );
100     private final static String[] AVAILABLE_FONT_FAMILIES_SORTED = GraphicsEnvironment.getLocalGraphicsEnvironment()
101                                                                          .getAvailableFontFamilyNames();
102     static {
103         Arrays.sort( AVAILABLE_FONT_FAMILIES_SORTED );
104     }
105
106     public final static String createUriForSeqWeb( final PhylogenyNode node,
107                                                    final Configuration conf,
108                                                    final TreePanel tp ) {
109         String uri_str = null;
110         final String upkb = ForesterUtil.extractUniProtKbProteinSeqIdentifier( node );
111         if ( !ForesterUtil.isEmpty( upkb ) ) {
112             try {
113                 uri_str = ForesterUtil.UNIPROT_KB + URLEncoder.encode( upkb, ForesterConstants.UTF8 );
114             }
115             catch ( final UnsupportedEncodingException e ) {
116                 showErrorMessage( tp, e.toString() );
117                 e.printStackTrace();
118             }
119         }
120         if ( ForesterUtil.isEmpty( uri_str ) ) {
121             final String v = ForesterUtil.extractGenbankAccessor( node );
122             if ( !ForesterUtil.isEmpty( v ) ) {
123                 try {
124                     if ( SequenceIdParser.isProtein( v ) ) {
125                         uri_str = ForesterUtil.NCBI_PROTEIN + URLEncoder.encode( v, ForesterConstants.UTF8 );
126                     }
127                     else {
128                         uri_str = ForesterUtil.NCBI_NUCCORE + URLEncoder.encode( v, ForesterConstants.UTF8 );
129                     }
130                 }
131                 catch ( final UnsupportedEncodingException e ) {
132                     showErrorMessage( tp, e.toString() );
133                     e.printStackTrace();
134                 }
135             }
136         }
137         if ( ForesterUtil.isEmpty( uri_str ) ) {
138             final String v = ForesterUtil.extractRefSeqAccessorAccessor( node );
139             if ( !ForesterUtil.isEmpty( v ) ) {
140                 try {
141                     if ( SequenceIdParser.isProtein( v ) ) {
142                         uri_str = ForesterUtil.NCBI_PROTEIN + URLEncoder.encode( v, ForesterConstants.UTF8 );
143                     }
144                     else {
145                         uri_str = ForesterUtil.NCBI_NUCCORE + URLEncoder.encode( v, ForesterConstants.UTF8 );
146                     }
147                 }
148                 catch ( final UnsupportedEncodingException e ) {
149                     showErrorMessage( tp, e.toString() );
150                     e.printStackTrace();
151                 }
152             }
153         }
154         if ( ForesterUtil.isEmpty( uri_str ) ) {
155             final String v = ForesterUtil.extractGInumber( node );
156             if ( !ForesterUtil.isEmpty( v ) ) {
157                 try {
158                     uri_str = ForesterUtil.NCBI_GI + URLEncoder.encode( v, ForesterConstants.UTF8 );
159                 }
160                 catch ( final UnsupportedEncodingException e ) {
161                     showErrorMessage( tp, e.toString() );
162                     e.printStackTrace();
163                 }
164             }
165         }
166         return uri_str;
167     }
168
169     public static MaskFormatter createMaskFormatter( final String s ) {
170         MaskFormatter formatter = null;
171         try {
172             formatter = new MaskFormatter( s );
173         }
174         catch ( final ParseException e ) {
175             throw new IllegalArgumentException( e );
176         }
177         return formatter;
178     }
179
180     final static public boolean isHasAtLeastNodeWithEvent( final Phylogeny phy ) {
181         final PhylogenyNodeIterator it = phy.iteratorPostorder();
182         while ( it.hasNext() ) {
183             if ( it.next().getNodeData().isHasEvent() ) {
184                 return true;
185             }
186         }
187         return false;
188     }
189
190     /**
191      * Returns true if at least one branch has a length larger than zero.
192      * 
193      * 
194      * @param phy
195      */
196     final static public boolean isHasAtLeastOneBranchLengthLargerThanZero( final Phylogeny phy ) {
197         final PhylogenyNodeIterator it = phy.iteratorPostorder();
198         while ( it.hasNext() ) {
199             if ( it.next().getDistanceToParent() > 0.0 ) {
200                 return true;
201             }
202         }
203         return false;
204     }
205
206     final static public boolean isHasAtLeastOneBranchWithSupportValues( final Phylogeny phy ) {
207         final PhylogenyNodeIterator it = phy.iteratorPostorder();
208         while ( it.hasNext() ) {
209             if ( it.next().getBranchData().isHasConfidences() ) {
210                 return true;
211             }
212         }
213         return false;
214     }
215
216     final public static void launchWebBrowser( final URI uri,
217                                                final boolean is_applet,
218                                                final JApplet applet,
219                                                final String frame_name ) throws IOException {
220         if ( is_applet ) {
221             applet.getAppletContext().showDocument( uri.toURL(), frame_name );
222         }
223         else {
224             // This requires Java 1.6:
225             // =======================
226             // boolean no_desktop = false;
227             // try {
228             // if ( Desktop.isDesktopSupported() ) {
229             // System.out.println( "desktop supported" );
230             // final Desktop dt = Desktop.getDesktop();
231             // dt.browse( uri );
232             // }
233             // else {
234             // no_desktop = true;
235             // }
236             // }
237             // catch ( final Exception ex ) {
238             // ex.printStackTrace();
239             // no_desktop = true;
240             // }
241             // catch ( final Error er ) {
242             // er.printStackTrace();
243             // no_desktop = true;
244             // }
245             // if ( no_desktop ) {
246             // System.out.println( "desktop not supported" );
247             try {
248                 openUrlInWebBrowser( uri.toString() );
249             }
250             catch ( final Exception e ) {
251                 throw new IOException( e );
252             }
253             // }
254         }
255     }
256
257     public static Set<Taxonomy> obtainAllDistinctTaxonomies( final PhylogenyNode node ) {
258         final List<PhylogenyNode> descs = node.getAllExternalDescendants();
259         final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
260         for( final PhylogenyNode n : descs ) {
261             if ( n.getNodeData().isHasTaxonomy() && !n.getNodeData().getTaxonomy().isEmpty() ) {
262                 tax_set.add( n.getNodeData().getTaxonomy() );
263             }
264         }
265         return tax_set;
266     }
267
268     /**
269      * Returns the set of distinct taxonomies of
270      * all external nodes of node.
271      * If at least one the external nodes has no taxonomy,
272      * null is returned.
273      * 
274      */
275     public static Set<Taxonomy> obtainDistinctTaxonomies( final PhylogenyNode node ) {
276         final List<PhylogenyNode> descs = node.getAllExternalDescendants();
277         final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
278         for( final PhylogenyNode n : descs ) {
279             if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
280                 return null;
281             }
282             tax_set.add( n.getNodeData().getTaxonomy() );
283         }
284         return tax_set;
285     }
286
287     public final static Accession obtainSequenceAccessionFromName( final String sequence_name ) {
288         final String n = sequence_name.trim();
289         final Matcher matcher1 = seq_identifier_pattern_1.matcher( n );
290         String group1 = "";
291         String group2 = "";
292         if ( matcher1.matches() ) {
293             group1 = matcher1.group( 1 );
294             group2 = matcher1.group( 2 );
295         }
296         else {
297             final Matcher matcher2 = seq_identifier_pattern_2.matcher( n );
298             if ( matcher2.matches() ) {
299                 group1 = matcher2.group( 1 );
300                 group2 = matcher2.group( 2 );
301             }
302         }
303         if ( ForesterUtil.isEmpty( group1 ) || ForesterUtil.isEmpty( group2 ) ) {
304             return null;
305         }
306         return new Accession( group2, group1 );
307     }
308
309     public final static void printWarningMessage( final String name, final String message ) {
310         System.out.println( "[" + name + "] > " + message );
311     }
312
313     final public static void showErrorMessage( final Component parent, final String error_msg ) {
314         printAppletMessage( Constants.PRG_NAME, error_msg );
315         JOptionPane.showMessageDialog( parent, error_msg, "[" + Constants.PRG_NAME + " " + Constants.VERSION
316                 + "] Error", JOptionPane.ERROR_MESSAGE );
317     }
318
319     public final static void showExtDescNodeDataUserSelectedHelper( final ControlPanel cp,
320                                                                     final PhylogenyNode node,
321                                                                     final List<String> data ) {
322         final StringBuilder sb = new StringBuilder();
323         if ( cp.isShowNodeNames() && !ForesterUtil.isEmpty( node.getName() ) ) {
324             showExtDescNodeDataUserSelectedHelperHelper( node.getName(), sb );
325         }
326         if ( cp.isShowGeneNames() && node.getNodeData().isHasSequence()
327                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) ) {
328             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getName(), sb );
329         }
330         if ( cp.isShowGeneSymbols() && node.getNodeData().isHasSequence()
331                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getSymbol() ) ) {
332             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getSymbol(), sb );
333         }
334         if ( cp.isShowSequenceAcc() && node.getNodeData().isHasSequence()
335                 && ( node.getNodeData().getSequence().getAccession() != null )
336                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().toString() ) ) {
337             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getAccession().toString(), sb );
338         }
339         if ( cp.isShowTaxonomyCode() && node.getNodeData().isHasTaxonomy()
340                 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
341             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getTaxonomyCode(), sb );
342         }
343         if ( cp.isShowTaxonomyScientificNames() && node.getNodeData().isHasTaxonomy()
344                 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
345             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getScientificName(), sb );
346         }
347         if ( cp.isShowTaxonomyCommonNames() && node.getNodeData().isHasTaxonomy()
348                 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getCommonName() ) ) {
349             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getCommonName(), sb );
350         }
351         if ( ( cp.isShowGeneNames() || cp.isShowGeneSymbols() || cp.isShowSequenceAcc() )
352                 && node.getNodeData().isHasSequence()
353                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getMolecularSequence() ) ) {
354             showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getMolecularSequence(), sb );
355         }
356         final String s = sb.toString().trim();
357         if ( !ForesterUtil.isEmpty( s ) ) {
358             data.add( s );
359         }
360     }
361
362     public final static void showExtDescNodeDataUserSelectedHelperHelper( final String s, final StringBuilder sb ) {
363         if ( sb.length() > 0 ) {
364             sb.append( "\t" );
365         }
366         sb.append( s );
367     }
368
369     final public static void showInformationMessage( final Component parent, final String title, final String msg ) {
370         JOptionPane.showMessageDialog( parent, msg, title, JOptionPane.INFORMATION_MESSAGE );
371     }
372
373     public static void writePhylogenyToGraphicsFile( final File intree,
374                                                      final File outfile,
375                                                      final int width,
376                                                      final int height,
377                                                      final GraphicsExportType type,
378                                                      final Configuration config ) throws IOException {
379         final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( intree, true );
380         Phylogeny[] phys = null;
381         phys = PhylogenyMethods.readPhylogenies( parser, intree );
382         writePhylogenyToGraphicsFile( phys[ 0 ], outfile, width, height, type, config );
383     }
384
385     public static void writePhylogenyToGraphicsFile( final Phylogeny phy,
386                                                      final File outfile,
387                                                      final int width,
388                                                      final int height,
389                                                      final GraphicsExportType type,
390                                                      final Configuration config ) throws IOException {
391         final Phylogeny[] phys = new Phylogeny[ 1 ];
392         phys[ 0 ] = phy;
393         final MainFrameApplication mf = MainFrameApplication.createInstance( phys, config );
394         AptxUtil.writePhylogenyToGraphicsFileNonInteractive( outfile, width, height, mf.getMainPanel()
395                 .getCurrentTreePanel(), mf.getMainPanel().getControlPanel(), type, mf.getOptions() );
396         mf.end();
397     }
398
399     public final static void writePhylogenyToGraphicsFileNonInteractive( final File outfile,
400                                                                          final int width,
401                                                                          final int height,
402                                                                          final TreePanel tree_panel,
403                                                                          final ControlPanel ac,
404                                                                          final GraphicsExportType type,
405                                                                          final Options options ) throws IOException {
406         tree_panel.calcParametersForPainting( width, height, true );
407         tree_panel.resetPreferredSize();
408         tree_panel.repaint();
409         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
410                                                                    RenderingHints.VALUE_RENDER_QUALITY );
411         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
412         if ( options.isAntialiasPrint() ) {
413             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
414             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
415         }
416         else {
417             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
418             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
419         }
420         final Phylogeny phylogeny = tree_panel.getPhylogeny();
421         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
422             return;
423         }
424         if ( outfile.isDirectory() ) {
425             throw new IOException( "\"" + outfile + "\" is a directory" );
426         }
427         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
428         final Graphics2D g2d = buffered_img.createGraphics();
429         g2d.setRenderingHints( rendering_hints );
430         tree_panel.paintPhylogeny( g2d, false, true, width, height, 0, 0 );
431         if ( type == GraphicsExportType.TIFF ) {
432             writeToTiff( outfile, buffered_img );
433         }
434         else {
435             ImageIO.write( buffered_img, type.toString(), outfile );
436         }
437         g2d.dispose();
438     }
439
440     final static void addPhylogeniesToTabs( final Phylogeny[] phys,
441                                             final String default_name,
442                                             final String full_path,
443                                             final Configuration configuration,
444                                             final MainPanel main_panel ) {
445         if ( phys.length > Constants.MAX_TREES_TO_LOAD ) {
446             JOptionPane.showMessageDialog( main_panel, "Attempt to load " + phys.length
447                     + " phylogenies,\ngoing to load only the first " + Constants.MAX_TREES_TO_LOAD, Constants.PRG_NAME
448                     + " more than " + Constants.MAX_TREES_TO_LOAD + " phylogenies", JOptionPane.WARNING_MESSAGE );
449         }
450         int i = 1;
451         for( final Phylogeny phy : phys ) {
452             if ( !phy.isEmpty() ) {
453                 if ( i <= Constants.MAX_TREES_TO_LOAD ) {
454                     String my_name = "";
455                     String my_name_for_file = "";
456                     if ( phys.length > 1 ) {
457                         if ( !ForesterUtil.isEmpty( default_name ) ) {
458                             my_name = new String( default_name );
459                         }
460                         if ( !ForesterUtil.isEmpty( full_path ) ) {
461                             my_name_for_file = new String( full_path );
462                         }
463                         else if ( !ForesterUtil.isEmpty( default_name ) ) {
464                             my_name_for_file = new String( default_name );
465                         }
466                         String suffix = "";
467                         if ( my_name_for_file.indexOf( '.' ) > 0 ) {
468                             suffix = my_name_for_file.substring( my_name_for_file.lastIndexOf( '.' ),
469                                                                  my_name_for_file.length() );
470                             my_name_for_file = my_name_for_file.substring( 0, my_name_for_file.lastIndexOf( '.' ) );
471                         }
472                         if ( !ForesterUtil.isEmpty( my_name_for_file ) ) {
473                             my_name_for_file += "_";
474                         }
475                         if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
476                             my_name_for_file += phy.getName().replaceAll( " ", "_" );
477                         }
478                         else if ( phy.getIdentifier() != null ) {
479                             final StringBuffer sb = new StringBuffer();
480                             if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
481                                 sb.append( phy.getIdentifier().getProvider() );
482                                 sb.append( "_" );
483                             }
484                             sb.append( phy.getIdentifier().getValue() );
485                             my_name_for_file += sb;
486                         }
487                         else {
488                             my_name_for_file += i;
489                         }
490                         if ( !ForesterUtil.isEmpty( my_name ) && ForesterUtil.isEmpty( phy.getName() )
491                                 && ( phy.getIdentifier() == null ) ) {
492                             my_name = my_name + " [" + i + "]";
493                         }
494                         if ( !ForesterUtil.isEmpty( suffix ) ) {
495                             my_name_for_file += suffix;
496                         }
497                     }
498                     else {
499                         if ( !ForesterUtil.isEmpty( default_name ) ) {
500                             my_name = new String( default_name );
501                         }
502                         my_name_for_file = "";
503                         if ( !ForesterUtil.isEmpty( full_path ) ) {
504                             my_name_for_file = new String( full_path );
505                         }
506                         else if ( !ForesterUtil.isEmpty( default_name ) ) {
507                             my_name_for_file = new String( default_name );
508                         }
509                         if ( ForesterUtil.isEmpty( my_name_for_file ) ) {
510                             if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
511                                 my_name_for_file = new String( phy.getName() ).replaceAll( " ", "_" );
512                             }
513                             else if ( phy.getIdentifier() != null ) {
514                                 final StringBuffer sb = new StringBuffer();
515                                 if ( !ForesterUtil.isEmpty( phy.getIdentifier().getProvider() ) ) {
516                                     sb.append( phy.getIdentifier().getProvider() );
517                                     sb.append( "_" );
518                                 }
519                                 sb.append( phy.getIdentifier().getValue() );
520                                 my_name_for_file = new String( sb.toString().replaceAll( " ", "_" ) );
521                             }
522                         }
523                     }
524                     main_panel.addPhylogenyInNewTab( phy, configuration, my_name, full_path );
525                     main_panel.getCurrentTreePanel().setTreeFile( new File( my_name_for_file ) );
526                     lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
527                     ++i;
528                 }
529             }
530         }
531     }
532
533     final static void addPhylogenyToPanel( final Phylogeny[] phys,
534                                            final Configuration configuration,
535                                            final MainPanel main_panel ) {
536         final Phylogeny phy = phys[ 0 ];
537         main_panel.addPhylogenyInPanel( phy, configuration );
538         lookAtSomeTreePropertiesForAptxControlSettings( phy, main_panel.getControlPanel(), configuration );
539     }
540
541     final static Color calculateColorFromString( final String str ) {
542         final String species_uc = str.toUpperCase();
543         char first = species_uc.charAt( 0 );
544         char second = ' ';
545         char third = ' ';
546         if ( species_uc.length() > 1 ) {
547             second = species_uc.charAt( 1 );
548             if ( species_uc.length() > 2 ) {
549                 if ( species_uc.indexOf( " " ) > 0 ) {
550                     third = species_uc.charAt( species_uc.indexOf( " " ) + 1 );
551                 }
552                 else {
553                     third = species_uc.charAt( 2 );
554                 }
555             }
556         }
557         first = AptxUtil.normalizeCharForRGB( first );
558         second = AptxUtil.normalizeCharForRGB( second );
559         third = AptxUtil.normalizeCharForRGB( third );
560         if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
561             first = 0;
562         }
563         else if ( ( first < 80 ) && ( second < 80 ) && ( third < 80 ) ) {
564             second = 255;
565         }
566         return new Color( first, second, third );
567     }
568
569     // Returns true if the specified format name can be written
570     final static boolean canWriteFormat( final String format_name ) {
571         final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName( format_name );
572         return iter.hasNext();
573     }
574
575     final static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
576         boolean inferred = false;
577         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
578             final PhylogenyNode n = it.next();
579             if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
580                 final Set<Taxonomy> taxs = obtainDistinctTaxonomies( n );
581                 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
582                     AptxUtil.collapseSubtree( n, true );
583                     if ( !n.getNodeData().isHasTaxonomy() ) {
584                         n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
585                                 .getTaxonomy().copy() );
586                     }
587                     inferred = true;
588                 }
589                 else {
590                     n.setCollapse( false );
591                 }
592             }
593         }
594         if ( inferred ) {
595             phy.setRerootable( false );
596         }
597     }
598
599     final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
600         node.setCollapse( collapse );
601         if ( node.isExternal() ) {
602             return;
603         }
604         final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
605         while ( it.hasNext() ) {
606             it.next().setCollapse( collapse );
607         }
608     }
609
610     final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
611         double max_conf = 0.0;
612         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
613             final PhylogenyNode n = it.next();
614             n.getBranchData().setBranchColor( null );
615             if ( n.getBranchData().isHasConfidences() ) {
616                 final double conf = PhylogenyMethods.getConfidenceValue( n );
617                 if ( conf > max_conf ) {
618                     max_conf = conf;
619                 }
620             }
621         }
622         if ( max_conf > 0.0 ) {
623             final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
624             final Color br = tree_panel.getTreeColorSet().getBranchColor();
625             for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
626                 final PhylogenyNode n = it.next();
627                 if ( n.getBranchData().isHasConfidences() ) {
628                     final double conf = PhylogenyMethods.getConfidenceValue( n );
629                     final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
630                     colorizeSubtree( n, c );
631                 }
632             }
633         }
634     }
635
636     final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
637         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
638             it.next().getBranchData().setBranchColor( null );
639         }
640         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
641             final PhylogenyNode n = it.next();
642             if ( !n.getBranchData().isHasBranchColor() ) {
643                 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
644                 if ( tax != null ) {
645                     n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
646                     final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
647                     for( final PhylogenyNode desc : descs ) {
648                         desc.getBranchData()
649                                 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
650                     }
651                 }
652             }
653         }
654     }
655
656     final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
657         final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
658         int colorizations = 0;
659         for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
660             final PhylogenyNode n = it.next();
661             if ( n.getNodeData().isHasTaxonomy()
662                     && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
663                             || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
664                             .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
665                 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
666                         && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
667                     final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
668                             .getTaxonomy() ) );
669                     colorizeSubtree( n, c );
670                     ++colorizations;
671                     if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
672                         true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
673                     }
674                 }
675             }
676         }
677         for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
678             final PhylogenyNode node = it.next();
679             if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
680                     && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
681                 boolean success = false;
682                 if ( !true_lineage_to_color_map.isEmpty() ) {
683                     for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
684                         if ( true_lineage_to_color_map.containsKey( lin ) ) {
685                             colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
686                             ++colorizations;
687                             success = true;
688                             break;
689                         }
690                     }
691                 }
692                 if ( !success ) {
693                     final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
694                     for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
695                         final Taxonomy temp_tax = new Taxonomy();
696                         temp_tax.setScientificName( lin );
697                         if ( lineage_to_rank_map.containsKey( lin )
698                                 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
699                                 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
700                             final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
701                             colorizeSubtree( node, c );
702                             ++colorizations;
703                             true_lineage_to_color_map.put( lin, c.getValue() );
704                             break;
705                         }
706                         else {
707                             UniProtTaxonomy up = null;
708                             try {
709                                 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
710                             }
711                             catch ( final Exception e ) {
712                                 e.printStackTrace();
713                             }
714                             if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
715                                 lineage_to_rank_map.put( lin, up.getRank() );
716                                 if ( up.getRank().equalsIgnoreCase( rank ) ) {
717                                     final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
718                                     colorizeSubtree( node, c );
719                                     ++colorizations;
720                                     true_lineage_to_color_map.put( lin, c.getValue() );
721                                     break;
722                                 }
723                             }
724                         }
725                     }
726                 }
727             }
728         }
729         return colorizations;
730     }
731
732     final static String createBasicInformation( final Phylogeny phy ) {
733         final StringBuilder desc = new StringBuilder();
734         if ( ( phy != null ) && !phy.isEmpty() ) {
735             if ( !ForesterUtil.isEmpty( phy.getName() ) ) {
736                 desc.append( "Name: " );
737                 desc.append( phy.getName() );
738                 desc.append( "\n" );
739             }
740             if ( phy.getIdentifier() != null ) {
741                 desc.append( "Id: " );
742                 desc.append( phy.getIdentifier().toString() );
743                 desc.append( "\n" );
744             }
745             if ( !ForesterUtil.isEmpty( phy.getDescription() ) ) {
746                 desc.append( "Description: " );
747                 desc.append( phy.getDescription() );
748                 desc.append( "\n" );
749             }
750             if ( !ForesterUtil.isEmpty( phy.getDistanceUnit() ) ) {
751                 desc.append( "Distance Unit: " );
752                 desc.append( phy.getDistanceUnit() );
753                 desc.append( "\n" );
754             }
755             if ( !ForesterUtil.isEmpty( phy.getType() ) ) {
756                 desc.append( "Type: " );
757                 desc.append( phy.getType() );
758                 desc.append( "\n" );
759             }
760             desc.append( "Rooted: " );
761             desc.append( phy.isRooted() );
762             desc.append( "\n" );
763             desc.append( "Rerootable: " );
764             desc.append( phy.isRerootable() );
765             desc.append( "\n" );
766             desc.append( "Nodes: " );
767             desc.append( phy.getNodeCount() );
768             desc.append( "\n" );
769             desc.append( "External nodes: " );
770             desc.append( phy.getNumberOfExternalNodes() );
771             desc.append( "\n" );
772             desc.append( "Internal nodes: " );
773             desc.append( phy.getNodeCount() - phy.getNumberOfExternalNodes() );
774             desc.append( "\n" );
775             desc.append( "Internal nodes with polytomies: " );
776             desc.append( PhylogenyMethods.countNumberOfPolytomies( phy ) );
777             desc.append( "\n" );
778             desc.append( "Branches: " );
779             desc.append( phy.getNumberOfBranches() );
780             desc.append( "\n" );
781             desc.append( "Depth: " );
782             desc.append( PhylogenyMethods.calculateMaxDepth( phy ) );
783             desc.append( "\n" );
784             desc.append( "Maximum distance to root: " );
785             desc.append( ForesterUtil.round( PhylogenyMethods.calculateMaxDistanceToRoot( phy ), 6 ) );
786             desc.append( "\n" );
787             final Set<Taxonomy> taxs = obtainAllDistinctTaxonomies( phy.getRoot() );
788             if ( taxs != null ) {
789                 desc.append( "Distinct external taxonomies: " );
790                 desc.append( taxs.size() );
791             }
792             for( final Taxonomy t : taxs ) {
793                 System.out.println( t.toString() );
794             }
795             desc.append( "\n" );
796             final DescriptiveStatistics bs = PhylogenyMethods.calculatBranchLengthStatistics( phy );
797             if ( bs.getN() > 3 ) {
798                 desc.append( "\n" );
799                 desc.append( "Branch-length statistics: " );
800                 desc.append( "\n" );
801                 desc.append( "    Number of branches with non-negative branch-lengths: " + bs.getN() );
802                 desc.append( "\n" );
803                 desc.append( "    Median: " + ForesterUtil.round( bs.median(), 6 ) );
804                 desc.append( "\n" );
805                 desc.append( "    Mean: " + ForesterUtil.round( bs.arithmeticMean(), 6 ) + " (stdev: "
806                         + ForesterUtil.round( bs.sampleStandardDeviation(), 6 ) + ")" );
807                 desc.append( "\n" );
808                 desc.append( "    Minimum: " + ForesterUtil.round( bs.getMin(), 6 ) );
809                 desc.append( "\n" );
810                 desc.append( "    Maximum: " + ForesterUtil.round( bs.getMax(), 6 ) );
811                 desc.append( "\n" );
812                 if ( Math.abs( bs.getMax() - bs.getMin() ) > 0.0001 ) {
813                     desc.append( "\n" );
814                     final AsciiHistogram histo = new AsciiHistogram( bs );
815                     desc.append( histo.toStringBuffer( 12, '#', 40, 7, "    " ) );
816                 }
817             }
818             final DescriptiveStatistics ds = PhylogenyMethods.calculatNumberOfDescendantsPerNodeStatistics( phy );
819             if ( ds.getN() > 2 ) {
820                 desc.append( "\n" );
821                 desc.append( "Descendants per node statistics: " );
822                 desc.append( "\n" );
823                 desc.append( "    Median: " + ForesterUtil.round( ds.median(), 2 ) );
824                 desc.append( "\n" );
825                 desc.append( "    Mean: " + ForesterUtil.round( ds.arithmeticMean(), 2 ) + " (stdev: "
826                         + ForesterUtil.round( ds.sampleStandardDeviation(), 2 ) + ")" );
827                 desc.append( "\n" );
828                 desc.append( "    Minimum: " + ForesterUtil.roundToInt( ds.getMin() ) );
829                 desc.append( "\n" );
830                 desc.append( "    Maximum: " + ForesterUtil.roundToInt( ds.getMax() ) );
831                 desc.append( "\n" );
832             }
833             List<DescriptiveStatistics> css = null;
834             try {
835                 css = PhylogenyMethods.calculatConfidenceStatistics( phy );
836             }
837             catch ( final IllegalArgumentException e ) {
838                 ForesterUtil.printWarningMessage( Constants.PRG_NAME, e.getMessage() );
839             }
840             if ( ( css != null ) && ( css.size() > 0 ) ) {
841                 desc.append( "\n" );
842                 for( int i = 0; i < css.size(); ++i ) {
843                     final DescriptiveStatistics cs = css.get( i );
844                     if ( ( cs != null ) && ( cs.getN() > 1 ) ) {
845                         if ( css.size() > 1 ) {
846                             desc.append( "Support statistics " + ( i + 1 ) + ": " );
847                         }
848                         else {
849                             desc.append( "Support statistics: " );
850                         }
851                         if ( !ForesterUtil.isEmpty( cs.getDescription() ) ) {
852                             desc.append( "\n" );
853                             desc.append( "    Type: " + cs.getDescription() );
854                         }
855                         desc.append( "\n" );
856                         desc.append( "    Branches with support: " + cs.getN() );
857                         desc.append( "\n" );
858                         desc.append( "    Median: " + ForesterUtil.round( cs.median(), 6 ) );
859                         desc.append( "\n" );
860                         desc.append( "    Mean: " + ForesterUtil.round( cs.arithmeticMean(), 6 ) );
861                         if ( cs.getN() > 2 ) {
862                             desc.append( " (stdev: " + ForesterUtil.round( cs.sampleStandardDeviation(), 6 ) + ")" );
863                         }
864                         desc.append( "\n" );
865                         desc.append( "    Minimum: " + ForesterUtil.roundToInt( cs.getMin() ) );
866                         desc.append( "\n" );
867                         desc.append( "    Maximum: " + ForesterUtil.roundToInt( cs.getMax() ) );
868                         desc.append( "\n" );
869                     }
870                 }
871             }
872         }
873         return desc.toString();
874     }
875
876     /**
877      * Exits with -1.
878      * 
879      * 
880      * @param message
881      *            to message to be printed
882      */
883     final static void dieWithSystemError( final String message ) {
884         System.out.println();
885         System.out.println( Constants.PRG_NAME + " encountered the following system error: " + message );
886         System.out.println( "Please contact the authors." );
887         System.out.println( Constants.PRG_NAME + " needs to close." );
888         System.out.println();
889         System.exit( -1 );
890     }
891
892     final static String[] getAllPossibleRanks() {
893         final String[] str_array = new String[ PhyloXmlUtil.TAXONOMY_RANKS_LIST.size() - 2 ];
894         int i = 0;
895         for( final String e : PhyloXmlUtil.TAXONOMY_RANKS_LIST ) {
896             if ( !e.equals( PhyloXmlUtil.UNKNOWN ) && !e.equals( PhyloXmlUtil.OTHER ) ) {
897                 str_array[ i++ ] = e;
898             }
899         }
900         return str_array;
901     }
902
903     final static String[] getAllRanks( final Phylogeny tree ) {
904         final SortedSet<String> ranks = new TreeSet<String>();
905         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
906             final PhylogenyNode n = it.next();
907             if ( n.getNodeData().isHasTaxonomy() && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() ) ) {
908                 ranks.add( n.getNodeData().getTaxonomy().getRank() );
909             }
910         }
911         return ForesterUtil.stringSetToArray( ranks );
912     }
913
914     final static String[] getAvailableFontFamiliesSorted() {
915         return AVAILABLE_FONT_FAMILIES_SORTED;
916     }
917
918     final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
919         if ( !node.getNodeData().isHasEvent() ) {
920             return false;
921         }
922         if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
923             return false;
924         }
925         return true;
926     }
927
928     final static boolean isUsOrCanada() {
929         try {
930             if ( ( Locale.getDefault().equals( Locale.CANADA ) ) || ( Locale.getDefault().equals( Locale.US ) ) ) {
931                 return true;
932             }
933         }
934         catch ( final Exception e ) {
935             return false;
936         }
937         return false;
938     }
939
940     final static void lookAtSomeTreePropertiesForAptxControlSettings( final Phylogeny t,
941                                                                       final ControlPanel atv_control,
942                                                                       final Configuration configuration ) {
943         if ( ( t != null ) && !t.isEmpty() ) {
944             if ( !AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
945                 atv_control.setDrawPhylogram( false );
946                 atv_control.setDrawPhylogramEnabled( false );
947             }
948             if ( configuration.doGuessCheckOption( Configuration.display_as_phylogram ) ) {
949                 if ( atv_control.getDisplayAsPhylogramCb() != null ) {
950                     if ( AptxUtil.isHasAtLeastOneBranchLengthLargerThanZero( t ) ) {
951                         atv_control.setDrawPhylogram( true );
952                         atv_control.setDrawPhylogramEnabled( true );
953                     }
954                     else {
955                         atv_control.setDrawPhylogram( false );
956                     }
957                 }
958             }
959             if ( configuration.doGuessCheckOption( Configuration.write_confidence_values ) ) {
960                 if ( atv_control.getWriteConfidenceCb() != null ) {
961                     if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( t ) ) {
962                         atv_control.setCheckbox( Configuration.write_confidence_values, true );
963                     }
964                     else {
965                         atv_control.setCheckbox( Configuration.write_confidence_values, false );
966                     }
967                 }
968             }
969             if ( configuration.doGuessCheckOption( Configuration.write_events ) ) {
970                 if ( atv_control.getShowEventsCb() != null ) {
971                     if ( AptxUtil.isHasAtLeastNodeWithEvent( t ) ) {
972                         atv_control.setCheckbox( Configuration.write_events, true );
973                     }
974                     else {
975                         atv_control.setCheckbox( Configuration.write_events, false );
976                     }
977                 }
978             }
979         }
980     }
981
982     final static void openWebsite( final String url, final boolean is_applet, final JApplet applet ) throws IOException {
983         try {
984             AptxUtil.launchWebBrowser( new URI( url ), is_applet, applet, Constants.PRG_NAME );
985         }
986         catch ( final Exception e ) {
987             throw new IOException( e );
988         }
989     }
990
991     final static void outOfMemoryError( final OutOfMemoryError e ) {
992         System.err.println();
993         System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
994         System.err.println();
995         e.printStackTrace();
996         System.err.println();
997         JOptionPane.showMessageDialog( null,
998                                        "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option"
999                                                + "\n\nError: " + e.getLocalizedMessage(),
1000                                        "Out of Memory Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
1001                                        JOptionPane.ERROR_MESSAGE );
1002         System.exit( -1 );
1003     }
1004
1005     final static void printAppletMessage( final String applet_name, final String message ) {
1006         System.out.println( "[" + applet_name + "] > " + message );
1007     }
1008
1009     final static Phylogeny[] readPhylogeniesFromUrl( final URL url,
1010                                                      final boolean phyloxml_validate_against_xsd,
1011                                                      final boolean replace_underscores,
1012                                                      final boolean internal_numbers_are_confidences,
1013                                                      final TAXONOMY_EXTRACTION taxonomy_extraction,
1014                                                      final boolean midpoint_reroot ) throws FileNotFoundException,
1015             IOException {
1016         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
1017         final PhylogenyParser parser;
1018         boolean nhx_or_nexus = false;
1019         if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
1020             parser = new TolParser();
1021         }
1022         else {
1023             parser = ParserUtils.createParserDependingOnUrlContents( url, phyloxml_validate_against_xsd );
1024             if ( parser instanceof NHXParser ) {
1025                 nhx_or_nexus = true;
1026                 final NHXParser nhx = ( NHXParser ) parser;
1027                 nhx.setReplaceUnderscores( replace_underscores );
1028                 nhx.setIgnoreQuotes( false );
1029                 nhx.setTaxonomyExtraction( taxonomy_extraction );
1030             }
1031             else if ( parser instanceof NexusPhylogeniesParser ) {
1032                 nhx_or_nexus = true;
1033                 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser;
1034                 nex.setReplaceUnderscores( replace_underscores );
1035                 nex.setIgnoreQuotes( false );
1036             }
1037         }
1038         final Phylogeny[] phys = factory.create( url.openStream(), parser );
1039         if ( nhx_or_nexus && internal_numbers_are_confidences ) {
1040             for( final Phylogeny phy : phys ) {
1041                 PhylogenyMethods.transferInternalNodeNamesToConfidence( phy );
1042             }
1043         }
1044         if ( midpoint_reroot ) {
1045             for( final Phylogeny phy : phys ) {
1046                 PhylogenyMethods.midpointRoot( phy );
1047                 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME );
1048             }
1049         }
1050         return phys;
1051     }
1052
1053     final static void removeBranchColors( final Phylogeny phy ) {
1054         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
1055             it.next().getBranchData().setBranchColor( null );
1056         }
1057     }
1058
1059     final static void unexpectedError( final Error e ) {
1060         System.err.println();
1061         e.printStackTrace( System.err );
1062         System.err.println();
1063         final StringBuffer sb = new StringBuffer();
1064         for( final StackTraceElement s : e.getStackTrace() ) {
1065             sb.append( s + "\n" );
1066         }
1067         JOptionPane
1068                 .showMessageDialog( null,
1069                                     "An unexpected (possibly severe) error has occured - terminating. \nPlease contact: "
1070                                             + Constants.AUTHOR_EMAIL + " \nError: " + e.getLocalizedMessage() + "\n"
1071                                             + sb,
1072                                     "Unexpected Severe Error [" + Constants.PRG_NAME + " " + Constants.VERSION + "]",
1073                                     JOptionPane.ERROR_MESSAGE );
1074         System.exit( -1 );
1075     }
1076
1077     final static void unexpectedException( final Exception e ) {
1078         System.err.println();
1079         e.printStackTrace( System.err );
1080         System.err.println();
1081         final StringBuffer sb = new StringBuffer();
1082         for( final StackTraceElement s : e.getStackTrace() ) {
1083             sb.append( s + "\n" );
1084         }
1085         JOptionPane.showMessageDialog( null,
1086                                        "An unexpected exception has occured. \nPlease contact: "
1087                                                + Constants.AUTHOR_EMAIL + " \nException: " + e.getLocalizedMessage()
1088                                                + "\n" + sb,
1089                                        "Unexpected Exception [" + Constants.PRG_NAME + Constants.VERSION + "]",
1090                                        JOptionPane.ERROR_MESSAGE );
1091     }
1092
1093     final static String writePhylogenyToGraphicsByteArrayOutputStream( final ByteArrayOutputStream baos,
1094                                                                        int width,
1095                                                                        int height,
1096                                                                        final TreePanel tree_panel,
1097                                                                        final ControlPanel ac,
1098                                                                        final GraphicsExportType type,
1099                                                                        final Options options ) throws IOException {
1100         if ( !options.isGraphicsExportUsingActualSize() ) {
1101             if ( options.isGraphicsExportVisibleOnly() ) {
1102                 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1103             }
1104             tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1105             tree_panel.resetPreferredSize();
1106             tree_panel.repaint();
1107         }
1108         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1109                                                                    RenderingHints.VALUE_RENDER_QUALITY );
1110         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1111         if ( options.isAntialiasPrint() ) {
1112             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1113             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1114         }
1115         else {
1116             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1117             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1118         }
1119         final Phylogeny phylogeny = tree_panel.getPhylogeny();
1120         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1121             return "";
1122         }
1123         Rectangle visible = null;
1124         if ( !options.isGraphicsExportUsingActualSize() ) {
1125             width = options.getPrintSizeX();
1126             height = options.getPrintSizeY();
1127         }
1128         else if ( options.isGraphicsExportVisibleOnly() ) {
1129             visible = tree_panel.getVisibleRect();
1130             width = visible.width;
1131             height = visible.height;
1132         }
1133         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1134         Graphics2D g2d = buffered_img.createGraphics();
1135         g2d.setRenderingHints( rendering_hints );
1136         int x = 0;
1137         int y = 0;
1138         if ( options.isGraphicsExportVisibleOnly() ) {
1139             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1140             g2d.setClip( null );
1141             x = visible.x;
1142             y = visible.y;
1143         }
1144         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1145         ImageIO.write( buffered_img, type.toString(), baos );
1146         g2d.dispose();
1147         System.gc();
1148         if ( !options.isGraphicsExportUsingActualSize() ) {
1149             tree_panel.getMainPanel().getControlPanel().showWhole();
1150         }
1151         String msg = baos.toString();
1152         if ( ( width > 0 ) && ( height > 0 ) ) {
1153             msg += " [size: " + width + ", " + height + "]";
1154         }
1155         return msg;
1156     }
1157
1158     final static String writePhylogenyToGraphicsFile( final String file_name,
1159                                                       int width,
1160                                                       int height,
1161                                                       final TreePanel tree_panel,
1162                                                       final ControlPanel ac,
1163                                                       final GraphicsExportType type,
1164                                                       final Options options ) throws IOException {
1165         if ( !options.isGraphicsExportUsingActualSize() ) {
1166             if ( options.isGraphicsExportVisibleOnly() ) {
1167                 throw new IllegalArgumentException( "cannot export visible rectangle only without exporting in actual size" );
1168             }
1169             tree_panel.calcParametersForPainting( options.getPrintSizeX(), options.getPrintSizeY(), true );
1170             tree_panel.resetPreferredSize();
1171             tree_panel.repaint();
1172         }
1173         final RenderingHints rendering_hints = new RenderingHints( RenderingHints.KEY_RENDERING,
1174                                                                    RenderingHints.VALUE_RENDER_QUALITY );
1175         rendering_hints.put( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
1176         if ( options.isAntialiasPrint() ) {
1177             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
1178             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
1179         }
1180         else {
1181             rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
1182             rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
1183         }
1184         final Phylogeny phylogeny = tree_panel.getPhylogeny();
1185         if ( ( phylogeny == null ) || phylogeny.isEmpty() ) {
1186             return "";
1187         }
1188         final File file = new File( file_name );
1189         if ( file.isDirectory() ) {
1190             throw new IOException( "\"" + file_name + "\" is a directory" );
1191         }
1192         Rectangle visible = null;
1193         if ( !options.isGraphicsExportUsingActualSize() ) {
1194             width = options.getPrintSizeX();
1195             height = options.getPrintSizeY();
1196         }
1197         else if ( options.isGraphicsExportVisibleOnly() ) {
1198             visible = tree_panel.getVisibleRect();
1199             width = visible.width;
1200             height = visible.height;
1201         }
1202         final BufferedImage buffered_img = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
1203         Graphics2D g2d = buffered_img.createGraphics();
1204         g2d.setRenderingHints( rendering_hints );
1205         int x = 0;
1206         int y = 0;
1207         if ( options.isGraphicsExportVisibleOnly() ) {
1208             g2d = ( Graphics2D ) g2d.create( -visible.x, -visible.y, visible.width, visible.height );
1209             g2d.setClip( null );
1210             x = visible.x;
1211             y = visible.y;
1212         }
1213         tree_panel.paintPhylogeny( g2d, false, true, width, height, x, y );
1214         if ( type == GraphicsExportType.TIFF ) {
1215             writeToTiff( file, buffered_img );
1216         }
1217         else {
1218             ImageIO.write( buffered_img, type.toString(), file );
1219         }
1220         g2d.dispose();
1221         System.gc();
1222         if ( !options.isGraphicsExportUsingActualSize() ) {
1223             tree_panel.getMainPanel().getControlPanel().showWhole();
1224         }
1225         String msg = file.toString();
1226         if ( ( width > 0 ) && ( height > 0 ) ) {
1227             msg += " [size: " + width + ", " + height + "]";
1228         }
1229         return msg;
1230     }
1231
1232     final static void writeToTiff( final File file, final BufferedImage image ) throws IOException {
1233         // See: http://log.robmeek.com/2005/08/write-tiff-in-java.html
1234         ImageWriter writer = null;
1235         ImageOutputStream ios = null;
1236         // Find an appropriate writer:
1237         final Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName( "TIF" );
1238         if ( it.hasNext() ) {
1239             writer = it.next();
1240         }
1241         else {
1242             throw new IOException( "failed to get TIFF image writer" );
1243         }
1244         // Setup writer:
1245         ios = ImageIO.createImageOutputStream( file );
1246         writer.setOutput( ios );
1247         final ImageWriteParam image_write_param = new ImageWriteParam( Locale.getDefault() );
1248         image_write_param.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
1249         // see writeParam.getCompressionTypes() for available compression type
1250         // strings.
1251         image_write_param.setCompressionType( "PackBits" );
1252         final String t[] = image_write_param.getCompressionTypes();
1253         for( final String string : t ) {
1254             System.out.println( string );
1255         }
1256         // Convert to an IIOImage:
1257         final IIOImage iio_image = new IIOImage( image, null, null );
1258         writer.write( null, iio_image, image_write_param );
1259     }
1260
1261     private static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
1262         node.getBranchData().setBranchColor( c );
1263         final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
1264         for( final PhylogenyNode desc : descs ) {
1265             desc.getBranchData().setBranchColor( c );
1266         }
1267     }
1268
1269     final private static char normalizeCharForRGB( char c ) {
1270         c -= 65;
1271         c *= 10.2;
1272         c = c > 255 ? 255 : c;
1273         c = c < 0 ? 0 : c;
1274         return c;
1275     }
1276
1277     final private static void openUrlInWebBrowser( final String url ) throws IOException, ClassNotFoundException,
1278             SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
1279             InvocationTargetException, InterruptedException {
1280         final String os = System.getProperty( "os.name" );
1281         final Runtime runtime = Runtime.getRuntime();
1282         if ( os.toLowerCase().startsWith( "win" ) ) {
1283             Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url );
1284         }
1285         else if ( ForesterUtil.isMac() ) {
1286             final Class<?> file_mgr = Class.forName( "com.apple.eio.FileManager" );
1287             final Method open_url = file_mgr.getDeclaredMethod( "openURL", new Class[] { String.class } );
1288             open_url.invoke( null, new Object[] { url } );
1289         }
1290         else {
1291             final String[] browsers = { "firefox", "opera", "konqueror", "mozilla", "netscape", "epiphany" };
1292             String browser = null;
1293             for( int i = 0; ( i < browsers.length ) && ( browser == null ); ++i ) {
1294                 if ( runtime.exec( new String[] { "which", browsers[ i ] } ).waitFor() == 0 ) {
1295                     browser = browsers[ i ];
1296                 }
1297             }
1298             if ( browser == null ) {
1299                 throw new IOException( "could not find a web browser to open [" + url + "] in" );
1300             }
1301             else {
1302                 runtime.exec( new String[] { browser, url } );
1303             }
1304         }
1305     }
1306
1307     // See: http://www.xml.nig.ac.jp/tutorial/rest/index.html#2.2
1308     // static void openDDBJRest() throws IOException {
1309     // //set URL
1310     // URL url = new URL( "http://xml.nig.ac.jp/rest/Invoke" );
1311     // //set parameter
1312     // String query = "service=GetEntry&method=getDDBJEntry&accession=AB000100";
1313     // //make connection
1314     // URLConnection urlc = url.openConnection();
1315     // //use post mode
1316     // urlc.setDoOutput( true );
1317     // urlc.setAllowUserInteraction( false );
1318     // //send query
1319     // PrintStream ps = new PrintStream( urlc.getOutputStream() );
1320     // ps.print( query );
1321     // ps.close();
1322     // //get result
1323     // BufferedReader br = new BufferedReader( new InputStreamReader(
1324     // urlc.getInputStream() ) );
1325     // String l = null;
1326     // while ( ( l = br.readLine() ) != null ) {
1327     // System.out.println( l );
1328     // }
1329     // br.close();
1330     // }
1331     public static enum GraphicsExportType {
1332         GIF( "gif" ), JPG( "jpg" ), PDF( "pdf" ), PNG( "png" ), TIFF( "tif" ), BMP( "bmp" );
1333
1334         private final String _suffix;
1335
1336         private GraphicsExportType( final String suffix ) {
1337             _suffix = suffix;
1338         }
1339
1340         @Override
1341         public String toString() {
1342             return _suffix;
1343         }
1344     }
1345 }