2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
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;
39 import java.awt.Color;
40 import java.awt.Dimension;
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;
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;
72 public class TreeCanvas extends JPanel implements MouseListener, Runnable,
73 Printable, MouseMotionListener, SelectionSource
76 public static final String PLACEHOLDER = " * ";
80 JScrollPane scrollPane;
92 boolean fitToWindow = true;
94 boolean showDistances = false;
96 boolean showBootstrap = false;
98 boolean markPlaceholders = false;
108 int labelLength = -1;
110 Hashtable nameHash = new Hashtable();
112 Hashtable nodeHash = new Hashtable();
114 SequenceNode highlightNode;
116 boolean applyToAllViews = false;
119 * Creates a new TreeCanvas object.
130 public TreeCanvas(TreePanel tp, AlignmentPanel ap, JScrollPane scroller)
136 scrollPane = scroller;
137 addMouseListener(this);
138 addMouseMotionListener(this);
139 ToolTipManager.sharedInstance().registerComponent(this);
148 public void treeSelectionChanged(SequenceI sequence)
150 AlignmentPanel[] aps = getAssociatedPanels();
152 for (int a = 0; a < aps.length; a++)
154 SequenceGroup selected = aps[a].av.getSelectionGroup();
156 if (selected == null)
158 selected = new SequenceGroup();
159 aps[a].av.setSelectionGroup(selected);
162 selected.setEndRes(aps[a].av.getAlignment().getWidth() - 1);
163 selected.addOrRemove(sequence, true);
173 public void setTree(TreeModel tree)
176 tree.findHeight(tree.getTopNode());
178 // Now have to calculate longest name based on the leaves
179 Vector<SequenceNode> leaves = tree.findLeaves(tree.getTopNode());
180 boolean has_placeholders = false;
183 for (int i = 0; i < leaves.size(); i++)
185 SequenceNode lf = leaves.elementAt(i);
187 if (lf.isPlaceholder())
189 has_placeholders = true;
192 if (longestName.length() < ((Sequence) lf.element()).getName()
195 longestName = TreeCanvas.PLACEHOLDER
196 + ((Sequence) lf.element()).getName();
200 setMarkPlaceholders(has_placeholders);
221 public void drawNode(Graphics g, SequenceNode node, float chunk,
222 double wscale, int width, int offx, int offy)
229 if ((node.left() == null) && (node.right() == null))
232 double height = node.height;
233 double dist = node.dist;
235 int xstart = (int) ((height - dist) * wscale) + offx;
236 int xend = (int) (height * wscale) + offx;
238 int ypos = (int) (node.ycount * chunk) + offy;
240 if (node.element() instanceof SequenceI)
242 SequenceI seq = (SequenceI) node.element();
244 if (av.getSequenceColour(seq) == Color.white)
246 g.setColor(Color.black);
250 g.setColor(av.getSequenceColour(seq).darker());
255 g.setColor(Color.black);
258 // Draw horizontal line
259 g.drawLine(xstart, ypos, xend, ypos);
261 String nodeLabel = "";
263 if (showDistances && (node.dist > 0))
265 nodeLabel = new Format("%-.2f").form(node.dist);
268 if (showBootstrap && node.bootstrap > -1)
272 nodeLabel = nodeLabel + " : ";
275 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
278 if (!nodeLabel.equals(""))
280 g.drawString(nodeLabel, xstart + 2, ypos - 2);
283 String name = (markPlaceholders && node.isPlaceholder())
284 ? (PLACEHOLDER + node.getName())
287 int charWidth = fm.stringWidth(name) + 3;
288 int charHeight = font.getSize();
290 Rectangle rect = new Rectangle(xend + 10, ypos - charHeight / 2,
291 charWidth, charHeight);
293 nameHash.put(node.element(), rect);
295 // Colour selected leaves differently
296 SequenceGroup selected = av.getSelectionGroup();
298 if ((selected != null)
299 && selected.getSequences(null).contains(node.element()))
301 g.setColor(Color.gray);
303 g.fillRect(xend + 10, ypos - charHeight / 2, charWidth, charHeight);
304 g.setColor(Color.white);
307 g.drawString(name, xend + 10, ypos + fm.getDescent());
308 g.setColor(Color.black);
312 drawNode(g, (SequenceNode) node.left(), chunk, wscale, width, offx,
314 drawNode(g, (SequenceNode) node.right(), chunk, wscale, width, offx,
317 double height = node.height;
318 double dist = node.dist;
320 int xstart = (int) ((height - dist) * wscale) + offx;
321 int xend = (int) (height * wscale) + offx;
322 int ypos = (int) (node.ycount * chunk) + offy;
324 g.setColor(node.color.darker());
326 // Draw horizontal line
327 g.drawLine(xstart, ypos, xend, ypos);
328 if (node == highlightNode)
330 g.fillRect(xend - 3, ypos - 3, 6, 6);
334 g.fillRect(xend - 2, ypos - 2, 4, 4);
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))
343 Rectangle pos = new Rectangle(xend - 2, ypos - 2, 5, 5);
344 nodeHash.put(node, pos);
346 g.drawLine((int) (height * wscale) + offx, ystart,
347 (int) (height * wscale) + offx, yend);
349 String nodeLabel = "";
351 if (showDistances && (node.dist > 0))
353 nodeLabel = new Format("%-.2f").form(node.dist);
356 if (showBootstrap && node.bootstrap > -1)
360 nodeLabel = nodeLabel + " : ";
363 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
366 if (!nodeLabel.equals(""))
368 g.drawString(nodeLabel, xstart + 2, ypos - 2);
381 * @return DOCUMENT ME!
383 public Object findElement(int x, int y)
385 Enumeration keys = nameHash.keys();
387 while (keys.hasMoreElements())
389 Object ob = keys.nextElement();
390 Rectangle rect = (Rectangle) nameHash.get(ob);
392 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
393 && (y <= (rect.y + rect.height)))
399 keys = nodeHash.keys();
401 while (keys.hasMoreElements())
403 Object ob = keys.nextElement();
404 Rectangle rect = (Rectangle) nodeHash.get(ob);
406 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
407 && (y <= (rect.y + rect.height)))
422 public void pickNodes(Rectangle pickBox)
424 int width = getWidth();
425 int height = getHeight();
427 SequenceNode top = tree.getTopNode();
429 double wscale = ((width * .8) - (offx * 2)) / tree.getMaxHeight();
433 top.count = ((SequenceNode) top.left()).count
434 + ((SequenceNode) top.right()).count;
437 float chunk = (float) (height - (offy)) / top.count;
439 pickNode(pickBox, top, chunk, wscale, width, offx, offy);
460 public void pickNode(Rectangle pickBox, SequenceNode node, float chunk,
461 double wscale, int width, int offx, int offy)
468 if ((node.left() == null) && (node.right() == null))
470 double height = node.height;
471 double dist = node.dist;
473 int xstart = (int) ((height - dist) * wscale) + offx;
474 int xend = (int) (height * wscale) + offx;
476 int ypos = (int) (node.ycount * chunk) + offy;
478 if (pickBox.contains(new Point(xend, ypos)))
480 if (node.element() instanceof SequenceI)
482 SequenceI seq = (SequenceI) node.element();
483 SequenceGroup sg = av.getSelectionGroup();
487 sg.addOrRemove(seq, true);
494 pickNode(pickBox, (SequenceNode) node.left(), chunk, wscale, width,
496 pickNode(pickBox, (SequenceNode) node.right(), chunk, wscale, width,
509 public void setColor(SequenceNode node, Color c)
516 if ((node.left() == null) && (node.right() == null)) // TODO: internal node
520 if (node.element() instanceof SequenceI)
522 AlignmentPanel[] aps = getAssociatedPanels();
525 for (int a = 0; a < aps.length; a++)
527 final SequenceI seq = (SequenceI) node.element();
528 aps[a].av.setSequenceColour(seq, c);
536 setColor((SequenceNode) node.left(), c);
537 setColor((SequenceNode) node.right(), c);
546 Thread thread = new Thread(this);
550 // put printing in a thread to avoid painting problems
554 PrinterJob printJob = PrinterJob.getPrinterJob();
555 PageFormat defaultPage = printJob.defaultPage();
556 PageFormat pf = printJob.pageDialog(defaultPage);
558 if (defaultPage == pf)
566 printJob.setPrintable(this, pf);
568 if (printJob.printDialog())
573 } catch (Exception PrintException)
575 PrintException.printStackTrace();
590 * @return DOCUMENT ME!
592 * @throws PrinterException
596 public int print(Graphics pg, PageFormat pf, int pi)
597 throws PrinterException
600 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
602 int pwidth = (int) pf.getImageableWidth();
603 int pheight = (int) pf.getImageableHeight();
605 int noPages = getHeight() / pheight;
609 return Printable.NO_SUCH_PAGE;
612 if (pwidth > getWidth())
619 if (pheight > getHeight())
621 pheight = getHeight();
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);
633 // translate number of pages,
634 // height is screen size as this is the
635 // non overlapping text size
639 draw(pg, pwidth, pheight);
641 return Printable.PAGE_EXISTS;
651 public void paintComponent(Graphics g)
653 super.paintComponent(g);
659 MessageManager.getString("label.calculating_tree") + "....",
660 20, getHeight() / 2);
664 fm = g.getFontMetrics(font);
666 if (nameHash.size() == 0)
671 if (fitToWindow || (!fitToWindow && (scrollPane
672 .getHeight() > ((fm.getHeight() * nameHash.size()) + offy))))
674 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
675 setPreferredSize(null);
679 setPreferredSize(new Dimension(scrollPane.getWidth(),
680 fm.getHeight() * nameHash.size()));
681 draw(g, scrollPane.getWidth(), fm.getHeight() * nameHash.size());
684 scrollPane.revalidate();
695 public void setFont(Font font)
711 public void draw(Graphics g1, int width, int height)
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);
720 if (longestName == null || tree == null)
722 g2.drawString("Calculating tree.", 20, 20);
724 offy = font.getSize() + 10;
726 fm = g2.getFontMetrics(font);
728 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
730 double wscale = (width - labelLength - (offx * 2))
731 / tree.getMaxHeight();
733 SequenceNode top = tree.getTopNode();
737 top.count = ((SequenceNode) top.left()).count
738 + ((SequenceNode) top.right()).count;
741 float chunk = (float) (height - (offy)) / top.count;
743 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
747 if (av.getCurrentTree() == tree)
749 g2.setColor(Color.red);
753 g2.setColor(Color.gray);
756 int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx)))
759 g2.drawLine(x, 0, x, getHeight());
764 * Empty method to satisfy the MouseListener interface
769 public void mouseReleased(MouseEvent e)
772 * isPopupTrigger is set on mouseReleased on Windows
774 if (e.isPopupTrigger())
776 chooseSubtreeColour();
777 e.consume(); // prevent mouseClicked happening
782 * Empty method to satisfy the MouseListener interface
787 public void mouseEntered(MouseEvent e)
792 * Empty method to satisfy the MouseListener interface
797 public void mouseExited(MouseEvent e)
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.
809 public void mouseClicked(MouseEvent evt)
811 if (highlightNode == null)
816 if (evt.getClickCount() > 1)
818 tree.swapNodes(highlightNode);
819 tree.reCount(tree.getTopNode());
820 tree.findHeight(tree.getTopNode());
824 Vector<SequenceNode> leaves = tree.findLeaves(highlightNode);
826 for (int i = 0; i < leaves.size(); i++)
828 SequenceI seq = (SequenceI) leaves.elementAt(i).element();
829 treeSelectionChanged(seq);
834 PaintRefresher.Refresh(tp, av.getSequenceSetId());
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
843 void chooseSubtreeColour()
845 String ttl = MessageManager.getString("label.select_subtree_colour");
846 ColourChooserListener listener = new ColourChooserListener() {
848 public void colourSelected(Color c)
850 setColor(highlightNode, c);
851 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
855 JalviewColourChooser.showColourChooser(this, ttl, highlightNode.color, listener);
859 public void mouseMoved(MouseEvent evt)
861 av.setCurrentTree(tree);
863 Object ob = findElement(evt.getX(), evt.getY());
865 if (ob instanceof SequenceNode)
867 highlightNode = (SequenceNode) ob;
869 "<html>" + MessageManager.getString("label.highlightnode"));
875 if (highlightNode != null)
877 highlightNode = null;
878 setToolTipText(null);
885 public void mouseDragged(MouseEvent ect)
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.
898 public void mousePressed(MouseEvent e)
900 av.setCurrentTree(tree);
903 * isPopupTrigger is set for mousePressed (Mac)
904 * or mouseReleased (Windows)
906 if (e.isPopupTrigger())
908 if (highlightNode != null)
910 chooseSubtreeColour();
916 * defer right-click handling on Windows to
917 * mouseClicked; note isRightMouseButton
918 * also matches Cmd-click on Mac which should do
921 if (SwingUtilities.isRightMouseButton(e))
929 Object ob = findElement(x, y);
931 if (ob instanceof SequenceI)
933 treeSelectionChanged((Sequence) ob);
934 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
939 else if (!(ob instanceof SequenceNode))
942 if (tree.getMaxHeight() != 0)
944 threshold = (float) (x - offx)
945 / (float) (getWidth() - labelLength - (2 * offx));
947 List<SequenceNode> groups = tree.groupNodes(threshold);
948 setColor(tree.getTopNode(), Color.black);
950 AlignmentPanel[] aps = getAssociatedPanels();
952 // TODO push calls below into a single AlignViewportI method?
953 // see also AlignViewController.deleteGroups
954 for (int a = 0; a < aps.length; a++)
956 aps[a].av.setSelectionGroup(null);
957 aps[a].av.getAlignment().deleteAllGroups();
958 aps[a].av.clearSequenceColours();
959 if (aps[a].av.getCodingComplement() != null)
961 aps[a].av.getCodingComplement().setSelectionGroup(null);
962 aps[a].av.getCodingComplement().getAlignment()
964 aps[a].av.getCodingComplement().clearSequenceColours();
967 colourGroups(groups);
970 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
976 void colourGroups(List<SequenceNode> groups)
978 AlignmentPanel[] aps = getAssociatedPanels();
979 for (int i = 0; i < groups.size(); i++)
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());
985 Vector<SequenceNode> l = tree.findLeaves(groups.get(i));
987 Vector<SequenceI> sequences = new Vector<SequenceI>();
989 for (int j = 0; j < l.size(); j++)
991 SequenceI s1 = (SequenceI) l.elementAt(j).element();
993 if (!sequences.contains(s1))
995 sequences.addElement(s1);
999 ColourSchemeI cs = null;
1000 SequenceGroup sg = new SequenceGroup(sequences, null, cs, true, true,
1001 false, 0, av.getAlignment().getWidth() - 1);
1003 if (av.getGlobalColourScheme() != null)
1005 if (av.getGlobalColourScheme() instanceof UserColourScheme)
1007 cs = new UserColourScheme(
1008 ((UserColourScheme) av.getGlobalColourScheme())
1014 cs = ColourSchemeProperty.getColourScheme(sg, ColourSchemeProperty
1015 .getColourName(av.getGlobalColourScheme()));
1017 // cs is null if shading is an annotationColourGradient
1020 // cs.setThreshold(av.getViewportColourScheme().getThreshold(),
1021 // av.isIgnoreGapsConsensus());
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);
1032 for (int a = 0; a < aps.length; a++)
1034 if (aps[a].av.getGlobalColourScheme() != null
1035 && aps[a].av.getResidueShading().conservationApplied())
1037 Conservation c = new Conservation("Group", sg.getSequences(null),
1038 sg.getStartRes(), sg.getEndRes());
1040 c.verdict(false, aps[a].av.getConsPercGaps());
1041 sg.cs.setConservation(c);
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)
1050 SequenceGroup mappedGroup = MappingUtils.mapSequenceGroup(sg, av,
1052 if (mappedGroup.getSequences().size() > 0)
1054 codingComplement.getAlignment().addGroup(mappedGroup);
1055 for (SequenceI seq : mappedGroup.getSequences())
1057 codingComplement.setSequenceColour(seq, col.brighter());
1064 // notify the panel(s) to redo any group specific stuff.
1065 for (int a = 0; a < aps.length; a++)
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)
1074 ((AlignViewport) codingComplement).getAlignPanel()
1075 .updateAnnotation();
1086 public void setShowDistances(boolean state)
1088 this.showDistances = state;
1098 public void setShowBootstrap(boolean state)
1100 this.showBootstrap = state;
1110 public void setMarkPlaceholders(boolean state)
1112 this.markPlaceholders = state;
1116 AlignmentPanel[] getAssociatedPanels()
1118 if (applyToAllViews)
1120 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1124 return new AlignmentPanel[] { ap };