JAL-3127 use AlignViewportI.addGroup() to add group and propagate to complement view...
[jalview.git] / src / jalview / gui / TreeCanvas.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.analysis.Conservation;
24 import jalview.analysis.TreeModel;
25 import jalview.api.AlignViewportI;
26 import jalview.datamodel.Sequence;
27 import jalview.datamodel.SequenceGroup;
28 import jalview.datamodel.SequenceI;
29 import jalview.datamodel.SequenceNode;
30 import jalview.schemes.ColourSchemeI;
31 import jalview.schemes.ColourSchemeProperty;
32 import jalview.schemes.UserColourScheme;
33 import jalview.structure.SelectionSource;
34 import jalview.util.Format;
35 import jalview.util.MessageManager;
36
37 import java.awt.Color;
38 import java.awt.Dimension;
39 import java.awt.Font;
40 import java.awt.FontMetrics;
41 import java.awt.Graphics;
42 import java.awt.Graphics2D;
43 import java.awt.Point;
44 import java.awt.Rectangle;
45 import java.awt.RenderingHints;
46 import java.awt.event.MouseEvent;
47 import java.awt.event.MouseListener;
48 import java.awt.event.MouseMotionListener;
49 import java.awt.print.PageFormat;
50 import java.awt.print.Printable;
51 import java.awt.print.PrinterException;
52 import java.awt.print.PrinterJob;
53 import java.util.Enumeration;
54 import java.util.Hashtable;
55 import java.util.List;
56 import java.util.Vector;
57
58 import javax.swing.JColorChooser;
59 import javax.swing.JPanel;
60 import javax.swing.JScrollPane;
61 import javax.swing.SwingUtilities;
62 import javax.swing.ToolTipManager;
63
64 /**
65  * DOCUMENT ME!
66  * 
67  * @author $author$
68  * @version $Revision$
69  */
70 public class TreeCanvas extends JPanel implements MouseListener, Runnable,
71         Printable, MouseMotionListener, SelectionSource
72 {
73   /** DOCUMENT ME!! */
74   public static final String PLACEHOLDER = " * ";
75
76   TreeModel tree;
77
78   JScrollPane scrollPane;
79
80   TreePanel tp;
81
82   AlignViewport av;
83
84   AlignmentPanel ap;
85
86   Font font;
87
88   FontMetrics fm;
89
90   boolean fitToWindow = true;
91
92   boolean showDistances = false;
93
94   boolean showBootstrap = false;
95
96   boolean markPlaceholders = false;
97
98   int offx = 20;
99
100   int offy;
101
102   float threshold;
103
104   String longestName;
105
106   int labelLength = -1;
107
108   Hashtable nameHash = new Hashtable();
109
110   Hashtable nodeHash = new Hashtable();
111
112   SequenceNode highlightNode;
113
114   boolean applyToAllViews = false;
115
116   /**
117    * Creates a new TreeCanvas object.
118    * 
119    * @param av
120    *          DOCUMENT ME!
121    * @param tree
122    *          DOCUMENT ME!
123    * @param scroller
124    *          DOCUMENT ME!
125    * @param label
126    *          DOCUMENT ME!
127    */
128   public TreeCanvas(TreePanel tp, AlignmentPanel ap, JScrollPane scroller)
129   {
130     this.tp = tp;
131     this.av = ap.av;
132     this.ap = ap;
133     font = av.getFont();
134     scrollPane = scroller;
135     addMouseListener(this);
136     addMouseMotionListener(this);
137     ToolTipManager.sharedInstance().registerComponent(this);
138   }
139
140   /**
141    * DOCUMENT ME!
142    * 
143    * @param sequence
144    *          DOCUMENT ME!
145    */
146   public void treeSelectionChanged(SequenceI sequence)
147   {
148     AlignmentPanel[] aps = getAssociatedPanels();
149
150     for (int a = 0; a < aps.length; a++)
151     {
152       SequenceGroup selected = aps[a].av.getSelectionGroup();
153
154       if (selected == null)
155       {
156         selected = new SequenceGroup();
157         aps[a].av.setSelectionGroup(selected);
158       }
159
160       selected.setEndRes(aps[a].av.getAlignment().getWidth() - 1);
161       selected.addOrRemove(sequence, true);
162     }
163   }
164
165   /**
166    * DOCUMENT ME!
167    * 
168    * @param tree
169    *          DOCUMENT ME!
170    */
171   public void setTree(TreeModel tree)
172   {
173     this.tree = tree;
174     tree.findHeight(tree.getTopNode());
175
176     // Now have to calculate longest name based on the leaves
177     Vector<SequenceNode> leaves = tree.findLeaves(tree.getTopNode());
178     boolean has_placeholders = false;
179     longestName = "";
180
181     for (int i = 0; i < leaves.size(); i++)
182     {
183       SequenceNode lf = leaves.elementAt(i);
184
185       if (lf.isPlaceholder())
186       {
187         has_placeholders = true;
188       }
189
190       if (longestName.length() < ((Sequence) lf.element()).getName()
191               .length())
192       {
193         longestName = TreeCanvas.PLACEHOLDER
194                 + ((Sequence) lf.element()).getName();
195       }
196     }
197
198     setMarkPlaceholders(has_placeholders);
199   }
200
201   /**
202    * DOCUMENT ME!
203    * 
204    * @param g
205    *          DOCUMENT ME!
206    * @param node
207    *          DOCUMENT ME!
208    * @param chunk
209    *          DOCUMENT ME!
210    * @param wscale
211    *          DOCUMENT ME!
212    * @param width
213    *          DOCUMENT ME!
214    * @param offx
215    *          DOCUMENT ME!
216    * @param offy
217    *          DOCUMENT ME!
218    */
219   public void drawNode(Graphics g, SequenceNode node, float chunk,
220           double wscale, int width, int offx, int offy)
221   {
222     if (node == null)
223     {
224       return;
225     }
226
227     if ((node.left() == null) && (node.right() == null))
228     {
229       // Drawing leaf node
230       double height = node.height;
231       double dist = node.dist;
232
233       int xstart = (int) ((height - dist) * wscale) + offx;
234       int xend = (int) (height * wscale) + offx;
235
236       int ypos = (int) (node.ycount * chunk) + offy;
237
238       if (node.element() instanceof SequenceI)
239       {
240         SequenceI seq = (SequenceI) node.element();
241
242         if (av.getSequenceColour(seq) == Color.white)
243         {
244           g.setColor(Color.black);
245         }
246         else
247         {
248           g.setColor(av.getSequenceColour(seq).darker());
249         }
250       }
251       else
252       {
253         g.setColor(Color.black);
254       }
255
256       // Draw horizontal line
257       g.drawLine(xstart, ypos, xend, ypos);
258
259       String nodeLabel = "";
260
261       if (showDistances && (node.dist > 0))
262       {
263         nodeLabel = new Format("%-.2f").form(node.dist);
264       }
265
266       if (showBootstrap && node.bootstrap > -1)
267       {
268         if (showDistances)
269         {
270           nodeLabel = nodeLabel + " : ";
271         }
272
273         nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
274       }
275
276       if (!nodeLabel.equals(""))
277       {
278         g.drawString(nodeLabel, xstart + 2, ypos - 2);
279       }
280
281       String name = (markPlaceholders && node.isPlaceholder())
282               ? (PLACEHOLDER + node.getName())
283               : node.getName();
284
285       int charWidth = fm.stringWidth(name) + 3;
286       int charHeight = font.getSize();
287
288       Rectangle rect = new Rectangle(xend + 10, ypos - charHeight / 2,
289               charWidth, charHeight);
290
291       nameHash.put(node.element(), rect);
292
293       // Colour selected leaves differently
294       SequenceGroup selected = av.getSelectionGroup();
295
296       if ((selected != null)
297               && selected.getSequences(null).contains(node.element()))
298       {
299         g.setColor(Color.gray);
300
301         g.fillRect(xend + 10, ypos - charHeight / 2, charWidth, charHeight);
302         g.setColor(Color.white);
303       }
304
305       g.drawString(name, xend + 10, ypos + fm.getDescent());
306       g.setColor(Color.black);
307     }
308     else
309     {
310       drawNode(g, (SequenceNode) node.left(), chunk, wscale, width, offx,
311               offy);
312       drawNode(g, (SequenceNode) node.right(), chunk, wscale, width, offx,
313               offy);
314
315       double height = node.height;
316       double dist = node.dist;
317
318       int xstart = (int) ((height - dist) * wscale) + offx;
319       int xend = (int) (height * wscale) + offx;
320       int ypos = (int) (node.ycount * chunk) + offy;
321
322       g.setColor(node.color.darker());
323
324       // Draw horizontal line
325       g.drawLine(xstart, ypos, xend, ypos);
326       if (node == highlightNode)
327       {
328         g.fillRect(xend - 3, ypos - 3, 6, 6);
329       }
330       else
331       {
332         g.fillRect(xend - 2, ypos - 2, 4, 4);
333       }
334
335       int ystart = (node.left() == null ? 0
336               : (int) (((SequenceNode) node.left()).ycount * chunk)) + offy;
337       int yend = (node.right() == null ? 0
338               : (int) (((SequenceNode) node.right()).ycount * chunk))
339               + offy;
340
341       Rectangle pos = new Rectangle(xend - 2, ypos - 2, 5, 5);
342       nodeHash.put(node, pos);
343
344       g.drawLine((int) (height * wscale) + offx, ystart,
345               (int) (height * wscale) + offx, yend);
346
347       String nodeLabel = "";
348
349       if (showDistances && (node.dist > 0))
350       {
351         nodeLabel = new Format("%-.2f").form(node.dist);
352       }
353
354       if (showBootstrap && node.bootstrap > -1)
355       {
356         if (showDistances)
357         {
358           nodeLabel = nodeLabel + " : ";
359         }
360
361         nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
362       }
363
364       if (!nodeLabel.equals(""))
365       {
366         g.drawString(nodeLabel, xstart + 2, ypos - 2);
367       }
368     }
369   }
370
371   /**
372    * DOCUMENT ME!
373    * 
374    * @param x
375    *          DOCUMENT ME!
376    * @param y
377    *          DOCUMENT ME!
378    * 
379    * @return DOCUMENT ME!
380    */
381   public Object findElement(int x, int y)
382   {
383     Enumeration keys = nameHash.keys();
384
385     while (keys.hasMoreElements())
386     {
387       Object ob = keys.nextElement();
388       Rectangle rect = (Rectangle) nameHash.get(ob);
389
390       if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
391               && (y <= (rect.y + rect.height)))
392       {
393         return ob;
394       }
395     }
396
397     keys = nodeHash.keys();
398
399     while (keys.hasMoreElements())
400     {
401       Object ob = keys.nextElement();
402       Rectangle rect = (Rectangle) nodeHash.get(ob);
403
404       if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
405               && (y <= (rect.y + rect.height)))
406       {
407         return ob;
408       }
409     }
410
411     return null;
412   }
413
414   /**
415    * DOCUMENT ME!
416    * 
417    * @param pickBox
418    *          DOCUMENT ME!
419    */
420   public void pickNodes(Rectangle pickBox)
421   {
422     int width = getWidth();
423     int height = getHeight();
424
425     SequenceNode top = tree.getTopNode();
426
427     double wscale = ((width * .8) - (offx * 2)) / tree.getMaxHeight();
428
429     if (top.count == 0)
430     {
431       top.count = ((SequenceNode) top.left()).count
432               + ((SequenceNode) top.right()).count;
433     }
434
435     float chunk = (float) (height - (offy)) / top.count;
436
437     pickNode(pickBox, top, chunk, wscale, width, offx, offy);
438   }
439
440   /**
441    * DOCUMENT ME!
442    * 
443    * @param pickBox
444    *          DOCUMENT ME!
445    * @param node
446    *          DOCUMENT ME!
447    * @param chunk
448    *          DOCUMENT ME!
449    * @param wscale
450    *          DOCUMENT ME!
451    * @param width
452    *          DOCUMENT ME!
453    * @param offx
454    *          DOCUMENT ME!
455    * @param offy
456    *          DOCUMENT ME!
457    */
458   public void pickNode(Rectangle pickBox, SequenceNode node, float chunk,
459           double wscale, int width, int offx, int offy)
460   {
461     if (node == null)
462     {
463       return;
464     }
465
466     if ((node.left() == null) && (node.right() == null))
467     {
468       double height = node.height;
469       double dist = node.dist;
470
471       int xstart = (int) ((height - dist) * wscale) + offx;
472       int xend = (int) (height * wscale) + offx;
473
474       int ypos = (int) (node.ycount * chunk) + offy;
475
476       if (pickBox.contains(new Point(xend, ypos)))
477       {
478         if (node.element() instanceof SequenceI)
479         {
480           SequenceI seq = (SequenceI) node.element();
481           SequenceGroup sg = av.getSelectionGroup();
482
483           if (sg != null)
484           {
485             sg.addOrRemove(seq, true);
486           }
487         }
488       }
489     }
490     else
491     {
492       pickNode(pickBox, (SequenceNode) node.left(), chunk, wscale, width,
493               offx, offy);
494       pickNode(pickBox, (SequenceNode) node.right(), chunk, wscale, width,
495               offx, offy);
496     }
497   }
498
499   /**
500    * DOCUMENT ME!
501    * 
502    * @param node
503    *          DOCUMENT ME!
504    * @param c
505    *          DOCUMENT ME!
506    */
507   public void setColor(SequenceNode node, Color c)
508   {
509     if (node == null)
510     {
511       return;
512     }
513
514     node.color = c;
515
516     if ((node.left() != null) || (node.right() != null)) // TODO: internal node
517     {
518       setColor((SequenceNode) node.left(), c);
519       setColor((SequenceNode) node.right(), c);
520     }
521   }
522
523   /**
524    * DOCUMENT ME!
525    */
526   void startPrinting()
527   {
528     Thread thread = new Thread(this);
529     thread.start();
530   }
531
532   // put printing in a thread to avoid painting problems
533   @Override
534   public void run()
535   {
536     PrinterJob printJob = PrinterJob.getPrinterJob();
537     PageFormat defaultPage = printJob.defaultPage();
538     PageFormat pf = printJob.pageDialog(defaultPage);
539
540     if (defaultPage == pf)
541     {
542       /*
543        * user cancelled
544        */
545       return;
546     }
547
548     printJob.setPrintable(this, pf);
549
550     if (printJob.printDialog())
551     {
552       try
553       {
554         printJob.print();
555       } catch (Exception PrintException)
556       {
557         PrintException.printStackTrace();
558       }
559     }
560   }
561
562   /**
563    * DOCUMENT ME!
564    * 
565    * @param pg
566    *          DOCUMENT ME!
567    * @param pf
568    *          DOCUMENT ME!
569    * @param pi
570    *          DOCUMENT ME!
571    * 
572    * @return DOCUMENT ME!
573    * 
574    * @throws PrinterException
575    *           DOCUMENT ME!
576    */
577   @Override
578   public int print(Graphics pg, PageFormat pf, int pi)
579           throws PrinterException
580   {
581     pg.setFont(font);
582     pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
583
584     int pwidth = (int) pf.getImageableWidth();
585     int pheight = (int) pf.getImageableHeight();
586
587     int noPages = getHeight() / pheight;
588
589     if (pi > noPages)
590     {
591       return Printable.NO_SUCH_PAGE;
592     }
593
594     if (pwidth > getWidth())
595     {
596       pwidth = getWidth();
597     }
598
599     if (fitToWindow)
600     {
601       if (pheight > getHeight())
602       {
603         pheight = getHeight();
604       }
605
606       noPages = 0;
607     }
608     else
609     {
610       FontMetrics fm = pg.getFontMetrics(font);
611       int height = fm.getHeight() * nameHash.size();
612       pg.translate(0, -pi * pheight);
613       pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
614
615       // translate number of pages,
616       // height is screen size as this is the
617       // non overlapping text size
618       pheight = height;
619     }
620
621     draw(pg, pwidth, pheight);
622
623     return Printable.PAGE_EXISTS;
624   }
625
626   /**
627    * DOCUMENT ME!
628    * 
629    * @param g
630    *          DOCUMENT ME!
631    */
632   @Override
633   public void paintComponent(Graphics g)
634   {
635     super.paintComponent(g);
636     g.setFont(font);
637
638     if (tree == null)
639     {
640       g.drawString(
641               MessageManager.getString("label.calculating_tree") + "....",
642               20, getHeight() / 2);
643     }
644     else
645     {
646       fm = g.getFontMetrics(font);
647
648       if (nameHash.size() == 0)
649       {
650         repaint();
651       }
652
653       if (fitToWindow || (!fitToWindow && (scrollPane
654               .getHeight() > ((fm.getHeight() * nameHash.size()) + offy))))
655       {
656         draw(g, scrollPane.getWidth(), scrollPane.getHeight());
657         setPreferredSize(null);
658       }
659       else
660       {
661         setPreferredSize(new Dimension(scrollPane.getWidth(),
662                 fm.getHeight() * nameHash.size()));
663         draw(g, scrollPane.getWidth(), fm.getHeight() * nameHash.size());
664       }
665
666       scrollPane.revalidate();
667     }
668   }
669
670   /**
671    * DOCUMENT ME!
672    * 
673    * @param fontSize
674    *          DOCUMENT ME!
675    */
676   @Override
677   public void setFont(Font font)
678   {
679     this.font = font;
680     repaint();
681   }
682
683   /**
684    * DOCUMENT ME!
685    * 
686    * @param g1
687    *          DOCUMENT ME!
688    * @param width
689    *          DOCUMENT ME!
690    * @param height
691    *          DOCUMENT ME!
692    */
693   public void draw(Graphics g1, int width, int height)
694   {
695     Graphics2D g2 = (Graphics2D) g1;
696     g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
697             RenderingHints.VALUE_ANTIALIAS_ON);
698     g2.setColor(Color.white);
699     g2.fillRect(0, 0, width, height);
700     g2.setFont(font);
701
702     if (longestName == null || tree == null)
703     {
704       g2.drawString("Calculating tree.", 20, 20);
705     }
706     offy = font.getSize() + 10;
707
708     fm = g2.getFontMetrics(font);
709
710     labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
711
712     double wscale = (width - labelLength - (offx * 2))
713             / tree.getMaxHeight();
714
715     SequenceNode top = tree.getTopNode();
716
717     if (top.count == 0)
718     {
719       top.count = ((SequenceNode) top.left()).count
720               + ((SequenceNode) top.right()).count;
721     }
722
723     float chunk = (float) (height - (offy)) / top.count;
724
725     drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
726
727     if (threshold != 0)
728     {
729       if (av.getCurrentTree() == tree)
730       {
731         g2.setColor(Color.red);
732       }
733       else
734       {
735         g2.setColor(Color.gray);
736       }
737
738       int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx)))
739               + offx);
740
741       g2.drawLine(x, 0, x, getHeight());
742     }
743   }
744
745   /**
746    * Empty method to satisfy the MouseListener interface
747    * 
748    * @param e
749    */
750   @Override
751   public void mouseReleased(MouseEvent e)
752   {
753     /*
754      * isPopupTrigger is set on mouseReleased on Windows
755      */
756     if (e.isPopupTrigger())
757     {
758       chooseSubtreeColour();
759       e.consume(); // prevent mouseClicked happening
760     }
761   }
762
763   /**
764    * Empty method to satisfy the MouseListener interface
765    * 
766    * @param e
767    */
768   @Override
769   public void mouseEntered(MouseEvent e)
770   {
771   }
772
773   /**
774    * Empty method to satisfy the MouseListener interface
775    * 
776    * @param e
777    */
778   @Override
779   public void mouseExited(MouseEvent e)
780   {
781   }
782
783   /**
784    * Handles a mouse click on a tree node (clicks elsewhere are handled in
785    * mousePressed). Click selects the sub-tree, double-click swaps leaf nodes
786    * order, right-click opens a dialogue to choose colour for the sub-tree.
787    * 
788    * @param e
789    */
790   @Override
791   public void mouseClicked(MouseEvent evt)
792   {
793     if (highlightNode == null)
794     {
795       return;
796     }
797
798     if (evt.getClickCount() > 1)
799     {
800       tree.swapNodes(highlightNode);
801       tree.reCount(tree.getTopNode());
802       tree.findHeight(tree.getTopNode());
803     }
804     else
805     {
806       Vector<SequenceNode> leaves = tree.findLeaves(highlightNode);
807
808       for (int i = 0; i < leaves.size(); i++)
809       {
810         SequenceI seq = (SequenceI) leaves.elementAt(i).element();
811         treeSelectionChanged(seq);
812       }
813       av.sendSelection();
814     }
815
816     PaintRefresher.Refresh(tp, av.getSequenceSetId());
817     repaint();
818   }
819
820   /**
821    * Offer the user the option to choose a colour for the highlighted node and
822    * its children; this colour is also applied to the corresponding sequence ids
823    * in the alignment
824    */
825   void chooseSubtreeColour()
826   {
827     Color col = JColorChooser.showDialog(this,
828             MessageManager.getString("label.select_subtree_colour"),
829             highlightNode.color);
830     if (col != null)
831     {
832       setColor(highlightNode, col);
833       PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
834       repaint();
835     }
836   }
837
838   @Override
839   public void mouseMoved(MouseEvent evt)
840   {
841     av.setCurrentTree(tree);
842
843     Object ob = findElement(evt.getX(), evt.getY());
844
845     if (ob instanceof SequenceNode)
846     {
847       highlightNode = (SequenceNode) ob;
848       this.setToolTipText(
849               "<html>" + MessageManager.getString("label.highlightnode"));
850       repaint();
851
852     }
853     else
854     {
855       if (highlightNode != null)
856       {
857         highlightNode = null;
858         setToolTipText(null);
859         repaint();
860       }
861     }
862   }
863
864   @Override
865   public void mouseDragged(MouseEvent ect)
866   {
867   }
868
869   /**
870    * Handles a mouse press on a sequence name or the tree background canvas
871    * (click on a node is handled in mouseClicked). The action is to create
872    * groups by partitioning the tree at the mouse position. Colours for the
873    * groups (and sequence names) are generated randomly.
874    * 
875    * @param e
876    */
877   @Override
878   public void mousePressed(MouseEvent e)
879   {
880     av.setCurrentTree(tree);
881
882     /*
883      * isPopupTrigger is set for mousePressed (Mac)
884      * or mouseReleased (Windows)
885      */
886     if (e.isPopupTrigger())
887     {
888       if (highlightNode != null)
889       {
890         chooseSubtreeColour();
891       }
892       return;
893     }
894
895     /*
896      * defer right-click handling on Windows to
897      * mouseClicked; note isRightMouseButton
898      * also matches Cmd-click on Mac which should do
899      * nothing here
900      */
901     if (SwingUtilities.isRightMouseButton(e))
902     {
903       return;
904     }
905
906     int x = e.getX();
907     int y = e.getY();
908
909     Object ob = findElement(x, y);
910
911     if (ob instanceof SequenceI)
912     {
913       treeSelectionChanged((Sequence) ob);
914       PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
915       repaint();
916       av.sendSelection();
917       return;
918     }
919     else if (!(ob instanceof SequenceNode))
920     {
921       // Find threshold
922       if (tree.getMaxHeight() != 0)
923       {
924         threshold = (float) (x - offx)
925                 / (float) (getWidth() - labelLength - (2 * offx));
926
927         List<SequenceNode> groups = tree.groupNodes(threshold);
928         setColor(tree.getTopNode(), Color.black);
929
930         AlignmentPanel[] aps = getAssociatedPanels();
931
932         // TODO push calls below into a single AlignViewportI method?
933         // see also AlignViewController.deleteGroups
934         for (int a = 0; a < aps.length; a++)
935         {
936           aps[a].av.setSelectionGroup(null);
937           aps[a].av.getAlignment().deleteAllGroups();
938           aps[a].av.clearSequenceColours();
939           if (aps[a].av.getCodingComplement() != null)
940           {
941             aps[a].av.getCodingComplement().setSelectionGroup(null);
942             aps[a].av.getCodingComplement().getAlignment()
943                     .deleteAllGroups();
944             aps[a].av.getCodingComplement().clearSequenceColours();
945           }
946         }
947         colourGroups(groups);
948
949         /*
950          * clear partition (don't show vertical line) if
951          * it is to the right of all nodes
952          */
953         if (groups.isEmpty())
954         {
955           threshold = 0f;
956         }
957       }
958
959       PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
960       repaint();
961     }
962
963   }
964
965   void colourGroups(List<SequenceNode> groups)
966   {
967     AlignmentPanel[] aps = getAssociatedPanels();
968     for (int i = 0; i < groups.size(); i++)
969     {
970       Color col = new Color((int) (Math.random() * 255),
971               (int) (Math.random() * 255), (int) (Math.random() * 255));
972       setColor(groups.get(i), col.brighter());
973
974       Vector<SequenceNode> l = tree.findLeaves(groups.get(i));
975
976       Vector<SequenceI> sequences = new Vector<>();
977
978       for (int j = 0; j < l.size(); j++)
979       {
980         SequenceI s1 = (SequenceI) l.elementAt(j).element();
981
982         if (!sequences.contains(s1))
983         {
984           sequences.addElement(s1);
985         }
986       }
987
988       ColourSchemeI cs = null;
989       SequenceGroup sg = new SequenceGroup(sequences, null, cs, true, true,
990               false, 0, av.getAlignment().getWidth() - 1);
991
992       if (av.getGlobalColourScheme() != null)
993       {
994         if (av.getGlobalColourScheme() instanceof UserColourScheme)
995         {
996           cs = new UserColourScheme(
997                   ((UserColourScheme) av.getGlobalColourScheme())
998                           .getColours());
999
1000         }
1001         else
1002         {
1003           cs = ColourSchemeProperty.getColourScheme(av, sg,
1004                   ColourSchemeProperty
1005                   .getColourName(av.getGlobalColourScheme()));
1006         }
1007         // cs is null if shading is an annotationColourGradient
1008         // if (cs != null)
1009         // {
1010         // cs.setThreshold(av.getViewportColourScheme().getThreshold(),
1011         // av.isIgnoreGapsConsensus());
1012         // }
1013       }
1014       sg.setColourScheme(cs);
1015       sg.getGroupColourScheme().setThreshold(
1016               av.getResidueShading().getThreshold(),
1017               av.isIgnoreGapsConsensus());
1018       // sg.recalcConservation();
1019       sg.setName("JTreeGroup:" + sg.hashCode());
1020       sg.setIdColour(col);
1021
1022       for (int a = 0; a < aps.length; a++)
1023       {
1024         if (aps[a].av.getGlobalColourScheme() != null
1025                 && aps[a].av.getResidueShading().conservationApplied())
1026         {
1027           Conservation c = new Conservation("Group", sg.getSequences(null),
1028                   sg.getStartRes(), sg.getEndRes());
1029           c.calculate();
1030           c.verdict(false, aps[a].av.getConsPercGaps());
1031           sg.cs.setConservation(c);
1032         }
1033         // indicate that associated structure views will need an update
1034         aps[a].av.setUpdateStructures(true);
1035         // propagate structure view update and sequence group to complement view
1036         aps[a].av.addSequenceGroup(new SequenceGroup(sg));
1037       }
1038     }
1039
1040     // notify the panel(s) to redo any group specific stuff
1041     // also updates structure views if necessary
1042     for (int a = 0; a < aps.length; a++)
1043     {
1044       aps[a].updateAnnotation();
1045       final AlignViewportI codingComplement = aps[a].av
1046               .getCodingComplement();
1047       if (codingComplement != null)
1048       {
1049         ((AlignViewport) codingComplement).getAlignPanel()
1050                 .updateAnnotation();
1051       }
1052     }
1053   }
1054
1055   /**
1056    * DOCUMENT ME!
1057    * 
1058    * @param state
1059    *          DOCUMENT ME!
1060    */
1061   public void setShowDistances(boolean state)
1062   {
1063     this.showDistances = state;
1064     repaint();
1065   }
1066
1067   /**
1068    * DOCUMENT ME!
1069    * 
1070    * @param state
1071    *          DOCUMENT ME!
1072    */
1073   public void setShowBootstrap(boolean state)
1074   {
1075     this.showBootstrap = state;
1076     repaint();
1077   }
1078
1079   /**
1080    * DOCUMENT ME!
1081    * 
1082    * @param state
1083    *          DOCUMENT ME!
1084    */
1085   public void setMarkPlaceholders(boolean state)
1086   {
1087     this.markPlaceholders = state;
1088     repaint();
1089   }
1090
1091   AlignmentPanel[] getAssociatedPanels()
1092   {
1093     if (applyToAllViews)
1094     {
1095       return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1096     }
1097     else
1098     {
1099       return new AlignmentPanel[] { ap };
1100     }
1101   }
1102 }