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