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