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