5866ba3329869baa0d9a09476798942118662812
[jalview.git] / forester / java / src / org / forester / archaeopteryx / TreePanel.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: www.phylosoft.org/forester
25
26 package org.forester.archaeopteryx;
27
28 import java.awt.BasicStroke;
29 import java.awt.Color;
30 import java.awt.Cursor;
31 import java.awt.Dimension;
32 import java.awt.Font;
33 import java.awt.GradientPaint;
34 import java.awt.Graphics;
35 import java.awt.Graphics2D;
36 import java.awt.Point;
37 import java.awt.Polygon;
38 import java.awt.Rectangle;
39 import java.awt.RenderingHints;
40 import java.awt.event.ActionEvent;
41 import java.awt.event.ActionListener;
42 import java.awt.event.FocusAdapter;
43 import java.awt.event.FocusEvent;
44 import java.awt.event.InputEvent;
45 import java.awt.event.KeyAdapter;
46 import java.awt.event.KeyEvent;
47 import java.awt.event.MouseEvent;
48 import java.awt.event.MouseWheelEvent;
49 import java.awt.event.MouseWheelListener;
50 import java.awt.font.FontRenderContext;
51 import java.awt.font.TextLayout;
52 import java.awt.geom.AffineTransform;
53 import java.awt.geom.Arc2D;
54 import java.awt.geom.CubicCurve2D;
55 import java.awt.geom.Ellipse2D;
56 import java.awt.geom.Line2D;
57 import java.awt.geom.QuadCurve2D;
58 import java.awt.geom.Rectangle2D;
59 import java.awt.image.BufferedImage;
60 import java.awt.print.PageFormat;
61 import java.awt.print.Printable;
62 import java.awt.print.PrinterException;
63 import java.io.File;
64 import java.io.IOException;
65 import java.io.UnsupportedEncodingException;
66 import java.net.URI;
67 import java.net.URISyntaxException;
68 import java.net.URLEncoder;
69 import java.text.DecimalFormat;
70 import java.text.DecimalFormatSymbols;
71 import java.text.NumberFormat;
72 import java.util.ArrayList;
73 import java.util.Collections;
74 import java.util.HashMap;
75 import java.util.HashSet;
76 import java.util.Hashtable;
77 import java.util.List;
78 import java.util.Set;
79
80 import javax.swing.BorderFactory;
81 import javax.swing.JApplet;
82 import javax.swing.JColorChooser;
83 import javax.swing.JDialog;
84 import javax.swing.JMenuItem;
85 import javax.swing.JOptionPane;
86 import javax.swing.JPanel;
87 import javax.swing.JPopupMenu;
88 import javax.swing.JTextArea;
89 import javax.swing.Popup;
90 import javax.swing.PopupFactory;
91
92 import org.forester.archaeopteryx.ControlPanel.NodeClickAction;
93 import org.forester.archaeopteryx.Options.CLADOGRAM_TYPE;
94 import org.forester.archaeopteryx.Options.NODE_LABEL_DIRECTION;
95 import org.forester.archaeopteryx.Options.NodeFill;
96 import org.forester.archaeopteryx.Options.NodeShape;
97 import org.forester.archaeopteryx.Options.PHYLOGENY_GRAPHICS_TYPE;
98 import org.forester.archaeopteryx.phylogeny.data.RenderableDomainArchitecture;
99 import org.forester.archaeopteryx.phylogeny.data.RenderableVector;
100 import org.forester.archaeopteryx.tools.Blast;
101 import org.forester.archaeopteryx.tools.ImageLoader;
102 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
103 import org.forester.phylogeny.Phylogeny;
104 import org.forester.phylogeny.PhylogenyMethods;
105 import org.forester.phylogeny.PhylogenyNode;
106 import org.forester.phylogeny.data.Annotation;
107 import org.forester.phylogeny.data.BranchColor;
108 import org.forester.phylogeny.data.Confidence;
109 import org.forester.phylogeny.data.Event;
110 import org.forester.phylogeny.data.PhylogenyData;
111 import org.forester.phylogeny.data.PropertiesMap;
112 import org.forester.phylogeny.data.Property;
113 import org.forester.phylogeny.data.Sequence;
114 import org.forester.phylogeny.data.SequenceRelation;
115 import org.forester.phylogeny.data.Taxonomy;
116 import org.forester.phylogeny.data.Uri;
117 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
118 import org.forester.phylogeny.iterators.PreorderTreeIterator;
119 import org.forester.util.BasicDescriptiveStatistics;
120 import org.forester.util.DescriptiveStatistics;
121 import org.forester.util.ForesterConstants;
122 import org.forester.util.ForesterUtil;
123
124 public final class TreePanel extends JPanel implements ActionListener, MouseWheelListener, Printable {
125
126     private static final float              PI                                = ( float ) ( Math.PI );
127     private static final double             TWO_PI                            = 2 * Math.PI;
128     private static final float              ONEHALF_PI                        = ( float ) ( 1.5 * Math.PI );
129     private static final float              HALF_PI                           = ( float ) ( Math.PI / 2.0 );
130     private static final float              ANGLE_ROTATION_UNIT               = ( float ) ( Math.PI / 32 );
131     private static final short              OV_BORDER                         = 10;
132     final static Cursor                     CUT_CURSOR                        = Cursor.getPredefinedCursor( Cursor.CROSSHAIR_CURSOR );
133     final static Cursor                     MOVE_CURSOR                       = Cursor.getPredefinedCursor( Cursor.MOVE_CURSOR );
134     final static Cursor                     ARROW_CURSOR                      = Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR );
135     final static Cursor                     HAND_CURSOR                       = Cursor.getPredefinedCursor( Cursor.HAND_CURSOR );
136     final static Cursor                     WAIT_CURSOR                       = Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR );
137     private final static long               serialVersionUID                  = -978349745916505029L;
138     private final static int                EURO_D                            = 10;
139     private final static String             NODE_POPMENU_NODE_CLIENT_PROPERTY = "node";
140     private final static int                MIN_ROOT_LENGTH                   = 3;
141     private final static int                MAX_SUBTREES                      = 100;
142     private final static int                MAX_NODE_FRAMES                   = 10;
143     private final static int                MOVE                              = 20;
144     private final static NumberFormat       FORMATTER_CONFIDENCE;
145     private final static NumberFormat       FORMATTER_BRANCH_LENGTH;
146     private final static int                WIGGLE                            = 2;
147     //private final int                       _half_box_size_plus_wiggle;
148     private final static int                LIMIT_FOR_HQ_RENDERING            = 1000;
149     private final static int                CONFIDENCE_LEFT_MARGIN            = 4;
150     // TODO "rendering_hints" was static before. Need to make sure everything is OK with it not
151     // being static anymore (02/20/2009).
152     private final RenderingHints            _rendering_hints                  = new RenderingHints( RenderingHints.KEY_RENDERING,
153                                                                                                     RenderingHints.VALUE_RENDER_DEFAULT );
154     private File                            _treefile                         = null;
155     private Configuration                   _configuration                    = null;
156     private final NodeFrame[]               _node_frames                      = new NodeFrame[ TreePanel.MAX_NODE_FRAMES ];
157     private int                             _node_frame_index                 = 0;
158     private Phylogeny                       _phylogeny                        = null;
159     private final Phylogeny[]               _sub_phylogenies                  = new Phylogeny[ TreePanel.MAX_SUBTREES ];
160     private final PhylogenyNode[]           _sub_phylogenies_temp_roots       = new PhylogenyNode[ TreePanel.MAX_SUBTREES ];
161     private int                             _subtree_index                    = 0;
162     private MainPanel                       _main_panel                       = null;
163     private Set<Integer>                    _found_nodes                      = null;
164     private PhylogenyNode                   _highlight_node                   = null;
165     private JPopupMenu                      _node_popup_menu                  = null;
166     private JMenuItem                       _node_popup_menu_items[]          = null;
167     private int                             _longest_ext_node_info            = 0;
168     private float                           _x_correction_factor              = 0.0f;
169     private float                           _ov_x_correction_factor           = 0.0f;
170     private float                           _x_distance                       = 0.0f;
171     private float                           _y_distance                       = 0.0f;
172     private PHYLOGENY_GRAPHICS_TYPE         _graphics_type                    = PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR;
173     private double                          _domain_structure_width           = Constants.DOMAIN_STRUCTURE_DEFAULT_WIDTH;
174     private int                             _domain_structure_e_value_thr_exp = Constants.DOMAIN_STRUCTURE_E_VALUE_THR_DEFAULT_EXP;
175     private float                           _last_drag_point_x                = 0;
176     private float                           _last_drag_point_y                = 0;
177     private ControlPanel                    _control_panel                    = null;
178     private int                             _external_node_index              = 0;
179     private final Polygon                   _polygon                          = new Polygon();
180     private final StringBuilder             _sb                               = new StringBuilder();
181     private JColorChooser                   _color_chooser                    = null;
182     private double                          _scale_distance                   = 0.0;
183     private String                          _scale_label                      = null;
184     private final CubicCurve2D              _cubic_curve                      = new CubicCurve2D.Float();
185     private final QuadCurve2D               _quad_curve                       = new QuadCurve2D.Float();
186     private final Line2D                    _line                             = new Line2D.Float();
187     private final Ellipse2D                 _ellipse                          = new Ellipse2D.Float();
188     private final Rectangle2D               _rectangle                        = new Rectangle2D.Float();
189     private Options                         _options                          = null;
190     private float                           _ov_max_width                     = 0;
191     private float                           _ov_max_height                    = 0;
192     private int                             _ov_x_position                    = 0;
193     private int                             _ov_y_position                    = 0;
194     private int                             _ov_y_start                       = 0;
195     private float                           _ov_y_distance                    = 0;
196     private float                           _ov_x_distance                    = 0;
197     private boolean                         _ov_on                            = false;
198     private double                          _urt_starting_angle               = ( float ) ( Math.PI / 2 );
199     private float                           _urt_factor                       = 1;
200     private float                           _urt_factor_ov                    = 1;
201     private final boolean                   _phy_has_branch_lengths;
202     private final Rectangle2D               _ov_rectangle                     = new Rectangle2D.Float();
203     private boolean                         _in_ov_rect                       = false;
204     private boolean                         _in_ov                            = false;
205     private final Rectangle                 _ov_virtual_rectangle             = new Rectangle();
206     final private static double             _180_OVER_PI                      = 180.0 / Math.PI;
207     private static final float              ROUNDED_D                         = 8;
208     private int                             _circ_max_depth;
209     private int                             _circ_num_ext_nodes;
210     private PhylogenyNode                   _root;
211     final private Arc2D                     _arc                              = new Arc2D.Double();
212     final private HashMap<Integer, Double>  _urt_nodeid_angle_map             = new HashMap<Integer, Double>();
213     final private HashMap<Integer, Integer> _urt_nodeid_index_map             = new HashMap<Integer, Integer>();
214     HashMap<Integer, Short>                 _nodeid_dist_to_leaf              = new HashMap<Integer, Short>();
215     private AffineTransform                 _at;
216     private double                          _max_distance_to_root             = -1;
217     private int                             _dynamic_hiding_factor            = 0;
218     private boolean                         _edited                           = false;
219     private Popup                           _node_desc_popup;
220     private JTextArea                       _rollover_popup;
221     // private final int                       _box_size;
222     // private final int                       _half_box_size;
223     //private final short                     _skip_counter                     = 0;
224     private final StringBuffer              _popup_buffer                     = new StringBuffer();
225     final private static Font               POPUP_FONT                        = new Font( Configuration.getDefaultFontFamilyName(),
226                                                                                           Font.PLAIN,
227                                                                                           12 );
228     private static final boolean            DRAW_MEAN_COUNTS                  = true;                                                     //TODO remove me later
229     private Sequence                        _query_sequence                   = null;
230     private final FontRenderContext         _frc                              = new FontRenderContext( null,
231                                                                                                        false,
232                                                                                                        false );
233     // expression values menu:
234     private DescriptiveStatistics           _statistics_for_vector_data;
235     private PhylogenyNode[]                 _nodes_in_preorder                = null;
236     //  private Image                           offscreenImage;
237     //  private Graphics                        offscreenGraphics;
238     //  private Dimension                       offscreenDimension;
239     static {
240         final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
241         dfs.setDecimalSeparator( '.' );
242         FORMATTER_CONFIDENCE = new DecimalFormat( "#.###", dfs );
243         FORMATTER_BRANCH_LENGTH = new DecimalFormat( "#.###", dfs );
244     }
245
246     TreePanel( final Phylogeny t, final Configuration configuration, final MainPanel tjp ) {
247         requestFocusInWindow();
248         addKeyListener( new KeyAdapter() {
249
250             @Override
251             public void keyPressed( final KeyEvent key_event ) {
252                 keyPressedCalls( key_event );
253                 requestFocusInWindow();
254             }
255         } );
256         addFocusListener( new FocusAdapter() {
257
258             @Override
259             public void focusGained( final FocusEvent e ) {
260                 requestFocusInWindow();
261             }
262         } );
263         if ( ( t == null ) || t.isEmpty() ) {
264             throw new IllegalArgumentException( "attempt to draw phylogeny which is null or empty" );
265         }
266         _graphics_type = tjp.getOptions().getPhylogenyGraphicsType();
267         _main_panel = tjp;
268         _configuration = configuration;
269         _phylogeny = t;
270         _phy_has_branch_lengths = ForesterUtil.isHasAtLeastOneBranchLengthLargerThanZero( _phylogeny );
271         init();
272         // if ( !_phylogeny.isEmpty() ) {
273         _phylogeny.recalculateNumberOfExternalDescendants( true );
274         checkForVectorProperties( _phylogeny );
275         // }
276         setBackground( getTreeColorSet().getBackgroundColor() );
277         final MouseListener mouse_listener = new MouseListener( this );
278         addMouseListener( mouse_listener );
279         addMouseMotionListener( mouse_listener );
280         addMouseWheelListener( this );
281         calculateScaleDistance();
282         FORMATTER_CONFIDENCE.setMaximumFractionDigits( configuration.getNumberOfDigitsAfterCommaForConfidenceValues() );
283         FORMATTER_BRANCH_LENGTH.setMaximumFractionDigits( configuration
284                 .getNumberOfDigitsAfterCommaForBranchLengthValues() );
285     }
286
287     public void checkForVectorProperties( final Phylogeny phy ) {
288         final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
289         for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
290             final PhylogenyNode node = iter.next();
291             if ( node.getNodeData().getProperties() != null ) {
292                 final PropertiesMap pm = node.getNodeData().getProperties();
293                 final double[] vector = new double[ pm.getProperties().size() ];
294                 int counter = 0;
295                 for( final String ref : pm.getProperties().keySet() ) {
296                     if ( ref.startsWith( PhyloXmlUtil.VECTOR_PROPERTY_REF ) ) {
297                         final Property p = pm.getProperty( ref );
298                         final String value_str = p.getValue();
299                         final String index_str = ref
300                                 .substring( PhyloXmlUtil.VECTOR_PROPERTY_REF.length(), ref.length() );
301                         double d = -100;
302                         try {
303                             d = Double.parseDouble( value_str );
304                         }
305                         catch ( final NumberFormatException e ) {
306                             JOptionPane.showMessageDialog( this, "Could not parse \"" + value_str
307                                     + "\" into a decimal value", "Problem with Vector Data", JOptionPane.ERROR_MESSAGE );
308                             return;
309                         }
310                         int i = -1;
311                         try {
312                             i = Integer.parseInt( index_str );
313                         }
314                         catch ( final NumberFormatException e ) {
315                             JOptionPane.showMessageDialog( this,
316                                                            "Could not parse \"" + index_str
317                                                                    + "\" into index for vector data",
318                                                            "Problem with Vector Data",
319                                                            JOptionPane.ERROR_MESSAGE );
320                             return;
321                         }
322                         if ( i < 0 ) {
323                             JOptionPane.showMessageDialog( this,
324                                                            "Attempt to use negative index for vector data",
325                                                            "Problem with Vector Data",
326                                                            JOptionPane.ERROR_MESSAGE );
327                             return;
328                         }
329                         vector[ i ] = d;
330                         ++counter;
331                         stats.addValue( d );
332                     }
333                 }
334                 final List<Double> vector_l = new ArrayList<Double>( counter );
335                 for( int i = 0; i < counter; ++i ) {
336                     vector_l.add( vector[ i ] );
337                 }
338                 node.getNodeData().setVector( vector_l );
339             }
340         }
341         if ( stats.getN() > 0 ) {
342             _statistics_for_vector_data = stats;
343         }
344     }
345
346     final public void actionPerformed( final ActionEvent e ) {
347         int index;
348         boolean done = false;
349         final JMenuItem node_popup_menu_item = ( JMenuItem ) e.getSource();
350         for( index = 0; ( index < _node_popup_menu_items.length ) && !done; index++ ) {
351             // NOTE: index corresponds to the indices of click-to options
352             // in the control panel.
353             if ( node_popup_menu_item == _node_popup_menu_items[ index ] ) {
354                 // Set this as the new default click-to action
355                 _main_panel.getControlPanel().setClickToAction( index );
356                 final PhylogenyNode node = ( PhylogenyNode ) _node_popup_menu
357                         .getClientProperty( NODE_POPMENU_NODE_CLIENT_PROPERTY );
358                 handleClickToAction( _control_panel.getActionWhenNodeClicked(), node );
359                 done = true;
360             }
361         }
362         repaint();
363         requestFocusInWindow();
364     }
365
366     final private void addEmptyNode( final PhylogenyNode node ) {
367         if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) {
368             errorMessageNoCutCopyPasteInUnrootedDisplay();
369             return;
370         }
371         final String label = getASimpleTextRepresentationOfANode( node );
372         String msg = "";
373         if ( ForesterUtil.isEmpty( label ) ) {
374             msg = "How to add the new, empty node?";
375         }
376         else {
377             msg = "How to add the new, empty node to node" + label + "?";
378         }
379         final Object[] options = { "As sibling", "As descendant", "Cancel" };
380         final int r = JOptionPane.showOptionDialog( this,
381                                                     msg,
382                                                     "Addition of Empty New Node",
383                                                     JOptionPane.CLOSED_OPTION,
384                                                     JOptionPane.QUESTION_MESSAGE,
385                                                     null,
386                                                     options,
387                                                     options[ 2 ] );
388         boolean add_as_sibling = true;
389         if ( r == 1 ) {
390             add_as_sibling = false;
391         }
392         else if ( r != 0 ) {
393             return;
394         }
395         final Phylogeny phy = new Phylogeny();
396         phy.setRoot( new PhylogenyNode() );
397         phy.setRooted( true );
398         if ( add_as_sibling ) {
399             if ( node.isRoot() ) {
400                 JOptionPane.showMessageDialog( this,
401                                                "Cannot add sibling to root",
402                                                "Attempt to add sibling to root",
403                                                JOptionPane.ERROR_MESSAGE );
404                 return;
405             }
406             phy.addAsSibling( node );
407         }
408         else {
409             phy.addAsChild( node );
410         }
411         _nodes_in_preorder = null;
412         _phylogeny.externalNodesHaveChanged();
413         _phylogeny.hashIDs();
414         _phylogeny.recalculateNumberOfExternalDescendants( true );
415         resetNodeIdToDistToLeafMap();
416         setEdited( true );
417         repaint();
418     }
419
420     final private void assignGraphicsForBranchWithColorForParentBranch( final PhylogenyNode node,
421                                                                         final boolean is_vertical,
422                                                                         final Graphics g,
423                                                                         final boolean to_pdf,
424                                                                         final boolean to_graphics_file ) {
425         final NodeClickAction action = _control_panel.getActionWhenNodeClicked();
426         if ( ( to_pdf || to_graphics_file ) && getOptions().isPrintBlackAndWhite() ) {
427             g.setColor( Color.BLACK );
428         }
429         else if ( ( ( action == NodeClickAction.COPY_SUBTREE ) || ( action == NodeClickAction.CUT_SUBTREE )
430                 || ( action == NodeClickAction.DELETE_NODE_OR_SUBTREE ) || ( action == NodeClickAction.PASTE_SUBTREE ) || ( action == NodeClickAction.ADD_NEW_NODE ) )
431                 && ( getCutOrCopiedTree() != null )
432                 && ( getCopiedAndPastedNodes() != null )
433                 && !to_pdf
434                 && !to_graphics_file && getCopiedAndPastedNodes().contains( node.getId() ) ) {
435             g.setColor( getTreeColorSet().getFoundColor() );
436         }
437         else if ( getControlPanel().isColorBranches() && ( PhylogenyMethods.getBranchColorValue( node ) != null ) ) {
438             g.setColor( PhylogenyMethods.getBranchColorValue( node ) );
439         }
440         else if ( to_pdf ) {
441             g.setColor( getTreeColorSet().getBranchColorForPdf() );
442         }
443         else {
444             g.setColor( getTreeColorSet().getBranchColor() );
445         }
446     }
447
448     final Color getGraphicsForNodeBoxWithColorForParentBranch( final PhylogenyNode node ) {
449         if ( getControlPanel().isColorBranches() && ( PhylogenyMethods.getBranchColorValue( node ) != null ) ) {
450             return ( PhylogenyMethods.getBranchColorValue( node ) );
451         }
452         else {
453             return ( getTreeColorSet().getBranchColor() );
454         }
455     }
456
457     final private void blast( final PhylogenyNode node ) {
458         if ( !isCanBlast( node ) ) {
459             JOptionPane.showMessageDialog( this,
460                                            "No sequence information present",
461                                            "Cannot Blast",
462                                            JOptionPane.WARNING_MESSAGE );
463             return;
464         }
465         if ( node.getNodeData().isHasSequence() ) {
466             String name = "";
467             if ( !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) ) {
468                 name = node.getNodeData().getSequence().getName();
469             }
470             else if ( !ForesterUtil.isEmpty( node.getNodeData().getSequence().getSymbol() ) ) {
471                 name = node.getNodeData().getSequence().getSymbol();
472             }
473             else if ( node.getNodeData().getSequence().getAccession() != null ) {
474                 name = node.getNodeData().getSequence().getAccession().getValue();
475             }
476             if ( !ForesterUtil.isEmpty( name ) ) {
477                 try {
478                     System.out.println( "trying: " + name );
479                     final Blast s = new Blast();
480                     s.go( name );
481                 }
482                 catch ( final Exception e ) {
483                     e.printStackTrace();
484                 }
485             }
486         }
487     }
488
489     final void calcMaxDepth() {
490         if ( _phylogeny != null ) {
491             _circ_max_depth = PhylogenyMethods.calculateMaxDepth( _phylogeny );
492         }
493     }
494
495     /**
496      * Calculate the length of the distance between the given node and its
497      * parent.
498      * 
499      * @param node
500      * @param ext_node_x
501      * @factor
502      * @return the distance value
503      */
504     final private float calculateBranchLengthToParent( final PhylogenyNode node, final float factor ) {
505         if ( getControlPanel().isDrawPhylogram() ) {
506             if ( node.getDistanceToParent() < 0.0 ) {
507                 return 0.0f;
508             }
509             return ( float ) ( getXcorrectionFactor() * node.getDistanceToParent() );
510         }
511         else {
512             if ( ( factor == 0 ) || isNonLinedUpCladogram() ) {
513                 return getXdistance();
514             }
515             return getXdistance() * factor;
516         }
517     }
518
519     final private Color calculateColorForAnnotation( final PhylogenyData ann ) {
520         Color c = getTreeColorSet().getAnnotationColor();
521         if ( getControlPanel().isColorAccordingToAnnotation() && ( getControlPanel().getAnnotationColors() != null ) ) {
522             c = getControlPanel().getAnnotationColors().get( ann.asSimpleText().toString() );
523             if ( c == null ) {
524                 c = getTreeColorSet().getAnnotationColor();
525             }
526         }
527         return c;
528     }
529
530     final void calculateLongestExtNodeInfo() {
531         if ( ( _phylogeny == null ) || _phylogeny.isEmpty() ) {
532             return;
533         }
534         int longest = 20;
535         for( final PhylogenyNode node : _phylogeny.getExternalNodes() ) {
536             int sum = 0;
537             if ( node.isCollapse() ) {
538                 continue;
539             }
540             if ( getControlPanel().isShowNodeNames() ) {
541                 sum += getTreeFontSet()._fm_large.stringWidth( node.getName() + " " );
542             }
543             if ( node.getNodeData().isHasSequence() ) {
544                 if ( getControlPanel().isShowSequenceAcc()
545                         && ( node.getNodeData().getSequence().getAccession() != null ) ) {
546                     sum += getTreeFontSet()._fm_large.stringWidth( node.getNodeData().getSequence().getAccession()
547                             .getValue()
548                             + " " );
549                 }
550                 if ( getControlPanel().isShowGeneNames() && ( node.getNodeData().getSequence().getName().length() > 0 ) ) {
551                     sum += getTreeFontSet()._fm_large.stringWidth( node.getNodeData().getSequence().getName() + " " );
552                 }
553                 if ( getControlPanel().isShowGeneSymbols()
554                         && ( node.getNodeData().getSequence().getSymbol().length() > 0 ) ) {
555                     sum += getTreeFontSet()._fm_large.stringWidth( node.getNodeData().getSequence().getSymbol() + " " );
556                 }
557                 if ( getControlPanel().isShowAnnotation()
558                         && ( node.getNodeData().getSequence().getAnnotations() != null )
559                         && !node.getNodeData().getSequence().getAnnotations().isEmpty() ) {
560                     sum += getTreeFontSet()._fm_large.stringWidth( node.getNodeData().getSequence().getAnnotation( 0 )
561                             .asSimpleText()
562                             + " " );
563                 }
564             }
565             if ( node.getNodeData().isHasTaxonomy() ) {
566                 final Taxonomy tax = node.getNodeData().getTaxonomy();
567                 if ( getControlPanel().isShowTaxonomyCode() && !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
568                     sum += getTreeFontSet()._fm_large_italic.stringWidth( tax.getTaxonomyCode() + " " );
569                 }
570                 if ( getControlPanel().isShowTaxonomyScientificNames()
571                         && !ForesterUtil.isEmpty( tax.getScientificName() ) ) {
572                     sum += getTreeFontSet()._fm_large_italic.stringWidth( tax.getScientificName() + " " );
573                 }
574                 if ( getControlPanel().isShowTaxonomyCommonNames() && !ForesterUtil.isEmpty( tax.getCommonName() ) ) {
575                     sum += getTreeFontSet()._fm_large_italic.stringWidth( tax.getCommonName() + " ()" );
576                 }
577             }
578             if ( getControlPanel().isShowBinaryCharacters() && node.getNodeData().isHasBinaryCharacters() ) {
579                 sum += getTreeFontSet()._fm_large.stringWidth( node.getNodeData().getBinaryCharacters()
580                         .getGainedCharactersAsStringBuffer().toString() );
581             }
582             if ( getControlPanel().isShowDomainArchitectures() && node.getNodeData().isHasSequence()
583                     && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
584                 sum += ( ( RenderableDomainArchitecture ) node.getNodeData().getSequence().getDomainArchitecture() )
585                         .getRenderingSize().getWidth();
586             }
587             if ( sum >= Constants.EXT_NODE_INFO_LENGTH_MAX ) {
588                 setLongestExtNodeInfo( Constants.EXT_NODE_INFO_LENGTH_MAX );
589                 return;
590             }
591             if ( sum > longest ) {
592                 longest = sum;
593             }
594         }
595         if ( longest >= Constants.EXT_NODE_INFO_LENGTH_MAX ) {
596             setLongestExtNodeInfo( Constants.EXT_NODE_INFO_LENGTH_MAX );
597         }
598         else {
599             setLongestExtNodeInfo( longest );
600         }
601     }
602
603     final private float calculateOvBranchLengthToParent( final PhylogenyNode node, final int factor ) {
604         if ( getControlPanel().isDrawPhylogram() ) {
605             if ( node.getDistanceToParent() < 0.0 ) {
606                 return 0.0f;
607             }
608             return ( float ) ( getOvXcorrectionFactor() * node.getDistanceToParent() );
609         }
610         else {
611             if ( ( factor == 0 ) || isNonLinedUpCladogram() ) {
612                 return getOvXDistance();
613             }
614             return getOvXDistance() * factor;
615         }
616     }
617
618     final void calculateScaleDistance() {
619         if ( ( _phylogeny == null ) || _phylogeny.isEmpty() ) {
620             return;
621         }
622         final double height = getMaxDistanceToRoot();
623         if ( height > 0 ) {
624             if ( ( height <= 0.5 ) ) {
625                 setScaleDistance( 0.01 );
626             }
627             else if ( height <= 5.0 ) {
628                 setScaleDistance( 0.1 );
629             }
630             else if ( height <= 50.0 ) {
631                 setScaleDistance( 1 );
632             }
633             else if ( height <= 500.0 ) {
634                 setScaleDistance( 10 );
635             }
636             else {
637                 setScaleDistance( 100 );
638             }
639         }
640         else {
641             setScaleDistance( 0.0 );
642         }
643         String scale_label = String.valueOf( getScaleDistance() );
644         if ( !ForesterUtil.isEmpty( _phylogeny.getDistanceUnit() ) ) {
645             scale_label += " [" + _phylogeny.getDistanceUnit() + "]";
646         }
647         setScaleLabel( scale_label );
648     }
649
650     final Color calculateTaxonomyBasedColor( final Taxonomy tax ) {
651         String species = tax.getTaxonomyCode();
652         if ( ForesterUtil.isEmpty( species ) ) {
653             species = tax.getScientificName();
654             if ( ForesterUtil.isEmpty( species ) ) {
655                 species = tax.getCommonName();
656             }
657         }
658         if ( ForesterUtil.isEmpty( species ) ) {
659             return getTreeColorSet().getTaxonomyColor();
660         }
661         // Look in species hash
662         Color c = getControlPanel().getSpeciesColors().get( species );
663         if ( c == null ) {
664             c = Util.calculateColorFromString( species );
665             getControlPanel().getSpeciesColors().put( species, c );
666         }
667         return c;
668     }
669
670     final private void cannotOpenBrowserWarningMessage( final String type_type ) {
671         JOptionPane.showMessageDialog( this,
672                                        "Cannot launch web browser for " + type_type + " data of this node",
673                                        "Cannot launch web browser",
674                                        JOptionPane.WARNING_MESSAGE );
675     }
676
677     /**
678      * Collapse the tree from the given node
679      * 
680      * @param node
681      *            a PhylogenyNode
682      */
683     final void collapse( final PhylogenyNode node ) {
684         if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) {
685             JOptionPane.showMessageDialog( this,
686                                            "Cannot collapse in unrooted display type",
687                                            "Attempt to collapse in unrooted display",
688                                            JOptionPane.WARNING_MESSAGE );
689             return;
690         }
691         if ( !node.isExternal() && !node.isRoot() ) {
692             final boolean collapse = !node.isCollapse();
693             Util.collapseSubtree( node, collapse );
694             _phylogeny.recalculateNumberOfExternalDescendants( true );
695             resetNodeIdToDistToLeafMap();
696             calculateLongestExtNodeInfo();
697             _nodes_in_preorder = null;
698             resetPreferredSize();
699             updateOvSizes();
700             _main_panel.adjustJScrollPane();
701             repaint();
702         }
703     }
704
705     final void collapseSpeciesSpecificSubtrees() {
706         if ( ( _phylogeny == null ) || ( _phylogeny.getNumberOfExternalNodes() < 2 ) ) {
707             return;
708         }
709         setWaitCursor();
710         Util.collapseSpeciesSpecificSubtrees( _phylogeny );
711         _phylogeny.recalculateNumberOfExternalDescendants( true );
712         resetNodeIdToDistToLeafMap();
713         calculateLongestExtNodeInfo();
714         _nodes_in_preorder = null;
715         resetPreferredSize();
716         _main_panel.adjustJScrollPane();
717         setArrowCursor();
718         repaint();
719     }
720
721     final private void colorizeSubtree( final Color c, final PhylogenyNode node ) {
722         if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) {
723             JOptionPane.showMessageDialog( this,
724                                            "Cannot colorize subtree in unrooted display type",
725                                            "Attempt to colorize subtree in unrooted display",
726                                            JOptionPane.WARNING_MESSAGE );
727             return;
728         }
729         _control_panel.setColorBranches( true );
730         if ( _control_panel.getColorBranchesCb() != null ) {
731             _control_panel.getColorBranchesCb().setSelected( true );
732         }
733         for( final PreorderTreeIterator it = new PreorderTreeIterator( node ); it.hasNext(); ) {
734             it.next().getBranchData().setBranchColor( new BranchColor( c ) );
735         }
736         repaint();
737     }
738
739     final private void colorSubtree( final PhylogenyNode node ) {
740         Color intitial_color = null;
741         if ( getControlPanel().isColorBranches() && ( PhylogenyMethods.getBranchColorValue( node ) != null )
742                 && ( ( ( !node.isRoot() && ( node.getParent().getNumberOfDescendants() < 3 ) ) ) || ( node.isRoot() ) ) ) {
743             intitial_color = PhylogenyMethods.getBranchColorValue( node );
744         }
745         else {
746             intitial_color = getTreeColorSet().getBranchColor();
747         }
748         _color_chooser.setColor( intitial_color );
749         _color_chooser.setPreviewPanel( new JPanel() );
750         final JDialog dialog = JColorChooser
751                 .createDialog( this,
752                                "Subtree colorization",
753                                true,
754                                _color_chooser,
755                                new SubtreeColorizationActionListener( _color_chooser, node ),
756                                null );
757         dialog.setVisible( true );
758     }
759
760     final void confColor() {
761         if ( ( _phylogeny == null ) || ( _phylogeny.getNumberOfExternalNodes() < 2 ) ) {
762             return;
763         }
764         setWaitCursor();
765         Util.colorPhylogenyAccordingToConfidenceValues( _phylogeny, this );
766         _control_panel.setColorBranches( true );
767         if ( _control_panel.getColorBranchesCb() != null ) {
768             _control_panel.getColorBranchesCb().setSelected( true );
769         }
770         setArrowCursor();
771         repaint();
772     }
773
774     final private void copySubtree( final PhylogenyNode node ) {
775         if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) {
776             errorMessageNoCutCopyPasteInUnrootedDisplay();
777             return;
778         }
779         _nodes_in_preorder = null;
780         setCutOrCopiedTree( _phylogeny.copy( node ) );
781         final List<PhylogenyNode> nodes = PhylogenyMethods.getAllDescendants( node );
782         final Set<Integer> node_ids = new HashSet<Integer>( nodes.size() );
783         for( final PhylogenyNode n : nodes ) {
784             node_ids.add( n.getId() );
785         }
786         node_ids.add( node.getId() );
787         setCopiedAndPastedNodes( node_ids );
788         repaint();
789     }
790
791     final private void cutSubtree( final PhylogenyNode node ) {
792         if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) {
793             errorMessageNoCutCopyPasteInUnrootedDisplay();
794             return;
795         }
796         if ( node.isRoot() ) {
797             JOptionPane.showMessageDialog( this,
798                                            "Cannot cut entire tree as subtree",
799                                            "Attempt to cut entire tree",
800                                            JOptionPane.ERROR_MESSAGE );
801             return;
802         }
803         final String label = getASimpleTextRepresentationOfANode( node );
804         final int r = JOptionPane.showConfirmDialog( null,
805                                                      "Cut subtree" + label + "?",
806                                                      "Confirm Cutting of Subtree",
807                                                      JOptionPane.YES_NO_OPTION );
808         if ( r != JOptionPane.OK_OPTION ) {
809             return;
810         }
811         _nodes_in_preorder = null;
812         setCopiedAndPastedNodes( null );
813         setCutOrCopiedTree( _phylogeny.copy( node ) );
814         _phylogeny.deleteSubtree( node, true );
815         _phylogeny.hashIDs();
816         _phylogeny.recalculateNumberOfExternalDescendants( true );
817         resetNodeIdToDistToLeafMap();
818         setEdited( true );
819         repaint();
820     }
821
822     final private void cycleColors() {
823         getMainPanel().getTreeColorSet().cycleColorScheme();
824         for( final TreePanel tree_panel : getMainPanel().getTreePanels() ) {
825             tree_panel.setBackground( getMainPanel().getTreeColorSet().getBackgroundColor() );
826         }
827     }
828
829     final void decreaseDomainStructureEvalueThreshold() {
830         if ( _domain_structure_e_value_thr_exp > -20 ) {
831             _domain_structure_e_value_thr_exp -= 1;
832         }
833     }
834
835     final private void decreaseOvSize() {
836         if ( ( getOvMaxWidth() > 20 ) && ( getOvMaxHeight() > 20 ) ) {
837             setOvMaxWidth( getOvMaxWidth() - 5 );
838             setOvMaxHeight( getOvMaxHeight() - 5 );
839             updateOvSettings();
840             getControlPanel().displayedPhylogenyMightHaveChanged( false );
841         }
842     }
843
844     final private void deleteNodeOrSubtree( final PhylogenyNode node ) {
845         if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) {
846             errorMessageNoCutCopyPasteInUnrootedDisplay();
847             return;
848         }
849         if ( node.isRoot() ) {
850             JOptionPane.showMessageDialog( this,
851                                            "Cannot delete entire tree",
852                                            "Attempt to delete entire tree",
853                                            JOptionPane.ERROR_MESSAGE );
854             return;
855         }
856         final String label = getASimpleTextRepresentationOfANode( node );
857         final Object[] options = { "Node only", "Entire subtree", "Cancel" };
858         final int r = JOptionPane.showOptionDialog( this,
859                                                     "Delete" + label + "?",
860                                                     "Delete Node/Subtree",
861                                                     JOptionPane.CLOSED_OPTION,
862                                                     JOptionPane.QUESTION_MESSAGE,
863                                                     null,
864                                                     options,
865                                                     options[ 2 ] );
866         _nodes_in_preorder = null;
867         boolean node_only = true;
868         if ( r == 1 ) {
869             node_only = false;
870         }
871         else if ( r != 0 ) {
872             return;
873         }
874         if ( node_only ) {
875             PhylogenyMethods.removeNode( node, _phylogeny );
876         }
877         else {
878             _phylogeny.deleteSubtree( node, true );
879         }
880         _phylogeny.externalNodesHaveChanged();
881         _phylogeny.hashIDs();
882         _phylogeny.recalculateNumberOfExternalDescendants( true );
883         resetNodeIdToDistToLeafMap();
884         setEdited( true );
885         repaint();
886     }
887
888     final private void displayNodePopupMenu( final PhylogenyNode node, final int x, final int y ) {
889         makePopupMenus( node );
890         _node_popup_menu.putClientProperty( NODE_POPMENU_NODE_CLIENT_PROPERTY, node );
891         _node_popup_menu.show( this, x, y );
892     }
893
894     final private void drawArc( final double x,
895                                 final double y,
896                                 final double width,
897                                 final double heigth,
898                                 final double start_angle,
899                                 final double arc_angle,
900                                 final Graphics2D g ) {
901         _arc.setArc( x, y, width, heigth, _180_OVER_PI * start_angle, _180_OVER_PI * arc_angle, Arc2D.OPEN );
902         g.draw( _arc );
903     }
904
905     final private void drawLine( final double x1, final double y1, final double x2, final double y2, final Graphics2D g ) {
906         if ( ( x1 == x2 ) && ( y1 == y2 ) ) {
907             return;
908         }
909         _line.setLine( x1, y1, x2, y2 );
910         g.draw( _line );
911     }
912
913     final private void drawOval( final double x,
914                                  final double y,
915                                  final double width,
916                                  final double heigth,
917                                  final Graphics2D g ) {
918         _ellipse.setFrame( x, y, width, heigth );
919         g.draw( _ellipse );
920     }
921
922     final private void drawOvalFilled( final double x,
923                                        final double y,
924                                        final double width,
925                                        final double heigth,
926                                        final Graphics2D g ) {
927         _ellipse.setFrame( x, y, width, heigth );
928         g.fill( _ellipse );
929     }
930
931     final private void drawRect( final float x, final float y, final float width, final float heigth, final Graphics2D g ) {
932         _rectangle.setFrame( x, y, width, heigth );
933         g.draw( _rectangle );
934     }
935
936     final private void drawRectFilled( final double x,
937                                        final double y,
938                                        final double width,
939                                        final double heigth,
940                                        final Graphics2D g ) {
941         _rectangle.setFrame( x, y, width, heigth );
942         g.fill( _rectangle );
943     }
944
945     final private void drawRectGradient( final double x,
946                                          final double y,
947                                          final double width,
948                                          final double heigth,
949                                          final Graphics2D g,
950                                          final Color color_1,
951                                          final Color color_2,
952                                          final Color color_border ) {
953         _rectangle.setFrame( x, y, width, heigth );
954         g.setPaint( new GradientPaint( ( float ) x,
955                                        ( float ) y,
956                                        color_1,
957                                        ( float ) ( x + width ),
958                                        ( float ) ( y + heigth ),
959                                        color_2,
960                                        false ) );
961         g.fill( _rectangle );
962         if ( color_border != null ) {
963             g.setPaint( color_border );
964             g.draw( _rectangle );
965         }
966     }
967
968     final private void drawOvalGradient( final double x,
969                                          final double y,
970                                          final double width,
971                                          final double heigth,
972                                          final Graphics2D g,
973                                          final Color color_1,
974                                          final Color color_2,
975                                          final Color color_border ) {
976         _ellipse.setFrame( x, y, width, heigth );
977         g.setPaint( new GradientPaint( ( float ) x,
978                                        ( float ) y,
979                                        color_1,
980                                        ( float ) ( x + width ),
981                                        ( float ) ( y + heigth ),
982                                        color_2,
983                                        false ) );
984         g.fill( _ellipse );
985         if ( color_border != null ) {
986             g.setPaint( color_border );
987             g.draw( _ellipse );
988         }
989     }
990
991     final private void errorMessageNoCutCopyPasteInUnrootedDisplay() {
992         JOptionPane.showMessageDialog( this,
993                                        "Cannot cut, copy, paste, add, or delete subtrees/nodes in unrooted display",
994                                        "Attempt to cut/copy/paste/add/delete in unrooted display",
995                                        JOptionPane.ERROR_MESSAGE );
996     }
997
998     /**
999      * Find the node, if any, at the given location
1000      * 
1001      * @param x
1002      * @param y
1003      * @return pointer to the node at x,y, null if not found
1004      */
1005     final PhylogenyNode findNode( final int x, final int y ) {
1006         if ( ( _phylogeny == null ) || _phylogeny.isEmpty() ) {
1007             return null;
1008         }
1009         final int half_box_size_plus_wiggle = getOptions().getDefaultNodeShapeSize() / 2 + WIGGLE;
1010         for( final PhylogenyNodeIterator iter = _phylogeny.iteratorPostorder(); iter.hasNext(); ) {
1011             final PhylogenyNode node = iter.next();
1012             if ( ( _phylogeny.isRooted() || !node.isRoot() || ( node.getNumberOfDescendants() > 2 ) )
1013                     && ( ( node.getXcoord() - half_box_size_plus_wiggle ) <= x )
1014                     && ( ( node.getXcoord() + half_box_size_plus_wiggle ) >= x )
1015                     && ( ( node.getYcoord() - half_box_size_plus_wiggle ) <= y )
1016                     && ( ( node.getYcoord() + half_box_size_plus_wiggle ) >= y ) ) {
1017                 return node;
1018             }
1019         }
1020         return null;
1021     }
1022
1023     final private String getASimpleTextRepresentationOfANode( final PhylogenyNode node ) {
1024         final String tax = PhylogenyMethods.getSpecies( node );
1025         String label = node.getName();
1026         if ( !ForesterUtil.isEmpty( label ) && !ForesterUtil.isEmpty( tax ) ) {
1027             label = label + " " + tax;
1028         }
1029         else if ( !ForesterUtil.isEmpty( tax ) ) {
1030             label = tax;
1031         }
1032         else {
1033             label = "";
1034         }
1035         if ( !ForesterUtil.isEmpty( label ) ) {
1036             label = " [" + label + "]";
1037         }
1038         return label;
1039     }
1040
1041     final Configuration getConfiguration() {
1042         return _configuration;
1043     }
1044
1045     final ControlPanel getControlPanel() {
1046         return _control_panel;
1047     }
1048
1049     final private Set<Integer> getCopiedAndPastedNodes() {
1050         return getMainPanel().getCopiedAndPastedNodes();
1051     }
1052
1053     final private Phylogeny getCutOrCopiedTree() {
1054         return getMainPanel().getCutOrCopiedTree();
1055     }
1056
1057     final int getDomainStructureEvalueThreshold() {
1058         return _domain_structure_e_value_thr_exp;
1059     }
1060
1061     final Set<Integer> getFoundNodes() {
1062         return _found_nodes;
1063     }
1064
1065     final private float getLastDragPointX() {
1066         return _last_drag_point_x;
1067     }
1068
1069     final private float getLastDragPointY() {
1070         return _last_drag_point_y;
1071     }
1072
1073     final int getLongestExtNodeInfo() {
1074         return _longest_ext_node_info;
1075     }
1076
1077     final public MainPanel getMainPanel() {
1078         return _main_panel;
1079     }
1080
1081     final private short getMaxBranchesToLeaf( final PhylogenyNode node ) {
1082         if ( !_nodeid_dist_to_leaf.containsKey( node.getId() ) ) {
1083             final short m = PhylogenyMethods.calculateMaxBranchesToLeaf( node );
1084             _nodeid_dist_to_leaf.put( node.getId(), m );
1085             return m;
1086         }
1087         else {
1088             return _nodeid_dist_to_leaf.get( node.getId() );
1089         }
1090     }
1091
1092     final private double getMaxDistanceToRoot() {
1093         if ( _max_distance_to_root < 0 ) {
1094             recalculateMaxDistanceToRoot();
1095         }
1096         return _max_distance_to_root;
1097     }
1098
1099     final Options getOptions() {
1100         if ( _options == null ) {
1101             _options = getControlPanel().getOptions();
1102         }
1103         return _options;
1104     }
1105
1106     final private float getOvMaxHeight() {
1107         return _ov_max_height;
1108     }
1109
1110     final private float getOvMaxWidth() {
1111         return _ov_max_width;
1112     }
1113
1114     final Rectangle2D getOvRectangle() {
1115         return _ov_rectangle;
1116     }
1117
1118     final Rectangle getOvVirtualRectangle() {
1119         return _ov_virtual_rectangle;
1120     }
1121
1122     final private float getOvXcorrectionFactor() {
1123         return _ov_x_correction_factor;
1124     }
1125
1126     final private float getOvXDistance() {
1127         return _ov_x_distance;
1128     }
1129
1130     final private int getOvXPosition() {
1131         return _ov_x_position;
1132     }
1133
1134     final private float getOvYDistance() {
1135         return _ov_y_distance;
1136     }
1137
1138     final private int getOvYPosition() {
1139         return _ov_y_position;
1140     }
1141
1142     final private int getOvYStart() {
1143         return _ov_y_start;
1144     }
1145
1146     /**
1147      * Get a pointer to the phylogeny 
1148      * 
1149      * @return a pointer to the phylogeny
1150      */
1151     public final Phylogeny getPhylogeny() {
1152         return _phylogeny;
1153     }
1154
1155     final PHYLOGENY_GRAPHICS_TYPE getPhylogenyGraphicsType() {
1156         return _graphics_type;
1157     }
1158
1159     final private double getScaleDistance() {
1160         return _scale_distance;
1161     }
1162
1163     final private String getScaleLabel() {
1164         return _scale_label;
1165     }
1166
1167     final double getStartingAngle() {
1168         return _urt_starting_angle;
1169     }
1170
1171     /**
1172      * Find a color for this species name.
1173      * 
1174      * @param species
1175      * @return the species color
1176      */
1177     final Color getTaxonomyBasedColor( final PhylogenyNode node ) {
1178         if ( node.getNodeData().isHasTaxonomy() ) {
1179             return calculateTaxonomyBasedColor( node.getNodeData().getTaxonomy() );
1180         }
1181         // return non-colorized color
1182         return getTreeColorSet().getTaxonomyColor();
1183     }
1184
1185     /**
1186      * @return pointer to colorset for tree drawing
1187      */
1188     final TreeColorSet getTreeColorSet() {
1189         return getMainPanel().getTreeColorSet();
1190     }
1191
1192     final File getTreeFile() {
1193         return _treefile;
1194     }
1195
1196     final private TreeFontSet getTreeFontSet() {
1197         return getMainPanel().getTreeFontSet();
1198     }
1199
1200     final private float getUrtFactor() {
1201         return _urt_factor;
1202     }
1203
1204     final private float getUrtFactorOv() {
1205         return _urt_factor_ov;
1206     }
1207
1208     final float getXcorrectionFactor() {
1209         return _x_correction_factor;
1210     }
1211
1212     final float getXdistance() {
1213         return _x_distance;
1214     }
1215
1216     final float getYdistance() {
1217         return _y_distance;
1218     }
1219
1220     final private void handleClickToAction( final NodeClickAction action, final PhylogenyNode node ) {
1221         switch ( action ) {
1222             case SHOW_DATA:
1223                 showNodeFrame( node );
1224                 break;
1225             case COLLAPSE:
1226                 collapse( node );
1227                 break;
1228             case REROOT:
1229                 reRoot( node );
1230                 break;
1231             case SUBTREE:
1232                 subTree( node );
1233                 break;
1234             case SWAP:
1235                 swap( node );
1236                 break;
1237             case COLOR_SUBTREE:
1238                 colorSubtree( node );
1239                 break;
1240             case OPEN_SEQ_WEB:
1241                 openSeqWeb( node );
1242                 break;
1243             case BLAST:
1244                 blast( node );
1245                 break;
1246             case OPEN_TAX_WEB:
1247                 openTaxWeb( node );
1248                 break;
1249             case CUT_SUBTREE:
1250                 cutSubtree( node );
1251                 break;
1252             case COPY_SUBTREE:
1253                 copySubtree( node );
1254                 break;
1255             case PASTE_SUBTREE:
1256                 pasteSubtree( node );
1257                 break;
1258             case DELETE_NODE_OR_SUBTREE:
1259                 deleteNodeOrSubtree( node );
1260                 break;
1261             case ADD_NEW_NODE:
1262                 addEmptyNode( node );
1263                 break;
1264             case EDIT_NODE_DATA:
1265                 showNodeEditFrame( node );
1266                 break;
1267             default:
1268                 throw new IllegalArgumentException( "unknown action: " + action );
1269         }
1270     }
1271
1272     final void increaseDomainStructureEvalueThreshold() {
1273         if ( _domain_structure_e_value_thr_exp < 3 ) {
1274             _domain_structure_e_value_thr_exp += 1;
1275         }
1276     }
1277
1278     final private void increaseOvSize() {
1279         if ( ( getOvMaxWidth() < getMainPanel().getCurrentScrollPane().getViewport().getVisibleRect().getWidth() / 2 )
1280                 && ( getOvMaxHeight() < getMainPanel().getCurrentScrollPane().getViewport().getVisibleRect()
1281                         .getHeight() / 2 ) ) {
1282             setOvMaxWidth( getOvMaxWidth() + 5 );
1283             setOvMaxHeight( getOvMaxHeight() + 5 );
1284             updateOvSettings();
1285             getControlPanel().displayedPhylogenyMightHaveChanged( false );
1286         }
1287     }
1288
1289     final void inferCommonPartOfScientificNames() {
1290         if ( ( _phylogeny == null ) || ( _phylogeny.getNumberOfExternalNodes() < 2 ) ) {
1291             return;
1292         }
1293         setWaitCursor();
1294         Util.inferCommonPartOfScientificNames( _phylogeny );
1295         setArrowCursor();
1296         repaint();
1297     }
1298
1299     final private void init() {
1300         _color_chooser = new JColorChooser();
1301         _rollover_popup = new JTextArea();
1302         _rollover_popup.setFont( POPUP_FONT );
1303         resetNodeIdToDistToLeafMap();
1304         setTextAntialias();
1305         setTreeFile( null );
1306         setEdited( false );
1307         initializeOvSettings();
1308         setStartingAngle( TWO_PI * 3 / 4 );
1309         final ImageLoader il = new ImageLoader( this );
1310         new Thread( il ).start();
1311     }
1312
1313     final private void initializeOvSettings() {
1314         setOvMaxHeight( getConfiguration().getOvMaxHeight() );
1315         setOvMaxWidth( getConfiguration().getOvMaxWidth() );
1316     }
1317
1318     final void initNodeData() {
1319         if ( ( _phylogeny == null ) || _phylogeny.isEmpty() ) {
1320             return;
1321         }
1322         double max_original_domain_structure_width = 0.0;
1323         for( final PhylogenyNode node : _phylogeny.getExternalNodes() ) {
1324             if ( node.getNodeData().isHasSequence()
1325                     && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1326                 RenderableDomainArchitecture rds = null;
1327                 if ( !( node.getNodeData().getSequence().getDomainArchitecture() instanceof RenderableDomainArchitecture ) ) {
1328                     rds = new RenderableDomainArchitecture( node.getNodeData().getSequence().getDomainArchitecture(),
1329                                                             getConfiguration() );
1330                     node.getNodeData().getSequence().setDomainArchitecture( rds );
1331                 }
1332                 else {
1333                     rds = ( RenderableDomainArchitecture ) node.getNodeData().getSequence().getDomainArchitecture();
1334                 }
1335                 if ( getControlPanel().isShowDomainArchitectures() ) {
1336                     final double dsw = rds.getOriginalSize().getWidth();
1337                     if ( dsw > max_original_domain_structure_width ) {
1338                         max_original_domain_structure_width = dsw;
1339                     }
1340                 }
1341             }
1342         }
1343         if ( getControlPanel().isShowDomainArchitectures() ) {
1344             final double ds_factor_width = _domain_structure_width / max_original_domain_structure_width;
1345             for( final PhylogenyNode node : _phylogeny.getExternalNodes() ) {
1346                 if ( node.getNodeData().isHasSequence()
1347                         && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1348                     final RenderableDomainArchitecture rds = ( RenderableDomainArchitecture ) node.getNodeData()
1349                             .getSequence().getDomainArchitecture();
1350                     rds.setRenderingFactorWidth( ds_factor_width );
1351                     rds.setParameter( _domain_structure_e_value_thr_exp );
1352                 }
1353             }
1354         }
1355     }
1356
1357     final boolean inOv( final MouseEvent e ) {
1358         return ( ( e.getX() > getVisibleRect().x + getOvXPosition() + 1 )
1359                 && ( e.getX() < getVisibleRect().x + getOvXPosition() + getOvMaxWidth() - 1 )
1360                 && ( e.getY() > getVisibleRect().y + getOvYPosition() + 1 ) && ( e.getY() < getVisibleRect().y
1361                 + getOvYPosition() + getOvMaxHeight() - 1 ) );
1362     }
1363
1364     final boolean inOvRectangle( final MouseEvent e ) {
1365         return ( ( e.getX() >= getOvRectangle().getX() - 1 )
1366                 && ( e.getX() <= getOvRectangle().getX() + getOvRectangle().getWidth() + 1 )
1367                 && ( e.getY() >= getOvRectangle().getY() - 1 ) && ( e.getY() <= getOvRectangle().getY()
1368                 + getOvRectangle().getHeight() + 1 ) );
1369     }
1370
1371     final private boolean inOvVirtualRectangle( final int x, final int y ) {
1372         return ( ( x >= getOvVirtualRectangle().x - 1 )
1373                 && ( x <= getOvVirtualRectangle().x + getOvVirtualRectangle().width + 1 )
1374                 && ( y >= getOvVirtualRectangle().y - 1 ) && ( y <= getOvVirtualRectangle().y
1375                 + getOvVirtualRectangle().height + 1 ) );
1376     }
1377
1378     final private boolean inOvVirtualRectangle( final MouseEvent e ) {
1379         return ( inOvVirtualRectangle( e.getX(), e.getY() ) );
1380     }
1381
1382     final boolean isApplet() {
1383         return getMainPanel() instanceof MainPanelApplets;
1384     }
1385
1386     final private boolean isCanBlast( final PhylogenyNode node ) {
1387         return ( node.getNodeData().isHasSequence() && ( ( ( node.getNodeData().getSequence().getAccession() != null ) && !ForesterUtil
1388                 .isEmpty( node.getNodeData().getSequence().getAccession().getValue() ) )
1389                 || !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) || !ForesterUtil.isEmpty( node
1390                 .getNodeData().getSequence().getSymbol() ) ) );
1391     }
1392
1393     final boolean isCanCollapse() {
1394         return ( getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.UNROOTED );
1395     }
1396
1397     final boolean isCanColorSubtree() {
1398         return ( getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.UNROOTED );
1399     }
1400
1401     final boolean isCanCopy() {
1402         return ( ( getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) && getOptions().isEditable() );
1403     }
1404
1405     final boolean isCanCut( final PhylogenyNode node ) {
1406         return ( ( getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) && getOptions().isEditable() && !node
1407                 .isRoot() );
1408     }
1409
1410     final boolean isCanDelete() {
1411         return ( ( getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) && getOptions().isEditable() );
1412     }
1413
1414     final private boolean isCanOpenSeqWeb( final PhylogenyNode node ) {
1415         if ( node.getNodeData().isHasSequence()
1416                 && ( node.getNodeData().getSequence().getAccession() != null )
1417                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().getSource() )
1418                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().getValue() )
1419                 && getConfiguration().isHasWebLink( node.getNodeData().getSequence().getAccession().getSource()
1420                         .toLowerCase() ) ) {
1421             return true;
1422         }
1423         return false;
1424     }
1425
1426     final private boolean isCanOpenTaxWeb( final PhylogenyNode node ) {
1427         if ( node.getNodeData().isHasTaxonomy()
1428                 && ( ( ( node.getNodeData().getTaxonomy().getIdentifier() != null )
1429                         && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getIdentifier().getProvider() )
1430                         && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getIdentifier().getValue() ) && getConfiguration()
1431                         .isHasWebLink( node.getNodeData().getTaxonomy().getIdentifier().getProvider().toLowerCase() ) )
1432                         || ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) )
1433                         || ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1434                         || ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getCommonName() ) ) || ( ( node
1435                         .getNodeData().getTaxonomy().getIdentifier() != null )
1436                         && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getIdentifier().getValue() ) && node
1437                         .getNodeData().getTaxonomy().getIdentifier().getValue().startsWith( "http://" ) ) ) ) {
1438             return true;
1439         }
1440         else {
1441             return false;
1442         }
1443     }
1444
1445     final boolean isCanPaste() {
1446         return ( ( getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) && getOptions().isEditable()
1447                 && ( getCutOrCopiedTree() != null ) && !getCutOrCopiedTree().isEmpty() );
1448     }
1449
1450     final boolean isCanReroot() {
1451         return ( ( getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) && ( _subtree_index < 1 ) );
1452     }
1453
1454     final boolean isCanSubtree( final PhylogenyNode node ) {
1455         return ( ( getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) && !node.isExternal() && ( !node
1456                 .isRoot() || ( _subtree_index > 0 ) ) );
1457     }
1458
1459     final boolean isEdited() {
1460         return _edited;
1461     }
1462
1463     final private boolean isInFoundNodes( final PhylogenyNode node ) {
1464         return ( ( getFoundNodes() != null ) && getFoundNodes().contains( node.getId() ) );
1465     }
1466
1467     final private boolean isInOv() {
1468         return _in_ov;
1469     }
1470
1471     final boolean isInOvRect() {
1472         return _in_ov_rect;
1473     }
1474
1475     final private boolean isNodeDataInvisible( final PhylogenyNode node ) {
1476         int y_dist = 40;
1477         if ( getControlPanel().isShowTaxonomyImages() ) {
1478             y_dist = 40 + ( int ) getYdistance();
1479         }
1480         return ( ( node.getYcoord() < getVisibleRect().getMinY() - y_dist )
1481                 || ( node.getYcoord() > getVisibleRect().getMaxY() + y_dist ) || ( ( node.getParent() != null ) && ( node
1482                 .getParent().getXcoord() > getVisibleRect().getMaxX() ) ) );
1483     }
1484
1485     final private boolean isNodeDataInvisibleUnrootedCirc( final PhylogenyNode node ) {
1486         return ( ( node.getYcoord() < getVisibleRect().getMinY() - 20 )
1487                 || ( node.getYcoord() > getVisibleRect().getMaxY() + 20 )
1488                 || ( node.getXcoord() < getVisibleRect().getMinX() - 20 ) || ( node.getXcoord() > getVisibleRect()
1489                 .getMaxX() + 20 ) );
1490     }
1491
1492     final private boolean isNonLinedUpCladogram() {
1493         return getOptions().getCladogramType() == CLADOGRAM_TYPE.NON_LINED_UP;
1494     }
1495
1496     final boolean isOvOn() {
1497         return _ov_on;
1498     }
1499
1500     final boolean isPhyHasBranchLengths() {
1501         return _phy_has_branch_lengths;
1502     }
1503
1504     final private boolean isUniformBranchLengthsForCladogram() {
1505         return getOptions().getCladogramType() == CLADOGRAM_TYPE.TOTAL_NODE_SUM_DEP;
1506     }
1507
1508     final private void keyPressedCalls( final KeyEvent e ) {
1509         if ( isOvOn() && ( getMousePosition() != null ) && ( getMousePosition().getLocation() != null ) ) {
1510             if ( inOvVirtualRectangle( getMousePosition().x, getMousePosition().y ) ) {
1511                 if ( !isInOvRect() ) {
1512                     setInOvRect( true );
1513                 }
1514             }
1515             else if ( isInOvRect() ) {
1516                 setInOvRect( false );
1517             }
1518         }
1519         if ( e.getModifiersEx() == InputEvent.CTRL_DOWN_MASK ) {
1520             if ( ( e.getKeyCode() == KeyEvent.VK_DELETE ) || ( e.getKeyCode() == KeyEvent.VK_HOME )
1521                     || ( e.getKeyCode() == KeyEvent.VK_F ) ) {
1522                 getMainPanel().getTreeFontSet().mediumFonts();
1523                 getMainPanel().getControlPanel().displayedPhylogenyMightHaveChanged( true );
1524             }
1525             else if ( ( e.getKeyCode() == KeyEvent.VK_SUBTRACT ) || ( e.getKeyCode() == KeyEvent.VK_MINUS ) ) {
1526                 getMainPanel().getTreeFontSet().decreaseFontSize();
1527                 getMainPanel().getControlPanel().displayedPhylogenyMightHaveChanged( true );
1528             }
1529             else if ( plusPressed( e.getKeyCode() ) ) {
1530                 getMainPanel().getTreeFontSet().increaseFontSize();
1531                 getMainPanel().getControlPanel().displayedPhylogenyMightHaveChanged( true );
1532             }
1533         }
1534         else {
1535             if ( ( e.getKeyCode() == KeyEvent.VK_DELETE ) || ( e.getKeyCode() == KeyEvent.VK_HOME )
1536                     || ( e.getKeyCode() == KeyEvent.VK_F ) ) {
1537                 getControlPanel().showWhole();
1538             }
1539             else if ( ( e.getKeyCode() == KeyEvent.VK_UP ) || ( e.getKeyCode() == KeyEvent.VK_DOWN )
1540                     || ( e.getKeyCode() == KeyEvent.VK_LEFT ) || ( e.getKeyCode() == KeyEvent.VK_RIGHT ) ) {
1541                 if ( e.getModifiersEx() == InputEvent.SHIFT_DOWN_MASK ) {
1542                     if ( e.getKeyCode() == KeyEvent.VK_UP ) {
1543                         getMainPanel().getControlPanel().zoomInY( Constants.WHEEL_ZOOM_IN_FACTOR );
1544                         getMainPanel().getControlPanel().displayedPhylogenyMightHaveChanged( false );
1545                     }
1546                     else if ( e.getKeyCode() == KeyEvent.VK_DOWN ) {
1547                         getMainPanel().getControlPanel().zoomOutY( Constants.WHEEL_ZOOM_OUT_FACTOR );
1548                         getMainPanel().getControlPanel().displayedPhylogenyMightHaveChanged( false );
1549                     }
1550                     else if ( e.getKeyCode() == KeyEvent.VK_LEFT ) {
1551                         getMainPanel().getControlPanel().zoomOutX( Constants.WHEEL_ZOOM_OUT_FACTOR,
1552                                                                    Constants.WHEEL_ZOOM_OUT_X_CORRECTION_FACTOR );
1553                         getMainPanel().getControlPanel().displayedPhylogenyMightHaveChanged( false );
1554                     }
1555                     else if ( e.getKeyCode() == KeyEvent.VK_RIGHT ) {
1556                         getMainPanel().getControlPanel().zoomInX( Constants.WHEEL_ZOOM_IN_FACTOR,
1557                                                                   Constants.WHEEL_ZOOM_IN_FACTOR );
1558                         getMainPanel().getControlPanel().displayedPhylogenyMightHaveChanged( false );
1559                     }
1560                 }
1561                 else {
1562                     final int d = 80;
1563                     int dx = 0;
1564                     int dy = -d;
1565                     if ( e.getKeyCode() == KeyEvent.VK_DOWN ) {
1566                         dy = d;
1567                     }
1568                     else if ( e.getKeyCode() == KeyEvent.VK_LEFT ) {
1569                         dx = -d;
1570                         dy = 0;
1571                     }
1572                     else if ( e.getKeyCode() == KeyEvent.VK_RIGHT ) {
1573                         dx = d;
1574                         dy = 0;
1575                     }
1576                     final Point scroll_position = getMainPanel().getCurrentScrollPane().getViewport().getViewPosition();
1577                     scroll_position.x = scroll_position.x + dx;
1578                     scroll_position.y = scroll_position.y + dy;
1579                     if ( scroll_position.x <= 0 ) {
1580                         scroll_position.x = 0;
1581                     }
1582                     else {
1583                         final int max_x = getMainPanel().getCurrentScrollPane().getHorizontalScrollBar().getMaximum()
1584                                 - getMainPanel().getCurrentScrollPane().getHorizontalScrollBar().getVisibleAmount();
1585                         if ( scroll_position.x >= max_x ) {
1586                             scroll_position.x = max_x;
1587                         }
1588                     }
1589                     if ( scroll_position.y <= 0 ) {
1590                         scroll_position.y = 0;
1591                     }
1592                     else {
1593                         final int max_y = getMainPanel().getCurrentScrollPane().getVerticalScrollBar().getMaximum()
1594                                 - getMainPanel().getCurrentScrollPane().getVerticalScrollBar().getVisibleAmount();
1595                         if ( scroll_position.y >= max_y ) {
1596                             scroll_position.y = max_y;
1597                         }
1598                     }
1599                     repaint();
1600                     getMainPanel().getCurrentScrollPane().getViewport().setViewPosition( scroll_position );
1601                 }
1602             }
1603             else if ( ( e.getKeyCode() == KeyEvent.VK_SUBTRACT ) || ( e.getKeyCode() == KeyEvent.VK_MINUS ) ) {
1604                 getMainPanel().getControlPanel().zoomOutY( Constants.WHEEL_ZOOM_OUT_FACTOR );
1605                 getMainPanel().getControlPanel().zoomOutX( Constants.WHEEL_ZOOM_OUT_FACTOR,
1606                                                            Constants.WHEEL_ZOOM_OUT_X_CORRECTION_FACTOR );
1607                 getMainPanel().getControlPanel().displayedPhylogenyMightHaveChanged( false );
1608             }
1609             else if ( plusPressed( e.getKeyCode() ) ) {
1610                 getMainPanel().getControlPanel().zoomInX( Constants.WHEEL_ZOOM_IN_FACTOR,
1611                                                           Constants.WHEEL_ZOOM_IN_FACTOR );
1612                 getMainPanel().getControlPanel().zoomInY( Constants.WHEEL_ZOOM_IN_FACTOR );
1613                 getMainPanel().getControlPanel().displayedPhylogenyMightHaveChanged( false );
1614             }
1615             else if ( e.getKeyCode() == KeyEvent.VK_S ) {
1616                 if ( ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED )
1617                         || ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) {
1618                     setStartingAngle( ( getStartingAngle() % TWO_PI ) + ANGLE_ROTATION_UNIT );
1619                     getControlPanel().displayedPhylogenyMightHaveChanged( false );
1620                 }
1621             }
1622             else if ( e.getKeyCode() == KeyEvent.VK_A ) {
1623                 if ( ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED )
1624                         || ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) {
1625                     setStartingAngle( ( getStartingAngle() % TWO_PI ) - ANGLE_ROTATION_UNIT );
1626                     if ( getStartingAngle() < 0 ) {
1627                         setStartingAngle( TWO_PI + getStartingAngle() );
1628                     }
1629                     getControlPanel().displayedPhylogenyMightHaveChanged( false );
1630                 }
1631             }
1632             else if ( e.getKeyCode() == KeyEvent.VK_D ) {
1633                 boolean selected = false;
1634                 if ( getOptions().getNodeLabelDirection() == NODE_LABEL_DIRECTION.HORIZONTAL ) {
1635                     getOptions().setNodeLabelDirection( NODE_LABEL_DIRECTION.RADIAL );
1636                     selected = true;
1637                 }
1638                 else {
1639                     getOptions().setNodeLabelDirection( NODE_LABEL_DIRECTION.HORIZONTAL );
1640                 }
1641                 if ( getMainPanel().getMainFrame() == null ) {
1642                     // Must be "E" applet version.
1643                     final ArchaeopteryxE ae = ( ArchaeopteryxE ) ( ( MainPanelApplets ) getMainPanel() ).getApplet();
1644                     if ( ae.getlabelDirectionCbmi() != null ) {
1645                         ae.getlabelDirectionCbmi().setSelected( selected );
1646                     }
1647                 }
1648                 else {
1649                     getMainPanel().getMainFrame().getlabelDirectionCbmi().setSelected( selected );
1650                 }
1651                 repaint();
1652             }
1653             else if ( e.getKeyCode() == KeyEvent.VK_X ) {
1654                 switchDisplaygetPhylogenyGraphicsType();
1655                 repaint();
1656             }
1657             else if ( e.getKeyCode() == KeyEvent.VK_C ) {
1658                 cycleColors();
1659                 repaint();
1660             }
1661             else if ( getOptions().isShowOverview() && isOvOn() && ( e.getKeyCode() == KeyEvent.VK_O ) ) {
1662                 MainFrame.cycleOverview( getOptions(), this );
1663                 repaint();
1664             }
1665             else if ( getOptions().isShowOverview() && isOvOn() && ( e.getKeyCode() == KeyEvent.VK_I ) ) {
1666                 increaseOvSize();
1667             }
1668             else if ( getOptions().isShowOverview() && isOvOn() && ( e.getKeyCode() == KeyEvent.VK_U ) ) {
1669                 decreaseOvSize();
1670             }
1671             e.consume();
1672         }
1673     }
1674
1675     final private void makePopupMenus( final PhylogenyNode node ) {
1676         _node_popup_menu = new JPopupMenu();
1677         final List<String> clickto_names = _main_panel.getControlPanel().getSingleClickToNames();
1678         _node_popup_menu_items = new JMenuItem[ clickto_names.size() ];
1679         for( int i = 0; i < clickto_names.size(); i++ ) {
1680             final String title = clickto_names.get( i );
1681             _node_popup_menu_items[ i ] = new JMenuItem( title );
1682             if ( title.equals( Configuration.clickto_options[ Configuration.open_seq_web ][ 0 ] ) ) {
1683                 _node_popup_menu_items[ i ].setEnabled( isCanOpenSeqWeb( node ) );
1684             }
1685             else if ( title.equals( Configuration.clickto_options[ Configuration.open_tax_web ][ 0 ] ) ) {
1686                 _node_popup_menu_items[ i ].setEnabled( isCanOpenTaxWeb( node ) );
1687             }
1688             else if ( title.equals( Configuration.clickto_options[ Configuration.blast ][ 0 ] ) ) {
1689                 if ( Constants.__RELEASE || Constants.__SNAPSHOT_RELEASE ) {
1690                     continue;
1691                 }
1692                 _node_popup_menu_items[ i ].setEnabled( isCanBlast( node ) );
1693             }
1694             else if ( title.equals( Configuration.clickto_options[ Configuration.delete_subtree_or_node ][ 0 ] ) ) {
1695                 if ( !getOptions().isEditable() ) {
1696                     continue;
1697                 }
1698                 _node_popup_menu_items[ i ].setEnabled( isCanDelete() );
1699             }
1700             else if ( title.equals( Configuration.clickto_options[ Configuration.cut_subtree ][ 0 ] ) ) {
1701                 if ( !getOptions().isEditable() ) {
1702                     continue;
1703                 }
1704                 _node_popup_menu_items[ i ].setEnabled( isCanCut( node ) );
1705             }
1706             else if ( title.equals( Configuration.clickto_options[ Configuration.copy_subtree ][ 0 ] ) ) {
1707                 if ( !getOptions().isEditable() ) {
1708                     continue;
1709                 }
1710                 _node_popup_menu_items[ i ].setEnabled( isCanCopy() );
1711             }
1712             else if ( title.equals( Configuration.clickto_options[ Configuration.paste_subtree ][ 0 ] ) ) {
1713                 if ( !getOptions().isEditable() ) {
1714                     continue;
1715                 }
1716                 _node_popup_menu_items[ i ].setEnabled( isCanPaste() );
1717             }
1718             else if ( title.equals( Configuration.clickto_options[ Configuration.edit_node_data ][ 0 ] ) ) {
1719                 if ( !getOptions().isEditable() ) {
1720                     continue;
1721                 }
1722             }
1723             else if ( title.equals( Configuration.clickto_options[ Configuration.add_new_node ][ 0 ] ) ) {
1724                 if ( !getOptions().isEditable() ) {
1725                     continue;
1726                 }
1727             }
1728             else if ( title.equals( Configuration.clickto_options[ Configuration.reroot ][ 0 ] ) ) {
1729                 _node_popup_menu_items[ i ].setEnabled( isCanReroot() );
1730             }
1731             else if ( title.equals( Configuration.clickto_options[ Configuration.collapse_uncollapse ][ 0 ] ) ) {
1732                 _node_popup_menu_items[ i ].setEnabled( isCanCollapse() );
1733             }
1734             else if ( title.equals( Configuration.clickto_options[ Configuration.color_subtree ][ 0 ] ) ) {
1735                 _node_popup_menu_items[ i ].setEnabled( isCanColorSubtree() );
1736             }
1737             else if ( title.equals( Configuration.clickto_options[ Configuration.subtree ][ 0 ] ) ) {
1738                 _node_popup_menu_items[ i ].setEnabled( isCanSubtree( node ) );
1739             }
1740             _node_popup_menu_items[ i ].addActionListener( this );
1741             _node_popup_menu.add( _node_popup_menu_items[ i ] );
1742         }
1743     }
1744
1745     final void midpointRoot() {
1746         if ( ( _phylogeny == null ) || ( _phylogeny.getNumberOfExternalNodes() < 2 ) ) {
1747             return;
1748         }
1749         if ( !_phylogeny.isRerootable() ) {
1750             JOptionPane.showMessageDialog( this,
1751                                            "This is not rerootable",
1752                                            "Not rerootable",
1753                                            JOptionPane.WARNING_MESSAGE );
1754             return;
1755         }
1756         _nodes_in_preorder = null;
1757         setWaitCursor();
1758         PhylogenyMethods.midpointRoot( _phylogeny );
1759         resetNodeIdToDistToLeafMap();
1760         setArrowCursor();
1761         repaint();
1762     }
1763
1764     final void mouseClicked( final MouseEvent e ) {
1765         if ( getOptions().isShowOverview() && isOvOn() && isInOv() ) {
1766             final double w_ratio = getVisibleRect().width / getOvRectangle().getWidth();
1767             final double h_ratio = getVisibleRect().height / getOvRectangle().getHeight();
1768             double x = ( e.getX() - getVisibleRect().x - getOvXPosition() - getOvRectangle().getWidth() / 2.0 )
1769                     * w_ratio;
1770             double y = ( e.getY() - getVisibleRect().y - getOvYPosition() - getOvRectangle().getHeight() / 2.0 )
1771                     * h_ratio;
1772             if ( x < 0 ) {
1773                 x = 0;
1774             }
1775             if ( y < 0 ) {
1776                 y = 0;
1777             }
1778             final double max_x = getWidth() - getVisibleRect().width;
1779             final double max_y = getHeight() - getVisibleRect().height;
1780             if ( x > max_x ) {
1781                 x = max_x;
1782             }
1783             if ( y > max_y ) {
1784                 y = max_y;
1785             }
1786             getMainPanel().getCurrentScrollPane().getViewport()
1787                     .setViewPosition( new Point( ForesterUtil.roundToInt( x ), ForesterUtil.roundToInt( y ) ) );
1788             setInOvRect( true );
1789             repaint();
1790         }
1791         else {
1792             final PhylogenyNode node = findNode( e.getX(), e.getY() );
1793             if ( node != null ) {
1794                 if ( !node.isRoot() && node.getParent().isCollapse() ) {
1795                     return;
1796                 }
1797                 _highlight_node = node;
1798                 // Check if shift key is down
1799                 if ( ( e.getModifiers() & InputEvent.SHIFT_MASK ) != 0 ) {
1800                     // Yes, so add to _found_nodes
1801                     if ( getFoundNodes() == null ) {
1802                         setFoundNodes( new HashSet<Integer>() );
1803                     }
1804                     getFoundNodes().add( node.getId() );
1805                     // Check if control key is down
1806                 }
1807                 else if ( ( e.getModifiers() & InputEvent.CTRL_MASK ) != 0 ) {
1808                     // Yes, so pop-up menu
1809                     displayNodePopupMenu( node, e.getX(), e.getY() );
1810                     // Handle unadorned click
1811                 }
1812                 else {
1813                     // Check for right mouse button
1814                     if ( e.getModifiers() == 4 ) {
1815                         displayNodePopupMenu( node, e.getX(), e.getY() );
1816                     }
1817                     else {
1818                         // if not in _found_nodes, clear _found_nodes
1819                         handleClickToAction( _control_panel.getActionWhenNodeClicked(), node );
1820                     }
1821                 }
1822             }
1823             else {
1824                 // no node was clicked
1825                 _highlight_node = null;
1826             }
1827         }
1828         repaint();
1829     }
1830
1831     final void mouseDragInBrowserPanel( final MouseEvent e ) {
1832         setCursor( MOVE_CURSOR );
1833         final Point scroll_position = getMainPanel().getCurrentScrollPane().getViewport().getViewPosition();
1834         scroll_position.x -= ( e.getX() - getLastDragPointX() );
1835         scroll_position.y -= ( e.getY() - getLastDragPointY() );
1836         if ( scroll_position.x < 0 ) {
1837             scroll_position.x = 0;
1838         }
1839         else {
1840             final int max_x = getMainPanel().getCurrentScrollPane().getHorizontalScrollBar().getMaximum()
1841                     - getMainPanel().getCurrentScrollPane().getHorizontalScrollBar().getVisibleAmount();
1842             if ( scroll_position.x > max_x ) {
1843                 scroll_position.x = max_x;
1844             }
1845         }
1846         if ( scroll_position.y < 0 ) {
1847             scroll_position.y = 0;
1848         }
1849         else {
1850             final int max_y = getMainPanel().getCurrentScrollPane().getVerticalScrollBar().getMaximum()
1851                     - getMainPanel().getCurrentScrollPane().getVerticalScrollBar().getVisibleAmount();
1852             if ( scroll_position.y > max_y ) {
1853                 scroll_position.y = max_y;
1854             }
1855         }
1856         if ( isOvOn() || getOptions().isShowScale() ) {
1857             repaint();
1858         }
1859         getMainPanel().getCurrentScrollPane().getViewport().setViewPosition( scroll_position );
1860     }
1861
1862     final void mouseDragInOvRectangle( final MouseEvent e ) {
1863         setCursor( HAND_CURSOR );
1864         final double w_ratio = getVisibleRect().width / getOvRectangle().getWidth();
1865         final double h_ratio = getVisibleRect().height / getOvRectangle().getHeight();
1866         final Point scroll_position = getMainPanel().getCurrentScrollPane().getViewport().getViewPosition();
1867         double dx = ( w_ratio * e.getX() - w_ratio * getLastDragPointX() );
1868         double dy = ( h_ratio * e.getY() - h_ratio * getLastDragPointY() );
1869         scroll_position.x = ForesterUtil.roundToInt( scroll_position.x + dx );
1870         scroll_position.y = ForesterUtil.roundToInt( scroll_position.y + dy );
1871         if ( scroll_position.x <= 0 ) {
1872             scroll_position.x = 0;
1873             dx = 0;
1874         }
1875         else {
1876             final int max_x = getMainPanel().getCurrentScrollPane().getHorizontalScrollBar().getMaximum()
1877                     - getMainPanel().getCurrentScrollPane().getHorizontalScrollBar().getVisibleAmount();
1878             if ( scroll_position.x >= max_x ) {
1879                 dx = 0;
1880                 scroll_position.x = max_x;
1881             }
1882         }
1883         if ( scroll_position.y <= 0 ) {
1884             dy = 0;
1885             scroll_position.y = 0;
1886         }
1887         else {
1888             final int max_y = getMainPanel().getCurrentScrollPane().getVerticalScrollBar().getMaximum()
1889                     - getMainPanel().getCurrentScrollPane().getVerticalScrollBar().getVisibleAmount();
1890             if ( scroll_position.y >= max_y ) {
1891                 dy = 0;
1892                 scroll_position.y = max_y;
1893             }
1894         }
1895         repaint();
1896         getMainPanel().getCurrentScrollPane().getViewport().setViewPosition( scroll_position );
1897         setLastMouseDragPointX( ( float ) ( e.getX() + dx ) );
1898         setLastMouseDragPointY( ( float ) ( e.getY() + dy ) );
1899     }
1900
1901     final void mouseMoved( final MouseEvent e ) {
1902         requestFocusInWindow();
1903         if ( getControlPanel().isNodeDescPopup() ) {
1904             if ( _node_desc_popup != null ) {
1905                 _node_desc_popup.hide();
1906                 _node_desc_popup = null;
1907             }
1908         }
1909         if ( getOptions().isShowOverview() && isOvOn() ) {
1910             if ( inOvVirtualRectangle( e ) ) {
1911                 if ( !isInOvRect() ) {
1912                     setInOvRect( true );
1913                     repaint();
1914                 }
1915             }
1916             else {
1917                 if ( isInOvRect() ) {
1918                     setInOvRect( false );
1919                     repaint();
1920                 }
1921             }
1922         }
1923         if ( inOv( e ) && getOptions().isShowOverview() && isOvOn() ) {
1924             if ( !isInOv() ) {
1925                 setInOv( true );
1926             }
1927         }
1928         else {
1929             if ( isInOv() ) {
1930                 setInOv( false );
1931             }
1932             final PhylogenyNode node = findNode( e.getX(), e.getY() );
1933             if ( ( node != null ) && ( node.isRoot() || !node.getParent().isCollapse() ) ) {
1934                 // cursor is over a tree node
1935                 if ( ( getControlPanel().getActionWhenNodeClicked() == NodeClickAction.CUT_SUBTREE )
1936                         || ( getControlPanel().getActionWhenNodeClicked() == NodeClickAction.COPY_SUBTREE )
1937                         || ( getControlPanel().getActionWhenNodeClicked() == NodeClickAction.PASTE_SUBTREE )
1938                         || ( getControlPanel().getActionWhenNodeClicked() == NodeClickAction.DELETE_NODE_OR_SUBTREE )
1939                         || ( getControlPanel().getActionWhenNodeClicked() == NodeClickAction.REROOT )
1940                         || ( getControlPanel().getActionWhenNodeClicked() == NodeClickAction.ADD_NEW_NODE ) ) {
1941                     setCursor( CUT_CURSOR );
1942                 }
1943                 else {
1944                     setCursor( HAND_CURSOR );
1945                     if ( getControlPanel().isNodeDescPopup() ) {
1946                         showNodeDataPopup( e, node );
1947                     }
1948                 }
1949             }
1950             else {
1951                 setCursor( ARROW_CURSOR );
1952             }
1953         }
1954     }
1955
1956     final void mouseReleasedInBrowserPanel( final MouseEvent e ) {
1957         setCursor( ARROW_CURSOR );
1958     }
1959
1960     final public void mouseWheelMoved( final MouseWheelEvent e ) {
1961         final int notches = e.getWheelRotation();
1962         if ( inOvVirtualRectangle( e ) ) {
1963             if ( !isInOvRect() ) {
1964                 setInOvRect( true );
1965                 repaint();
1966             }
1967         }
1968         else {
1969             if ( isInOvRect() ) {
1970                 setInOvRect( false );
1971                 repaint();
1972             }
1973         }
1974         if ( e.isControlDown() ) {
1975             if ( notches < 0 ) {
1976                 getTreeFontSet().increaseFontSize();
1977                 getControlPanel().displayedPhylogenyMightHaveChanged( true );
1978             }
1979             else {
1980                 getTreeFontSet().decreaseFontSize();
1981                 getControlPanel().displayedPhylogenyMightHaveChanged( true );
1982             }
1983         }
1984         else if ( e.isShiftDown() ) {
1985             if ( ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED )
1986                     || ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) {
1987                 if ( notches < 0 ) {
1988                     for( int i = 0; i < ( -notches ); ++i ) {
1989                         setStartingAngle( ( getStartingAngle() % TWO_PI ) + ANGLE_ROTATION_UNIT );
1990                         getControlPanel().displayedPhylogenyMightHaveChanged( false );
1991                     }
1992                 }
1993                 else {
1994                     for( int i = 0; i < notches; ++i ) {
1995                         setStartingAngle( ( getStartingAngle() % TWO_PI ) - ANGLE_ROTATION_UNIT );
1996                         if ( getStartingAngle() < 0 ) {
1997                             setStartingAngle( TWO_PI + getStartingAngle() );
1998                         }
1999                         getControlPanel().displayedPhylogenyMightHaveChanged( false );
2000                     }
2001                 }
2002             }
2003             else {
2004                 if ( notches < 0 ) {
2005                     for( int i = 0; i < ( -notches ); ++i ) {
2006                         getControlPanel().zoomInY( Constants.WHEEL_ZOOM_IN_FACTOR );
2007                         getControlPanel().displayedPhylogenyMightHaveChanged( false );
2008                     }
2009                 }
2010                 else {
2011                     for( int i = 0; i < notches; ++i ) {
2012                         getControlPanel().zoomOutY( Constants.WHEEL_ZOOM_OUT_FACTOR );
2013                         getControlPanel().displayedPhylogenyMightHaveChanged( false );
2014                     }
2015                 }
2016             }
2017         }
2018         else {
2019             if ( notches < 0 ) {
2020                 for( int i = 0; i < ( -notches ); ++i ) {
2021                     getControlPanel().zoomInX( Constants.WHEEL_ZOOM_IN_FACTOR,
2022                                                Constants.WHEEL_ZOOM_IN_X_CORRECTION_FACTOR );
2023                     getControlPanel().zoomInY( Constants.WHEEL_ZOOM_IN_FACTOR );
2024                     getControlPanel().displayedPhylogenyMightHaveChanged( false );
2025                 }
2026             }
2027             else {
2028                 for( int i = 0; i < notches; ++i ) {
2029                     getControlPanel().zoomOutY( Constants.WHEEL_ZOOM_OUT_FACTOR );
2030                     getControlPanel().zoomOutX( Constants.WHEEL_ZOOM_OUT_FACTOR,
2031                                                 Constants.WHEEL_ZOOM_OUT_X_CORRECTION_FACTOR );
2032                     getControlPanel().displayedPhylogenyMightHaveChanged( false );
2033                 }
2034             }
2035         }
2036         requestFocus();
2037         requestFocusInWindow();
2038         requestFocus();
2039     }
2040
2041     final void multiplyUrtFactor( final float f ) {
2042         _urt_factor *= f;
2043     }
2044
2045     final JApplet obtainApplet() {
2046         return ( ( MainPanelApplets ) getMainPanel() ).getApplet();
2047     }
2048
2049     final private void openSeqWeb( final PhylogenyNode node ) {
2050         if ( !isCanOpenSeqWeb( node ) ) {
2051             cannotOpenBrowserWarningMessage( "sequence" );
2052             return;
2053         }
2054         String uri_str = null;
2055         final Sequence seq = node.getNodeData().getSequence();
2056         final String source = seq.getAccession().getSource().toLowerCase();
2057         String url;
2058         if ( source.toLowerCase().equals( "ncbi" ) ) {
2059             url = Constants.NCBI_ALL_DATABASE_SEARCH;
2060         }
2061         else {
2062             final WebLink weblink = getConfiguration().getWebLink( source );
2063             url = weblink.getUrl().toString();
2064         }
2065         try {
2066             uri_str = url + URLEncoder.encode( seq.getAccession().getValue(), ForesterConstants.UTF8 );
2067         }
2068         catch ( final UnsupportedEncodingException e ) {
2069             Util.showErrorMessage( this, e.toString() );
2070             e.printStackTrace();
2071         }
2072         if ( !ForesterUtil.isEmpty( uri_str ) ) {
2073             try {
2074                 JApplet applet = null;
2075                 if ( isApplet() ) {
2076                     applet = obtainApplet();
2077                 }
2078                 Util.launchWebBrowser( new URI( uri_str ), isApplet(), applet, "_aptx_seq" );
2079             }
2080             catch ( final IOException e ) {
2081                 Util.showErrorMessage( this, e.toString() );
2082                 e.printStackTrace();
2083             }
2084             catch ( final URISyntaxException e ) {
2085                 Util.showErrorMessage( this, e.toString() );
2086                 e.printStackTrace();
2087             }
2088         }
2089         else {
2090             cannotOpenBrowserWarningMessage( "sequence" );
2091         }
2092     }
2093
2094     final private void openTaxWeb( final PhylogenyNode node ) {
2095         if ( !isCanOpenTaxWeb( node ) ) {
2096             cannotOpenBrowserWarningMessage( "taxonomic" );
2097             return;
2098         }
2099         String uri_str = null;
2100         final Taxonomy tax = node.getNodeData().getTaxonomy();
2101         if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getProvider() )
2102                 && getConfiguration().isHasWebLink( tax.getIdentifier().getProvider().toLowerCase() ) ) {
2103             final String type = tax.getIdentifier().getProvider().toLowerCase();
2104             final WebLink weblink = getConfiguration().getWebLink( type );
2105             try {
2106                 uri_str = weblink.getUrl() + URLEncoder.encode( tax.getIdentifier().getValue(), ForesterConstants.UTF8 );
2107             }
2108             catch ( final UnsupportedEncodingException e ) {
2109                 Util.showErrorMessage( this, e.toString() );
2110                 e.printStackTrace();
2111             }
2112         }
2113         else if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getValue() )
2114                 && tax.getIdentifier().getValue().startsWith( "http://" ) ) {
2115             try {
2116                 uri_str = new URI( tax.getIdentifier().getValue() ).toString();
2117             }
2118             catch ( final URISyntaxException e ) {
2119                 Util.showErrorMessage( this, e.toString() );
2120                 uri_str = null;
2121                 e.printStackTrace();
2122             }
2123         }
2124         else if ( !ForesterUtil.isEmpty( tax.getScientificName() ) ) {
2125             try {
2126                 uri_str = "http://www.eol.org/search?q="
2127                         + URLEncoder.encode( tax.getScientificName(), ForesterConstants.UTF8 );
2128             }
2129             catch ( final UnsupportedEncodingException e ) {
2130                 Util.showErrorMessage( this, e.toString() );
2131                 e.printStackTrace();
2132             }
2133         }
2134         else if ( !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
2135             try {
2136                 uri_str = "http://www.uniprot.org/taxonomy/?query="
2137                         + URLEncoder.encode( tax.getTaxonomyCode(), ForesterConstants.UTF8 );
2138             }
2139             catch ( final UnsupportedEncodingException e ) {
2140                 Util.showErrorMessage( this, e.toString() );
2141                 e.printStackTrace();
2142             }
2143         }
2144         else if ( !ForesterUtil.isEmpty( tax.getCommonName() ) ) {
2145             try {
2146                 uri_str = "http://www.eol.org/search?q="
2147                         + URLEncoder.encode( tax.getCommonName(), ForesterConstants.UTF8 );
2148             }
2149             catch ( final UnsupportedEncodingException e ) {
2150                 Util.showErrorMessage( this, e.toString() );
2151                 e.printStackTrace();
2152             }
2153         }
2154         if ( !ForesterUtil.isEmpty( uri_str ) ) {
2155             try {
2156                 JApplet applet = null;
2157                 if ( isApplet() ) {
2158                     applet = obtainApplet();
2159                 }
2160                 Util.launchWebBrowser( new URI( uri_str ), isApplet(), applet, "_aptx_tax" );
2161             }
2162             catch ( final IOException e ) {
2163                 Util.showErrorMessage( this, e.toString() );
2164                 e.printStackTrace();
2165             }
2166             catch ( final URISyntaxException e ) {
2167                 Util.showErrorMessage( this, e.toString() );
2168                 e.printStackTrace();
2169             }
2170         }
2171         else {
2172             cannotOpenBrowserWarningMessage( "taxonomic" );
2173         }
2174     }
2175
2176     final void paintBranchCircular( final PhylogenyNode p,
2177                                     final PhylogenyNode c,
2178                                     final Graphics2D g,
2179                                     final boolean radial_labels,
2180                                     final boolean to_pdf,
2181                                     final boolean to_graphics_file ) {
2182         final double angle = _urt_nodeid_angle_map.get( c.getId() );
2183         final double root_x = _root.getXcoord();
2184         final double root_y = _root.getYcoord();
2185         final double dx = root_x - p.getXcoord();
2186         final double dy = root_y - p.getYcoord();
2187         final double parent_radius = Math.sqrt( dx * dx + dy * dy );
2188         final double arc = ( _urt_nodeid_angle_map.get( p.getId() ) ) - angle;
2189         assignGraphicsForBranchWithColorForParentBranch( c, false, g, to_pdf, to_graphics_file );
2190         if ( ( c.isFirstChildNode() || c.isLastChildNode() )
2191                 && ( ( Math.abs( parent_radius * arc ) > 1.5 ) || to_pdf || to_graphics_file ) ) {
2192             final double r2 = 2.0 * parent_radius;
2193             drawArc( root_x - parent_radius, root_y - parent_radius, r2, r2, ( -angle - arc ), arc, g );
2194         }
2195         drawLine( c.getXcoord(),
2196                   c.getYcoord(),
2197                   root_x + ( Math.cos( angle ) * parent_radius ),
2198                   root_y + ( Math.sin( angle ) * parent_radius ),
2199                   g );
2200         paintNodeBox( c.getXcoord(), c.getYcoord(), c, g, to_pdf, to_graphics_file, isInFoundNodes( c ) );
2201         if ( c.isExternal() ) {
2202             final boolean is_in_found_nodes = isInFoundNodes( c );
2203             if ( ( _dynamic_hiding_factor > 1 ) && !is_in_found_nodes
2204                     && ( _urt_nodeid_index_map.get( c.getId() ) % _dynamic_hiding_factor != 1 ) ) {
2205                 return;
2206             }
2207             paintNodeDataUnrootedCirc( g, c, to_pdf, to_graphics_file, radial_labels, 0, is_in_found_nodes );
2208         }
2209     }
2210
2211     final void paintBranchCircularLite( final PhylogenyNode p, final PhylogenyNode c, final Graphics2D g ) {
2212         final double angle = _urt_nodeid_angle_map.get( c.getId() );
2213         final double root_x = _root.getXSecondary();
2214         final double root_y = _root.getYSecondary();
2215         final double dx = root_x - p.getXSecondary();
2216         final double dy = root_y - p.getYSecondary();
2217         final double arc = ( _urt_nodeid_angle_map.get( p.getId() ) ) - angle;
2218         final double parent_radius = Math.sqrt( dx * dx + dy * dy );
2219         g.setColor( getTreeColorSet().getOvColor() );
2220         if ( ( c.isFirstChildNode() || c.isLastChildNode() ) && ( Math.abs( arc ) > 0.02 ) ) {
2221             final double r2 = 2.0 * parent_radius;
2222             drawArc( root_x - parent_radius, root_y - parent_radius, r2, r2, ( -angle - arc ), arc, g );
2223         }
2224         drawLine( c.getXSecondary(),
2225                   c.getYSecondary(),
2226                   root_x + ( Math.cos( angle ) * parent_radius ),
2227                   root_y + ( Math.sin( angle ) * parent_radius ),
2228                   g );
2229         if ( isInFoundNodes( c ) ) {
2230             g.setColor( getTreeColorSet().getFoundColor() );
2231             drawRectFilled( c.getXSecondary() - 1, c.getYSecondary() - 1, 3, 3, g );
2232         }
2233     }
2234
2235     final private void paintBranchLength( final Graphics2D g,
2236                                           final PhylogenyNode node,
2237                                           final boolean to_pdf,
2238                                           final boolean to_graphics_file ) {
2239         g.setFont( getTreeFontSet().getSmallFont() );
2240         if ( ( to_pdf || to_graphics_file ) && getOptions().isPrintBlackAndWhite() ) {
2241             g.setColor( Color.BLACK );
2242         }
2243         else {
2244             g.setColor( getTreeColorSet().getBranchLengthColor() );
2245         }
2246         if ( !node.isRoot() ) {
2247             if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE ) {
2248                 TreePanel.drawString( FORMATTER_BRANCH_LENGTH.format( node.getDistanceToParent() ), node.getParent()
2249                         .getXcoord() + EURO_D, node.getYcoord() - getTreeFontSet()._small_max_descent, g );
2250             }
2251             else if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED ) {
2252                 TreePanel.drawString( FORMATTER_BRANCH_LENGTH.format( node.getDistanceToParent() ), node.getParent()
2253                         .getXcoord() + ROUNDED_D, node.getYcoord() - getTreeFontSet()._small_max_descent, g );
2254             }
2255             else {
2256                 TreePanel.drawString( FORMATTER_BRANCH_LENGTH.format( node.getDistanceToParent() ), node.getParent()
2257                         .getXcoord() + 3, node.getYcoord() - getTreeFontSet()._small_max_descent, g );
2258             }
2259         }
2260         else {
2261             TreePanel.drawString( FORMATTER_BRANCH_LENGTH.format( node.getDistanceToParent() ), 3, node.getYcoord()
2262                     - getTreeFontSet()._small_max_descent, g );
2263         }
2264     }
2265
2266     final private void paintBranchLite( final Graphics2D g,
2267                                         final float x1,
2268                                         final float x2,
2269                                         final float y1,
2270                                         final float y2,
2271                                         final PhylogenyNode node ) {
2272         g.setColor( getTreeColorSet().getOvColor() );
2273         if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.TRIANGULAR ) {
2274             drawLine( x1, y1, x2, y2, g );
2275         }
2276         else if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CONVEX ) {
2277             _quad_curve.setCurve( x1, y1, x1, y2, x2, y2 );
2278             ( g ).draw( _quad_curve );
2279         }
2280         else if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CURVED ) {
2281             final float dx = x2 - x1;
2282             final float dy = y2 - y1;
2283             _cubic_curve.setCurve( x1, y1, x1 + ( dx * 0.4f ), y1 + ( dy * 0.2f ), x1 + ( dx * 0.6f ), y1
2284                     + ( dy * 0.8f ), x2, y2 );
2285             ( g ).draw( _cubic_curve );
2286         }
2287         else {
2288             final float x2a = x2;
2289             final float x1a = x1;
2290             // draw the vertical line
2291             if ( node.isFirstChildNode() || node.isLastChildNode() ) {
2292                 drawLine( x1, y1, x1, y2, g );
2293             }
2294             // draw the horizontal line
2295             drawLine( x1a, y2, x2a, y2, g );
2296         }
2297     }
2298
2299     /**
2300      * Paint a branch which consists of a vertical and a horizontal bar
2301      * @param is_ind_found_nodes 
2302      */
2303     final private void paintBranchRectangular( final Graphics2D g,
2304                                                final float x1,
2305                                                final float x2,
2306                                                final float y1,
2307                                                final float y2,
2308                                                final PhylogenyNode node,
2309                                                final boolean to_pdf,
2310                                                final boolean to_graphics_file ) {
2311         assignGraphicsForBranchWithColorForParentBranch( node, false, g, to_pdf, to_graphics_file );
2312         if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.TRIANGULAR ) {
2313             drawLine( x1, y1, x2, y2, g );
2314         }
2315         else if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CONVEX ) {
2316             _quad_curve.setCurve( x1, y1, x1, y2, x2, y2 );
2317             g.draw( _quad_curve );
2318         }
2319         else if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CURVED ) {
2320             final float dx = x2 - x1;
2321             final float dy = y2 - y1;
2322             _cubic_curve.setCurve( x1, y1, x1 + ( dx * 0.4f ), y1 + ( dy * 0.2f ), x1 + ( dx * 0.6f ), y1
2323                     + ( dy * 0.8f ), x2, y2 );
2324             g.draw( _cubic_curve );
2325         }
2326         else {
2327             final float x2a = x2;
2328             final float x1a = x1;
2329             float y2_r = 0;
2330             if ( node.isFirstChildNode() || node.isLastChildNode()
2331                     || ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE )
2332                     || ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED ) ) {
2333                 if ( !to_graphics_file
2334                         && !to_pdf
2335                         && ( ( ( y2 < getVisibleRect().getMinY() - 20 ) && ( y1 < getVisibleRect().getMinY() - 20 ) ) || ( ( y2 > getVisibleRect()
2336                                 .getMaxY() + 20 ) && ( y1 > getVisibleRect().getMaxY() + 20 ) ) ) ) {
2337                     // Do nothing.
2338                 }
2339                 else {
2340                     if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE ) {
2341                         float x2c = x1 + EURO_D;
2342                         if ( x2c > x2a ) {
2343                             x2c = x2a;
2344                         }
2345                         drawLine( x1, y1, x2c, y2, g );
2346                     }
2347                     else if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED ) {
2348                         if ( y2 > y1 ) {
2349                             y2_r = y2 - ROUNDED_D;
2350                             if ( y2_r < y1 ) {
2351                                 y2_r = y1;
2352                             }
2353                             drawLine( x1, y1, x1, y2_r, g );
2354                         }
2355                         else {
2356                             y2_r = y2 + ROUNDED_D;
2357                             if ( y2_r > y1 ) {
2358                                 y2_r = y1;
2359                             }
2360                             drawLine( x1, y1, x1, y2_r, g );
2361                         }
2362                     }
2363                     else {
2364                         drawLine( x1, y1, x1, y2, g );
2365                     }
2366                 }
2367             }
2368             // draw the horizontal line
2369             if ( !to_graphics_file && !to_pdf
2370                     && ( ( y2 < getVisibleRect().getMinY() - 20 ) || ( y2 > getVisibleRect().getMaxY() + 20 ) ) ) {
2371                 return;
2372             }
2373             float x1_r = 0;
2374             if ( !getControlPanel().isWidthBranches() || ( PhylogenyMethods.getBranchWidthValue( node ) == 1 ) ) {
2375                 if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED ) {
2376                     x1_r = x1a + ROUNDED_D;
2377                     if ( x1_r < x2a ) {
2378                         drawLine( x1_r, y2, x2a, y2, g );
2379                     }
2380                 }
2381                 else if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE ) {
2382                     final float x1c = x1a + EURO_D;
2383                     if ( x1c < x2a ) {
2384                         drawLine( x1c, y2, x2a, y2, g );
2385                     }
2386                 }
2387                 else {
2388                     drawLine( x1a, y2, x2a, y2, g );
2389                 }
2390             }
2391             else {
2392                 final double w = PhylogenyMethods.getBranchWidthValue( node );
2393                 if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED ) {
2394                     x1_r = x1a + ROUNDED_D;
2395                     if ( x1_r < x2a ) {
2396                         drawRectFilled( x1_r, y2 - ( w / 2 ), x2a - x1_r, w, g );
2397                     }
2398                 }
2399                 else if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE ) {
2400                     final float x1c = x1a + EURO_D;
2401                     if ( x1c < x2a ) {
2402                         drawRectFilled( x1c, y2 - ( w / 2 ), x2a - x1c, w, g );
2403                     }
2404                 }
2405                 else {
2406                     drawRectFilled( x1a, y2 - ( w / 2 ), x2a - x1a, w, g );
2407                 }
2408             }
2409             if ( ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED ) ) {
2410                 if ( x1_r > x2a ) {
2411                     x1_r = x2a;
2412                 }
2413                 if ( y2 > y2_r ) {
2414                     final double diff = y2 - y2_r;
2415                     _arc.setArc( x1, y2_r - diff, 2 * ( x1_r - x1 ), 2 * diff, 180, 90, Arc2D.OPEN );
2416                 }
2417                 else {
2418                     _arc.setArc( x1, y2, 2 * ( x1_r - x1 ), 2 * ( y2_r - y2 ), 90, 90, Arc2D.OPEN );
2419                 }
2420                 g.draw( _arc );
2421             }
2422         }
2423         if ( node.isExternal() ) {
2424             paintNodeBox( x2, y2, node, g, to_pdf, to_graphics_file, isInFoundNodes( node ) );
2425         }
2426     }
2427
2428     final void paintCircular( final Phylogeny phy,
2429                               final double starting_angle,
2430                               final int center_x,
2431                               final int center_y,
2432                               final int radius,
2433                               final Graphics2D g,
2434                               final boolean to_pdf,
2435                               final boolean to_graphics_file ) {
2436         _circ_num_ext_nodes = phy.getNumberOfExternalNodes();
2437         _root = phy.getRoot();
2438         _root.setXcoord( center_x );
2439         _root.setYcoord( center_y );
2440         final boolean radial_labels = getOptions().getNodeLabelDirection() == NODE_LABEL_DIRECTION.RADIAL;
2441         double current_angle = starting_angle;
2442         int i = 0;
2443         for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
2444             final PhylogenyNode n = it.next();
2445             n.setXcoord( ( float ) ( center_x + ( radius * Math.cos( current_angle ) ) ) );
2446             n.setYcoord( ( float ) ( center_y + ( radius * Math.sin( current_angle ) ) ) );
2447             _urt_nodeid_angle_map.put( n.getId(), current_angle );
2448             _urt_nodeid_index_map.put( n.getId(), i++ );
2449             current_angle += ( TWO_PI / _circ_num_ext_nodes );
2450         }
2451         paintCirculars( phy.getRoot(), phy, center_x, center_y, radius, radial_labels, g, to_pdf, to_graphics_file );
2452         paintNodeBox( _root.getXcoord(), _root.getYcoord(), _root, g, to_pdf, to_graphics_file, isInFoundNodes( _root ) );
2453     }
2454
2455     final void paintCircularLite( final Phylogeny phy,
2456                                   final double starting_angle,
2457                                   final int center_x,
2458                                   final int center_y,
2459                                   final int radius,
2460                                   final Graphics2D g ) {
2461         _circ_num_ext_nodes = phy.getNumberOfExternalNodes();
2462         _root = phy.getRoot();
2463         _root.setXSecondary( center_x );
2464         _root.setYSecondary( center_y );
2465         double current_angle = starting_angle;
2466         for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
2467             final PhylogenyNode n = it.next();
2468             n.setXSecondary( ( float ) ( center_x + radius * Math.cos( current_angle ) ) );
2469             n.setYSecondary( ( float ) ( center_y + radius * Math.sin( current_angle ) ) );
2470             _urt_nodeid_angle_map.put( n.getId(), current_angle );
2471             current_angle += ( TWO_PI / _circ_num_ext_nodes );
2472         }
2473         paintCircularsLite( phy.getRoot(), phy, center_x, center_y, radius, g );
2474     }
2475
2476     final private double paintCirculars( final PhylogenyNode n,
2477                                          final Phylogeny phy,
2478                                          final float center_x,
2479                                          final float center_y,
2480                                          final double radius,
2481                                          final boolean radial_labels,
2482                                          final Graphics2D g,
2483                                          final boolean to_pdf,
2484                                          final boolean to_graphics_file ) {
2485         if ( n.isExternal() ) {
2486             if ( !_urt_nodeid_angle_map.containsKey( n.getId() ) ) {
2487                 System.out.println( "no " + n + ", ERROR!" );//TODO
2488             }
2489             return _urt_nodeid_angle_map.get( n.getId() );
2490         }
2491         else {
2492             final List<PhylogenyNode> descs = n.getDescendants();
2493             double sum = 0;
2494             for( final PhylogenyNode desc : descs ) {
2495                 sum += paintCirculars( desc,
2496                                        phy,
2497                                        center_x,
2498                                        center_y,
2499                                        radius,
2500                                        radial_labels,
2501                                        g,
2502                                        to_pdf,
2503                                        to_graphics_file );
2504             }
2505             double r = 0;
2506             if ( !n.isRoot() ) {
2507                 r = 1 - ( ( ( double ) _circ_max_depth - PhylogenyMethods.calculateDepth( n ) ) / _circ_max_depth );
2508             }
2509             final double theta = sum / descs.size();
2510             n.setXcoord( ( float ) ( center_x + r * radius * Math.cos( theta ) ) );
2511             n.setYcoord( ( float ) ( center_y + r * radius * Math.sin( theta ) ) );
2512             _urt_nodeid_angle_map.put( n.getId(), theta );
2513             for( final PhylogenyNode desc : descs ) {
2514                 paintBranchCircular( n, desc, g, radial_labels, to_pdf, to_graphics_file );
2515             }
2516             return theta;
2517         }
2518     }
2519
2520     final private void paintCircularsLite( final PhylogenyNode n,
2521                                            final Phylogeny phy,
2522                                            final int center_x,
2523                                            final int center_y,
2524                                            final int radius,
2525                                            final Graphics2D g ) {
2526         if ( n.isExternal() ) {
2527             return;
2528         }
2529         else {
2530             final List<PhylogenyNode> descs = n.getDescendants();
2531             for( final PhylogenyNode desc : descs ) {
2532                 paintCircularsLite( desc, phy, center_x, center_y, radius, g );
2533             }
2534             float r = 0;
2535             if ( !n.isRoot() ) {
2536                 r = 1 - ( ( ( float ) _circ_max_depth - PhylogenyMethods.calculateDepth( n ) ) / _circ_max_depth );
2537             }
2538             final double theta = _urt_nodeid_angle_map.get( n.getId() );
2539             n.setXSecondary( ( float ) ( center_x + radius * r * Math.cos( theta ) ) );
2540             n.setYSecondary( ( float ) ( center_y + radius * r * Math.sin( theta ) ) );
2541             for( final PhylogenyNode desc : descs ) {
2542                 paintBranchCircularLite( n, desc, g );
2543             }
2544         }
2545     }
2546
2547     final private void paintCollapsedNode( final Graphics2D g,
2548                                            final PhylogenyNode node,
2549                                            final boolean to_graphics_file,
2550                                            final boolean to_pdf,
2551                                            final boolean is_in_found_nodes ) {
2552         Color c = null;
2553         if ( ( to_pdf || to_graphics_file ) && getOptions().isPrintBlackAndWhite() ) {
2554             c = Color.BLACK;
2555         }
2556         else if ( is_in_found_nodes ) {
2557             c = getTreeColorSet().getFoundColor();
2558         }
2559         else if ( getControlPanel().isColorAccordingToTaxonomy() ) {
2560             c = getTaxonomyBasedColor( node );
2561         }
2562         else if ( getOptions().isColorLabelsSameAsParentBranch() && getControlPanel().isColorBranches()
2563                 && ( PhylogenyMethods.getBranchColorValue( node ) != null ) ) {
2564             c = PhylogenyMethods.getBranchColorValue( node );
2565         }
2566         else {
2567             c = getTreeColorSet().getCollapseFillColor();
2568         }
2569         double d = node.getAllExternalDescendants().size();
2570         if ( d > 1000 ) {
2571             d = ( 3 * _y_distance ) / 3;
2572         }
2573         else {
2574             d = ( Math.log10( d ) * _y_distance ) / 2.5;
2575         }
2576         final int box_size = getOptions().getDefaultNodeShapeSize();
2577         if ( d < box_size ) {
2578             d = box_size;
2579         }
2580         _polygon.reset();
2581         _polygon.addPoint( ForesterUtil.roundToInt( node.getXcoord() - box_size ),
2582                            ForesterUtil.roundToInt( node.getYcoord() ) );
2583         _polygon.addPoint( ForesterUtil.roundToInt( node.getXcoord() + box_size ),
2584                            ForesterUtil.roundToInt( node.getYcoord() - d ) );
2585         _polygon.addPoint( ForesterUtil.roundToInt( node.getXcoord() + box_size ),
2586                            ForesterUtil.roundToInt( node.getYcoord() + d ) );
2587         if ( getOptions().getDefaultNodeFill() == NodeFill.SOLID ) {
2588             g.setColor( c );
2589             g.fillPolygon( _polygon );
2590         }
2591         else if ( getOptions().getDefaultNodeFill() == NodeFill.NONE ) {
2592             g.setColor( getBackground() );
2593             g.fillPolygon( _polygon );
2594             g.setColor( c );
2595             g.drawPolygon( _polygon );
2596         }
2597         else if ( getOptions().getDefaultNodeFill() == NodeFill.GRADIENT ) {
2598             g.setPaint( new GradientPaint( node.getXcoord() - box_size, node.getYcoord(), getBackground(), ( node
2599                     .getXcoord() + box_size ), ( float ) ( node.getYcoord() - d ), c, false ) );
2600             g.fill( _polygon );
2601             g.setPaint( c );
2602             g.draw( _polygon );
2603         }
2604         paintNodeData( g, node, to_graphics_file, to_pdf, is_in_found_nodes );
2605     }
2606
2607     @Override
2608     final public void paintComponent( final Graphics g ) {
2609         // Dimension currentSize = getSize();
2610         //  if ( offscreenImage == null || !currentSize.equals( offscreenDimension ) ) {
2611         // call the 'java.awt.Component.createImage(...)' method to get an
2612         // image
2613         //   offscreenImage = createImage( currentSize.width, currentSize.height );
2614         //  offscreenGraphics = offscreenImage.getGraphics();
2615         //  offscreenDimension = currentSize;
2616         // }
2617         // super.paintComponent( g ); //why?
2618         //final Graphics2D g2d = ( Graphics2D ) offscreenGraphics;
2619         final Graphics2D g2d = ( Graphics2D ) g;
2620         g2d.setRenderingHints( _rendering_hints );
2621         paintPhylogeny( g2d, false, false, 0, 0, 0, 0 );
2622         //g.drawImage( offscreenImage, 0, 0, this );
2623     }
2624
2625     @Override
2626     public void update( final Graphics g ) {
2627         paint( g );
2628     }
2629
2630     final private void paintConfidenceValues( final Graphics2D g,
2631                                               final PhylogenyNode node,
2632                                               final boolean to_pdf,
2633                                               final boolean to_graphics_file ) {
2634         String conf_str = "";
2635         final List<Confidence> confidences = node.getBranchData().getConfidences();
2636         if ( confidences.size() == 1 ) {
2637             final double value = node.getBranchData().getConfidence( 0 ).getValue();
2638             if ( ( value == Confidence.CONFIDENCE_DEFAULT_VALUE ) || ( value < getOptions().getMinConfidenceValue() ) ) {
2639                 return;
2640             }
2641             conf_str = FORMATTER_CONFIDENCE.format( value );
2642         }
2643         else if ( confidences.size() > 1 ) {
2644             boolean one_ok = false;
2645             boolean not_first = false;
2646             Collections.sort( confidences );
2647             final StringBuilder sb = new StringBuilder();
2648             for( final Confidence confidence : confidences ) {
2649                 final double value = confidence.getValue();
2650                 if ( value != Confidence.CONFIDENCE_DEFAULT_VALUE ) {
2651                     if ( value >= getOptions().getMinConfidenceValue() ) {
2652                         one_ok = true;
2653                     }
2654                     if ( not_first ) {
2655                         sb.append( "/" );
2656                     }
2657                     else {
2658                         not_first = true;
2659                     }
2660                     sb.append( FORMATTER_CONFIDENCE.format( ForesterUtil.round( value, getOptions()
2661                             .getNumberOfDigitsAfterCommaForConfidenceValues() ) ) );
2662                 }
2663             }
2664             if ( one_ok ) {
2665                 conf_str = sb.toString();
2666             }
2667         }
2668         if ( conf_str.length() > 0 ) {
2669             final double parent_x = node.getParent().getXcoord();
2670             double x = node.getXcoord();
2671             g.setFont( getTreeFontSet().getSmallFont() );
2672             if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE ) {
2673                 x += EURO_D;
2674             }
2675             else if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED ) {
2676                 x += ROUNDED_D;
2677             }
2678             if ( ( to_pdf || to_graphics_file ) && getOptions().isPrintBlackAndWhite() ) {
2679                 g.setColor( Color.BLACK );
2680             }
2681             else {
2682                 g.setColor( getTreeColorSet().getConfidenceColor() );
2683             }
2684             TreePanel
2685                     .drawString( conf_str,
2686                                  parent_x
2687                                          + ( ( x - parent_x - getTreeFontSet()._fm_small.stringWidth( conf_str ) ) / 2 ),
2688                                  ( node.getYcoord() + getTreeFontSet()._small_max_ascent ) - 1,
2689                                  g );
2690         }
2691     }
2692
2693     final private void paintFoundNode( final int x, final int y, final Graphics2D g ) {
2694         final int box_size = getOptions().getDefaultNodeShapeSize();
2695         final int half_box_size = getOptions().getDefaultNodeShapeSize() / 2;
2696         g.setColor( getTreeColorSet().getFoundColor() );
2697         g.fillRect( x - half_box_size, y - half_box_size, box_size, box_size );
2698     }
2699
2700     final private void paintGainedAndLostCharacters( final Graphics2D g,
2701                                                      final PhylogenyNode node,
2702                                                      final String gained,
2703                                                      final String lost ) {
2704         if ( node.getParent() != null ) {
2705             final double parent_x = node.getParent().getXcoord();
2706             final double x = node.getXcoord();
2707             g.setFont( getTreeFontSet().getLargeFont() );
2708             g.setColor( getTreeColorSet().getGainedCharactersColor() );
2709             if ( Constants.SPECIAL_CUSTOM ) {
2710                 g.setColor( Color.BLUE );
2711             }
2712             TreePanel
2713                     .drawString( gained,
2714                                  parent_x + ( ( x - parent_x - getTreeFontSet()._fm_large.stringWidth( gained ) ) / 2 ),
2715                                  ( node.getYcoord() - getTreeFontSet()._fm_large.getMaxDescent() ),
2716                                  g );
2717             g.setColor( getTreeColorSet().getLostCharactersColor() );
2718             TreePanel.drawString( lost,
2719                                   parent_x + ( ( x - parent_x - getTreeFontSet()._fm_large.stringWidth( lost ) ) / 2 ),
2720                                   ( node.getYcoord() + getTreeFontSet()._fm_large.getMaxAscent() ),
2721                                   g );
2722         }
2723     }
2724
2725     /**
2726      * Draw a box at the indicated node.
2727      * 
2728      * @param x
2729      * @param y
2730      * @param node
2731      * @param g
2732      */
2733     final private void paintNodeBox( final double x,
2734                                      final double y,
2735                                      final PhylogenyNode node,
2736                                      final Graphics2D g,
2737                                      final boolean to_pdf,
2738                                      final boolean to_graphics_file,
2739                                      final boolean is_in_found_nodes ) {
2740         if ( node.isCollapse() ) {
2741             return;
2742         }
2743         // if this node should be highlighted, do so
2744         if ( ( _highlight_node == node ) && !to_pdf && !to_graphics_file ) {
2745             g.setColor( getTreeColorSet().getFoundColor() );
2746             drawOval( x - 8, y - 8, 16, 16, g );
2747             drawOval( x - 9, y - 8, 17, 17, g );
2748             drawOval( x - 9, y - 9, 18, 18, g );
2749         }
2750         if ( is_in_found_nodes ) {
2751             paintFoundNode( ForesterUtil.roundToInt( x ), ForesterUtil.roundToInt( y ), g );
2752         }
2753         else {
2754             Color outline_color = null;
2755             if ( ( to_pdf || to_graphics_file ) && getOptions().isPrintBlackAndWhite() ) {
2756                 outline_color = Color.BLACK;
2757             }
2758             else if ( getControlPanel().isEvents() && Util.isHasAssignedEvent( node ) ) {
2759                 final Event event = node.getNodeData().getEvent();
2760                 if ( event.isDuplication() ) {
2761                     outline_color = getTreeColorSet().getDuplicationBoxColor();
2762                 }
2763                 else if ( event.isSpeciation() ) {
2764                     outline_color = getTreeColorSet().getSpecBoxColor();
2765                 }
2766                 else if ( event.isSpeciationOrDuplication() ) {
2767                     outline_color = getTreeColorSet().getDuplicationOrSpeciationColor();
2768                 }
2769             }
2770             else if ( getOptions().isTaxonomyColorizeNodeShapes() ) {
2771                 outline_color = getTaxonomyBasedColor( node );
2772             }
2773             else {
2774                 outline_color = getGraphicsForNodeBoxWithColorForParentBranch( node );
2775                 if ( to_pdf && ( outline_color == getTreeColorSet().getBranchColor() ) ) {
2776                     outline_color = getTreeColorSet().getBranchColorForPdf();
2777                 }
2778             }
2779             final int box_size = getOptions().getDefaultNodeShapeSize();
2780             final int half_box_size = box_size / 2;
2781             if ( getOptions().isShowDefaultNodeShapes() || ( getControlPanel().isEvents() && node.isHasAssignedEvent() ) ) {
2782                 if ( getOptions().getDefaultNodeShape() == NodeShape.CIRCLE ) {
2783                     if ( getOptions().getDefaultNodeFill() == NodeFill.GRADIENT ) {
2784                         drawOvalGradient( x - half_box_size,
2785                                           y - half_box_size,
2786                                           box_size,
2787                                           box_size,
2788                                           g,
2789                                           to_pdf ? Color.WHITE : outline_color,
2790                                           to_pdf ? outline_color : getBackground(),
2791                                           outline_color );
2792                     }
2793                     else if ( getOptions().getDefaultNodeFill() == NodeFill.NONE ) {
2794                         Color background = getBackground();
2795                         if ( to_pdf ) {
2796                             background = Color.WHITE;
2797                         }
2798                         drawOvalGradient( x - half_box_size,
2799                                           y - half_box_size,
2800                                           box_size,
2801                                           box_size,
2802                                           g,
2803                                           background,
2804                                           background,
2805                                           outline_color );
2806                     }
2807                     else if ( getOptions().getDefaultNodeFill() == NodeFill.SOLID ) {
2808                         g.setColor( outline_color );
2809                         drawOvalFilled( x - half_box_size, y - half_box_size, box_size, box_size, g );
2810                     }
2811                 }
2812                 else if ( getOptions().getDefaultNodeShape() == NodeShape.RECTANGLE ) {
2813                     if ( getOptions().getDefaultNodeFill() == NodeFill.GRADIENT ) {
2814                         drawRectGradient( x - half_box_size,
2815                                           y - half_box_size,
2816                                           box_size,
2817                                           box_size,
2818                                           g,
2819                                           to_pdf ? Color.WHITE : outline_color,
2820                                           to_pdf ? outline_color : getBackground(),
2821                                           outline_color );
2822                     }
2823                     else if ( getOptions().getDefaultNodeFill() == NodeFill.NONE ) {
2824                         Color background = getBackground();
2825                         if ( to_pdf ) {
2826                             background = Color.WHITE;
2827                         }
2828                         drawRectGradient( x - half_box_size,
2829                                           y - half_box_size,
2830                                           box_size,
2831                                           box_size,
2832                                           g,
2833                                           background,
2834                                           background,
2835                                           outline_color );
2836                     }
2837                     else if ( getOptions().getDefaultNodeFill() == NodeFill.SOLID ) {
2838                         g.setColor( outline_color );
2839                         drawRectFilled( x - half_box_size, y - half_box_size, box_size, box_size, g );
2840                     }
2841                 }
2842             }
2843         }
2844     }
2845
2846     final private void paintNodeData( final Graphics2D g,
2847                                       final PhylogenyNode node,
2848                                       final boolean to_graphics_file,
2849                                       final boolean to_pdf,
2850                                       final boolean is_in_found_nodes ) {
2851         if ( isNodeDataInvisible( node ) && !to_graphics_file && !to_pdf ) {
2852             return;
2853         }
2854         if ( getOptions().isShowBranchLengthValues()
2855                 && ( ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR )
2856                         || ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED ) || ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE ) )
2857                 && ( !node.isRoot() ) && ( node.getDistanceToParent() != PhylogenyNode.DISTANCE_DEFAULT ) ) {
2858             paintBranchLength( g, node, to_pdf, to_graphics_file );
2859         }
2860         if ( !getControlPanel().isShowInternalData() && !node.isExternal() && !node.isCollapse() ) {
2861             return;
2862         }
2863         int x = 0;
2864         final int half_box_size = getOptions().getDefaultNodeShapeSize() / 2;
2865         if ( getControlPanel().isShowTaxonomyImages()
2866                 && ( getImageMap() != null )
2867                 && !getImageMap().isEmpty()
2868                 && node.getNodeData().isHasTaxonomy()
2869                 && ( ( node.getNodeData().getTaxonomy().getUris() != null ) && !node.getNodeData().getTaxonomy()
2870                         .getUris().isEmpty() ) ) {
2871             x += drawTaxonomyImage( node.getXcoord() + 2 + half_box_size, node.getYcoord(), node, g );
2872         }
2873         if ( ( getControlPanel().isShowTaxonomyCode() || getControlPanel().isShowTaxonomyScientificNames() || getControlPanel()
2874                 .isShowTaxonomyCommonNames() ) && node.getNodeData().isHasTaxonomy() ) {
2875             x += paintTaxonomy( g, node, is_in_found_nodes, to_pdf, to_graphics_file, x );
2876         }
2877         if ( ( to_pdf || to_graphics_file ) && getOptions().isPrintBlackAndWhite() ) {
2878             g.setColor( Color.BLACK );
2879         }
2880         else if ( is_in_found_nodes ) {
2881             g.setColor( getTreeColorSet().getFoundColor() );
2882         }
2883         else if ( getControlPanel().isColorAccordingToTaxonomy() ) {
2884             g.setColor( getTaxonomyBasedColor( node ) );
2885         }
2886         else if ( getOptions().isColorLabelsSameAsParentBranch() && getControlPanel().isColorBranches()
2887                 && ( PhylogenyMethods.getBranchColorValue( node ) != null ) ) {
2888             g.setColor( PhylogenyMethods.getBranchColorValue( node ) );
2889         }
2890         else if ( to_pdf ) {
2891             g.setColor( Color.BLACK );
2892         }
2893         else {
2894             g.setColor( getTreeColorSet().getSequenceColor() );
2895         }
2896         _sb.setLength( 0 );
2897         if ( node.isCollapse() && ( ( !node.isRoot() && !node.getParent().isCollapse() ) || node.isRoot() ) ) {
2898             _sb.append( " [" );
2899             _sb.append( node.getAllExternalDescendants().size() );
2900             _sb.append( "]" );
2901         }
2902         if ( getControlPanel().isShowNodeNames() && ( node.getName().length() > 0 ) ) {
2903             if ( _sb.length() > 0 ) {
2904                 _sb.append( " " );
2905             }
2906             _sb.append( node.getName() );
2907         }
2908         if ( node.getNodeData().isHasSequence() ) {
2909             if ( getControlPanel().isShowGeneSymbols() && ( node.getNodeData().getSequence().getSymbol().length() > 0 ) ) {
2910                 if ( _sb.length() > 0 ) {
2911                     _sb.append( " " );
2912                 }
2913                 _sb.append( node.getNodeData().getSequence().getSymbol() );
2914             }
2915             if ( getControlPanel().isShowGeneNames() && ( node.getNodeData().getSequence().getName().length() > 0 ) ) {
2916                 if ( _sb.length() > 0 ) {
2917                     _sb.append( " " );
2918                 }
2919                 _sb.append( node.getNodeData().getSequence().getName() );
2920             }
2921             if ( getControlPanel().isShowSequenceAcc() && ( node.getNodeData().getSequence().getAccession() != null ) ) {
2922                 if ( _sb.length() > 0 ) {
2923                     _sb.append( " " );
2924                 }
2925                 if ( !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().getSource() ) ) {
2926                     _sb.append( node.getNodeData().getSequence().getAccession().getSource() );
2927                     _sb.append( ":" );
2928                 }
2929                 _sb.append( node.getNodeData().getSequence().getAccession().getValue() );
2930             }
2931         }
2932         g.setFont( getTreeFontSet().getLargeFont() );
2933         if ( is_in_found_nodes ) {
2934             g.setFont( getTreeFontSet().getLargeFont().deriveFont( Font.BOLD ) );
2935         }
2936         double down_shift_factor = 3.0;
2937         if ( !node.isExternal() && ( node.getNumberOfDescendants() == 1 ) ) {
2938             down_shift_factor = 1;
2939         }
2940         final double pos_x = node.getXcoord() + x + 2 + half_box_size;
2941         final double pos_y = ( node.getYcoord() + ( getTreeFontSet()._fm_large.getAscent() / down_shift_factor ) );
2942         final String sb_str = _sb.toString();
2943         // GUILHEM_BEG ______________
2944         if ( _control_panel.isShowSequenceRelations() && node.getNodeData().isHasSequence()
2945                 && ( _query_sequence != null ) ) {
2946             int nodeTextBoundsWidth = 0;
2947             if ( sb_str.length() > 0 ) {
2948                 final Rectangle2D node_text_bounds = new TextLayout( sb_str, g.getFont(), _frc ).getBounds(); //would like to remove this 'new', but how...
2949                 nodeTextBoundsWidth = ( int ) node_text_bounds.getWidth();
2950             }
2951             if ( node.getNodeData().getSequence().equals( _query_sequence ) ) {
2952                 if ( nodeTextBoundsWidth > 0 ) { // invert font color and background color to show that this is the query sequence
2953                     g.fillRect( ( int ) pos_x - 1, ( int ) pos_y - 8, nodeTextBoundsWidth + 5, 11 );
2954                     g.setColor( getTreeColorSet().getBackgroundColor() );
2955                 }
2956             }
2957             else {
2958                 final List<SequenceRelation> seqRelations = node.getNodeData().getSequence().getSequenceRelations();
2959                 for( final SequenceRelation seqRelation : seqRelations ) {
2960                     final boolean fGotRelationWithQuery = ( seqRelation.getRef0().isEqual( _query_sequence ) || seqRelation
2961                             .getRef1().isEqual( _query_sequence ) )
2962                             && seqRelation.getType().equals( getControlPanel().getSequenceRelationTypeBox()
2963                                     .getSelectedItem() );
2964                     if ( fGotRelationWithQuery ) { // we will underline the text to show that this sequence is ortholog to the query
2965                         final double linePosX = node.getXcoord() + 2 + half_box_size;
2966                         final String sConfidence = ( !getControlPanel().isShowSequenceRelationConfidence() || ( seqRelation
2967                                 .getConfidence() == null ) ) ? null : " (" + seqRelation.getConfidence().getValue()
2968                                 + ")";
2969                         if ( sConfidence != null ) {
2970                             double confidenceX = pos_x;
2971                             if ( sb_str.length() > 0 ) {
2972                                 confidenceX += new TextLayout( sb_str, g.getFont(), _frc ).getBounds().getWidth()
2973                                         + CONFIDENCE_LEFT_MARGIN;
2974                             }
2975                             if ( confidenceX > linePosX ) { // let's only display confidence value if we are already displaying at least one of Prot/Gene Name and Taxonomy Code 
2976                                 final int confidenceWidth = ( int ) new TextLayout( sConfidence, g.getFont(), _frc )
2977                                         .getBounds().getWidth();
2978                                 TreePanel.drawString( sConfidence, confidenceX, pos_y, g );
2979                                 x += CONFIDENCE_LEFT_MARGIN + confidenceWidth;
2980                             }
2981                         }
2982                         if ( x + nodeTextBoundsWidth > 0 ) /* we only underline if there is something displayed */
2983                         {
2984                             if ( nodeTextBoundsWidth == 0 ) {
2985                                 nodeTextBoundsWidth -= 3; /* the gap between taxonomy code and node name should not be underlined if nothing comes after it */
2986                             }
2987                             else {
2988                                 nodeTextBoundsWidth += 2;
2989                             }
2990                             g.drawLine( ( int ) linePosX + 1, 3 + ( int ) pos_y, ( int ) linePosX + x
2991                                     + nodeTextBoundsWidth, 3 + ( int ) pos_y );
2992                             break;
2993                         }
2994                     }
2995                 }
2996             }
2997         }
2998         if ( sb_str.length() > 0 ) {
2999             TreePanel.drawString( sb_str, pos_x, pos_y, g );
3000         }
3001         // GUILHEM_END _____________
3002         // COMMENTED_OUT_BY_GUILHEM_BEG _______________
3003         // TODO FIXME need to check this one!
3004         //if ( _sb.length() > 0 ) {
3005         //    TreePanel.drawString( _sb.toString(), node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE, node.getYcoord()
3006         //            + ( getTreeFontSet()._fm_large.getAscent() / down_shift_factor ), g );
3007         //}
3008         // COMMENTED_OUT_BY_GUILHEM_END ________________
3009         if ( getControlPanel().isShowAnnotation() && node.getNodeData().isHasSequence()
3010                 && ( node.getNodeData().getSequence().getAnnotations() != null )
3011                 && ( !node.getNodeData().getSequence().getAnnotations().isEmpty() ) ) {
3012             if ( _sb.length() > 0 ) {
3013                 x += getTreeFontSet()._fm_large.stringWidth( _sb.toString() ) + 5;
3014             }
3015             final Annotation ann = node.getNodeData().getSequence().getAnnotation( 0 );
3016             if ( ( to_pdf || to_graphics_file ) && getOptions().isPrintBlackAndWhite() ) {
3017                 g.setColor( Color.BLACK );
3018             }
3019             else {
3020                 g.setColor( calculateColorForAnnotation( ann ) );
3021             }
3022             final String ann_str = ann.asSimpleText().toString();
3023             TreePanel.drawString( ann_str, node.getXcoord() + x + 3 + half_box_size, node.getYcoord()
3024                     + ( getTreeFontSet()._fm_large.getAscent() / down_shift_factor ), g );
3025             _sb.setLength( 0 );
3026             _sb.append( ann_str );
3027         }
3028         if ( ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR )
3029                 || ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE )
3030                 || ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED ) ) {
3031             if ( ( getControlPanel().isShowBinaryCharacters() || getControlPanel().isShowBinaryCharacterCounts() )
3032                     && node.getNodeData().isHasBinaryCharacters() ) {
3033                 if ( _sb.length() > 0 ) {
3034                     x += getTreeFontSet()._fm_large.stringWidth( _sb.toString() ) + 5;
3035                 }
3036                 if ( ( to_pdf || to_graphics_file ) && getOptions().isPrintBlackAndWhite() ) {
3037                     g.setColor( Color.BLACK );
3038                 }
3039                 else {
3040                     g.setColor( getTreeColorSet().getBinaryDomainCombinationsColor() );
3041                 }
3042                 if ( getControlPanel().isShowBinaryCharacters() ) {
3043                     TreePanel.drawString( node.getNodeData().getBinaryCharacters().getPresentCharactersAsStringBuffer()
3044                             .toString(), node.getXcoord() + x + 1 + half_box_size, node.getYcoord()
3045                             + ( getTreeFontSet()._fm_large.getAscent() / down_shift_factor ), g );
3046                     paintGainedAndLostCharacters( g, node, node.getNodeData().getBinaryCharacters()
3047                             .getGainedCharactersAsStringBuffer().toString(), node.getNodeData().getBinaryCharacters()
3048                             .getLostCharactersAsStringBuffer().toString() );
3049                 }
3050                 else {
3051                     if ( DRAW_MEAN_COUNTS && node.isInternal() ) {
3052                         final List<PhylogenyNode> ec = node.getAllExternalDescendants();
3053                         double sum = 0;
3054                         int count = 0;
3055                         for( final PhylogenyNode phylogenyNode : ec ) {
3056                             count++;
3057                             if ( phylogenyNode.getNodeData().getBinaryCharacters() != null ) {
3058                                 sum += phylogenyNode.getNodeData().getBinaryCharacters().getPresentCount();
3059                             }
3060                         }
3061                         final double mean = ForesterUtil.round( sum / count, 1 );
3062                         TreePanel.drawString( " " + node.getNodeData().getBinaryCharacters().getPresentCount() + " ["
3063                                 + mean + "]", node.getXcoord() + x + 4 + half_box_size, node.getYcoord()
3064                                 + ( getTreeFontSet()._fm_large.getAscent() / down_shift_factor ), g );
3065                     }
3066                     else {
3067                         TreePanel.drawString( " " + node.getNodeData().getBinaryCharacters().getPresentCount(),
3068                                               node.getXcoord() + x + 4 + half_box_size,
3069                                               node.getYcoord()
3070                                                       + ( getTreeFontSet()._fm_large.getAscent() / down_shift_factor ),
3071                                               g );
3072                     }
3073                     paintGainedAndLostCharacters( g, node, "+"
3074                             + node.getNodeData().getBinaryCharacters().getGainedCount(), "-"
3075                             + node.getNodeData().getBinaryCharacters().getLostCount() );
3076                 }
3077             }
3078         }
3079     }
3080
3081     private double drawTaxonomyImage( final double x, final double y, final PhylogenyNode node, final Graphics2D g ) {
3082         final List<Uri> us = new ArrayList<Uri>();
3083         for( final Taxonomy t : node.getNodeData().getTaxonomies() ) {
3084             for( final Uri uri : t.getUris() ) {
3085                 us.add( uri );
3086             }
3087         }
3088         double offset = 0;
3089         for( final Uri uri : us ) {
3090             if ( uri != null ) {
3091                 final String uri_str = uri.getValue().toString().toLowerCase();
3092                 if ( getImageMap().containsKey( uri_str ) ) {
3093                     final BufferedImage bi = getImageMap().get( uri_str );
3094                     if ( ( bi != null ) && ( bi.getHeight() > 5 ) && ( bi.getWidth() > 5 ) ) {
3095                         double scaling_factor = 1;
3096                         if ( getOptions().isAllowMagnificationOfTaxonomyImages()
3097                                 || ( bi.getHeight() > ( 1.8 * getYdistance() ) ) ) {
3098                             scaling_factor = ( 1.8 * getYdistance() ) / bi.getHeight();
3099                         }
3100                         // y = y - ( 0.9 * getYdistance() );
3101                         final double hs = bi.getHeight() * scaling_factor;
3102                         double ws = bi.getWidth() * scaling_factor + offset;
3103                         final double my_y = y - ( 0.5 * hs );
3104                         final int x_w = ( int ) ( x + ws + 0.5 );
3105                         final int y_h = ( int ) ( my_y + hs + 0.5 );
3106                         if ( ( x_w - x > 7 ) && ( y_h - my_y > 7 ) ) {
3107                             g.drawImage( bi,
3108                                          ( int ) ( x + 0.5 + offset ),
3109                                          ( int ) ( my_y + 0.5 ),
3110                                          x_w,
3111                                          y_h,
3112                                          0,
3113                                          0,
3114                                          bi.getWidth(),
3115                                          bi.getHeight(),
3116                                          null );
3117                             ws += 8;
3118                         }
3119                         else {
3120                             ws = 0.0;
3121                         }
3122                         offset = ws;
3123                     }
3124                 }
3125             }
3126         }
3127         return offset;
3128     }
3129
3130     final private void paintNodeDataUnrootedCirc( final Graphics2D g,
3131                                                   final PhylogenyNode node,
3132                                                   final boolean to_pdf,
3133                                                   final boolean to_graphics_file,
3134                                                   final boolean radial_labels,
3135                                                   final double ur_angle,
3136                                                   final boolean is_in_found_nodes ) {
3137         if ( isNodeDataInvisibleUnrootedCirc( node ) && !to_graphics_file && !to_pdf ) {
3138             return;
3139         }
3140         if ( ( to_pdf || to_graphics_file ) && getOptions().isPrintBlackAndWhite() ) {
3141             g.setColor( Color.BLACK );
3142         }
3143         else if ( is_in_found_nodes ) {
3144             g.setColor( getTreeColorSet().getFoundColor() );
3145         }
3146         else if ( getControlPanel().isColorAccordingToTaxonomy() ) {
3147             g.setColor( getTaxonomyBasedColor( node ) );
3148         }
3149         else {
3150             g.setColor( getTreeColorSet().getSequenceColor() );
3151         }
3152         _sb.setLength( 0 );
3153         _sb.append( " " );
3154         if ( node.getNodeData().isHasTaxonomy()
3155                 && ( getControlPanel().isShowTaxonomyCode() || getControlPanel().isShowTaxonomyScientificNames() || getControlPanel()
3156                         .isShowTaxonomyCommonNames() ) ) {
3157             final Taxonomy taxonomy = node.getNodeData().getTaxonomy();
3158             if ( _control_panel.isShowTaxonomyCode() && !ForesterUtil.isEmpty( taxonomy.getTaxonomyCode() ) ) {
3159                 _sb.append( taxonomy.getTaxonomyCode() );
3160                 _sb.append( " " );
3161             }
3162             if ( _control_panel.isShowTaxonomyScientificNames() && _control_panel.isShowTaxonomyCommonNames() ) {
3163                 if ( !ForesterUtil.isEmpty( taxonomy.getScientificName() )
3164                         && !ForesterUtil.isEmpty( taxonomy.getCommonName() ) ) {
3165                     _sb.append( taxonomy.getScientificName() );
3166                     _sb.append( " (" );
3167                     _sb.append( taxonomy.getCommonName() );
3168                     _sb.append( ") " );
3169                 }
3170                 else if ( !ForesterUtil.isEmpty( taxonomy.getScientificName() ) ) {
3171                     _sb.append( taxonomy.getScientificName() );
3172                     _sb.append( " " );
3173                 }
3174                 else if ( !ForesterUtil.isEmpty( taxonomy.getCommonName() ) ) {
3175                     _sb.append( taxonomy.getCommonName() );
3176                     _sb.append( " " );
3177                 }
3178             }
3179             else if ( _control_panel.isShowTaxonomyScientificNames() ) {
3180                 if ( !ForesterUtil.isEmpty( taxonomy.getScientificName() ) ) {
3181                     _sb.append( taxonomy.getScientificName() );
3182                     _sb.append( " " );
3183                 }
3184             }
3185             else if ( _control_panel.isShowTaxonomyCommonNames() ) {
3186                 if ( !ForesterUtil.isEmpty( taxonomy.getCommonName() ) ) {
3187                     _sb.append( taxonomy.getCommonName() );
3188                     _sb.append( " " );
3189                 }
3190             }
3191         }
3192         if ( node.isCollapse() && ( ( !node.isRoot() && !node.getParent().isCollapse() ) || node.isRoot() ) ) {
3193             _sb.append( " [" );
3194             _sb.append( node.getAllExternalDescendants().size() );
3195             _sb.append( "]" );
3196         }
3197         if ( getControlPanel().isShowNodeNames() && ( node.getName().length() > 0 ) ) {
3198             if ( _sb.length() > 0 ) {
3199                 _sb.append( " " );
3200             }
3201             _sb.append( node.getName() );
3202         }
3203         if ( node.getNodeData().isHasSequence() ) {
3204             if ( getControlPanel().isShowSequenceAcc() && ( node.getNodeData().getSequence().getAccession() != null ) ) {
3205                 if ( _sb.length() > 0 ) {
3206                     _sb.append( " " );
3207                 }
3208                 if ( !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().getSource() ) ) {
3209                     _sb.append( node.getNodeData().getSequence().getAccession().getSource() );
3210                     _sb.append( ":" );
3211                 }
3212                 _sb.append( node.getNodeData().getSequence().getAccession().getValue() );
3213             }
3214             if ( getControlPanel().isShowGeneNames() && ( node.getNodeData().getSequence().getName().length() > 0 ) ) {
3215                 if ( _sb.length() > 0 ) {
3216                     _sb.append( " " );
3217                 }
3218                 _sb.append( node.getNodeData().getSequence().getName() );
3219             }
3220         }
3221         g.setFont( getTreeFontSet().getLargeFont() );
3222         if ( is_in_found_nodes ) {
3223             g.setFont( getTreeFontSet().getLargeFont().deriveFont( Font.BOLD ) );
3224         }
3225         if ( _sb.length() > 1 ) {
3226             final String sb_str = _sb.toString();
3227             double m = 0;
3228             if ( _graphics_type == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) {
3229                 m = _urt_nodeid_angle_map.get( node.getId() ) % TWO_PI;
3230             }
3231             else {
3232                 m = ( float ) ( ur_angle % TWO_PI );
3233             }
3234             _at = g.getTransform();
3235             boolean need_to_reset = false;
3236             final float x_coord = node.getXcoord();
3237             final float y_coord = node.getYcoord() + ( getTreeFontSet()._fm_large.getAscent() / 3.0f );
3238             if ( radial_labels ) {
3239                 need_to_reset = true;
3240                 boolean left = false;
3241                 if ( ( m > HALF_PI ) && ( m < ONEHALF_PI ) ) {
3242                     m -= PI;
3243                     left = true;
3244                 }
3245                 g.rotate( m, x_coord, node.getYcoord() );
3246                 if ( left ) {
3247                     g.translate( -( getTreeFontSet()._fm_large.getStringBounds( sb_str, g ).getWidth() ), 0 );
3248                 }
3249             }
3250             else {
3251                 if ( ( m > HALF_PI ) && ( m < ONEHALF_PI ) ) {
3252                     need_to_reset = true;
3253                     g.translate( -getTreeFontSet()._fm_large.getStringBounds( sb_str, g ).getWidth(), 0 );
3254                 }
3255             }
3256             TreePanel.drawString( sb_str, x_coord, y_coord, g );
3257             if ( need_to_reset ) {
3258                 g.setTransform( _at );
3259             }
3260         }
3261     }
3262
3263     final private void paintNodeLite( final Graphics2D g, final PhylogenyNode node ) {
3264         if ( node.isCollapse() ) {
3265             if ( ( !node.isRoot() && !node.getParent().isCollapse() ) || node.isRoot() ) {
3266                 paintCollapsedNode( g, node, false, false, false );
3267             }
3268             return;
3269         }
3270         if ( isInFoundNodes( node ) ) {
3271             g.setColor( getTreeColorSet().getFoundColor() );
3272             drawRectFilled( node.getXSecondary() - 1, node.getYSecondary() - 1, 3, 3, g );
3273         }
3274         float new_x = 0;
3275         if ( !node.isExternal() && !node.isCollapse() ) {
3276             boolean first_child = true;
3277             float y2 = 0.0f;
3278             final int parent_max_branch_to_leaf = getMaxBranchesToLeaf( node );
3279             for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
3280                 final PhylogenyNode child_node = node.getChildNode( i );
3281                 int factor_x;
3282                 if ( !isUniformBranchLengthsForCladogram() ) {
3283                     factor_x = node.getNumberOfExternalNodes() - child_node.getNumberOfExternalNodes();
3284                 }
3285                 else {
3286                     factor_x = parent_max_branch_to_leaf - getMaxBranchesToLeaf( child_node );
3287                 }
3288                 if ( first_child ) {
3289                     first_child = false;
3290                     y2 = node.getYSecondary()
3291                             - ( getOvYDistance() * ( node.getNumberOfExternalNodes() - child_node
3292                                     .getNumberOfExternalNodes() ) );
3293                 }
3294                 else {
3295                     y2 += getOvYDistance() * child_node.getNumberOfExternalNodes();
3296                 }
3297                 final float x2 = calculateOvBranchLengthToParent( child_node, factor_x );
3298                 new_x = x2 + node.getXSecondary();
3299                 final float diff_y = node.getYSecondary() - y2;
3300                 final float diff_x = node.getXSecondary() - new_x;
3301                 if ( ( diff_y > 2 ) || ( diff_y < -2 ) || ( diff_x > 2 ) || ( diff_x < -2 ) ) {
3302                     paintBranchLite( g, node.getXSecondary(), new_x, node.getYSecondary(), y2, child_node );
3303                 }
3304                 child_node.setXSecondary( new_x );
3305                 child_node.setYSecondary( y2 );
3306                 y2 += getOvYDistance() * child_node.getNumberOfExternalNodes();
3307             }
3308         }
3309     }
3310
3311     final private void paintNodeRectangular( final Graphics2D g,
3312                                              final PhylogenyNode node,
3313                                              final boolean to_pdf,
3314                                              final boolean dynamically_hide,
3315                                              final int dynamic_hiding_factor,
3316                                              final boolean to_graphics_file ) {
3317         final boolean is_in_found_nodes = isInFoundNodes( node );
3318         if ( node.isCollapse() ) {
3319             if ( ( !node.isRoot() && !node.getParent().isCollapse() ) || node.isRoot() ) {
3320                 paintCollapsedNode( g, node, to_graphics_file, to_pdf, is_in_found_nodes );
3321             }
3322             return;
3323         }
3324         if ( node.isExternal() ) {
3325             ++_external_node_index;
3326         }
3327         // Confidence values
3328         if ( getControlPanel().isShowBootstrapValues()
3329                 && !node.isExternal()
3330                 && !node.isRoot()
3331                 && ( ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED )
3332                         || ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ) || ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE ) )
3333                 && node.getBranchData().isHasConfidences() ) {
3334             paintConfidenceValues( g, node, to_pdf, to_graphics_file );
3335         }
3336         // Draw a line to root:
3337         if ( node.isRoot() && _phylogeny.isRooted() ) {
3338             paintRootBranch( g, node.getXcoord(), node.getYcoord(), node, to_pdf, to_graphics_file );
3339         }
3340         float new_x = 0;
3341         float new_x_min = Float.MAX_VALUE;
3342         final boolean disallow_shortcutting = dynamic_hiding_factor < 40;
3343         float min_dist = 1.5f;
3344         if ( !disallow_shortcutting ) {
3345             //   System.out.println( dynamic_hiding_factor );
3346             if ( dynamic_hiding_factor > 4000 ) {
3347                 min_dist = 4;
3348             }
3349             else if ( dynamic_hiding_factor > 1000 ) {
3350                 min_dist = 3;
3351             }
3352             else if ( dynamic_hiding_factor > 100 ) {
3353                 min_dist = 2;
3354             }
3355         }
3356         if ( !node.isExternal() && !node.isCollapse() ) {
3357             boolean first_child = true;
3358             float y2 = 0.0f;
3359             final int parent_max_branch_to_leaf = getMaxBranchesToLeaf( node );
3360             for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
3361                 final PhylogenyNode child_node = node.getChildNode( i );
3362                 int factor_x;
3363                 if ( !isUniformBranchLengthsForCladogram() ) {
3364                     factor_x = node.getNumberOfExternalNodes() - child_node.getNumberOfExternalNodes();
3365                 }
3366                 else {
3367                     factor_x = parent_max_branch_to_leaf - getMaxBranchesToLeaf( child_node );
3368                 }
3369                 if ( first_child ) {
3370                     first_child = false;
3371                     y2 = node.getYcoord()
3372                             - ( _y_distance * ( node.getNumberOfExternalNodes() - child_node.getNumberOfExternalNodes() ) );
3373                 }
3374                 else {
3375                     y2 += _y_distance * child_node.getNumberOfExternalNodes();
3376                 }
3377                 final float x2 = calculateBranchLengthToParent( child_node, factor_x );
3378                 new_x = x2 + node.getXcoord();
3379                 if ( dynamically_hide && ( x2 < new_x_min ) ) {
3380                     new_x_min = x2;
3381                 }
3382                 final float diff_y = node.getYcoord() - y2;
3383                 final float diff_x = node.getXcoord() - new_x;
3384                 if ( disallow_shortcutting || ( diff_y > min_dist ) || ( diff_y < -min_dist ) || ( diff_x > min_dist )
3385                         || ( diff_x < -min_dist ) || to_graphics_file || to_pdf ) {
3386                     paintBranchRectangular( g,
3387                                             node.getXcoord(),
3388                                             new_x,
3389                                             node.getYcoord(),
3390                                             y2,
3391                                             child_node,
3392                                             to_pdf,
3393                                             to_graphics_file );
3394                 }
3395                 child_node.setXcoord( new_x );
3396                 child_node.setYcoord( y2 );
3397                 y2 += _y_distance * child_node.getNumberOfExternalNodes();
3398             }
3399             paintNodeBox( node.getXcoord(), node.getYcoord(), node, g, to_pdf, to_graphics_file, isInFoundNodes( node ) );
3400         }
3401         if ( dynamically_hide
3402                 && !is_in_found_nodes
3403                 && ( ( node.isExternal() && ( _external_node_index % dynamic_hiding_factor != 1 ) ) || ( !node
3404                         .isExternal() && ( ( new_x_min < 20 ) || ( _y_distance * node.getNumberOfExternalNodes() < getTreeFontSet()._fm_large
3405                         .getHeight() ) ) ) ) ) {
3406             return;
3407         }
3408         paintNodeData( g, node, to_graphics_file, to_pdf, is_in_found_nodes );
3409         paintNodeWithRenderableData( g, node, to_graphics_file, to_pdf );
3410     }
3411
3412     final private void paintNodeWithRenderableData( final Graphics2D g,
3413                                                     final PhylogenyNode node,
3414                                                     final boolean to_graphics_file,
3415                                                     final boolean to_pdf ) {
3416         if ( isNodeDataInvisible( node ) && !to_graphics_file ) {
3417             return;
3418         }
3419         if ( ( !getControlPanel().isShowInternalData() && !node.isExternal() ) ) {
3420             return;
3421         }
3422         if ( getControlPanel().isShowDomainArchitectures() && node.getNodeData().isHasSequence()
3423                 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
3424             RenderableDomainArchitecture rds = null;
3425             if ( node.getNodeData().getSequence().getDomainArchitecture() instanceof RenderableDomainArchitecture ) {
3426                 try {
3427                     rds = ( RenderableDomainArchitecture ) node.getNodeData().getSequence().getDomainArchitecture();
3428                 }
3429                 catch ( final ClassCastException cce ) {
3430                     cce.printStackTrace();
3431                     return;
3432                 }
3433                 rds.setRenderingHeight( 6 );
3434                 int x = 0;
3435                 if ( getControlPanel().isShowTaxonomyCode() && ( PhylogenyMethods.getSpecies( node ).length() > 0 ) ) {
3436                     x += getTreeFontSet()._fm_large_italic.stringWidth( PhylogenyMethods.getSpecies( node ) + " " );
3437                 }
3438                 if ( getControlPanel().isShowGeneNames() ) {
3439                     x += getTreeFontSet()._fm_large.stringWidth( node.getNodeData().getSequence().getName() + " " );
3440                 }
3441                 if ( getControlPanel().isShowGeneSymbols() ) {
3442                     x += getTreeFontSet()._fm_large.stringWidth( node.getNodeData().getSequence().getSymbol() + " " );
3443                 }
3444                 if ( getControlPanel().isShowSequenceAcc() ) {
3445                     x += getTreeFontSet()._fm_large.stringWidth( node.getNodeData().getSequence().getAccession()
3446                             .toString()
3447                             + " " );
3448                 }
3449                 if ( getControlPanel().isShowNodeNames() && ( node.getName().length() > 0 ) ) {
3450                     x += getTreeFontSet()._fm_large.stringWidth( node.getName() + " " );
3451                 }
3452                 rds.render( node.getXcoord() + x, node.getYcoord() - 3, g, this, to_pdf );
3453             }
3454         }
3455         //////////////
3456         if ( getControlPanel().isShowVectorData() && ( node.getNodeData().getVector() != null )
3457                 && ( node.getNodeData().getVector().size() > 0 ) && ( getStatisticsForExpressionValues() != null ) ) {
3458             final RenderableVector rv = RenderableVector.createInstance( node.getNodeData().getVector(),
3459                                                                          getStatisticsForExpressionValues(),
3460                                                                          getConfiguration() );
3461             int x = 0;
3462             PhylogenyNode my_node = node;
3463             if ( !getControlPanel().isDrawPhylogram() ) {
3464                 my_node = getPhylogeny().getFirstExternalNode();
3465             }
3466             if ( getControlPanel().isShowTaxonomyCode() && ( PhylogenyMethods.getSpecies( my_node ).length() > 0 ) ) {
3467                 x += getTreeFontSet()._fm_large_italic.stringWidth( PhylogenyMethods.getSpecies( my_node ) + " " );
3468             }
3469             if ( getControlPanel().isShowNodeNames() && ( my_node.getName().length() > 0 ) ) {
3470                 x += getTreeFontSet()._fm_large.stringWidth( my_node.getName() + " " );
3471             }
3472             rv.render( my_node.getXcoord() + x, node.getYcoord() - 5, g, this, to_pdf );
3473         }
3474         //////////////
3475     }
3476
3477     final private void paintOvRectangle( final Graphics2D g ) {
3478         final float w_ratio = ( float ) getWidth() / getVisibleRect().width;
3479         final float h_ratio = ( float ) getHeight() / getVisibleRect().height;
3480         final float x_ratio = ( float ) getWidth() / getVisibleRect().x;
3481         final float y_ratio = ( float ) getHeight() / getVisibleRect().y;
3482         final float width = getOvMaxWidth() / w_ratio;
3483         final float height = getOvMaxHeight() / h_ratio;
3484         final float x = getVisibleRect().x + getOvXPosition() + getOvMaxWidth() / x_ratio;
3485         final float y = getVisibleRect().y + getOvYPosition() + getOvMaxHeight() / y_ratio;
3486         g.setColor( getTreeColorSet().getFoundColor() );
3487         getOvRectangle().setRect( x, y, width, height );
3488         if ( ( width < 6 ) && ( height < 6 ) ) {
3489             drawRectFilled( x, y, 6, 6, g );
3490             getOvVirtualRectangle().setRect( x, y, 6, 6 );
3491         }
3492         else if ( width < 6 ) {
3493             drawRectFilled( x, y, 6, height, g );
3494             getOvVirtualRectangle().setRect( x, y, 6, height );
3495         }
3496         else if ( height < 6 ) {
3497             drawRectFilled( x, y, width, 6, g );
3498             getOvVirtualRectangle().setRect( x, y, width, 6 );
3499         }
3500         else {
3501             drawRect( x, y, width, height, g );
3502             if ( isInOvRect() ) {
3503                 drawRect( x + 1, y + 1, width - 2, height - 2, g );
3504             }
3505             getOvVirtualRectangle().setRect( x, y, width, height );
3506         }
3507     }
3508
3509     final void paintPhylogeny( final Graphics2D g,
3510                                final boolean to_pdf,
3511                                final boolean to_graphics_file,
3512                                final int graphics_file_width,
3513                                final int graphics_file_height,
3514                                final int graphics_file_x,
3515                                final int graphics_file_y ) {
3516         if ( _control_panel.isShowSequenceRelations() ) {
3517             _query_sequence = _control_panel.getSelectedQuerySequence();
3518         }
3519         // Color the background
3520         if ( !to_pdf ) {
3521             final Rectangle r = getVisibleRect();
3522             if ( !getOptions().isBackgroundColorGradient() || getOptions().isPrintBlackAndWhite() ) {
3523                 g.setColor( getTreeColorSet().getBackgroundColor() );
3524                 if ( !to_graphics_file ) {
3525                     g.fill( r );
3526                 }
3527                 else {
3528                     if ( getOptions().isPrintBlackAndWhite() ) {
3529                         g.setColor( Color.WHITE );
3530                     }
3531                     g.fillRect( graphics_file_x, graphics_file_y, graphics_file_width, graphics_file_height );
3532                 }
3533             }
3534             else {
3535                 if ( !to_graphics_file ) {
3536                     g.setPaint( new GradientPaint( r.x, r.y, getTreeColorSet().getBackgroundColor(), r.x, r.y
3537                             + r.height, getTreeColorSet().getBackgroundColorGradientBottom() ) );
3538                     g.fill( r );
3539                 }
3540                 else {
3541                     g.setPaint( new GradientPaint( graphics_file_x,
3542                                                    graphics_file_y,
3543                                                    getTreeColorSet().getBackgroundColor(),
3544                                                    graphics_file_x,
3545                                                    graphics_file_y + graphics_file_height,
3546                                                    getTreeColorSet().getBackgroundColorGradientBottom() ) );
3547                     g.fillRect( graphics_file_x, graphics_file_y, graphics_file_width, graphics_file_height );
3548                 }
3549             }
3550             g.setStroke( new BasicStroke( 1 ) );
3551         }
3552         else {
3553             g.setStroke( new BasicStroke( getOptions().getPrintLineWidth() ) );
3554         }
3555         if ( ( getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.UNROOTED )
3556                 && ( getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) {
3557             _external_node_index = 0;
3558             // Position starting X of tree
3559             if ( !_phylogeny.isRooted() /*|| ( _subtree_index > 0 )*/) {
3560                 _phylogeny.getRoot().setXcoord( TreePanel.MOVE );
3561             }
3562             else if ( ( _phylogeny.getRoot().getDistanceToParent() > 0.0 ) && getControlPanel().isDrawPhylogram() ) {
3563                 _phylogeny.getRoot().setXcoord( ( float ) ( TreePanel.MOVE + ( _phylogeny.getRoot()
3564                         .getDistanceToParent() * getXcorrectionFactor() ) ) );
3565             }
3566             else {
3567                 _phylogeny.getRoot().setXcoord( TreePanel.MOVE + getXdistance() );
3568             }
3569             // Position starting Y of tree
3570             _phylogeny.getRoot().setYcoord( ( getYdistance() * _phylogeny.getRoot().getNumberOfExternalNodes() )
3571                     + ( TreePanel.MOVE / 2.0f ) );
3572             final int dynamic_hiding_factor = ( int ) ( getTreeFontSet()._fm_large.getHeight() / ( 1.5 * getYdistance() ) );
3573             if ( getControlPanel().isDynamicallyHideData() ) {
3574                 if ( dynamic_hiding_factor > 1 ) {
3575                     getControlPanel().setDynamicHidingIsOn( true );
3576                 }
3577                 else {
3578                     getControlPanel().setDynamicHidingIsOn( false );
3579                 }
3580             }
3581             if ( _nodes_in_preorder == null ) {
3582                 _nodes_in_preorder = new PhylogenyNode[ _phylogeny.getNodeCount() ];
3583                 int i = 0;
3584                 for( final PhylogenyNodeIterator it = _phylogeny.iteratorPreorder(); it.hasNext(); ) {
3585                     _nodes_in_preorder[ i++ ] = it.next();
3586                 }
3587             }
3588             //final PhylogenyNodeIterator it;
3589             //for( it = _phylogeny.iteratorPreorder(); it.hasNext(); ) {
3590             //    paintNodeRectangular( g, it.next(), to_pdf, getControlPanel().isDynamicallyHideData()
3591             //            && ( dynamic_hiding_factor > 1 ), dynamic_hiding_factor, to_graphics_file );
3592             //}
3593             for( int i = 0; i < _nodes_in_preorder.length; ++i ) {
3594                 paintNodeRectangular( g, _nodes_in_preorder[ i ], to_pdf, getControlPanel().isDynamicallyHideData()
3595                         && ( dynamic_hiding_factor > 1 ), dynamic_hiding_factor, to_graphics_file );
3596             }
3597             if ( getOptions().isShowScale() && getControlPanel().isDrawPhylogram() && ( getScaleDistance() > 0.0 ) ) {
3598                 if ( !( to_graphics_file || to_pdf ) ) {
3599                     paintScale( g,
3600                                 getVisibleRect().x,
3601                                 getVisibleRect().y + getVisibleRect().height,
3602                                 to_pdf,
3603                                 to_graphics_file );
3604                 }
3605                 else {
3606                     paintScale( g, graphics_file_x, graphics_file_y + graphics_file_height, to_pdf, to_graphics_file );
3607                 }
3608             }
3609             if ( getOptions().isShowOverview() && isOvOn() && !to_graphics_file && !to_pdf ) {
3610                 paintPhylogenyLite( g );
3611             }
3612         }
3613         else if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) {
3614             if ( getControlPanel().getDynamicallyHideData() != null ) {
3615                 getControlPanel().setDynamicHidingIsOn( false );
3616             }
3617             final double angle = getStartingAngle();
3618             final boolean radial_labels = getOptions().getNodeLabelDirection() == NODE_LABEL_DIRECTION.RADIAL;
3619             _dynamic_hiding_factor = 0;
3620             if ( getControlPanel().isDynamicallyHideData() ) {
3621                 _dynamic_hiding_factor = ( int ) ( ( getTreeFontSet()._fm_large.getHeight() * 1.5 * getPhylogeny()
3622                         .getNumberOfExternalNodes() ) / ( TWO_PI * 10 ) );
3623             }
3624             if ( getControlPanel().getDynamicallyHideData() != null ) {
3625                 if ( _dynamic_hiding_factor > 1 ) {
3626                     getControlPanel().setDynamicHidingIsOn( true );
3627                 }
3628                 else {
3629                     getControlPanel().setDynamicHidingIsOn( false );
3630                 }
3631             }
3632             paintUnrooted( _phylogeny.getRoot(),
3633                            angle,
3634                            ( float ) ( angle + 2 * Math.PI ),
3635                            radial_labels,
3636                            g,
3637                            to_pdf,
3638                            to_graphics_file );
3639             if ( getOptions().isShowScale() ) {
3640                 if ( !( to_graphics_file || to_pdf ) ) {
3641                     paintScale( g,
3642                                 getVisibleRect().x,
3643                                 getVisibleRect().y + getVisibleRect().height,
3644                                 to_pdf,
3645                                 to_graphics_file );
3646                 }
3647                 else {
3648                     paintScale( g, graphics_file_x, graphics_file_y + graphics_file_height, to_pdf, to_graphics_file );
3649                 }
3650             }
3651             if ( getOptions().isShowOverview() && isOvOn() && !to_graphics_file && !to_pdf ) {
3652                 g.setColor( getTreeColorSet().getOvColor() );
3653                 paintUnrootedLite( _phylogeny.getRoot(),
3654                                    angle,
3655                                    angle + 2 * Math.PI,
3656                                    g,
3657                                    ( getUrtFactorOv() / ( getVisibleRect().width / getOvMaxWidth() ) ) );
3658                 paintOvRectangle( g );
3659             }
3660         }
3661         else if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) {
3662             final int radius = ( int ) ( ( Math.min( getPreferredSize().getWidth(), getPreferredSize().getHeight() ) / 2 ) - ( MOVE + getLongestExtNodeInfo() ) );
3663             final int d = radius + MOVE + getLongestExtNodeInfo();
3664             _dynamic_hiding_factor = 0;
3665             if ( getControlPanel().isDynamicallyHideData() && ( radius > 0 ) ) {
3666                 _dynamic_hiding_factor = ( int ) ( ( getTreeFontSet()._fm_large.getHeight() * 1.5 * getPhylogeny()
3667                         .getNumberOfExternalNodes() ) / ( TWO_PI * radius ) );
3668             }
3669             if ( getControlPanel().getDynamicallyHideData() != null ) {
3670                 if ( _dynamic_hiding_factor > 1 ) {
3671                     getControlPanel().setDynamicHidingIsOn( true );
3672                 }
3673                 else {
3674                     getControlPanel().setDynamicHidingIsOn( false );
3675                 }
3676             }
3677             paintCircular( _phylogeny, getStartingAngle(), d, d, radius > 0 ? radius : 0, g, to_pdf, to_graphics_file );
3678             if ( getOptions().isShowOverview() && isOvOn() && !to_graphics_file && !to_pdf ) {
3679                 final int radius_ov = ( int ) ( getOvMaxHeight() < getOvMaxWidth() ? getOvMaxHeight() / 2
3680                         : getOvMaxWidth() / 2 );
3681                 double x_scale = 1.0;
3682                 double y_scale = 1.0;
3683                 int x_pos = getVisibleRect().x + getOvXPosition();
3684                 int y_pos = getVisibleRect().y + getOvYPosition();
3685                 if ( getWidth() > getHeight() ) {
3686                     x_scale = ( double ) getHeight() / getWidth();
3687                     x_pos = ForesterUtil.roundToInt( x_pos / x_scale );
3688                 }
3689                 else {
3690                     y_scale = ( double ) getWidth() / getHeight();
3691                     y_pos = ForesterUtil.roundToInt( y_pos / y_scale );
3692                 }
3693                 _at = g.getTransform();
3694                 g.scale( x_scale, y_scale );
3695                 paintCircularLite( _phylogeny,
3696                                    getStartingAngle(),
3697                                    x_pos + radius_ov,
3698                                    y_pos + radius_ov,
3699                                    ( int ) ( radius_ov - ( getLongestExtNodeInfo() / ( getVisibleRect().width / getOvRectangle()
3700                                            .getWidth() ) ) ),
3701                                    g );
3702                 g.setTransform( _at );
3703                 paintOvRectangle( g );
3704             }
3705         }
3706     }
3707
3708     final private void paintPhylogenyLite( final Graphics2D g ) {
3709         //System.out.println( getVisibleRect().x + " " + getVisibleRect().y );
3710         _phylogeny
3711                 .getRoot()
3712                 .setXSecondary( ( float ) ( getVisibleRect().x + getOvXPosition() + ( MOVE / ( getVisibleRect().width / getOvRectangle()
3713                         .getWidth() ) ) ) );
3714         _phylogeny.getRoot().setYSecondary( ( getVisibleRect().y + getOvYStart() ) );
3715         //final PhylogenyNodeIterator it;
3716         //for( it = _phylogeny.iteratorPreorder(); it.hasNext(); ) {
3717         //    paintNodeLite( g, it.next() );
3718         //}
3719         for( int i = 0; i < _nodes_in_preorder.length; ++i ) {
3720             paintNodeLite( g, _nodes_in_preorder[ i ] );
3721         }
3722         paintOvRectangle( g );
3723     }
3724
3725     /**
3726      * Paint the root branch. (Differs from others because it will always be a
3727      * single horizontal line).
3728      * @param to_graphics_file 
3729      * 
3730      * @return new x1 value
3731      */
3732     final private void paintRootBranch( final Graphics2D g,
3733                                         final float x1,
3734                                         final float y1,
3735                                         final PhylogenyNode root,
3736                                         final boolean to_pdf,
3737                                         final boolean to_graphics_file ) {
3738         assignGraphicsForBranchWithColorForParentBranch( root, false, g, to_pdf, to_graphics_file );
3739         float d = getXdistance();
3740         if ( getControlPanel().isDrawPhylogram() && ( root.getDistanceToParent() > 0.0 ) ) {
3741             d = ( float ) ( getXcorrectionFactor() * root.getDistanceToParent() );
3742         }
3743         if ( d < MIN_ROOT_LENGTH ) {
3744             d = MIN_ROOT_LENGTH;
3745         }
3746         if ( !getControlPanel().isWidthBranches() || ( PhylogenyMethods.getBranchWidthValue( root ) == 1 ) ) {
3747             drawLine( x1 - d, root.getYcoord(), x1, root.getYcoord(), g );
3748         }
3749         else {
3750             final double w = PhylogenyMethods.getBranchWidthValue( root );
3751             drawRectFilled( x1 - d, root.getYcoord() - ( w / 2 ), d, w, g );
3752         }
3753         paintNodeBox( x1, root.getYcoord(), root, g, to_pdf, to_graphics_file, isInFoundNodes( root ) );
3754     }
3755
3756     final private void paintScale( final Graphics2D g,
3757                                    int x1,
3758                                    int y1,
3759                                    final boolean to_pdf,
3760                                    final boolean to_graphics_file ) {
3761         x1 += MOVE;
3762         final double x2 = x1 + ( getScaleDistance() * getXcorrectionFactor() );
3763         y1 -= 12;
3764         final int y2 = y1 - 8;
3765         final int y3 = y1 - 4;
3766         g.setFont( getTreeFontSet().getSmallFont() );
3767         if ( ( to_pdf || to_graphics_file ) && getOptions().isPrintBlackAndWhite() ) {
3768             g.setColor( Color.BLACK );
3769         }
3770         else {
3771             g.setColor( getTreeColorSet().getBranchLengthColor() );
3772         }
3773         drawLine( x1, y1, x1, y2, g );
3774         drawLine( x2, y1, x2, y2, g );
3775         drawLine( x1, y3, x2, y3, g );
3776         if ( getScaleLabel() != null ) {
3777             g.drawString( getScaleLabel(), ( x1 + 2 ), y3 - 2 );
3778         }
3779     }
3780
3781     final private int paintTaxonomy( final Graphics2D g,
3782                                      final PhylogenyNode node,
3783                                      final boolean is_in_found_nodes,
3784                                      final boolean to_pdf,
3785                                      final boolean to_graphics_file,
3786                                      final double x_shift ) {
3787         final Taxonomy taxonomy = node.getNodeData().getTaxonomy();
3788         g.setFont( getTreeFontSet().getLargeItalicFont() );
3789         if ( ( to_pdf || to_graphics_file ) && getOptions().isPrintBlackAndWhite() ) {
3790             g.setColor( Color.BLACK );
3791         }
3792         else if ( is_in_found_nodes ) {
3793             g.setFont( getTreeFontSet().getLargeItalicFont().deriveFont( TreeFontSet.BOLD_AND_ITALIC ) );
3794             g.setColor( getTreeColorSet().getFoundColor() );
3795         }
3796         else if ( getControlPanel().isColorAccordingToTaxonomy() ) {
3797             g.setColor( getTaxonomyBasedColor( node ) );
3798         }
3799         else if ( getOptions().isColorLabelsSameAsParentBranch() && getControlPanel().isColorBranches()
3800                 && ( PhylogenyMethods.getBranchColorValue( node ) != null ) ) {
3801             g.setColor( PhylogenyMethods.getBranchColorValue( node ) );
3802         }
3803         else if ( to_pdf ) {
3804             g.setColor( Color.BLACK );
3805         }
3806         else {
3807             g.setColor( getTreeColorSet().getTaxonomyColor() );
3808         }
3809         final double start_x = node.getXcoord() + 3 + ( getOptions().getDefaultNodeShapeSize() / 2 ) + x_shift;
3810         final double start_y = node.getYcoord()
3811                 + ( getTreeFontSet()._fm_large.getAscent() / ( node.getNumberOfDescendants() == 1 ? 1 : 3.0 ) );
3812         _sb.setLength( 0 );
3813         if ( _control_panel.isShowTaxonomyCode() && !ForesterUtil.isEmpty( taxonomy.getTaxonomyCode() ) ) {
3814             _sb.append( taxonomy.getTaxonomyCode() );
3815             _sb.append( " " );
3816         }
3817         if ( _control_panel.isShowTaxonomyScientificNames() && _control_panel.isShowTaxonomyCommonNames() ) {
3818             if ( !ForesterUtil.isEmpty( taxonomy.getScientificName() )
3819                     && !ForesterUtil.isEmpty( taxonomy.getCommonName() ) ) {
3820                 if ( getOptions().isAbbreviateScientificTaxonNames()
3821                         && ( taxonomy.getScientificName().indexOf( ' ' ) > 0 ) ) {
3822                     abbreviateScientificName( taxonomy.getScientificName() );
3823                 }
3824                 else {
3825                     _sb.append( taxonomy.getScientificName() );
3826                 }
3827                 _sb.append( " (" );
3828                 _sb.append( taxonomy.getCommonName() );
3829                 _sb.append( ") " );
3830             }
3831             else if ( !ForesterUtil.isEmpty( taxonomy.getScientificName() ) ) {
3832                 if ( getOptions().isAbbreviateScientificTaxonNames()
3833                         && ( taxonomy.getScientificName().indexOf( ' ' ) > 0 ) ) {
3834                     abbreviateScientificName( taxonomy.getScientificName() );
3835                 }
3836                 else {
3837                     _sb.append( taxonomy.getScientificName() );
3838                 }
3839                 _sb.append( " " );
3840             }
3841             else if ( !ForesterUtil.isEmpty( taxonomy.getCommonName() ) ) {
3842                 _sb.append( taxonomy.getCommonName() );
3843                 _sb.append( " " );
3844             }
3845         }
3846         else if ( _control_panel.isShowTaxonomyScientificNames() ) {
3847             if ( !ForesterUtil.isEmpty( taxonomy.getScientificName() ) ) {
3848                 if ( getOptions().isAbbreviateScientificTaxonNames()
3849                         && ( taxonomy.getScientificName().indexOf( ' ' ) > 0 ) ) {
3850                     abbreviateScientificName( taxonomy.getScientificName() );
3851                 }
3852                 else {
3853                     _sb.append( taxonomy.getScientificName() );
3854                 }
3855                 _sb.append( " " );
3856             }
3857         }
3858         else if ( _control_panel.isShowTaxonomyCommonNames() ) {
3859             if ( !ForesterUtil.isEmpty( taxonomy.getCommonName() ) ) {
3860                 _sb.append( taxonomy.getCommonName() );
3861                 _sb.append( " " );
3862             }
3863         }
3864         final String label = _sb.toString();
3865         /* GUILHEM_BEG */
3866         if ( _control_panel.isShowSequenceRelations() && ( label.length() > 0 )
3867                 && ( node.getNodeData().isHasSequence() ) && node.getNodeData().getSequence().equals( _query_sequence ) ) {
3868             // invert font color and background color to show that this is the query sequence
3869             final Rectangle2D nodeTextBounds = new TextLayout( label, g.getFont(), new FontRenderContext( null,
3870                                                                                                           false,
3871                                                                                                           false ) )
3872                     .getBounds();
3873             g.fillRect( ( int ) start_x - 1, ( int ) start_y - 8, ( int ) nodeTextBounds.getWidth() + 4, 11 );
3874             g.setColor( getTreeColorSet().getBackgroundColor() );
3875         }
3876         /* GUILHEM_END */
3877         TreePanel.drawString( label, start_x, start_y, g );
3878         if ( is_in_found_nodes ) {
3879             return getTreeFontSet()._fm_large_italic_bold.stringWidth( label );
3880         }
3881         else {
3882             return getTreeFontSet()._fm_large_italic.stringWidth( label );
3883         }
3884     }
3885
3886     private void abbreviateScientificName( final String sn ) {
3887         final String[] a = sn.split( "\\s+" );
3888         _sb.append( a[ 0 ].substring( 0, 1 ) );
3889         _sb.append( a[ 1 ].substring( 0, 2 ) );
3890         if ( a.length > 2 ) {
3891             for( int i = 2; i < a.length; i++ ) {
3892                 _sb.append( " " );
3893                 _sb.append( a[ i ] );
3894             }
3895         }
3896     }
3897
3898     final private void paintUnrooted( final PhylogenyNode n,
3899                                       final double low_angle,
3900                                       final double high_angle,
3901                                       final boolean radial_labels,
3902                                       final Graphics2D g,
3903                                       final boolean to_pdf,
3904                                       final boolean to_graphics_file ) {
3905         if ( n.isRoot() ) {
3906             n.setXcoord( getWidth() / 2 );
3907             n.setYcoord( getHeight() / 2 );
3908         }
3909         if ( n.isExternal() ) {
3910             paintNodeDataUnrootedCirc( g,
3911                                        n,
3912                                        to_pdf,
3913                                        to_graphics_file,
3914                                        radial_labels,
3915                                        ( high_angle + low_angle ) / 2,
3916                                        isInFoundNodes( n ) );
3917             return;
3918         }
3919         final float num_enclosed = n.getNumberOfExternalNodes();
3920         final float x = n.getXcoord();
3921         final float y = n.getYcoord();
3922         double current_angle = low_angle;
3923         // final boolean n_below = n.getYcoord() < getVisibleRect().getMinY() - 20;
3924         // final boolean n_above = n.getYcoord() > getVisibleRect().getMaxY() + 20;
3925         // final boolean n_left = n.getXcoord() < getVisibleRect().getMinX() - 20;
3926         // final boolean n_right = n.getXcoord() > getVisibleRect().getMaxX() + 20;
3927         for( int i = 0; i < n.getNumberOfDescendants(); ++i ) {
3928             final PhylogenyNode desc = n.getChildNode( i );
3929             ///  if ( ( ( n_below ) & ( desc.getYcoord() < getVisibleRect().getMinY() - 20 ) )
3930             //          || ( ( n_above ) & ( desc.getYcoord() > getVisibleRect().getMaxY() + 20 ) )
3931             //         || ( ( n_left ) & ( desc.getXcoord() < getVisibleRect().getMinX() - 20 ) )
3932             //          || ( ( n_right ) & ( desc.getXcoord() > getVisibleRect().getMaxX() + 20 ) ) ) {
3933             //     continue;
3934             // }
3935             //if ( ( desc.getYcoord() > n.getYcoord() ) && ( n.getYcoord() > getVisibleRect().getMaxY() - 20 ) ) {
3936             //    continue;
3937             //}
3938             //if ( ( desc.getYcoord() < n.getYcoord() ) && ( n.getYcoord() < getVisibleRect().getMinY() + 20 ) ) {
3939             //    continue;
3940             // }
3941             final int desc_num_enclosed = desc.getNumberOfExternalNodes();
3942             final double arc_size = ( desc_num_enclosed / num_enclosed ) * ( high_angle - low_angle );
3943             float length;
3944             if ( isPhyHasBranchLengths() && getControlPanel().isDrawPhylogram() ) {
3945                 if ( desc.getDistanceToParent() < 0 ) {
3946                     length = 0;
3947                 }
3948                 else {
3949                     length = ( float ) ( desc.getDistanceToParent() * getUrtFactor() );
3950                 }
3951             }
3952             else {
3953                 length = getUrtFactor();
3954             }
3955             final double mid_angle = current_angle + arc_size / 2;
3956             final float new_x = ( float ) ( x + Math.cos( mid_angle ) * length );
3957             final float new_y = ( float ) ( y + Math.sin( mid_angle ) * length );
3958             desc.setXcoord( new_x );
3959             desc.setYcoord( new_y );
3960             paintUnrooted( desc, current_angle, current_angle + arc_size, radial_labels, g, to_pdf, to_graphics_file );
3961             current_angle += arc_size;
3962             assignGraphicsForBranchWithColorForParentBranch( desc, false, g, to_pdf, to_graphics_file );
3963             drawLine( x, y, new_x, new_y, g );
3964             paintNodeBox( new_x, new_y, desc, g, to_pdf, to_graphics_file, isInFoundNodes( desc ) );
3965         }
3966         if ( n.isRoot() ) {
3967             paintNodeBox( n.getXcoord(), n.getYcoord(), n, g, to_pdf, to_graphics_file, isInFoundNodes( n ) );
3968         }
3969     }
3970
3971     final private void paintUnrootedLite( final PhylogenyNode n,
3972                                           final double low_angle,
3973                                           final double high_angle,
3974                                           final Graphics2D g,
3975                                           final float urt_ov_factor ) {
3976         if ( n.isRoot() ) {
3977             final int x_pos = ( int ) ( getVisibleRect().x + getOvXPosition() + getOvMaxWidth() / 2 );
3978             final int y_pos = ( int ) ( getVisibleRect().y + getOvYPosition() + getOvMaxHeight() / 2 );
3979             n.setXSecondary( x_pos );
3980             n.setYSecondary( y_pos );
3981         }
3982         if ( n.isExternal() ) {
3983             return;
3984         }
3985         final float num_enclosed = n.getNumberOfExternalNodes();
3986         final float x = n.getXSecondary();
3987         final float y = n.getYSecondary();
3988         double current_angle = low_angle;
3989         for( int i = 0; i < n.getNumberOfDescendants(); ++i ) {
3990             final PhylogenyNode desc = n.getChildNode( i );
3991             final int desc_num_enclosed = desc.getNumberOfExternalNodes();
3992             final double arc_size = ( desc_num_enclosed / num_enclosed ) * ( high_angle - low_angle );
3993             float length;
3994             if ( isPhyHasBranchLengths() && getControlPanel().isDrawPhylogram() ) {
3995                 if ( desc.getDistanceToParent() < 0 ) {
3996                     length = 0;
3997                 }
3998                 else {
3999                     length = ( float ) ( desc.getDistanceToParent() * urt_ov_factor );
4000                 }
4001             }
4002             else {
4003                 length = urt_ov_factor;
4004             }
4005             final double mid_angle = current_angle + arc_size / 2;
4006             final float new_x = ( float ) ( x + Math.cos( mid_angle ) * length );
4007             final float new_y = ( float ) ( y + Math.sin( mid_angle ) * length );
4008             desc.setXSecondary( new_x );
4009             desc.setYSecondary( new_y );
4010             if ( isInFoundNodes( desc ) ) {
4011                 g.setColor( getTreeColorSet().getFoundColor() );
4012                 drawRectFilled( desc.getXSecondary() - 1, desc.getYSecondary() - 1, 3, 3, g );
4013                 g.setColor( getTreeColorSet().getOvColor() );
4014             }
4015             paintUnrootedLite( desc, current_angle, current_angle + arc_size, g, urt_ov_factor );
4016             current_angle += arc_size;
4017             drawLine( x, y, new_x, new_y, g );
4018         }
4019     }
4020
4021     final private void pasteSubtree( final PhylogenyNode node ) {
4022         if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) {
4023             errorMessageNoCutCopyPasteInUnrootedDisplay();
4024             return;
4025         }
4026         if ( ( getCutOrCopiedTree() == null ) || getCutOrCopiedTree().isEmpty() ) {
4027             JOptionPane.showMessageDialog( this,
4028                                            "No tree in buffer (need to copy or cut a subtree first)",
4029                                            "Attempt to paste with empty buffer",
4030                                            JOptionPane.ERROR_MESSAGE );
4031             return;
4032         }
4033         final String label = getASimpleTextRepresentationOfANode( getCutOrCopiedTree().getRoot() );
4034         final Object[] options = { "As sibling", "As descendant", "Cancel" };
4035         final int r = JOptionPane.showOptionDialog( this,
4036                                                     "How to paste subtree" + label + "?",
4037                                                     "Paste Subtree",
4038                                                     JOptionPane.CLOSED_OPTION,
4039                                                     JOptionPane.QUESTION_MESSAGE,
4040                                                     null,
4041                                                     options,
4042                                                     options[ 2 ] );
4043         boolean paste_as_sibling = true;
4044         if ( r == 1 ) {
4045             paste_as_sibling = false;
4046         }
4047         else if ( r != 0 ) {
4048             return;
4049         }
4050         final Phylogeny buffer_phy = getCutOrCopiedTree().copy();
4051         buffer_phy.setAllNodesToNotCollapse();
4052         buffer_phy.preOrderReId();
4053         buffer_phy.setRooted( true );
4054         boolean need_to_show_whole = false;
4055         if ( paste_as_sibling ) {
4056             if ( node.isRoot() ) {
4057                 JOptionPane.showMessageDialog( this,
4058                                                "Cannot paste sibling to root",
4059                                                "Attempt to paste sibling to root",
4060                                                JOptionPane.ERROR_MESSAGE );
4061                 return;
4062             }
4063             buffer_phy.addAsSibling( node );
4064         }
4065         else {
4066             if ( ( node.getNumberOfExternalNodes() == 1 ) && node.isRoot() ) {
4067                 need_to_show_whole = true;
4068                 _phylogeny = buffer_phy;
4069             }
4070             else {
4071                 buffer_phy.addAsChild( node );
4072             }
4073         }
4074         if ( getCopiedAndPastedNodes() == null ) {
4075             setCopiedAndPastedNodes( new HashSet<Integer>() );
4076         }
4077         final List<PhylogenyNode> nodes = PhylogenyMethods.obtainAllNodesAsList( buffer_phy );
4078         final Set<Integer> node_ids = new HashSet<Integer>( nodes.size() );
4079         for( final PhylogenyNode n : nodes ) {
4080             node_ids.add( n.getId() );
4081         }
4082         node_ids.add( node.getId() );
4083         getCopiedAndPastedNodes().addAll( node_ids );
4084         _nodes_in_preorder = null;
4085         _phylogeny.externalNodesHaveChanged();
4086         _phylogeny.hashIDs();
4087         _phylogeny.recalculateNumberOfExternalDescendants( true );
4088         resetNodeIdToDistToLeafMap();
4089         setEdited( true );
4090         if ( need_to_show_whole ) {
4091             getControlPanel().showWhole();
4092         }
4093         repaint();
4094     }
4095
4096     final public int print( final Graphics g, final PageFormat page_format, final int page_index )
4097             throws PrinterException {
4098         if ( page_index > 0 ) {
4099             return ( NO_SUCH_PAGE );
4100         }
4101         else {
4102             final Graphics2D g2d = ( Graphics2D ) g;
4103             g2d.translate( page_format.getImageableX(), page_format.getImageableY() );
4104             // Turn off double buffering !?
4105             paintPhylogeny( g2d, true, false, 0, 0, 0, 0 );
4106             // Turn double buffering back on !?
4107             return ( PAGE_EXISTS );
4108         }
4109     }
4110
4111     final void recalculateMaxDistanceToRoot() {
4112         _max_distance_to_root = PhylogenyMethods.calculateMaxDistanceToRoot( getPhylogeny() );
4113     }
4114
4115     /**
4116      * Remove all edit-node frames
4117      */
4118     final void removeAllEditNodeJFrames() {
4119         for( int i = 0; i <= ( TreePanel.MAX_NODE_FRAMES - 1 ); i++ ) {
4120             if ( _node_frames[ i ] != null ) {
4121                 _node_frames[ i ].dispose();
4122                 _node_frames[ i ] = null;
4123             }
4124         }
4125         _node_frame_index = 0;
4126     }
4127
4128     /**
4129      * Remove a node-edit frame.
4130      */
4131     final void removeEditNodeFrame( final int i ) {
4132         _node_frame_index--;
4133         _node_frames[ i ] = null;
4134         if ( i < _node_frame_index ) {
4135             for( int j = 0; j < _node_frame_index - 1; j++ ) {
4136                 _node_frames[ j ] = _node_frames[ j + 1 ];
4137             }
4138             _node_frames[ _node_frame_index ] = null;
4139         }
4140     }
4141
4142     final void reRoot( final PhylogenyNode node ) {
4143         if ( !getPhylogeny().isRerootable() ) {
4144             JOptionPane.showMessageDialog( this,
4145                                            "This is not rerootable",
4146                                            "Not rerootable",
4147                                            JOptionPane.WARNING_MESSAGE );
4148             return;
4149         }
4150         if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) {
4151             JOptionPane.showMessageDialog( this,
4152                                            "Cannot reroot in unrooted display type",
4153                                            "Attempt to reroot tree in unrooted display",
4154                                            JOptionPane.WARNING_MESSAGE );
4155             return;
4156         }
4157         getPhylogeny().reRoot( node );
4158         getPhylogeny().recalculateNumberOfExternalDescendants( true );
4159         resetNodeIdToDistToLeafMap();
4160         _nodes_in_preorder = null;
4161         resetPreferredSize();
4162         getMainPanel().adjustJScrollPane();
4163         repaint();
4164         if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) {
4165             getControlPanel().showWhole();
4166         }
4167     }
4168
4169     final void resetNodeIdToDistToLeafMap() {
4170         _nodeid_dist_to_leaf = new HashMap<Integer, Short>();
4171     }
4172
4173     final void resetPreferredSize() {
4174         if ( ( getPhylogeny() == null ) || getPhylogeny().isEmpty() ) {
4175             return;
4176         }
4177         int x = 0;
4178         int y = 0;
4179         y = TreePanel.MOVE
4180                 + ForesterUtil.roundToInt( getYdistance() * getPhylogeny().getRoot().getNumberOfExternalNodes() * 2 );
4181         if ( getControlPanel().isDrawPhylogram() ) {
4182             x = TreePanel.MOVE
4183                     + getLongestExtNodeInfo()
4184                     + ForesterUtil
4185                             .roundToInt( ( getXcorrectionFactor() * getPhylogeny().getHeight() ) + getXdistance() );
4186         }
4187         else {
4188             if ( !isNonLinedUpCladogram() && !isUniformBranchLengthsForCladogram() ) {
4189                 x = TreePanel.MOVE
4190                         + getLongestExtNodeInfo()
4191                         + ForesterUtil.roundToInt( getXdistance()
4192                                 * ( getPhylogeny().getRoot().getNumberOfExternalNodes() + 2 ) );
4193             }
4194             else {
4195                 x = TreePanel.MOVE
4196                         + getLongestExtNodeInfo()
4197                         + ForesterUtil.roundToInt( getXdistance()
4198                                 * ( PhylogenyMethods.calculateMaxDepth( getPhylogeny() ) + 1 ) );
4199             }
4200         }
4201         setPreferredSize( new Dimension( x, y ) );
4202     }
4203
4204     public final void setArrowCursor() {
4205         setCursor( ARROW_CURSOR );
4206         repaint();
4207     }
4208
4209     final void setControlPanel( final ControlPanel atv_control ) {
4210         _control_panel = atv_control;
4211     }
4212
4213     final private void setCopiedAndPastedNodes( final Set<Integer> nodeIds ) {
4214         getMainPanel().setCopiedAndPastedNodes( nodeIds );
4215     }
4216
4217     final private void setCutOrCopiedTree( final Phylogeny cut_or_copied_tree ) {
4218         getMainPanel().setCutOrCopiedTree( cut_or_copied_tree );
4219     }
4220
4221     public final void setEdited( final boolean edited ) {
4222         _edited = edited;
4223     }
4224
4225     final void setFoundNodes( final Set<Integer> found_nodes ) {
4226         _found_nodes = found_nodes;
4227     }
4228
4229     final private void setInOv( final boolean in_ov ) {
4230         _in_ov = in_ov;
4231     }
4232
4233     final void setInOvRect( final boolean in_ov_rect ) {
4234         _in_ov_rect = in_ov_rect;
4235     }
4236
4237     final void setLargeFonts() {
4238         getTreeFontSet().largeFonts();
4239     }
4240
4241     final void setLastMouseDragPointX( final float x ) {
4242         _last_drag_point_x = x;
4243     }
4244
4245     final void setLastMouseDragPointY( final float y ) {
4246         _last_drag_point_y = y;
4247     }
4248
4249     final void setLongestExtNodeInfo( final int i ) {
4250         _longest_ext_node_info = i;
4251     }
4252
4253     final void setMediumFonts() {
4254         getTreeFontSet().mediumFonts();
4255     }
4256
4257     final private void setOvMaxHeight( final float ov_max_height ) {
4258         _ov_max_height = ov_max_height;
4259     }
4260
4261     final private void setOvMaxWidth( final float ov_max_width ) {
4262         _ov_max_width = ov_max_width;
4263     }
4264
4265     final void setOvOn( final boolean ov_on ) {
4266         _ov_on = ov_on;
4267     }
4268
4269     final private void setOvXcorrectionFactor( final float f ) {
4270         _ov_x_correction_factor = f;
4271     }
4272
4273     final private void setOvXDistance( final float ov_x_distance ) {
4274         _ov_x_distance = ov_x_distance;
4275     }
4276
4277     final private void setOvXPosition( final int ov_x_position ) {
4278         _ov_x_position = ov_x_position;
4279     }
4280
4281     final private void setOvYDistance( final float ov_y_distance ) {
4282         _ov_y_distance = ov_y_distance;
4283     }
4284
4285     final private void setOvYPosition( final int ov_y_position ) {
4286         _ov_y_position = ov_y_position;
4287     }
4288
4289     final private void setOvYStart( final int ov_y_start ) {
4290         _ov_y_start = ov_y_start;
4291     }
4292
4293     /**
4294      * Set parameters for printing the displayed tree
4295      * 
4296      * @param x
4297      * @param y
4298      */
4299     final void setParametersForPainting( final int x, final int y, final boolean recalc_longest_ext_node_info ) {
4300         // updateStyle(); not needed?
4301         if ( ( _phylogeny != null ) && !_phylogeny.isEmpty() ) {
4302             initNodeData();
4303             if ( recalc_longest_ext_node_info ) {
4304                 calculateLongestExtNodeInfo();
4305             }
4306             int ext_nodes = _phylogeny.getRoot().getNumberOfExternalNodes();
4307             final int max_depth = PhylogenyMethods.calculateMaxDepth( _phylogeny );
4308             if ( ext_nodes == 1 ) {
4309                 ext_nodes = max_depth;
4310                 if ( ext_nodes < 1 ) {
4311                     ext_nodes = 1;
4312                 }
4313             }
4314             updateOvSizes();
4315             float xdist = 0;
4316             float ov_xdist = 0;
4317             if ( !isNonLinedUpCladogram() && !isUniformBranchLengthsForCladogram() ) {
4318                 xdist = ( float ) ( ( x - getLongestExtNodeInfo() - TreePanel.MOVE ) / ( ext_nodes + 3.0 ) );
4319                 ov_xdist = ( float ) ( getOvMaxWidth() / ( ext_nodes + 3.0 ) );
4320             }
4321             else {
4322                 xdist = ( ( x - getLongestExtNodeInfo() - TreePanel.MOVE ) / ( max_depth + 1 ) );
4323                 ov_xdist = ( getOvMaxWidth() / ( max_depth + 1 ) );
4324             }
4325             float ydist = ( float ) ( ( y - TreePanel.MOVE ) / ( ext_nodes * 2.0 ) );
4326             if ( xdist < 0.0 ) {
4327                 xdist = 0.0f;
4328             }
4329             if ( ov_xdist < 0.0 ) {
4330                 ov_xdist = 0.0f;
4331             }
4332             if ( ydist < 0.0 ) {
4333                 ydist = 0.0f;
4334             }
4335             setXdistance( xdist );
4336             setYdistance( ydist );
4337             setOvXDistance( ov_xdist );
4338             final double height = _phylogeny.getHeight();
4339             if ( height > 0 ) {
4340                 final float corr = ( float ) ( ( x - TreePanel.MOVE - getLongestExtNodeInfo() - getXdistance() ) / height );
4341                 setXcorrectionFactor( corr > 0 ? corr : 0 );
4342                 final float ov_corr = ( float ) ( ( getOvMaxWidth() - getOvXDistance() ) / height );
4343                 setOvXcorrectionFactor( ov_corr > 0 ? ov_corr : 0 );
4344             }
4345             else {
4346                 setXcorrectionFactor( 0 );
4347                 setOvXcorrectionFactor( 0 );
4348             }
4349             _circ_max_depth = max_depth;
4350             setUpUrtFactor();
4351         }
4352     }
4353
4354     final void setPhylogenyGraphicsType( final PHYLOGENY_GRAPHICS_TYPE graphics_type ) {
4355         _graphics_type = graphics_type;
4356         setTextAntialias();
4357     }
4358
4359     final private void setScaleDistance( final double scale_distance ) {
4360         _scale_distance = scale_distance;
4361     }
4362
4363     final private void setScaleLabel( final String scale_label ) {
4364         _scale_label = scale_label;
4365     }
4366
4367     final void setSmallFonts() {
4368         getTreeFontSet().smallFonts();
4369     }
4370
4371     final void setStartingAngle( final double starting_angle ) {
4372         _urt_starting_angle = starting_angle;
4373     }
4374
4375     final void setSuperTinyFonts() {
4376         getTreeFontSet().superTinyFonts();
4377     }
4378
4379     final void setTextAntialias() {
4380         if ( ( _phylogeny != null ) && !_phylogeny.isEmpty() ) {
4381             if ( _phylogeny.getNumberOfExternalNodes() <= LIMIT_FOR_HQ_RENDERING ) {
4382                 _rendering_hints.put( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );
4383             }
4384             else {
4385                 _rendering_hints.put( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED );
4386             }
4387         }
4388         if ( getMainPanel().getOptions().isAntialiasScreen() ) {
4389             if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ) {
4390                 _rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
4391             }
4392             else {
4393                 _rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
4394             }
4395             try {
4396                 _rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING,
4397                                       RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB );
4398             }
4399             catch ( final Throwable e ) {
4400                 _rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
4401             }
4402         }
4403         else {
4404             _rendering_hints.put( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
4405             _rendering_hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
4406         }
4407     }
4408
4409     final void setTinyFonts() {
4410         getTreeFontSet().tinyFonts();
4411     }
4412
4413     /**
4414      * Set a phylogeny tree.
4415      * 
4416      * @param t
4417      *            an instance of a Phylogeny
4418      */
4419     public final void setTree( final Phylogeny t ) {
4420         _nodes_in_preorder = null;
4421         _phylogeny = t;
4422     }
4423
4424     final void setTreeFile( final File treefile ) {
4425         _treefile = treefile;
4426     }
4427
4428     final private void setUpUrtFactor() {
4429         final int d = getVisibleRect().width < getVisibleRect().height ? getVisibleRect().width
4430                 : getVisibleRect().height;
4431         if ( isPhyHasBranchLengths() && getControlPanel().isDrawPhylogram() ) {
4432             setUrtFactor( ( float ) ( d / ( 2 * getMaxDistanceToRoot() ) ) );
4433         }
4434         else {
4435             final int max_depth = _circ_max_depth;
4436             if ( max_depth > 0 ) {
4437                 setUrtFactor( d / ( 2 * max_depth ) );
4438             }
4439             else {
4440                 setUrtFactor( d / 2 );
4441             }
4442         }
4443         setUrtFactorOv( getUrtFactor() );
4444     }
4445
4446     final private void setUrtFactor( final float urt_factor ) {
4447         _urt_factor = urt_factor;
4448     }
4449
4450     final private void setUrtFactorOv( final float urt_factor_ov ) {
4451         _urt_factor_ov = urt_factor_ov;
4452     }
4453
4454     public final void setWaitCursor() {
4455         setCursor( WAIT_CURSOR );
4456         repaint();
4457     }
4458
4459     final void setXcorrectionFactor( final float f ) {
4460         _x_correction_factor = f;
4461     }
4462
4463     final void setXdistance( final float x ) {
4464         _x_distance = x;
4465     }
4466
4467     final void setYdistance( final float y ) {
4468         _y_distance = y;
4469     }
4470
4471     final private void showNodeDataPopup( final MouseEvent e, final PhylogenyNode node ) {
4472         try {
4473             if ( ( node.getName().length() > 0 )
4474                     || ( node.getNodeData().isHasTaxonomy() && !isTaxonomyEmpty( node.getNodeData().getTaxonomy() ) )
4475                     || ( node.getNodeData().isHasSequence() && !isSequenceEmpty( node.getNodeData().getSequence() ) )
4476                     || ( node.getNodeData().isHasDate() ) || ( node.getNodeData().isHasDistribution() )
4477                     || node.getBranchData().isHasConfidences() ) {
4478                 _popup_buffer.setLength( 0 );
4479                 short lines = 0;
4480                 if ( node.getName().length() > 0 ) {
4481                     lines++;
4482                     _popup_buffer.append( node.getName() );
4483                 }
4484                 if ( node.getNodeData().isHasTaxonomy() && !isTaxonomyEmpty( node.getNodeData().getTaxonomy() ) ) {
4485                     lines++;
4486                     boolean enc_data = false;
4487                     final Taxonomy tax = node.getNodeData().getTaxonomy();
4488                     if ( _popup_buffer.length() > 0 ) {
4489                         _popup_buffer.append( "\n" );
4490                     }
4491                     if ( !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
4492                         _popup_buffer.append( "[" );
4493                         _popup_buffer.append( tax.getTaxonomyCode() );
4494                         _popup_buffer.append( "]" );
4495                         enc_data = true;
4496                     }
4497                     if ( !ForesterUtil.isEmpty( tax.getScientificName() ) ) {
4498                         if ( enc_data ) {
4499                             _popup_buffer.append( " " );
4500                         }
4501                         _popup_buffer.append( tax.getScientificName() );
4502                         enc_data = true;
4503                     }
4504                     if ( !ForesterUtil.isEmpty( tax.getCommonName() ) ) {
4505                         if ( enc_data ) {
4506                             _popup_buffer.append( " (" );
4507                         }
4508                         else {
4509                             _popup_buffer.append( "(" );
4510                         }
4511                         _popup_buffer.append( tax.getCommonName() );
4512                         _popup_buffer.append( ")" );
4513                         enc_data = true;
4514                     }
4515                     if ( !ForesterUtil.isEmpty( tax.getAuthority() ) ) {
4516                         if ( enc_data ) {
4517                             _popup_buffer.append( " (" );
4518                         }
4519                         else {
4520                             _popup_buffer.append( "(" );
4521                         }
4522                         _popup_buffer.append( tax.getAuthority() );
4523                         _popup_buffer.append( ")" );
4524                         enc_data = true;
4525                     }
4526                     if ( !ForesterUtil.isEmpty( tax.getRank() ) ) {
4527                         if ( enc_data ) {
4528                             _popup_buffer.append( " [" );
4529                         }
4530                         else {
4531                             _popup_buffer.append( "[" );
4532                         }
4533                         _popup_buffer.append( tax.getRank() );
4534                         _popup_buffer.append( "]" );
4535                         enc_data = true;
4536                     }
4537                     if ( tax.getSynonyms().size() > 0 ) {
4538                         if ( enc_data ) {
4539                             _popup_buffer.append( " " );
4540                         }
4541                         _popup_buffer.append( "[" );
4542                         int counter = 1;
4543                         for( final String syn : tax.getSynonyms() ) {
4544                             if ( !ForesterUtil.isEmpty( syn ) ) {
4545                                 enc_data = true;
4546                                 _popup_buffer.append( syn );
4547                                 if ( counter < tax.getSynonyms().size() ) {
4548                                     _popup_buffer.append( ", " );
4549                                 }
4550                             }
4551                             counter++;
4552                         }
4553                         _popup_buffer.append( "]" );
4554                     }
4555                     if ( !enc_data ) {
4556                         if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) ) {
4557                             if ( !ForesterUtil.isEmpty( tax.getIdentifier().getProvider() ) ) {
4558                                 _popup_buffer.append( "[" );
4559                                 _popup_buffer.append( tax.getIdentifier().getProvider() );
4560                                 _popup_buffer.append( "] " );
4561                             }
4562                             _popup_buffer.append( tax.getIdentifier().getValue() );
4563                         }
4564                     }
4565                 }
4566                 if ( node.getNodeData().isHasSequence() && !isSequenceEmpty( node.getNodeData().getSequence() ) ) {
4567                     lines++;
4568                     boolean enc_data = false;
4569                     if ( _popup_buffer.length() > 0 ) {
4570                         _popup_buffer.append( "\n" );
4571                     }
4572                     final Sequence seq = node.getNodeData().getSequence();
4573                     if ( seq.getAccession() != null ) {
4574                         _popup_buffer.append( "[" );
4575                         if ( !ForesterUtil.isEmpty( seq.getAccession().getSource() ) ) {
4576                             _popup_buffer.append( seq.getAccession().getSource() );
4577                             _popup_buffer.append( ":" );
4578                         }
4579                         _popup_buffer.append( seq.getAccession().getValue() );
4580                         _popup_buffer.append( "]" );
4581                         enc_data = true;
4582                     }
4583                     if ( !ForesterUtil.isEmpty( seq.getSymbol() ) ) {
4584                         if ( enc_data ) {
4585                             _popup_buffer.append( " [" );
4586                         }
4587                         else {
4588                             _popup_buffer.append( "[" );
4589                         }
4590                         _popup_buffer.append( seq.getSymbol() );
4591                         _popup_buffer.append( "]" );
4592                         enc_data = true;
4593                     }
4594                     if ( !ForesterUtil.isEmpty( seq.getName() ) ) {
4595                         if ( enc_data ) {
4596                             _popup_buffer.append( " " );
4597                         }
4598                         _popup_buffer.append( seq.getName() );
4599                     }
4600                 }
4601                 if ( node.getNodeData().isHasDate() ) {
4602                     lines++;
4603                     if ( _popup_buffer.length() > 0 ) {
4604                         _popup_buffer.append( "\n" );
4605                     }
4606                     _popup_buffer.append( node.getNodeData().getDate().asSimpleText() );
4607                 }
4608                 if ( node.getNodeData().isHasDistribution() ) {
4609                     lines++;
4610                     if ( _popup_buffer.length() > 0 ) {
4611                         _popup_buffer.append( "\n" );
4612                     }
4613                     _popup_buffer.append( node.getNodeData().getDistribution().asSimpleText() );
4614                 }
4615                 if ( node.getBranchData().isHasConfidences() ) {
4616                     final List<Confidence> confs = node.getBranchData().getConfidences();
4617                     for( final Confidence confidence : confs ) {
4618                         lines++;
4619                         if ( _popup_buffer.length() > 0 ) {
4620                             _popup_buffer.append( "\n" );
4621                         }
4622                         if ( !ForesterUtil.isEmpty( confidence.getType() ) ) {
4623                             _popup_buffer.append( "[" );
4624                             _popup_buffer.append( confidence.getType() );
4625                             _popup_buffer.append( "] " );
4626                         }
4627                         _popup_buffer
4628                                 .append( FORMATTER_CONFIDENCE.format( ForesterUtil.round( confidence.getValue(),
4629                                                                                           getOptions()
4630                                                                                                   .getNumberOfDigitsAfterCommaForConfidenceValues() ) ) );
4631                     }
4632                 }
4633                 if ( _popup_buffer.length() > 0 ) {
4634                     if ( !getConfiguration().isUseNativeUI() ) {
4635                         _rollover_popup
4636                                 .setBorder( BorderFactory.createLineBorder( getTreeColorSet().getBranchColor() ) );
4637                         _rollover_popup.setBackground( getTreeColorSet().getBackgroundColor() );
4638                         if ( isInFoundNodes( node ) ) {
4639                             _rollover_popup.setForeground( getTreeColorSet().getFoundColor() );
4640                         }
4641                         else if ( getControlPanel().isColorAccordingToTaxonomy() ) {
4642                             _rollover_popup.setForeground( getTaxonomyBasedColor( node ) );
4643                         }
4644                         else {
4645                             _rollover_popup.setForeground( getTreeColorSet().getSequenceColor() );
4646                         }
4647                     }
4648                     else {
4649                         _rollover_popup.setBorder( BorderFactory.createLineBorder( Color.BLACK ) );
4650                     }
4651                     _rollover_popup.setText( _popup_buffer.toString() );
4652                     _node_desc_popup = PopupFactory.getSharedInstance().getPopup( null,
4653                                                                                   _rollover_popup,
4654                                                                                   e.getLocationOnScreen().x + 10,
4655                                                                                   e.getLocationOnScreen().y
4656                                                                                           - ( lines * 20 ) );
4657                     _node_desc_popup.show();
4658                 }
4659             }
4660         }
4661         catch ( final Exception ex ) {
4662             // Do nothing.
4663         }
4664     }
4665
4666     final private void showNodeEditFrame( final PhylogenyNode n ) {
4667         if ( _node_frame_index < TreePanel.MAX_NODE_FRAMES ) {
4668             // pop up edit box for single node
4669             _node_frames[ _node_frame_index ] = new NodeFrame( n, _phylogeny, this, _node_frame_index, "" );
4670             _node_frame_index++;
4671         }
4672         else {
4673             JOptionPane.showMessageDialog( this, "too many node windows are open" );
4674         }
4675     }
4676
4677     final private void showNodeFrame( final PhylogenyNode n ) {
4678         if ( _node_frame_index < TreePanel.MAX_NODE_FRAMES ) {
4679             // pop up edit box for single node
4680             _node_frames[ _node_frame_index ] = new NodeFrame( n, _phylogeny, this, _node_frame_index );
4681             _node_frame_index++;
4682         }
4683         else {
4684             JOptionPane.showMessageDialog( this, "too many node windows are open" );
4685         }
4686     }
4687
4688     final void subTree( final PhylogenyNode node ) {
4689         if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) {
4690             JOptionPane.showMessageDialog( this,
4691                                            "Cannot get a sub/super tree in unrooted display",
4692                                            "Attempt to get sub/super tree in unrooted display",
4693                                            JOptionPane.WARNING_MESSAGE );
4694             return;
4695         }
4696         if ( node.isExternal() ) {
4697             JOptionPane.showMessageDialog( this,
4698                                            "Cannot get a subtree of a external node",
4699                                            "Attempt to get subtree of external node",
4700                                            JOptionPane.WARNING_MESSAGE );
4701             return;
4702         }
4703         if ( node.isRoot() && !isCurrentTreeIsSubtree() ) {
4704             JOptionPane.showMessageDialog( this,
4705                                            "Cannot get a subtree of the root node",
4706                                            "Attempt to get subtree of root node",
4707                                            JOptionPane.WARNING_MESSAGE );
4708             return;
4709         }
4710         _nodes_in_preorder = null;
4711         if ( !node.isExternal() && !node.isRoot() && ( _subtree_index <= ( TreePanel.MAX_SUBTREES - 1 ) ) ) {
4712             _sub_phylogenies[ _subtree_index ] = _phylogeny;
4713             _sub_phylogenies_temp_roots[ _subtree_index ] = node;
4714             ++_subtree_index;
4715             _phylogeny = subTree( node, _phylogeny );
4716             updateSubSuperTreeButton();
4717         }
4718         else if ( node.isRoot() && isCurrentTreeIsSubtree() ) {
4719             superTree();
4720         }
4721         _main_panel.getControlPanel().showWhole();
4722         repaint();
4723     }
4724
4725     final boolean isCurrentTreeIsSubtree() {
4726         return ( _subtree_index > 0 );
4727     }
4728
4729     final private static Phylogeny subTree( final PhylogenyNode new_root, final Phylogeny source_phy ) {
4730         final Phylogeny new_phy = new Phylogeny();
4731         new_phy.setRooted( true );
4732         new_phy.setName( source_phy.getName() );
4733         new_phy.setDescription( source_phy.getDescription() );
4734         new_phy.setType( source_phy.getType() );
4735         new_phy.setDistanceUnit( source_phy.getDistanceUnit() );
4736         new_phy.setConfidence( source_phy.getConfidence() );
4737         new_phy.setIdentifier( source_phy.getIdentifier() );
4738         new_phy.setRoot( new_root.copyNodeDataShallow() );
4739         int i = 0;
4740         for( final PhylogenyNode n : new_root.getDescendants() ) {
4741             new_phy.getRoot().setChildNode( i++, n );
4742         }
4743         return new_phy;
4744     }
4745
4746     final void superTree() {
4747         _nodes_in_preorder = null;
4748         final PhylogenyNode temp_root = _sub_phylogenies_temp_roots[ _subtree_index - 1 ];
4749         for( final PhylogenyNode n : temp_root.getDescendants() ) {
4750             n.setParent( temp_root );
4751         }
4752         _sub_phylogenies[ _subtree_index ] = null;
4753         _sub_phylogenies_temp_roots[ _subtree_index ] = null;
4754         _phylogeny = _sub_phylogenies[ --_subtree_index ];
4755         updateSubSuperTreeButton();
4756     }
4757
4758     final void swap( final PhylogenyNode node ) {
4759         if ( !node.isExternal() ) {
4760             _phylogeny.swapChildren( node );
4761             _nodes_in_preorder = null;
4762         }
4763         repaint();
4764     }
4765
4766     final private void switchDisplaygetPhylogenyGraphicsType() {
4767         switch ( getPhylogenyGraphicsType() ) {
4768             case RECTANGULAR:
4769                 setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE );
4770                 getOptions().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE );
4771                 break;
4772             case EURO_STYLE:
4773                 setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.ROUNDED );
4774                 getOptions().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.ROUNDED );
4775                 break;
4776             case ROUNDED:
4777                 setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CURVED );
4778                 getOptions().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CURVED );
4779                 break;
4780             case CURVED:
4781                 setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.TRIANGULAR );
4782                 getOptions().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.TRIANGULAR );
4783                 break;
4784             case TRIANGULAR:
4785                 setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CONVEX );
4786                 getOptions().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CONVEX );
4787                 break;
4788             case CONVEX:
4789                 setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.UNROOTED );
4790                 getOptions().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.UNROOTED );
4791                 break;
4792             case UNROOTED:
4793                 setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CIRCULAR );
4794                 getOptions().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CIRCULAR );
4795                 break;
4796             case CIRCULAR:
4797                 setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
4798                 getOptions().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR );
4799                 break;
4800             default:
4801                 throw new RuntimeException( "unkwnown display type: " + getPhylogenyGraphicsType() );
4802         }
4803         if ( getControlPanel().getDynamicallyHideData() != null ) {
4804             if ( getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) {
4805                 getControlPanel().getDynamicallyHideData().setEnabled( false );
4806             }
4807             else {
4808                 getControlPanel().getDynamicallyHideData().setEnabled( true );
4809             }
4810         }
4811         if ( isPhyHasBranchLengths() && ( getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) {
4812             getControlPanel().setDrawPhylogramEnabled( true );
4813         }
4814         else {
4815             getControlPanel().setDrawPhylogramEnabled( false );
4816         }
4817         if ( getMainPanel().getMainFrame() == null ) {
4818             // Must be "E" applet version.
4819             ( ( ArchaeopteryxE ) ( ( MainPanelApplets ) getMainPanel() ).getApplet() )
4820                     .setSelectedTypeInTypeMenu( getPhylogenyGraphicsType() );
4821         }
4822         else {
4823             getMainPanel().getMainFrame().setSelectedTypeInTypeMenu( getPhylogenyGraphicsType() );
4824         }
4825     }
4826
4827     final void taxColor() {
4828         if ( ( _phylogeny == null ) || ( _phylogeny.getNumberOfExternalNodes() < 2 ) ) {
4829             return;
4830         }
4831         setWaitCursor();
4832         Util.colorPhylogenyAccordingToExternalTaxonomy( _phylogeny, this );
4833         _control_panel.setColorBranches( true );
4834         if ( _control_panel.getColorBranchesCb() != null ) {
4835             _control_panel.getColorBranchesCb().setSelected( true );
4836         }
4837         setArrowCursor();
4838         repaint();
4839     }
4840
4841     final void updateOvSettings() {
4842         switch ( getOptions().getOvPlacement() ) {
4843             case LOWER_LEFT:
4844                 setOvXPosition( OV_BORDER );
4845                 setOvYPosition( ForesterUtil.roundToInt( getVisibleRect().height - OV_BORDER - getOvMaxHeight() ) );
4846                 setOvYStart( ForesterUtil.roundToInt( getOvYPosition() + ( getOvMaxHeight() / 2 ) ) );
4847                 break;
4848             case LOWER_RIGHT:
4849                 setOvXPosition( ForesterUtil.roundToInt( getVisibleRect().width - OV_BORDER - getOvMaxWidth() ) );
4850                 setOvYPosition( ForesterUtil.roundToInt( getVisibleRect().height - OV_BORDER - getOvMaxHeight() ) );
4851                 setOvYStart( ForesterUtil.roundToInt( getOvYPosition() + ( getOvMaxHeight() / 2 ) ) );
4852                 break;
4853             case UPPER_RIGHT:
4854                 setOvXPosition( ForesterUtil.roundToInt( getVisibleRect().width - OV_BORDER - getOvMaxWidth() ) );
4855                 setOvYPosition( OV_BORDER );
4856                 setOvYStart( ForesterUtil.roundToInt( OV_BORDER + ( getOvMaxHeight() / 2 ) ) );
4857                 break;
4858             default:
4859                 setOvXPosition( OV_BORDER );
4860                 setOvYPosition( OV_BORDER );
4861                 setOvYStart( ForesterUtil.roundToInt( OV_BORDER + ( getOvMaxHeight() / 2 ) ) );
4862                 break;
4863         }
4864     }
4865
4866     final void updateOvSizes() {
4867         if ( ( getWidth() > 1.05 * getVisibleRect().width ) || ( getHeight() > 1.05 * getVisibleRect().height ) ) {
4868             setOvOn( true );
4869             float l = getLongestExtNodeInfo();
4870             final float w_ratio = getOvMaxWidth() / getWidth();
4871             l *= w_ratio;
4872             final int ext_nodes = _phylogeny.getRoot().getNumberOfExternalNodes();
4873             setOvYDistance( getOvMaxHeight() / ( 2 * ext_nodes ) );
4874             float ov_xdist = 0;
4875             if ( !isNonLinedUpCladogram() && !isUniformBranchLengthsForCladogram() ) {
4876                 ov_xdist = ( ( getOvMaxWidth() - l ) / ( ext_nodes ) );
4877             }
4878             else {
4879                 ov_xdist = ( ( getOvMaxWidth() - l ) / ( PhylogenyMethods.calculateMaxDepth( _phylogeny ) ) );
4880             }
4881             float ydist = ( float ) ( ( getOvMaxWidth() / ( ext_nodes * 2.0 ) ) );
4882             if ( ov_xdist < 0.0 ) {
4883                 ov_xdist = 0.0f;
4884             }
4885             if ( ydist < 0.0 ) {
4886                 ydist = 0.0f;
4887             }
4888             setOvXDistance( ov_xdist );
4889             final double height = _phylogeny.getHeight();
4890             if ( height > 0 ) {
4891                 final float ov_corr = ( float ) ( ( ( getOvMaxWidth() - l ) - getOvXDistance() ) / height );
4892                 setOvXcorrectionFactor( ov_corr > 0 ? ov_corr : 0 );
4893             }
4894             else {
4895                 setOvXcorrectionFactor( 0 );
4896             }
4897         }
4898         else {
4899             setOvOn( false );
4900         }
4901     }
4902
4903     final void updateSubSuperTreeButton() {
4904         if ( _subtree_index < 1 ) {
4905             getControlPanel().deactivateButtonToReturnToSuperTree();
4906         }
4907         else {
4908             getControlPanel().activateButtonToReturnToSuperTree( _subtree_index );
4909         }
4910     }
4911
4912     final void zoomInDomainStructure() {
4913         if ( _domain_structure_width < 2000 ) {
4914             _domain_structure_width *= 1.2;
4915         }
4916     }
4917
4918     final void zoomOutDomainStructure() {
4919         if ( _domain_structure_width > 20 ) {
4920             _domain_structure_width *= 0.8;
4921         }
4922     }
4923
4924     final private static void drawString( final int i, final double x, final double y, final Graphics2D g ) {
4925         g.drawString( String.valueOf( i ), ( int ) ( x + 0.5 ), ( int ) ( y + 0.5 ) );
4926     }
4927
4928     final private static void drawString( final String str, final double x, final double y, final Graphics2D g ) {
4929         g.drawString( str, ( int ) ( x + 0.5 ), ( int ) ( y + 0.5 ) );
4930     }
4931
4932     final private static boolean isSequenceEmpty( final Sequence seq ) {
4933         return ( seq.getAccession() == null ) && ForesterUtil.isEmpty( seq.getName() )
4934                 && ForesterUtil.isEmpty( seq.getSymbol() );
4935     }
4936
4937     final private static boolean isTaxonomyEmpty( final Taxonomy tax ) {
4938         return ( ( tax.getIdentifier() == null ) && ForesterUtil.isEmpty( tax.getTaxonomyCode() )
4939                 && ForesterUtil.isEmpty( tax.getCommonName() ) && ForesterUtil.isEmpty( tax.getScientificName() ) && tax
4940                 .getSynonyms().isEmpty() );
4941     }
4942
4943     final private static boolean plusPressed( final int key_code ) {
4944         return ( ( key_code == KeyEvent.VK_ADD ) || ( key_code == KeyEvent.VK_PLUS )
4945                 || ( key_code == KeyEvent.VK_EQUALS ) || ( key_code == KeyEvent.VK_SEMICOLON ) || ( key_code == KeyEvent.VK_1 ) );
4946     }
4947
4948     void setStatisticsForExpressionValues( final DescriptiveStatistics statistics_for_expression_values ) {
4949         _statistics_for_vector_data = statistics_for_expression_values;
4950     }
4951
4952     DescriptiveStatistics getStatisticsForExpressionValues() {
4953         return _statistics_for_vector_data;
4954     }
4955
4956     final private class SubtreeColorizationActionListener implements ActionListener {
4957
4958         JColorChooser _chooser;
4959         PhylogenyNode _node;
4960
4961         SubtreeColorizationActionListener( final JColorChooser chooser, final PhylogenyNode node ) {
4962             _chooser = chooser;
4963             _node = node;
4964         }
4965
4966         @Override
4967         public void actionPerformed( final ActionEvent e ) {
4968             final Color c = _chooser.getColor();
4969             if ( c != null ) {
4970                 colorizeSubtree( c, _node );
4971             }
4972         }
4973     }
4974
4975     public synchronized void setImageMap( final Hashtable<String, BufferedImage> image_map ) {
4976         getMainPanel().setImageMap( image_map );
4977     }
4978
4979     public synchronized Hashtable<String, BufferedImage> getImageMap() {
4980         return getMainPanel().getImageMap();
4981     }
4982 }