Merge branch 'bug/JAL-1923_290b2_group_annots' into Release_2_9_0b1_Branch
[jalview.git] / src / jalview / gui / TreeCanvas.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.9.0b1)
3  * Copyright (C) 2015 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.NJTree;
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.ResidueProperties;
33 import jalview.schemes.UserColourScheme;
34 import jalview.structure.SelectionSource;
35 import jalview.util.Format;
36 import jalview.util.MappingUtils;
37 import jalview.util.MessageManager;
38
39 import java.awt.Color;
40 import java.awt.Dimension;
41 import java.awt.Font;
42 import java.awt.FontMetrics;
43 import java.awt.Graphics;
44 import java.awt.Graphics2D;
45 import java.awt.Point;
46 import java.awt.Rectangle;
47 import java.awt.RenderingHints;
48 import java.awt.event.MouseEvent;
49 import java.awt.event.MouseListener;
50 import java.awt.event.MouseMotionListener;
51 import java.awt.print.PageFormat;
52 import java.awt.print.Printable;
53 import java.awt.print.PrinterException;
54 import java.awt.print.PrinterJob;
55 import java.util.Enumeration;
56 import java.util.Hashtable;
57 import java.util.Vector;
58
59 import javax.swing.JColorChooser;
60 import javax.swing.JPanel;
61 import javax.swing.JScrollPane;
62 import javax.swing.SwingUtilities;
63 import javax.swing.ToolTipManager;
64
65 /**
66  * DOCUMENT ME!
67  * 
68  * @author $author$
69  * @version $Revision$
70  */
71 public class TreeCanvas extends JPanel implements MouseListener, Runnable,
72         Printable, MouseMotionListener, SelectionSource
73 {
74   /** DOCUMENT ME!! */
75   public static final String PLACEHOLDER = " * ";
76
77   NJTree tree;
78
79   JScrollPane scrollPane;
80
81   TreePanel tp;
82
83   AlignViewport av;
84
85   AlignmentPanel ap;
86
87   Font font;
88
89   FontMetrics fm;
90
91   boolean fitToWindow = true;
92
93   boolean showDistances = false;
94
95   boolean showBootstrap = false;
96
97   boolean markPlaceholders = false;
98
99   int offx = 20;
100
101   int offy;
102
103   float threshold;
104
105   String longestName;
106
107   int labelLength = -1;
108
109   Hashtable nameHash = new Hashtable();
110
111   Hashtable nodeHash = new Hashtable();
112
113   SequenceNode highlightNode;
114
115   boolean applyToAllViews = false;
116
117   /**
118    * Creates a new TreeCanvas object.
119    * 
120    * @param av
121    *          DOCUMENT ME!
122    * @param tree
123    *          DOCUMENT ME!
124    * @param scroller
125    *          DOCUMENT ME!
126    * @param label
127    *          DOCUMENT ME!
128    */
129   public TreeCanvas(TreePanel tp, AlignmentPanel ap, JScrollPane scroller)
130   {
131     this.tp = tp;
132     this.av = ap.av;
133     this.ap = ap;
134     font = av.getFont();
135     scrollPane = scroller;
136     addMouseListener(this);
137     addMouseMotionListener(this);
138     ToolTipManager.sharedInstance().registerComponent(this);
139   }
140
141   /**
142    * DOCUMENT ME!
143    * 
144    * @param sequence
145    *          DOCUMENT ME!
146    */
147   public void treeSelectionChanged(SequenceI sequence)
148   {
149     AlignmentPanel[] aps = getAssociatedPanels();
150
151     for (int a = 0; a < aps.length; a++)
152     {
153       SequenceGroup selected = aps[a].av.getSelectionGroup();
154
155       if (selected == null)
156       {
157         selected = new SequenceGroup();
158         aps[a].av.setSelectionGroup(selected);
159       }
160
161       selected.setEndRes(aps[a].av.getAlignment().getWidth() - 1);
162       selected.addOrRemove(sequence, true);
163     }
164   }
165
166   /**
167    * DOCUMENT ME!
168    * 
169    * @param tree
170    *          DOCUMENT ME!
171    */
172   public void setTree(NJTree tree)
173   {
174     this.tree = tree;
175     tree.findHeight(tree.getTopNode());
176
177     // Now have to calculate longest name based on the leaves
178     Vector leaves = tree.findLeaves(tree.getTopNode(), new Vector());
179     boolean has_placeholders = false;
180     longestName = "";
181
182     for (int i = 0; i < leaves.size(); i++)
183     {
184       SequenceNode lf = (SequenceNode) leaves.elementAt(i);
185
186       if (lf.isPlaceholder())
187       {
188         has_placeholders = true;
189       }
190
191       if (longestName.length() < ((Sequence) lf.element()).getName()
192               .length())
193       {
194         longestName = TreeCanvas.PLACEHOLDER
195                 + ((Sequence) lf.element()).getName();
196       }
197     }
198
199     setMarkPlaceholders(has_placeholders);
200   }
201
202   /**
203    * DOCUMENT ME!
204    * 
205    * @param g
206    *          DOCUMENT ME!
207    * @param node
208    *          DOCUMENT ME!
209    * @param chunk
210    *          DOCUMENT ME!
211    * @param scale
212    *          DOCUMENT ME!
213    * @param width
214    *          DOCUMENT ME!
215    * @param offx
216    *          DOCUMENT ME!
217    * @param offy
218    *          DOCUMENT ME!
219    */
220   public void drawNode(Graphics g, SequenceNode node, float chunk,
221           float scale, int width, int offx, int offy)
222   {
223     if (node == null)
224     {
225       return;
226     }
227
228     if ((node.left() == null) && (node.right() == null))
229     {
230       // Drawing leaf node
231       float height = node.height;
232       float dist = node.dist;
233
234       int xstart = (int) ((height - dist) * scale) + offx;
235       int xend = (int) (height * scale) + offx;
236
237       int ypos = (int) (node.ycount * chunk) + offy;
238
239       if (node.element() instanceof SequenceI)
240       {
241         SequenceI seq = (SequenceI) node.element();
242
243         if (av.getSequenceColour(seq) == Color.white)
244         {
245           g.setColor(Color.black);
246         }
247         else
248         {
249           g.setColor(av.getSequenceColour(seq).darker());
250         }
251       }
252       else
253       {
254         g.setColor(Color.black);
255       }
256
257       // Draw horizontal line
258       g.drawLine(xstart, ypos, xend, ypos);
259
260       String nodeLabel = "";
261
262       if (showDistances && (node.dist > 0))
263       {
264         nodeLabel = new Format("%-.2f").form(node.dist);
265       }
266
267       if (showBootstrap && node.bootstrap > -1)
268       {
269         if (showDistances)
270         {
271           nodeLabel = nodeLabel + " : ";
272         }
273
274         nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
275       }
276
277       if (!nodeLabel.equals(""))
278       {
279         g.drawString(nodeLabel, xstart + 2, ypos - 2);
280       }
281
282       String name = (markPlaceholders && node.isPlaceholder()) ? (PLACEHOLDER + node
283               .getName()) : 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, scale, width, offx,
311               offy);
312       drawNode(g, (SequenceNode) node.right(), chunk, scale, width, offx,
313               offy);
314
315       float height = node.height;
316       float dist = node.dist;
317
318       int xstart = (int) ((height - dist) * scale) + offx;
319       int xend = (int) (height * scale) + 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 = (int) (((SequenceNode) node.left()).ycount * chunk)
336               + offy;
337       int yend = (int) (((SequenceNode) node.right()).ycount * chunk)
338               + offy;
339
340       Rectangle pos = new Rectangle(xend - 2, ypos - 2, 5, 5);
341       nodeHash.put(node, pos);
342
343       g.drawLine((int) (height * scale) + offx, ystart,
344               (int) (height * scale) + offx, yend);
345
346       String nodeLabel = "";
347
348       if (showDistances && (node.dist > 0))
349       {
350         nodeLabel = new Format("%-.2f").form(node.dist);
351       }
352
353       if (showBootstrap && node.bootstrap > -1)
354       {
355         if (showDistances)
356         {
357           nodeLabel = nodeLabel + " : ";
358         }
359
360         nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
361       }
362
363       if (!nodeLabel.equals(""))
364       {
365         g.drawString(nodeLabel, xstart + 2, ypos - 2);
366       }
367     }
368   }
369
370   /**
371    * DOCUMENT ME!
372    * 
373    * @param x
374    *          DOCUMENT ME!
375    * @param y
376    *          DOCUMENT ME!
377    * 
378    * @return DOCUMENT ME!
379    */
380   public Object findElement(int x, int y)
381   {
382     Enumeration keys = nameHash.keys();
383
384     while (keys.hasMoreElements())
385     {
386       Object ob = keys.nextElement();
387       Rectangle rect = (Rectangle) nameHash.get(ob);
388
389       if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
390               && (y <= (rect.y + rect.height)))
391       {
392         return ob;
393       }
394     }
395
396     keys = nodeHash.keys();
397
398     while (keys.hasMoreElements())
399     {
400       Object ob = keys.nextElement();
401       Rectangle rect = (Rectangle) nodeHash.get(ob);
402
403       if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
404               && (y <= (rect.y + rect.height)))
405       {
406         return ob;
407       }
408     }
409
410     return null;
411   }
412
413   /**
414    * DOCUMENT ME!
415    * 
416    * @param pickBox
417    *          DOCUMENT ME!
418    */
419   public void pickNodes(Rectangle pickBox)
420   {
421     int width = getWidth();
422     int height = getHeight();
423
424     SequenceNode top = tree.getTopNode();
425
426     float wscale = (float) ((width * .8) - (offx * 2))
427             / 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 scale
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           float scale, 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       float height = node.height;
469       float dist = node.dist;
470
471       int xstart = (int) ((height - dist) * scale) + offx;
472       int xend = (int) (height * scale) + 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, scale, width,
493               offx, offy);
494       pickNode(pickBox, (SequenceNode) node.right(), chunk, scale, 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     if ((node.left() == null) && (node.right() == null)) // TODO: internal node
515     {
516       node.color = c;
517
518       if (node.element() instanceof SequenceI)
519       {
520         AlignmentPanel[] aps = getAssociatedPanels();
521         if (aps != null)
522         {
523           for (int a = 0; a < aps.length; a++)
524           {
525             final SequenceI seq = (SequenceI) node.element();
526             aps[a].av.setSequenceColour(seq, c);
527           }
528         }
529       }
530     }
531     else
532     {
533       node.color = c;
534       setColor((SequenceNode) node.left(), c);
535       setColor((SequenceNode) node.right(), c);
536     }
537   }
538
539   /**
540    * DOCUMENT ME!
541    */
542   void startPrinting()
543   {
544     Thread thread = new Thread(this);
545     thread.start();
546   }
547
548   // put printing in a thread to avoid painting problems
549   @Override
550   public void run()
551   {
552     PrinterJob printJob = PrinterJob.getPrinterJob();
553     PageFormat pf = printJob.pageDialog(printJob.defaultPage());
554
555     printJob.setPrintable(this, pf);
556
557     if (printJob.printDialog())
558     {
559       try
560       {
561         printJob.print();
562       } catch (Exception PrintException)
563       {
564         PrintException.printStackTrace();
565       }
566     }
567   }
568
569   /**
570    * DOCUMENT ME!
571    * 
572    * @param pg
573    *          DOCUMENT ME!
574    * @param pf
575    *          DOCUMENT ME!
576    * @param pi
577    *          DOCUMENT ME!
578    * 
579    * @return DOCUMENT ME!
580    * 
581    * @throws PrinterException
582    *           DOCUMENT ME!
583    */
584   @Override
585   public int print(Graphics pg, PageFormat pf, int pi)
586           throws PrinterException
587   {
588     pg.setFont(font);
589     pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
590
591     int pwidth = (int) pf.getImageableWidth();
592     int pheight = (int) pf.getImageableHeight();
593
594     int noPages = getHeight() / pheight;
595
596     if (pi > noPages)
597     {
598       return Printable.NO_SUCH_PAGE;
599     }
600
601     if (pwidth > getWidth())
602     {
603       pwidth = getWidth();
604     }
605
606     if (fitToWindow)
607     {
608       if (pheight > getHeight())
609       {
610         pheight = getHeight();
611       }
612
613       noPages = 0;
614     }
615     else
616     {
617       FontMetrics fm = pg.getFontMetrics(font);
618       int height = fm.getHeight() * nameHash.size();
619       pg.translate(0, -pi * pheight);
620       pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
621
622       // translate number of pages,
623       // height is screen size as this is the
624       // non overlapping text size
625       pheight = height;
626     }
627
628     draw(pg, pwidth, pheight);
629
630     return Printable.PAGE_EXISTS;
631   }
632
633   /**
634    * DOCUMENT ME!
635    * 
636    * @param g
637    *          DOCUMENT ME!
638    */
639   @Override
640   public void paintComponent(Graphics g)
641   {
642     super.paintComponent(g);
643     g.setFont(font);
644
645     if (tree == null)
646     {
647       g.drawString(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
660               || (!fitToWindow && (scrollPane.getHeight() > ((fm
661                       .getHeight() * nameHash.size()) + offy))))
662       {
663         draw(g, scrollPane.getWidth(), scrollPane.getHeight());
664         setPreferredSize(null);
665       }
666       else
667       {
668         setPreferredSize(new Dimension(scrollPane.getWidth(),
669                 fm.getHeight() * nameHash.size()));
670         draw(g, scrollPane.getWidth(), fm.getHeight() * nameHash.size());
671       }
672
673       scrollPane.revalidate();
674     }
675   }
676
677   /**
678    * DOCUMENT ME!
679    * 
680    * @param fontSize
681    *          DOCUMENT ME!
682    */
683   @Override
684   public void setFont(Font font)
685   {
686     this.font = font;
687     repaint();
688   }
689
690   /**
691    * DOCUMENT ME!
692    * 
693    * @param g1
694    *          DOCUMENT ME!
695    * @param width
696    *          DOCUMENT ME!
697    * @param height
698    *          DOCUMENT ME!
699    */
700   public void draw(Graphics g1, int width, int height)
701   {
702     Graphics2D g2 = (Graphics2D) g1;
703     g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
704             RenderingHints.VALUE_ANTIALIAS_ON);
705     g2.setColor(Color.white);
706     g2.fillRect(0, 0, width, height);
707     g2.setFont(font);
708
709     if (longestName == null || tree == null)
710     {
711       g2.drawString("Calculating tree.", 20, 20);
712     }
713     offy = font.getSize() + 10;
714
715     fm = g2.getFontMetrics(font);
716
717     labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
718
719     float wscale = (width - labelLength - (offx * 2)) / 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))) + offx);
745
746       g2.drawLine(x, 0, x, getHeight());
747     }
748   }
749
750   /**
751    * DOCUMENT ME!
752    * 
753    * @param e
754    *          DOCUMENT ME!
755    */
756   @Override
757   public void mouseReleased(MouseEvent e)
758   {
759   }
760
761   /**
762    * DOCUMENT ME!
763    * 
764    * @param e
765    *          DOCUMENT ME!
766    */
767   @Override
768   public void mouseEntered(MouseEvent e)
769   {
770   }
771
772   /**
773    * DOCUMENT ME!
774    * 
775    * @param e
776    *          DOCUMENT ME!
777    */
778   @Override
779   public void mouseExited(MouseEvent e)
780   {
781   }
782
783   /**
784    * DOCUMENT ME!
785    * 
786    * @param e
787    *          DOCUMENT ME!
788    */
789   @Override
790   public void mouseClicked(MouseEvent evt)
791   {
792     if (highlightNode != null)
793     {
794       if (SwingUtilities.isRightMouseButton(evt))
795       {
796         Color col = JColorChooser.showDialog(this,
797                 MessageManager.getString("label.select_subtree_colour"),
798                 highlightNode.color);
799         if (col != null)
800         {
801           setColor(highlightNode, col);
802         }
803       }
804       else 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 leaves = new Vector();
813         tree.findLeaves(highlightNode, leaves);
814
815         for (int i = 0; i < leaves.size(); i++)
816         {
817           SequenceI seq = (SequenceI) ((SequenceNode) leaves.elementAt(i))
818                   .element();
819           treeSelectionChanged(seq);
820         }
821         av.sendSelection();
822       }
823
824       PaintRefresher.Refresh(tp, av.getSequenceSetId());
825       repaint();
826     }
827   }
828
829   @Override
830   public void mouseMoved(MouseEvent evt)
831   {
832     av.setCurrentTree(tree);
833
834     Object ob = findElement(evt.getX(), evt.getY());
835
836     if (ob instanceof SequenceNode)
837     {
838       highlightNode = (SequenceNode) ob;
839       this.setToolTipText("<html>"
840               + MessageManager.getString("label.highlightnode"));
841       repaint();
842
843     }
844     else
845     {
846       if (highlightNode != null)
847       {
848         highlightNode = null;
849         setToolTipText(null);
850         repaint();
851       }
852     }
853   }
854
855   @Override
856   public void mouseDragged(MouseEvent ect)
857   {
858   }
859
860   /**
861    * DOCUMENT ME!
862    * 
863    * @param e
864    *          DOCUMENT ME!
865    */
866   @Override
867   public void mousePressed(MouseEvent e)
868   {
869     av.setCurrentTree(tree);
870
871     int x = e.getX();
872     int y = e.getY();
873
874     Object ob = findElement(x, y);
875
876     if (ob instanceof SequenceI)
877     {
878       treeSelectionChanged((Sequence) ob);
879       PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
880       repaint();
881       av.sendSelection();
882       return;
883     }
884     else if (!(ob instanceof SequenceNode))
885     {
886       // Find threshold
887       if (tree.getMaxHeight() != 0)
888       {
889         threshold = (float) (x - offx)
890                 / (float) (getWidth() - labelLength - (2 * offx));
891
892         tree.getGroups().removeAllElements();
893         tree.groupNodes(tree.getTopNode(), threshold);
894         setColor(tree.getTopNode(), Color.black);
895
896         AlignmentPanel[] aps = getAssociatedPanels();
897
898         // TODO push calls below into a single AlignViewportI method?
899         // see also AlignViewController.deleteGroups
900         for (int a = 0; a < aps.length; a++)
901         {
902           aps[a].av.setSelectionGroup(null);
903           aps[a].av.getAlignment().deleteAllGroups();
904           aps[a].av.clearSequenceColours();
905           if (aps[a].av.getCodingComplement() != null)
906           {
907             aps[a].av.getCodingComplement().setSelectionGroup(null);
908             aps[a].av.getCodingComplement().getAlignment()
909                     .deleteAllGroups();
910             aps[a].av.getCodingComplement().clearSequenceColours();
911           }
912         }
913         colourGroups();
914       }
915
916       PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
917       repaint();
918     }
919
920   }
921
922   void colourGroups()
923   {
924     AlignmentPanel[] aps = getAssociatedPanels();
925     for (int i = 0; i < tree.getGroups().size(); i++)
926     {
927       Color col = new Color((int) (Math.random() * 255),
928               (int) (Math.random() * 255), (int) (Math.random() * 255));
929       setColor((SequenceNode) tree.getGroups().elementAt(i), col.brighter());
930
931       Vector l = tree.findLeaves(
932               (SequenceNode) tree.getGroups().elementAt(i), new Vector());
933
934       Vector sequences = new Vector();
935
936       for (int j = 0; j < l.size(); j++)
937       {
938         SequenceI s1 = (SequenceI) ((SequenceNode) l.elementAt(j))
939                 .element();
940
941         if (!sequences.contains(s1))
942         {
943           sequences.addElement(s1);
944         }
945       }
946
947       ColourSchemeI cs = null;
948       SequenceGroup sg = new SequenceGroup(sequences, null, cs, true, true,
949               false, 0, av.getAlignment().getWidth() - 1);
950
951       if (av.getGlobalColourScheme() != null)
952       {
953         if (av.getGlobalColourScheme() instanceof UserColourScheme)
954         {
955           cs = new UserColourScheme(
956                   ((UserColourScheme) av.getGlobalColourScheme())
957                           .getColours());
958
959         }
960         else
961         {
962           cs = ColourSchemeProperty.getColour(sg, ColourSchemeProperty
963                   .getColourName(av.getGlobalColourScheme()));
964         }
965         // cs is null if shading is an annotationColourGradient
966         if (cs != null)
967         {
968           cs.setThreshold(av.getGlobalColourScheme().getThreshold(),
969                   av.isIgnoreGapsConsensus());
970         }
971       }
972       sg.cs = cs;
973       // sg.recalcConservation();
974       sg.setName("JTreeGroup:" + sg.hashCode());
975       sg.setIdColour(col);
976
977       for (int a = 0; a < aps.length; a++)
978       {
979         if (aps[a].av.getGlobalColourScheme() != null
980                 && aps[a].av.getGlobalColourScheme().conservationApplied())
981         {
982           Conservation c = new Conservation("Group",
983                   ResidueProperties.propHash, 3, sg.getSequences(null),
984                   sg.getStartRes(), sg.getEndRes());
985
986           c.calculate();
987           c.verdict(false, aps[a].av.getConsPercGaps());
988           sg.cs.setConservation(c);
989         }
990
991         aps[a].av.getAlignment().addGroup(new SequenceGroup(sg));
992         // TODO can we push all of the below into AlignViewportI?
993         final AlignViewportI codingComplement = aps[a].av
994                 .getCodingComplement();
995         if (codingComplement != null)
996         {
997           if (codingComplement != null)
998           {
999             SequenceGroup mappedGroup = MappingUtils.mapSequenceGroup(sg,
1000                     av, codingComplement);
1001             if (mappedGroup.getSequences().size() > 0)
1002             {
1003               codingComplement.getAlignment().addGroup(mappedGroup);
1004               for (SequenceI seq : mappedGroup.getSequences())
1005               {
1006                 codingComplement.setSequenceColour(seq, col.brighter());
1007               }
1008             }
1009           }
1010         }
1011       }
1012     }
1013
1014     // notify the panel(s) to redo any group specific stuff.
1015     for (int a = 0; a < aps.length; a++)
1016     {
1017       aps[a].updateAnnotation();
1018       // TODO: JAL-868 - need to ensure view colour change message is broadcast
1019       // to any Jmols listening in
1020       final AlignViewportI codingComplement = aps[a].av
1021               .getCodingComplement();
1022       if (codingComplement != null)
1023       {
1024         ((AlignViewport) codingComplement).getAlignPanel()
1025                 .updateAnnotation();
1026
1027       }
1028
1029     }
1030
1031   }
1032
1033   /**
1034    * DOCUMENT ME!
1035    * 
1036    * @param state
1037    *          DOCUMENT ME!
1038    */
1039   public void setShowDistances(boolean state)
1040   {
1041     this.showDistances = state;
1042     repaint();
1043   }
1044
1045   /**
1046    * DOCUMENT ME!
1047    * 
1048    * @param state
1049    *          DOCUMENT ME!
1050    */
1051   public void setShowBootstrap(boolean state)
1052   {
1053     this.showBootstrap = state;
1054     repaint();
1055   }
1056
1057   /**
1058    * DOCUMENT ME!
1059    * 
1060    * @param state
1061    *          DOCUMENT ME!
1062    */
1063   public void setMarkPlaceholders(boolean state)
1064   {
1065     this.markPlaceholders = state;
1066     repaint();
1067   }
1068
1069   AlignmentPanel[] getAssociatedPanels()
1070   {
1071     if (applyToAllViews)
1072     {
1073       return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1074     }
1075     else
1076     {
1077       return new AlignmentPanel[] { ap };
1078     }
1079   }
1080 }