JAL-4134 - brutal hack to build a tree clustering columns of PAE Matrix
[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 java.awt.Color;
24 import java.awt.Dimension;
25 import java.awt.Font;
26 import java.awt.FontMetrics;
27 import java.awt.Graphics;
28 import java.awt.Graphics2D;
29 import java.awt.Point;
30 import java.awt.Rectangle;
31 import java.awt.RenderingHints;
32 import java.awt.event.MouseEvent;
33 import java.awt.event.MouseListener;
34 import java.awt.event.MouseMotionListener;
35 import java.awt.print.PageFormat;
36 import java.awt.print.Printable;
37 import java.awt.print.PrinterException;
38 import java.awt.print.PrinterJob;
39 import java.util.Hashtable;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.Map.Entry;
43 import java.util.Vector;
44
45 import javax.swing.JPanel;
46 import javax.swing.JScrollPane;
47 import javax.swing.SwingUtilities;
48 import javax.swing.ToolTipManager;
49
50 import jalview.analysis.Conservation;
51 import jalview.analysis.TreeModel;
52 import jalview.api.AlignViewportI;
53 import jalview.datamodel.BinaryNode;
54 import jalview.datamodel.Sequence;
55 import jalview.datamodel.SequenceGroup;
56 import jalview.datamodel.SequenceI;
57 import jalview.datamodel.SequenceNode;
58 import jalview.gui.JalviewColourChooser.ColourChooserListener;
59 import jalview.schemes.ColourSchemeI;
60 import jalview.structure.SelectionSource;
61 import jalview.util.Format;
62 import jalview.util.MessageManager;
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   private AlignViewport av;
83
84   private 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   private float threshold;
103
104   String longestName;
105
106   int labelLength = -1;
107
108   Map<Object, Rectangle> nameHash = new Hashtable<>();
109
110   Map<BinaryNode, Rectangle> nodeHash = new Hashtable<>();
111
112   BinaryNode 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.setAssociatedPanel(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<BinaryNode> leaves = tree.findLeaves(tree.getTopNode());
178     boolean has_placeholders = false;
179     longestName = "";
180
181     for (int i = 0; i < leaves.size(); i++)
182     {
183       BinaryNode lf = leaves.elementAt(i);
184
185       if (lf instanceof SequenceNode && ((SequenceNode)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, BinaryNode 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("%g").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 instanceof SequenceNode && ((SequenceNode)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, (BinaryNode) node.left(), chunk, wscale, width, offx,
311               offy);
312       drawNode(g, (BinaryNode) 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) (((BinaryNode) node.left()).ycount * chunk)) + offy;
337       int yend = (node.right() == null ? 0
338               : (int) (((BinaryNode) 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("%g").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     for (Entry<Object, Rectangle> entry : nameHash.entrySet())
384     {
385       Rectangle rect = entry.getValue();
386
387       if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
388               && (y <= (rect.y + rect.height)))
389       {
390         return entry.getKey();
391       }
392     }
393
394     for (Entry<BinaryNode, Rectangle> entry : nodeHash.entrySet())
395     {
396       Rectangle rect = entry.getValue();
397
398       if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
399               && (y <= (rect.y + rect.height)))
400       {
401         return entry.getKey();
402       }
403     }
404
405     return null;
406   }
407
408   /**
409    * DOCUMENT ME!
410    * 
411    * @param pickBox
412    *          DOCUMENT ME!
413    */
414   public void pickNodes(Rectangle pickBox)
415   {
416     int width = getWidth();
417     int height = getHeight();
418
419     BinaryNode top = tree.getTopNode();
420
421     double wscale = ((width * .8) - (offx * 2)) / tree.getMaxHeight();
422
423     if (top.count == 0)
424     {
425       top.count = ((BinaryNode) top.left()).count
426               + ((BinaryNode) top.right()).count;
427     }
428
429     float chunk = (float) (height - (offy)) / top.count;
430
431     pickNode(pickBox, top, chunk, wscale, width, offx, offy);
432   }
433
434   /**
435    * DOCUMENT ME!
436    * 
437    * @param pickBox
438    *          DOCUMENT ME!
439    * @param node
440    *          DOCUMENT ME!
441    * @param chunk
442    *          DOCUMENT ME!
443    * @param wscale
444    *          DOCUMENT ME!
445    * @param width
446    *          DOCUMENT ME!
447    * @param offx
448    *          DOCUMENT ME!
449    * @param offy
450    *          DOCUMENT ME!
451    */
452   public void pickNode(Rectangle pickBox, BinaryNode node, float chunk,
453           double wscale, int width, int offx, int offy)
454   {
455     if (node == null)
456     {
457       return;
458     }
459
460     if ((node.left() == null) && (node.right() == null))
461     {
462       double height = node.height;
463       // double dist = node.dist;
464       // int xstart = (int) ((height - dist) * wscale) + offx;
465       int xend = (int) (height * wscale) + offx;
466
467       int ypos = (int) (node.ycount * chunk) + offy;
468
469       if (pickBox.contains(new Point(xend, ypos)))
470       {
471         if (node.element() instanceof SequenceI)
472         {
473           SequenceI seq = (SequenceI) node.element();
474           SequenceGroup sg = av.getSelectionGroup();
475
476           if (sg != null)
477           {
478             sg.addOrRemove(seq, true);
479           }
480         }
481       }
482     }
483     else
484     {
485       pickNode(pickBox, (BinaryNode) node.left(), chunk, wscale, width,
486               offx, offy);
487       pickNode(pickBox, (BinaryNode) node.right(), chunk, wscale, width,
488               offx, offy);
489     }
490   }
491
492   /**
493    * DOCUMENT ME!
494    * 
495    * @param node
496    *          DOCUMENT ME!
497    * @param c
498    *          DOCUMENT ME!
499    */
500   public void setColor(BinaryNode node, Color c)
501   {
502     if (node == null)
503     {
504       return;
505     }
506
507     node.color = c;
508     if (node.element() instanceof SequenceI)
509     {
510       final SequenceI seq = (SequenceI) node.element();
511       AlignmentPanel[] aps = getAssociatedPanels();
512       if (aps != null)
513       {
514         for (int a = 0; a < aps.length; a++)
515         {
516           aps[a].av.setSequenceColour(seq, c);
517         }
518       }
519     }
520     setColor((BinaryNode) node.left(), c);
521     setColor((BinaryNode) node.right(), c);
522   }
523
524   /**
525    * DOCUMENT ME!
526    */
527   void startPrinting()
528   {
529     Thread thread = new Thread(this);
530     thread.start();
531   }
532
533   // put printing in a thread to avoid painting problems
534   @Override
535   public void run()
536   {
537     PrinterJob printJob = PrinterJob.getPrinterJob();
538     PageFormat defaultPage = printJob.defaultPage();
539     PageFormat pf = printJob.pageDialog(defaultPage);
540
541     if (defaultPage == pf)
542     {
543       /*
544        * user cancelled
545        */
546       return;
547     }
548
549     printJob.setPrintable(this, pf);
550
551     if (printJob.printDialog())
552     {
553       try
554       {
555         printJob.print();
556       } catch (Exception PrintException)
557       {
558         PrintException.printStackTrace();
559       }
560     }
561   }
562
563   /**
564    * DOCUMENT ME!
565    * 
566    * @param pg
567    *          DOCUMENT ME!
568    * @param pf
569    *          DOCUMENT ME!
570    * @param pi
571    *          DOCUMENT ME!
572    * 
573    * @return DOCUMENT ME!
574    * 
575    * @throws PrinterException
576    *           DOCUMENT ME!
577    */
578   @Override
579   public int print(Graphics pg, PageFormat pf, int pi)
580           throws PrinterException
581   {
582     pg.setFont(font);
583     pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
584
585     int pwidth = (int) pf.getImageableWidth();
586     int pheight = (int) pf.getImageableHeight();
587
588     int noPages = getHeight() / pheight;
589
590     if (pi > noPages)
591     {
592       return Printable.NO_SUCH_PAGE;
593     }
594
595     if (pwidth > getWidth())
596     {
597       pwidth = getWidth();
598     }
599
600     if (fitToWindow)
601     {
602       if (pheight > getHeight())
603       {
604         pheight = getHeight();
605       }
606
607       noPages = 0;
608     }
609     else
610     {
611       FontMetrics fm = pg.getFontMetrics(font);
612       int height = fm.getHeight() * nameHash.size();
613       pg.translate(0, -pi * pheight);
614       pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
615
616       // translate number of pages,
617       // height is screen size as this is the
618       // non overlapping text size
619       pheight = height;
620     }
621
622     draw(pg, pwidth, pheight);
623
624     return Printable.PAGE_EXISTS;
625   }
626
627   /**
628    * DOCUMENT ME!
629    * 
630    * @param g
631    *          DOCUMENT ME!
632    */
633   @Override
634   public void paintComponent(Graphics g)
635   {
636     super.paintComponent(g);
637     g.setFont(font);
638
639     if (tree == null)
640     {
641       g.drawString(
642               MessageManager.getString("label.calculating_tree") + "....",
643               20, getHeight() / 2);
644     }
645     else
646     {
647       fm = g.getFontMetrics(font);
648
649       int nameCount = nameHash.size();
650       if (nameCount == 0)
651       {
652         repaint();
653       }
654
655       if (fitToWindow || (!fitToWindow && (scrollPane
656               .getHeight() > ((fm.getHeight() * nameCount) + offy))))
657       {
658         draw(g, scrollPane.getWidth(), scrollPane.getHeight());
659         setPreferredSize(null);
660       }
661       else
662       {
663         setPreferredSize(new Dimension(scrollPane.getWidth(),
664                 fm.getHeight() * nameCount));
665         draw(g, scrollPane.getWidth(), fm.getHeight() * nameCount);
666       }
667
668       scrollPane.revalidate();
669     }
670   }
671
672   /**
673    * DOCUMENT ME!
674    * 
675    * @param fontSize
676    *          DOCUMENT ME!
677    */
678   @Override
679   public void setFont(Font font)
680   {
681     this.font = font;
682     repaint();
683   }
684
685   /**
686    * DOCUMENT ME!
687    * 
688    * @param g1
689    *          DOCUMENT ME!
690    * @param width
691    *          DOCUMENT ME!
692    * @param height
693    *          DOCUMENT ME!
694    */
695   public void draw(Graphics g1, int width, int height)
696   {
697     Graphics2D g2 = (Graphics2D) g1;
698     g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
699             RenderingHints.VALUE_ANTIALIAS_ON);
700     g2.setColor(Color.white);
701     g2.fillRect(0, 0, width, height);
702     g2.setFont(font);
703
704     if (longestName == null || tree == null)
705     {
706       g2.drawString("Calculating tree.", 20, 20);
707     }
708     offy = font.getSize() + 10;
709
710     fm = g2.getFontMetrics(font);
711
712     labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
713
714     double wscale = (width - labelLength - (offx * 2))
715             / tree.getMaxHeight();
716
717     BinaryNode top = tree.getTopNode();
718
719     if (top.count == 0)
720     {
721       top.count = ((BinaryNode) top.left()).count
722               + ((BinaryNode) top.right()).count;
723     }
724
725     float chunk = (float) (height - (offy)) / top.count;
726
727     drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
728
729     if (threshold != 0)
730     {
731       if (av.getCurrentTree() == tree)
732       {
733         g2.setColor(Color.red);
734       }
735       else
736       {
737         g2.setColor(Color.gray);
738       }
739
740       int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx)))
741               + offx);
742
743       g2.drawLine(x, 0, x, getHeight());
744     }
745   }
746
747   /**
748    * Empty method to satisfy the MouseListener interface
749    * 
750    * @param e
751    */
752   @Override
753   public void mouseReleased(MouseEvent e)
754   {
755     /*
756      * isPopupTrigger is set on mouseReleased on Windows
757      */
758     if (e.isPopupTrigger())
759     {
760       chooseSubtreeColour();
761       e.consume(); // prevent mouseClicked happening
762     }
763   }
764
765   /**
766    * Empty method to satisfy the MouseListener interface
767    * 
768    * @param e
769    */
770   @Override
771   public void mouseEntered(MouseEvent e)
772   {
773   }
774
775   /**
776    * Empty method to satisfy the MouseListener interface
777    * 
778    * @param e
779    */
780   @Override
781   public void mouseExited(MouseEvent e)
782   {
783   }
784
785   /**
786    * Handles a mouse click on a tree node (clicks elsewhere are handled in
787    * mousePressed). Click selects the sub-tree, double-click swaps leaf nodes
788    * order, right-click opens a dialogue to choose colour for the sub-tree.
789    * 
790    * @param e
791    */
792   @Override
793   public void mouseClicked(MouseEvent evt)
794   {
795     if (highlightNode == null)
796     {
797       return;
798     }
799
800     if (evt.getClickCount() > 1)
801     {
802       tree.swapNodes(highlightNode);
803       tree.reCount(tree.getTopNode());
804       tree.findHeight(tree.getTopNode());
805     }
806     else
807     {
808       Vector<BinaryNode> leaves = tree.findLeaves(highlightNode);
809
810       for (int i = 0; i < leaves.size(); i++)
811       {
812         SequenceI seq = (SequenceI) leaves.elementAt(i).element();
813         treeSelectionChanged(seq);
814       }
815       av.sendSelection();
816     }
817
818     PaintRefresher.Refresh(tp, av.getSequenceSetId());
819     repaint();
820   }
821
822   /**
823    * Offer the user the option to choose a colour for the highlighted node and
824    * its children; this colour is also applied to the corresponding sequence ids
825    * in the alignment
826    */
827   void chooseSubtreeColour()
828   {
829     String ttl = MessageManager.getString("label.select_subtree_colour");
830     ColourChooserListener listener = new ColourChooserListener()
831     {
832       @Override
833       public void colourSelected(Color c)
834       {
835         setColor(highlightNode, c);
836         PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
837         repaint();
838       }
839     };
840     JalviewColourChooser.showColourChooser(this, ttl, highlightNode.color,
841             listener);
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 BinaryNode)
852     {
853       highlightNode = (BinaryNode) 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,
921               getAssociatedPanel().av.getSequenceSetId());
922       repaint();
923       av.sendSelection();
924       return;
925     }
926     else if (!(ob instanceof BinaryNode))
927     {
928       // Find threshold
929       if (tree.getMaxHeight() != 0)
930       {
931         threshold = (float) (x - offx)
932                 / (float) (getWidth() - labelLength - (2 * offx));
933
934         List<BinaryNode> groups = tree.groupNodes(threshold);
935         setColor(tree.getTopNode(), Color.black);
936
937         AlignmentPanel[] aps = getAssociatedPanels();
938
939         // TODO push calls below into a single AlignViewportI method?
940         // see also AlignViewController.deleteGroups
941         for (int a = 0; a < aps.length; a++)
942         {
943           aps[a].av.setSelectionGroup(null);
944           aps[a].av.getAlignment().deleteAllGroups();
945           aps[a].av.clearSequenceColours();
946           if (aps[a].av.getCodingComplement() != null)
947           {
948             aps[a].av.getCodingComplement().setSelectionGroup(null);
949             aps[a].av.getCodingComplement().getAlignment()
950                     .deleteAllGroups();
951             aps[a].av.getCodingComplement().clearSequenceColours();
952           }
953           aps[a].av.setUpdateStructures(true);
954         }
955         colourGroups(groups);
956
957         /*
958          * clear partition (don't show vertical line) if
959          * it is to the right of all nodes
960          */
961         if (groups.isEmpty())
962         {
963           threshold = 0f;
964         }
965       }
966
967       PaintRefresher.Refresh(tp,
968               getAssociatedPanel().av.getSequenceSetId());
969       repaint();
970     }
971
972   }
973
974   void colourGroups(List<BinaryNode> groups)
975   {
976     AlignmentPanel[] aps = getAssociatedPanels();
977     for (int i = 0; i < groups.size(); i++)
978     {
979       Color col = new Color((int) (Math.random() * 255),
980               (int) (Math.random() * 255), (int) (Math.random() * 255));
981       setColor(groups.get(i), col.brighter());
982
983       Vector<BinaryNode> l = tree.findLeaves(groups.get(i));
984
985       Vector<SequenceI> sequences = new Vector<>();
986
987       for (int j = 0; j < l.size(); j++)
988       {
989         SequenceI s1 = (SequenceI) l.elementAt(j).element();
990
991         if (!sequences.contains(s1))
992         {
993           sequences.addElement(s1);
994         }
995       }
996
997       ColourSchemeI cs = null;
998       SequenceGroup _sg = new SequenceGroup(sequences, null, cs, true, true,
999               false, 0, av.getAlignment().getWidth() - 1);
1000
1001       _sg.setName("JTreeGroup:" + _sg.hashCode());
1002       _sg.setIdColour(col);
1003
1004       for (int a = 0; a < aps.length; a++)
1005       {
1006         SequenceGroup sg = new SequenceGroup(_sg);
1007         AlignViewport viewport = aps[a].av;
1008
1009         // Propagate group colours in each view
1010         if (viewport.getGlobalColourScheme() != null)
1011         {
1012           cs = viewport.getGlobalColourScheme().getInstance(viewport, sg);
1013           sg.setColourScheme(cs);
1014           sg.getGroupColourScheme().setThreshold(
1015                   viewport.getResidueShading().getThreshold(),
1016                   viewport.isIgnoreGapsConsensus());
1017
1018           if (viewport.getResidueShading().conservationApplied())
1019           {
1020             Conservation c = new Conservation("Group",
1021                     sg.getSequences(null), sg.getStartRes(),
1022                     sg.getEndRes());
1023             c.calculate();
1024             c.verdict(false, viewport.getConsPercGaps());
1025             sg.cs.setConservation(c);
1026           }
1027         }
1028         // indicate that associated structure views will need an update
1029         viewport.setUpdateStructures(true);
1030         // propagate structure view update and sequence group to complement view
1031         viewport.addSequenceGroup(sg);
1032       }
1033     }
1034
1035     // notify the panel(s) to redo any group specific stuff
1036     // also updates structure views if necessary
1037     for (int a = 0; a < aps.length; a++)
1038     {
1039       aps[a].updateAnnotation();
1040       final AlignViewportI codingComplement = aps[a].av
1041               .getCodingComplement();
1042       if (codingComplement != null)
1043       {
1044         ((AlignViewport) codingComplement).getAlignPanel()
1045                 .updateAnnotation();
1046       }
1047     }
1048   }
1049
1050   /**
1051    * DOCUMENT ME!
1052    * 
1053    * @param state
1054    *          DOCUMENT ME!
1055    */
1056   public void setShowDistances(boolean state)
1057   {
1058     this.showDistances = state;
1059     repaint();
1060   }
1061
1062   /**
1063    * DOCUMENT ME!
1064    * 
1065    * @param state
1066    *          DOCUMENT ME!
1067    */
1068   public void setShowBootstrap(boolean state)
1069   {
1070     this.showBootstrap = state;
1071     repaint();
1072   }
1073
1074   /**
1075    * DOCUMENT ME!
1076    * 
1077    * @param state
1078    *          DOCUMENT ME!
1079    */
1080   public void setMarkPlaceholders(boolean state)
1081   {
1082     this.markPlaceholders = state;
1083     repaint();
1084   }
1085
1086   AlignmentPanel[] getAssociatedPanels()
1087   {
1088     if (applyToAllViews)
1089     {
1090       return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1091     }
1092     else
1093     {
1094       return new AlignmentPanel[] { getAssociatedPanel() };
1095     }
1096   }
1097
1098   public AlignmentPanel getAssociatedPanel()
1099   {
1100     return ap;
1101   }
1102
1103   public void setAssociatedPanel(AlignmentPanel ap)
1104   {
1105     this.ap = ap;
1106   }
1107
1108   public AlignViewport getViewport()
1109   {
1110     return av;
1111   }
1112
1113   public void setViewport(AlignViewport av)
1114   {
1115     this.av = av;
1116   }
1117
1118   public float getThreshold()
1119   {
1120     return threshold;
1121   }
1122
1123   public void setThreshold(float threshold)
1124   {
1125     this.threshold = threshold;
1126   }
1127
1128   public boolean isApplyToAllViews()
1129   {
1130     return this.applyToAllViews;
1131   }
1132
1133   public void setApplyToAllViews(boolean applyToAllViews)
1134   {
1135     this.applyToAllViews = applyToAllViews;
1136   }
1137 }