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