Bamboo test #13 AlignViewport resize and jscrollbar set
[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.gui.JalviewColourChooser.ColourChooserListener;
31 import jalview.schemes.ColourSchemeI;
32 import jalview.structure.SelectionSource;
33 import jalview.util.Format;
34 import jalview.util.MessageManager;
35
36 import java.awt.Color;
37 import java.awt.Dimension;
38 import java.awt.Font;
39 import java.awt.FontMetrics;
40 import java.awt.Graphics;
41 import java.awt.Graphics2D;
42 import java.awt.Point;
43 import java.awt.Rectangle;
44 import java.awt.RenderingHints;
45 import java.awt.event.MouseEvent;
46 import java.awt.event.MouseListener;
47 import java.awt.event.MouseMotionListener;
48 import java.awt.print.PageFormat;
49 import java.awt.print.Printable;
50 import java.awt.print.PrinterException;
51 import java.awt.print.PrinterJob;
52 import java.util.Enumeration;
53 import java.util.Hashtable;
54 import java.util.List;
55 import java.util.Vector;
56
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   private AlignViewport av;
81
82   private 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   private 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.setAssociatedPanel(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
588     int pwidth = (int) pf.getImageableWidth();
589     int pheight = (int) pf.getImageableHeight();
590
591     int noPages = getHeight() / pheight;
592
593     if (pi > noPages)
594     {
595       return Printable.NO_SUCH_PAGE;
596     }
597
598     if (pwidth > getWidth())
599     {
600       pwidth = getWidth();
601     }
602
603     pg = pg.create();
604     pg.setFont(font);
605     pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
606
607     if (fitToWindow)
608     {
609       if (pheight > getHeight())
610       {
611         pheight = getHeight();
612       }
613
614       noPages = 0;
615     }
616     else
617     {
618       FontMetrics fm = pg.getFontMetrics(font);
619       int height = fm.getHeight() * nameHash.size();
620       pg.translate(0, -pi * pheight);
621       // BH 2020.03.19 avoiding setClip here
622       pg.clipRect(0, pi * pheight, pwidth, (pi * pheight) + pheight);
623
624       // translate number of pages,
625       // height is screen size as this is the
626       // non overlapping text size
627       pheight = height;
628     }
629
630     draw(pg, pwidth, pheight);
631
632     pg.dispose();
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     String ttl = MessageManager.getString("label.select_subtree_colour");
839     ColourChooserListener listener = new ColourChooserListener() {
840       @Override
841       public void colourSelected(Color c)
842       {
843         setColor(highlightNode, c);
844         PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
845         repaint();
846       }
847     };
848     JalviewColourChooser.showColourChooser(this, ttl,  highlightNode.color, listener);
849   }
850
851   @Override
852   public void mouseMoved(MouseEvent evt)
853   {
854     av.setCurrentTree(tree);
855
856     Object ob = findElement(evt.getX(), evt.getY());
857
858     if (ob instanceof SequenceNode)
859     {
860       highlightNode = (SequenceNode) ob;
861       this.setToolTipText(
862               "<html>" + MessageManager.getString("label.highlightnode"));
863       repaint();
864
865     }
866     else
867     {
868       if (highlightNode != null)
869       {
870         highlightNode = null;
871         setToolTipText(null);
872         repaint();
873       }
874     }
875   }
876
877   @Override
878   public void mouseDragged(MouseEvent ect)
879   {
880   }
881
882   /**
883    * Handles a mouse press on a sequence name or the tree background canvas
884    * (click on a node is handled in mouseClicked). The action is to create
885    * groups by partitioning the tree at the mouse position. Colours for the
886    * groups (and sequence names) are generated randomly.
887    * 
888    * @param e
889    */
890   @Override
891   public void mousePressed(MouseEvent e)
892   {
893     av.setCurrentTree(tree);
894
895     /*
896      * isPopupTrigger is set for mousePressed (Mac)
897      * or mouseReleased (Windows)
898      */
899     if (e.isPopupTrigger())
900     {
901       if (highlightNode != null)
902       {
903         chooseSubtreeColour();
904       }
905       return;
906     }
907
908     /*
909      * defer right-click handling on Windows to
910      * mouseClicked; note isRightMouseButton
911      * also matches Cmd-click on Mac which should do
912      * nothing here
913      */
914     if (SwingUtilities.isRightMouseButton(e))
915     {
916       return;
917     }
918
919     int x = e.getX();
920     int y = e.getY();
921
922     Object ob = findElement(x, y);
923
924     if (ob instanceof SequenceI)
925     {
926       treeSelectionChanged((Sequence) ob);
927       PaintRefresher.Refresh(tp, getAssociatedPanel().av.getSequenceSetId());
928       repaint();
929       av.sendSelection();
930       return;
931     }
932     else if (!(ob instanceof SequenceNode))
933     {
934       // Find threshold
935       if (tree.getMaxHeight() != 0)
936       {
937         threshold = (float) (x - offx)
938                 / (float) (getWidth() - labelLength - (2 * offx));
939
940         List<SequenceNode> groups = tree.groupNodes(threshold);
941         setColor(tree.getTopNode(), Color.black);
942
943         AlignmentPanel[] aps = getAssociatedPanels();
944
945         // TODO push calls below into a single AlignViewportI method?
946         // see also AlignViewController.deleteGroups
947         for (int a = 0; a < aps.length; a++)
948         {
949           aps[a].av.setSelectionGroup(null);
950           aps[a].av.getAlignment().deleteAllGroups();
951           aps[a].av.clearSequenceColours();
952           if (aps[a].av.getCodingComplement() != null)
953           {
954             aps[a].av.getCodingComplement().setSelectionGroup(null);
955             aps[a].av.getCodingComplement().getAlignment()
956                     .deleteAllGroups();
957             aps[a].av.getCodingComplement().clearSequenceColours();
958           }
959           aps[a].av.setUpdateStructures(true);
960         }
961         colourGroups(groups);
962
963         /*
964          * clear partition (don't show vertical line) if
965          * it is to the right of all nodes
966          */
967         if (groups.isEmpty())
968         {
969           threshold = 0f;
970         }
971       }
972
973       PaintRefresher.Refresh(tp, getAssociatedPanel().av.getSequenceSetId());
974       repaint();
975     }
976
977   }
978
979   void colourGroups(List<SequenceNode> groups)
980   {
981     AlignmentPanel[] aps = getAssociatedPanels();
982     for (int i = 0; i < groups.size(); i++)
983     {
984       Color col = new Color((int) (Math.random() * 255),
985               (int) (Math.random() * 255), (int) (Math.random() * 255));
986       setColor(groups.get(i), col.brighter());
987
988       Vector<SequenceNode> l = tree.findLeaves(groups.get(i));
989
990       Vector<SequenceI> sequences = new Vector<>();
991
992       for (int j = 0; j < l.size(); j++)
993       {
994         SequenceI s1 = (SequenceI) l.elementAt(j).element();
995
996         if (!sequences.contains(s1))
997         {
998           sequences.addElement(s1);
999         }
1000       }
1001
1002       ColourSchemeI cs = null;
1003       SequenceGroup _sg = new SequenceGroup(sequences, null, cs, true, true,
1004               false, 0, av.getAlignment().getWidth() - 1);
1005
1006       _sg.setName("JTreeGroup:" + _sg.hashCode());
1007       _sg.setIdColour(col);
1008
1009       for (int a = 0; a < aps.length; a++)
1010       {
1011         SequenceGroup sg = new SequenceGroup(_sg);
1012         AlignViewport viewport = aps[a].av;
1013
1014         // Propagate group colours in each view
1015         if (viewport.getGlobalColourScheme() != null)
1016         {
1017           cs = viewport.getGlobalColourScheme().getInstance(viewport, sg);
1018           sg.setColourScheme(cs);
1019           sg.getGroupColourScheme().setThreshold(
1020                   viewport.getResidueShading().getThreshold(),
1021                   viewport.isIgnoreGapsConsensus());
1022
1023           if (viewport.getResidueShading().conservationApplied())
1024           {
1025             Conservation c = new Conservation("Group",
1026                     sg.getSequences(null), sg.getStartRes(),
1027                     sg.getEndRes());
1028             c.calculate();
1029             c.verdict(false, viewport.getConsPercGaps());
1030             sg.cs.setConservation(c);
1031           }
1032         }
1033         // indicate that associated structure views will need an update
1034         viewport.setUpdateStructures(true);
1035         // propagate structure view update and sequence group to complement view
1036         viewport.addSequenceGroup(sg);
1037       }
1038     }
1039
1040     // notify the panel(s) to redo any group specific stuff
1041     // also updates structure views if necessary
1042     for (int a = 0; a < aps.length; a++)
1043     {
1044       aps[a].updateAnnotation();
1045       final AlignViewportI codingComplement = aps[a].av
1046               .getCodingComplement();
1047       if (codingComplement != null)
1048       {
1049         ((AlignViewport) codingComplement).getAlignPanel()
1050                 .updateAnnotation();
1051       }
1052     }
1053   }
1054
1055   /**
1056    * DOCUMENT ME!
1057    * 
1058    * @param state
1059    *          DOCUMENT ME!
1060    */
1061   public void setShowDistances(boolean state)
1062   {
1063     this.showDistances = state;
1064     repaint();
1065   }
1066
1067   /**
1068    * DOCUMENT ME!
1069    * 
1070    * @param state
1071    *          DOCUMENT ME!
1072    */
1073   public void setShowBootstrap(boolean state)
1074   {
1075     this.showBootstrap = state;
1076     repaint();
1077   }
1078
1079   /**
1080    * DOCUMENT ME!
1081    * 
1082    * @param state
1083    *          DOCUMENT ME!
1084    */
1085   public void setMarkPlaceholders(boolean state)
1086   {
1087     this.markPlaceholders = state;
1088     repaint();
1089   }
1090
1091   AlignmentPanel[] getAssociatedPanels()
1092   {
1093     if (applyToAllViews)
1094     {
1095       return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1096     }
1097     else
1098     {
1099       return new AlignmentPanel[] { getAssociatedPanel() };
1100     }
1101   }
1102
1103   public AlignmentPanel getAssociatedPanel()
1104   {
1105     return ap;
1106   }
1107
1108   public void setAssociatedPanel(AlignmentPanel ap)
1109   {
1110     this.ap = ap;
1111   }
1112
1113   public AlignViewport getViewport()
1114   {
1115     return av;
1116   }
1117
1118   public void setViewport(AlignViewport av)
1119   {
1120     this.av = av;
1121   }
1122
1123   public float getThreshold()
1124   {
1125     return threshold;
1126   }
1127
1128   public void setThreshold(float threshold)
1129   {
1130     this.threshold = threshold;
1131   }
1132
1133   public boolean isApplyToAllViews()
1134   {
1135     return this.applyToAllViews;
1136   }
1137
1138   public void setApplyToAllViews(boolean applyToAllViews)
1139   {
1140     this.applyToAllViews = applyToAllViews;
1141   }
1142 }