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