JAL-3127 reinstate ability to set sequence ID colour directly by right-clicking a...
[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     if (node.element() instanceof SequenceI)
516     {
517       AlignmentPanel[] aps = getAssociatedPanels();
518       if (aps != null)
519       {
520         for (int a = 0; a < aps.length; a++)
521         {
522           final SequenceI seq = (SequenceI) node.element();
523           aps[a].av.setSequenceColour(seq, c);
524         }
525       }
526     }
527     if ((node.left() != null) || (node.right() != null)) // TODO: internal node
528     {
529       setColor((SequenceNode) node.left(), c);
530       setColor((SequenceNode) node.right(), c);
531     }
532   }
533
534   /**
535    * DOCUMENT ME!
536    */
537   void startPrinting()
538   {
539     Thread thread = new Thread(this);
540     thread.start();
541   }
542
543   // put printing in a thread to avoid painting problems
544   @Override
545   public void run()
546   {
547     PrinterJob printJob = PrinterJob.getPrinterJob();
548     PageFormat defaultPage = printJob.defaultPage();
549     PageFormat pf = printJob.pageDialog(defaultPage);
550
551     if (defaultPage == pf)
552     {
553       /*
554        * user cancelled
555        */
556       return;
557     }
558
559     printJob.setPrintable(this, pf);
560
561     if (printJob.printDialog())
562     {
563       try
564       {
565         printJob.print();
566       } catch (Exception PrintException)
567       {
568         PrintException.printStackTrace();
569       }
570     }
571   }
572
573   /**
574    * DOCUMENT ME!
575    * 
576    * @param pg
577    *          DOCUMENT ME!
578    * @param pf
579    *          DOCUMENT ME!
580    * @param pi
581    *          DOCUMENT ME!
582    * 
583    * @return DOCUMENT ME!
584    * 
585    * @throws PrinterException
586    *           DOCUMENT ME!
587    */
588   @Override
589   public int print(Graphics pg, PageFormat pf, int pi)
590           throws PrinterException
591   {
592     pg.setFont(font);
593     pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
594
595     int pwidth = (int) pf.getImageableWidth();
596     int pheight = (int) pf.getImageableHeight();
597
598     int noPages = getHeight() / pheight;
599
600     if (pi > noPages)
601     {
602       return Printable.NO_SUCH_PAGE;
603     }
604
605     if (pwidth > getWidth())
606     {
607       pwidth = getWidth();
608     }
609
610     if (fitToWindow)
611     {
612       if (pheight > getHeight())
613       {
614         pheight = getHeight();
615       }
616
617       noPages = 0;
618     }
619     else
620     {
621       FontMetrics fm = pg.getFontMetrics(font);
622       int height = fm.getHeight() * nameHash.size();
623       pg.translate(0, -pi * pheight);
624       pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
625
626       // translate number of pages,
627       // height is screen size as this is the
628       // non overlapping text size
629       pheight = height;
630     }
631
632     draw(pg, pwidth, pheight);
633
634     return Printable.PAGE_EXISTS;
635   }
636
637   /**
638    * DOCUMENT ME!
639    * 
640    * @param g
641    *          DOCUMENT ME!
642    */
643   @Override
644   public void paintComponent(Graphics g)
645   {
646     super.paintComponent(g);
647     g.setFont(font);
648
649     if (tree == null)
650     {
651       g.drawString(
652               MessageManager.getString("label.calculating_tree") + "....",
653               20, getHeight() / 2);
654     }
655     else
656     {
657       fm = g.getFontMetrics(font);
658
659       if (nameHash.size() == 0)
660       {
661         repaint();
662       }
663
664       if (fitToWindow || (!fitToWindow && (scrollPane
665               .getHeight() > ((fm.getHeight() * nameHash.size()) + offy))))
666       {
667         draw(g, scrollPane.getWidth(), scrollPane.getHeight());
668         setPreferredSize(null);
669       }
670       else
671       {
672         setPreferredSize(new Dimension(scrollPane.getWidth(),
673                 fm.getHeight() * nameHash.size()));
674         draw(g, scrollPane.getWidth(), fm.getHeight() * nameHash.size());
675       }
676
677       scrollPane.revalidate();
678     }
679   }
680
681   /**
682    * DOCUMENT ME!
683    * 
684    * @param fontSize
685    *          DOCUMENT ME!
686    */
687   @Override
688   public void setFont(Font font)
689   {
690     this.font = font;
691     repaint();
692   }
693
694   /**
695    * DOCUMENT ME!
696    * 
697    * @param g1
698    *          DOCUMENT ME!
699    * @param width
700    *          DOCUMENT ME!
701    * @param height
702    *          DOCUMENT ME!
703    */
704   public void draw(Graphics g1, int width, int height)
705   {
706     Graphics2D g2 = (Graphics2D) g1;
707     g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
708             RenderingHints.VALUE_ANTIALIAS_ON);
709     g2.setColor(Color.white);
710     g2.fillRect(0, 0, width, height);
711     g2.setFont(font);
712
713     if (longestName == null || tree == null)
714     {
715       g2.drawString("Calculating tree.", 20, 20);
716     }
717     offy = font.getSize() + 10;
718
719     fm = g2.getFontMetrics(font);
720
721     labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
722
723     double wscale = (width - labelLength - (offx * 2))
724             / tree.getMaxHeight();
725
726     SequenceNode top = tree.getTopNode();
727
728     if (top.count == 0)
729     {
730       top.count = ((SequenceNode) top.left()).count
731               + ((SequenceNode) top.right()).count;
732     }
733
734     float chunk = (float) (height - (offy)) / top.count;
735
736     drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
737
738     if (threshold != 0)
739     {
740       if (av.getCurrentTree() == tree)
741       {
742         g2.setColor(Color.red);
743       }
744       else
745       {
746         g2.setColor(Color.gray);
747       }
748
749       int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx)))
750               + offx);
751
752       g2.drawLine(x, 0, x, getHeight());
753     }
754   }
755
756   /**
757    * Empty method to satisfy the MouseListener interface
758    * 
759    * @param e
760    */
761   @Override
762   public void mouseReleased(MouseEvent e)
763   {
764     /*
765      * isPopupTrigger is set on mouseReleased on Windows
766      */
767     if (e.isPopupTrigger())
768     {
769       chooseSubtreeColour();
770       e.consume(); // prevent mouseClicked happening
771     }
772   }
773
774   /**
775    * Empty method to satisfy the MouseListener interface
776    * 
777    * @param e
778    */
779   @Override
780   public void mouseEntered(MouseEvent e)
781   {
782   }
783
784   /**
785    * Empty method to satisfy the MouseListener interface
786    * 
787    * @param e
788    */
789   @Override
790   public void mouseExited(MouseEvent e)
791   {
792   }
793
794   /**
795    * Handles a mouse click on a tree node (clicks elsewhere are handled in
796    * mousePressed). Click selects the sub-tree, double-click swaps leaf nodes
797    * order, right-click opens a dialogue to choose colour for the sub-tree.
798    * 
799    * @param e
800    */
801   @Override
802   public void mouseClicked(MouseEvent evt)
803   {
804     if (highlightNode == null)
805     {
806       return;
807     }
808
809     if (evt.getClickCount() > 1)
810     {
811       tree.swapNodes(highlightNode);
812       tree.reCount(tree.getTopNode());
813       tree.findHeight(tree.getTopNode());
814     }
815     else
816     {
817       Vector<SequenceNode> leaves = tree.findLeaves(highlightNode);
818
819       for (int i = 0; i < leaves.size(); i++)
820       {
821         SequenceI seq = (SequenceI) leaves.elementAt(i).element();
822         treeSelectionChanged(seq);
823       }
824       av.sendSelection();
825     }
826
827     PaintRefresher.Refresh(tp, av.getSequenceSetId());
828     repaint();
829   }
830
831   /**
832    * Offer the user the option to choose a colour for the highlighted node and
833    * its children; this colour is also applied to the corresponding sequence ids
834    * in the alignment
835    */
836   void chooseSubtreeColour()
837   {
838     Color col = JColorChooser.showDialog(this,
839             MessageManager.getString("label.select_subtree_colour"),
840             highlightNode.color);
841     if (col != null)
842     {
843       setColor(highlightNode, col);
844       PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
845       repaint();
846     }
847   }
848
849   @Override
850   public void mouseMoved(MouseEvent evt)
851   {
852     av.setCurrentTree(tree);
853
854     Object ob = findElement(evt.getX(), evt.getY());
855
856     if (ob instanceof SequenceNode)
857     {
858       highlightNode = (SequenceNode) ob;
859       this.setToolTipText(
860               "<html>" + MessageManager.getString("label.highlightnode"));
861       repaint();
862
863     }
864     else
865     {
866       if (highlightNode != null)
867       {
868         highlightNode = null;
869         setToolTipText(null);
870         repaint();
871       }
872     }
873   }
874
875   @Override
876   public void mouseDragged(MouseEvent ect)
877   {
878   }
879
880   /**
881    * Handles a mouse press on a sequence name or the tree background canvas
882    * (click on a node is handled in mouseClicked). The action is to create
883    * groups by partitioning the tree at the mouse position. Colours for the
884    * groups (and sequence names) are generated randomly.
885    * 
886    * @param e
887    */
888   @Override
889   public void mousePressed(MouseEvent e)
890   {
891     av.setCurrentTree(tree);
892
893     /*
894      * isPopupTrigger is set for mousePressed (Mac)
895      * or mouseReleased (Windows)
896      */
897     if (e.isPopupTrigger())
898     {
899       if (highlightNode != null)
900       {
901         chooseSubtreeColour();
902       }
903       return;
904     }
905
906     /*
907      * defer right-click handling on Windows to
908      * mouseClicked; note isRightMouseButton
909      * also matches Cmd-click on Mac which should do
910      * nothing here
911      */
912     if (SwingUtilities.isRightMouseButton(e))
913     {
914       return;
915     }
916
917     int x = e.getX();
918     int y = e.getY();
919
920     Object ob = findElement(x, y);
921
922     if (ob instanceof SequenceI)
923     {
924       treeSelectionChanged((Sequence) ob);
925       PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
926       repaint();
927       av.sendSelection();
928       return;
929     }
930     else if (!(ob instanceof SequenceNode))
931     {
932       // Find threshold
933       if (tree.getMaxHeight() != 0)
934       {
935         threshold = (float) (x - offx)
936                 / (float) (getWidth() - labelLength - (2 * offx));
937
938         List<SequenceNode> groups = tree.groupNodes(threshold);
939         setColor(tree.getTopNode(), Color.black);
940
941         AlignmentPanel[] aps = getAssociatedPanels();
942
943         // TODO push calls below into a single AlignViewportI method?
944         // see also AlignViewController.deleteGroups
945         for (int a = 0; a < aps.length; a++)
946         {
947           aps[a].av.setSelectionGroup(null);
948           aps[a].av.getAlignment().deleteAllGroups();
949           aps[a].av.clearSequenceColours();
950           if (aps[a].av.getCodingComplement() != null)
951           {
952             aps[a].av.getCodingComplement().setSelectionGroup(null);
953             aps[a].av.getCodingComplement().getAlignment()
954                     .deleteAllGroups();
955             aps[a].av.getCodingComplement().clearSequenceColours();
956           }
957         }
958         colourGroups(groups);
959
960         /*
961          * clear partition (don't show vertical line) if
962          * it is to the right of all nodes
963          */
964         if (groups.isEmpty())
965         {
966           threshold = 0f;
967         }
968       }
969
970       PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
971       repaint();
972     }
973
974   }
975
976   void colourGroups(List<SequenceNode> groups)
977   {
978     AlignmentPanel[] aps = getAssociatedPanels();
979     for (int i = 0; i < groups.size(); i++)
980     {
981       Color col = new Color((int) (Math.random() * 255),
982               (int) (Math.random() * 255), (int) (Math.random() * 255));
983       setColor(groups.get(i), col.brighter());
984
985       Vector<SequenceNode> l = tree.findLeaves(groups.get(i));
986
987       Vector<SequenceI> sequences = new Vector<>();
988
989       for (int j = 0; j < l.size(); j++)
990       {
991         SequenceI s1 = (SequenceI) l.elementAt(j).element();
992
993         if (!sequences.contains(s1))
994         {
995           sequences.addElement(s1);
996         }
997       }
998
999       ColourSchemeI cs = null;
1000       SequenceGroup sg = new SequenceGroup(sequences, null, cs, true, true,
1001               false, 0, av.getAlignment().getWidth() - 1);
1002
1003       if (av.getGlobalColourScheme() != null)
1004       {
1005         if (av.getGlobalColourScheme() instanceof UserColourScheme)
1006         {
1007           cs = new UserColourScheme(
1008                   ((UserColourScheme) av.getGlobalColourScheme())
1009                           .getColours());
1010
1011         }
1012         else
1013         {
1014           cs = ColourSchemeProperty.getColourScheme(av, sg,
1015                   ColourSchemeProperty
1016                   .getColourName(av.getGlobalColourScheme()));
1017         }
1018         // cs is null if shading is an annotationColourGradient
1019         // if (cs != null)
1020         // {
1021         // cs.setThreshold(av.getViewportColourScheme().getThreshold(),
1022         // av.isIgnoreGapsConsensus());
1023         // }
1024       }
1025       sg.setColourScheme(cs);
1026       sg.getGroupColourScheme().setThreshold(
1027               av.getResidueShading().getThreshold(),
1028               av.isIgnoreGapsConsensus());
1029       // sg.recalcConservation();
1030       sg.setName("JTreeGroup:" + sg.hashCode());
1031       sg.setIdColour(col);
1032
1033       for (int a = 0; a < aps.length; a++)
1034       {
1035         if (aps[a].av.getGlobalColourScheme() != null
1036                 && aps[a].av.getResidueShading().conservationApplied())
1037         {
1038           Conservation c = new Conservation("Group", sg.getSequences(null),
1039                   sg.getStartRes(), sg.getEndRes());
1040           c.calculate();
1041           c.verdict(false, aps[a].av.getConsPercGaps());
1042           sg.cs.setConservation(c);
1043         }
1044         // indicate that associated structure views will need an update
1045         aps[a].av.setUpdateStructures(true);
1046         // propagate structure view update and sequence group to complement view
1047         aps[a].av.addSequenceGroup(new SequenceGroup(sg));
1048       }
1049     }
1050
1051     // notify the panel(s) to redo any group specific stuff
1052     // also updates structure views if necessary
1053     for (int a = 0; a < aps.length; a++)
1054     {
1055       aps[a].updateAnnotation();
1056       final AlignViewportI codingComplement = aps[a].av
1057               .getCodingComplement();
1058       if (codingComplement != null)
1059       {
1060         ((AlignViewport) codingComplement).getAlignPanel()
1061                 .updateAnnotation();
1062       }
1063     }
1064   }
1065
1066   /**
1067    * DOCUMENT ME!
1068    * 
1069    * @param state
1070    *          DOCUMENT ME!
1071    */
1072   public void setShowDistances(boolean state)
1073   {
1074     this.showDistances = state;
1075     repaint();
1076   }
1077
1078   /**
1079    * DOCUMENT ME!
1080    * 
1081    * @param state
1082    *          DOCUMENT ME!
1083    */
1084   public void setShowBootstrap(boolean state)
1085   {
1086     this.showBootstrap = state;
1087     repaint();
1088   }
1089
1090   /**
1091    * DOCUMENT ME!
1092    * 
1093    * @param state
1094    *          DOCUMENT ME!
1095    */
1096   public void setMarkPlaceholders(boolean state)
1097   {
1098     this.markPlaceholders = state;
1099     repaint();
1100   }
1101
1102   AlignmentPanel[] getAssociatedPanels()
1103   {
1104     if (applyToAllViews)
1105     {
1106       return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1107     }
1108     else
1109     {
1110       return new AlignmentPanel[] { ap };
1111     }
1112   }
1113 }