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.schemes.ColourSchemeI;
31 import jalview.schemes.ColourSchemeProperty;
32 import jalview.schemes.UserColourScheme;
33 import jalview.structure.SelectionSource;
34 import jalview.util.Format;
35 import jalview.util.MappingUtils;
36 import jalview.util.MessageManager;
38 import java.awt.Color;
39 import java.awt.Dimension;
41 import java.awt.FontMetrics;
42 import java.awt.Graphics;
43 import java.awt.Graphics2D;
44 import java.awt.Point;
45 import java.awt.Rectangle;
46 import java.awt.RenderingHints;
47 import java.awt.event.MouseEvent;
48 import java.awt.event.MouseListener;
49 import java.awt.event.MouseMotionListener;
50 import java.awt.print.PageFormat;
51 import java.awt.print.Printable;
52 import java.awt.print.PrinterException;
53 import java.awt.print.PrinterJob;
54 import java.util.Enumeration;
55 import java.util.Hashtable;
56 import java.util.List;
57 import java.util.Vector;
59 import javax.swing.JColorChooser;
60 import javax.swing.JPanel;
61 import javax.swing.JScrollPane;
62 import javax.swing.SwingUtilities;
63 import javax.swing.ToolTipManager;
71 public class TreeCanvas extends JPanel implements MouseListener, Runnable,
72 Printable, MouseMotionListener, SelectionSource
75 public static final String PLACEHOLDER = " * ";
79 JScrollPane scrollPane;
91 boolean fitToWindow = true;
93 boolean showDistances = false;
95 boolean showBootstrap = false;
97 boolean markPlaceholders = false;
107 int labelLength = -1;
109 Hashtable nameHash = new Hashtable();
111 Hashtable nodeHash = new Hashtable();
113 SequenceNode highlightNode;
115 boolean applyToAllViews = false;
118 * Creates a new TreeCanvas object.
129 public TreeCanvas(TreePanel tp, AlignmentPanel ap, JScrollPane scroller)
135 scrollPane = scroller;
136 addMouseListener(this);
137 addMouseMotionListener(this);
138 ToolTipManager.sharedInstance().registerComponent(this);
147 public void treeSelectionChanged(SequenceI sequence)
149 AlignmentPanel[] aps = getAssociatedPanels();
151 for (int a = 0; a < aps.length; a++)
153 SequenceGroup selected = aps[a].av.getSelectionGroup();
155 if (selected == null)
157 selected = new SequenceGroup();
158 aps[a].av.setSelectionGroup(selected);
161 selected.setEndRes(aps[a].av.getAlignment().getWidth() - 1);
162 selected.addOrRemove(sequence, true);
172 public void setTree(TreeModel tree)
175 tree.findHeight(tree.getTopNode());
177 // Now have to calculate longest name based on the leaves
178 Vector<SequenceNode> leaves = tree.findLeaves(tree.getTopNode());
179 boolean has_placeholders = false;
182 for (int i = 0; i < leaves.size(); i++)
184 SequenceNode lf = leaves.elementAt(i);
186 if (lf.isPlaceholder())
188 has_placeholders = true;
191 if (longestName.length() < ((Sequence) lf.element()).getName()
194 longestName = TreeCanvas.PLACEHOLDER
195 + ((Sequence) lf.element()).getName();
199 setMarkPlaceholders(has_placeholders);
220 public void drawNode(Graphics g, SequenceNode node, float chunk,
221 double wscale, int width, int offx, int offy)
228 if ((node.left() == null) && (node.right() == null))
231 double height = node.height;
232 double dist = node.dist;
234 int xstart = (int) ((height - dist) * wscale) + offx;
235 int xend = (int) (height * wscale) + offx;
237 int ypos = (int) (node.ycount * chunk) + offy;
239 if (node.element() instanceof SequenceI)
241 SequenceI seq = (SequenceI) node.element();
243 if (av.getSequenceColour(seq) == Color.white)
245 g.setColor(Color.black);
249 g.setColor(av.getSequenceColour(seq).darker());
254 g.setColor(Color.black);
257 // Draw horizontal line
258 g.drawLine(xstart, ypos, xend, ypos);
260 String nodeLabel = "";
262 if (showDistances && (node.dist > 0))
264 nodeLabel = new Format("%-.2f").form(node.dist);
267 if (showBootstrap && node.bootstrap > -1)
271 nodeLabel = nodeLabel + " : ";
274 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
277 if (!nodeLabel.equals(""))
279 g.drawString(nodeLabel, xstart + 2, ypos - 2);
282 String name = (markPlaceholders && node.isPlaceholder())
283 ? (PLACEHOLDER + node.getName())
286 int charWidth = fm.stringWidth(name) + 3;
287 int charHeight = font.getSize();
289 Rectangle rect = new Rectangle(xend + 10, ypos - charHeight / 2,
290 charWidth, charHeight);
292 nameHash.put(node.element(), rect);
294 // Colour selected leaves differently
295 SequenceGroup selected = av.getSelectionGroup();
297 if ((selected != null)
298 && selected.getSequences(null).contains(node.element()))
300 g.setColor(Color.gray);
302 g.fillRect(xend + 10, ypos - charHeight / 2, charWidth, charHeight);
303 g.setColor(Color.white);
306 g.drawString(name, xend + 10, ypos + fm.getDescent());
307 g.setColor(Color.black);
311 drawNode(g, (SequenceNode) node.left(), chunk, wscale, width, offx,
313 drawNode(g, (SequenceNode) node.right(), chunk, wscale, width, offx,
316 double height = node.height;
317 double dist = node.dist;
319 int xstart = (int) ((height - dist) * wscale) + offx;
320 int xend = (int) (height * wscale) + offx;
321 int ypos = (int) (node.ycount * chunk) + offy;
323 g.setColor(node.color.darker());
325 // Draw horizontal line
326 g.drawLine(xstart, ypos, xend, ypos);
327 if (node == highlightNode)
329 g.fillRect(xend - 3, ypos - 3, 6, 6);
333 g.fillRect(xend - 2, ypos - 2, 4, 4);
336 int ystart = (node.left() == null ? 0
337 : (int) (((SequenceNode) node.left()).ycount * chunk)) + offy;
338 int yend = (node.right() == null ? 0
339 : (int) (((SequenceNode) node.right()).ycount * chunk))
342 Rectangle pos = new Rectangle(xend - 2, ypos - 2, 5, 5);
343 nodeHash.put(node, pos);
345 g.drawLine((int) (height * wscale) + offx, ystart,
346 (int) (height * wscale) + offx, yend);
348 String nodeLabel = "";
350 if (showDistances && (node.dist > 0))
352 nodeLabel = new Format("%-.2f").form(node.dist);
355 if (showBootstrap && node.bootstrap > -1)
359 nodeLabel = nodeLabel + " : ";
362 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
365 if (!nodeLabel.equals(""))
367 g.drawString(nodeLabel, xstart + 2, ypos - 2);
380 * @return DOCUMENT ME!
382 public Object findElement(int x, int y)
384 Enumeration keys = nameHash.keys();
386 while (keys.hasMoreElements())
388 Object ob = keys.nextElement();
389 Rectangle rect = (Rectangle) nameHash.get(ob);
391 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
392 && (y <= (rect.y + rect.height)))
398 keys = nodeHash.keys();
400 while (keys.hasMoreElements())
402 Object ob = keys.nextElement();
403 Rectangle rect = (Rectangle) nodeHash.get(ob);
405 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
406 && (y <= (rect.y + rect.height)))
421 public void pickNodes(Rectangle pickBox)
423 int width = getWidth();
424 int height = getHeight();
426 SequenceNode top = tree.getTopNode();
428 double wscale = ((width * .8) - (offx * 2)) / tree.getMaxHeight();
432 top.count = ((SequenceNode) top.left()).count
433 + ((SequenceNode) top.right()).count;
436 float chunk = (float) (height - (offy)) / top.count;
438 pickNode(pickBox, top, chunk, wscale, width, offx, offy);
459 public void pickNode(Rectangle pickBox, SequenceNode node, float chunk,
460 double wscale, int width, int offx, int offy)
467 if ((node.left() == null) && (node.right() == null))
469 double height = node.height;
470 double dist = node.dist;
472 int xstart = (int) ((height - dist) * wscale) + offx;
473 int xend = (int) (height * wscale) + offx;
475 int ypos = (int) (node.ycount * chunk) + offy;
477 if (pickBox.contains(new Point(xend, ypos)))
479 if (node.element() instanceof SequenceI)
481 SequenceI seq = (SequenceI) node.element();
482 SequenceGroup sg = av.getSelectionGroup();
486 sg.addOrRemove(seq, true);
493 pickNode(pickBox, (SequenceNode) node.left(), chunk, wscale, width,
495 pickNode(pickBox, (SequenceNode) node.right(), chunk, wscale, width,
508 public void setColor(SequenceNode node, Color c)
515 if ((node.left() == null) && (node.right() == null)) // TODO: internal node
519 if (node.element() instanceof SequenceI)
521 AlignmentPanel[] aps = getAssociatedPanels();
524 for (int a = 0; a < aps.length; a++)
526 final SequenceI seq = (SequenceI) node.element();
527 aps[a].av.setSequenceColour(seq, c);
535 setColor((SequenceNode) node.left(), c);
536 setColor((SequenceNode) node.right(), c);
545 Thread thread = new Thread(this);
549 // put printing in a thread to avoid painting problems
553 PrinterJob printJob = PrinterJob.getPrinterJob();
554 PageFormat defaultPage = printJob.defaultPage();
555 PageFormat pf = printJob.pageDialog(defaultPage);
557 if (defaultPage == pf)
565 printJob.setPrintable(this, pf);
567 if (printJob.printDialog())
572 } catch (Exception PrintException)
574 PrintException.printStackTrace();
589 * @return DOCUMENT ME!
591 * @throws PrinterException
595 public int print(Graphics pg, PageFormat pf, int pi)
596 throws PrinterException
599 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
601 int pwidth = (int) pf.getImageableWidth();
602 int pheight = (int) pf.getImageableHeight();
604 int noPages = getHeight() / pheight;
608 return Printable.NO_SUCH_PAGE;
611 if (pwidth > getWidth())
618 if (pheight > getHeight())
620 pheight = getHeight();
627 FontMetrics fm = pg.getFontMetrics(font);
628 int height = fm.getHeight() * nameHash.size();
629 pg.translate(0, -pi * pheight);
630 pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
632 // translate number of pages,
633 // height is screen size as this is the
634 // non overlapping text size
638 draw(pg, pwidth, pheight);
640 return Printable.PAGE_EXISTS;
650 public void paintComponent(Graphics g)
652 super.paintComponent(g);
658 MessageManager.getString("label.calculating_tree") + "....",
659 20, getHeight() / 2);
663 fm = g.getFontMetrics(font);
665 if (nameHash.size() == 0)
670 if (fitToWindow || (!fitToWindow && (scrollPane
671 .getHeight() > ((fm.getHeight() * nameHash.size()) + offy))))
673 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
674 setPreferredSize(null);
678 setPreferredSize(new Dimension(scrollPane.getWidth(),
679 fm.getHeight() * nameHash.size()));
680 draw(g, scrollPane.getWidth(), fm.getHeight() * nameHash.size());
683 scrollPane.revalidate();
694 public void setFont(Font font)
710 public void draw(Graphics g1, int width, int height)
712 Graphics2D g2 = (Graphics2D) g1;
713 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
714 RenderingHints.VALUE_ANTIALIAS_ON);
715 g2.setColor(Color.white);
716 g2.fillRect(0, 0, width, height);
719 if (longestName == null || tree == null)
721 g2.drawString("Calculating tree.", 20, 20);
723 offy = font.getSize() + 10;
725 fm = g2.getFontMetrics(font);
727 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
729 double wscale = (width - labelLength - (offx * 2))
730 / tree.getMaxHeight();
732 SequenceNode top = tree.getTopNode();
736 top.count = ((SequenceNode) top.left()).count
737 + ((SequenceNode) top.right()).count;
740 float chunk = (float) (height - (offy)) / top.count;
742 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
746 if (av.getCurrentTree() == tree)
748 g2.setColor(Color.red);
752 g2.setColor(Color.gray);
755 int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx)))
758 g2.drawLine(x, 0, x, getHeight());
763 * Empty method to satisfy the MouseListener interface
768 public void mouseReleased(MouseEvent e)
771 * isPopupTrigger is set on mouseReleased on Windows
773 if (e.isPopupTrigger())
775 chooseSubtreeColour();
776 e.consume(); // prevent mouseClicked happening
781 * Empty method to satisfy the MouseListener interface
786 public void mouseEntered(MouseEvent e)
791 * Empty method to satisfy the MouseListener interface
796 public void mouseExited(MouseEvent e)
801 * Handles a mouse click on a tree node (clicks elsewhere are handled in
802 * mousePressed). Click selects the sub-tree, double-click swaps leaf nodes
803 * order, right-click opens a dialogue to choose colour for the sub-tree.
808 public void mouseClicked(MouseEvent evt)
810 if (highlightNode == null)
815 if (evt.getClickCount() > 1)
817 tree.swapNodes(highlightNode);
818 tree.reCount(tree.getTopNode());
819 tree.findHeight(tree.getTopNode());
823 Vector<SequenceNode> leaves = tree.findLeaves(highlightNode);
825 for (int i = 0; i < leaves.size(); i++)
827 SequenceI seq = (SequenceI) leaves.elementAt(i).element();
828 treeSelectionChanged(seq);
833 PaintRefresher.Refresh(tp, av.getSequenceSetId());
838 * Offer the user the option to choose a colour for the highlighted node and
839 * its children; this colour is also applied to the corresponding sequence ids
842 void chooseSubtreeColour()
844 Color col = JColorChooser.showDialog(this,
845 MessageManager.getString("label.select_subtree_colour"),
846 highlightNode.color);
849 setColor(highlightNode, col);
850 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
856 public void mouseMoved(MouseEvent evt)
858 av.setCurrentTree(tree);
860 Object ob = findElement(evt.getX(), evt.getY());
862 if (ob instanceof SequenceNode)
864 highlightNode = (SequenceNode) ob;
866 "<html>" + MessageManager.getString("label.highlightnode"));
872 if (highlightNode != null)
874 highlightNode = null;
875 setToolTipText(null);
882 public void mouseDragged(MouseEvent ect)
887 * Handles a mouse press on a sequence name or the tree background canvas
888 * (click on a node is handled in mouseClicked). The action is to create
889 * groups by partitioning the tree at the mouse position. Colours for the
890 * groups (and sequence names) are generated randomly.
895 public void mousePressed(MouseEvent e)
897 av.setCurrentTree(tree);
900 * isPopupTrigger is set for mousePressed (Mac)
901 * or mouseReleased (Windows)
903 if (e.isPopupTrigger())
905 if (highlightNode != null)
907 chooseSubtreeColour();
913 * defer right-click handling on Windows to
914 * mouseClicked; note isRightMouseButton
915 * also matches Cmd-click on Mac which should do
918 if (SwingUtilities.isRightMouseButton(e))
926 Object ob = findElement(x, y);
928 if (ob instanceof SequenceI)
930 treeSelectionChanged((Sequence) ob);
931 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
936 else if (!(ob instanceof SequenceNode))
939 if (tree.getMaxHeight() != 0)
941 threshold = (float) (x - offx)
942 / (float) (getWidth() - labelLength - (2 * offx));
944 List<SequenceNode> groups = tree.groupNodes(threshold);
945 setColor(tree.getTopNode(), Color.black);
947 AlignmentPanel[] aps = getAssociatedPanels();
949 // TODO push calls below into a single AlignViewportI method?
950 // see also AlignViewController.deleteGroups
951 for (int a = 0; a < aps.length; a++)
953 aps[a].av.setSelectionGroup(null);
954 aps[a].av.getAlignment().deleteAllGroups();
955 aps[a].av.clearSequenceColours();
956 if (aps[a].av.getCodingComplement() != null)
958 aps[a].av.getCodingComplement().setSelectionGroup(null);
959 aps[a].av.getCodingComplement().getAlignment()
961 aps[a].av.getCodingComplement().clearSequenceColours();
964 colourGroups(groups);
967 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
973 void colourGroups(List<SequenceNode> groups)
975 AlignmentPanel[] aps = getAssociatedPanels();
976 for (int i = 0; i < groups.size(); i++)
978 Color col = new Color((int) (Math.random() * 255),
979 (int) (Math.random() * 255), (int) (Math.random() * 255));
980 setColor(groups.get(i), col.brighter());
982 Vector<SequenceNode> l = tree.findLeaves(groups.get(i));
984 Vector<SequenceI> sequences = new Vector<SequenceI>();
986 for (int j = 0; j < l.size(); j++)
988 SequenceI s1 = (SequenceI) l.elementAt(j).element();
990 if (!sequences.contains(s1))
992 sequences.addElement(s1);
996 ColourSchemeI cs = null;
997 SequenceGroup sg = new SequenceGroup(sequences, null, cs, true, true,
998 false, 0, av.getAlignment().getWidth() - 1);
1000 if (av.getGlobalColourScheme() != null)
1002 if (av.getGlobalColourScheme() instanceof UserColourScheme)
1004 cs = new UserColourScheme(
1005 ((UserColourScheme) av.getGlobalColourScheme())
1011 cs = ColourSchemeProperty.getColourScheme(sg, ColourSchemeProperty
1012 .getColourName(av.getGlobalColourScheme()));
1014 // cs is null if shading is an annotationColourGradient
1017 // cs.setThreshold(av.getViewportColourScheme().getThreshold(),
1018 // av.isIgnoreGapsConsensus());
1021 sg.setColourScheme(cs);
1022 sg.getGroupColourScheme().setThreshold(
1023 av.getResidueShading().getThreshold(),
1024 av.isIgnoreGapsConsensus());
1025 // sg.recalcConservation();
1026 sg.setName("JTreeGroup:" + sg.hashCode());
1027 sg.setIdColour(col);
1029 for (int a = 0; a < aps.length; a++)
1031 if (aps[a].av.getGlobalColourScheme() != null
1032 && aps[a].av.getResidueShading().conservationApplied())
1034 Conservation c = new Conservation("Group", sg.getSequences(null),
1035 sg.getStartRes(), sg.getEndRes());
1037 c.verdict(false, aps[a].av.getConsPercGaps());
1038 sg.cs.setConservation(c);
1041 aps[a].av.getAlignment().addGroup(new SequenceGroup(sg));
1042 // TODO can we push all of the below into AlignViewportI?
1043 final AlignViewportI codingComplement = aps[a].av
1044 .getCodingComplement();
1045 if (codingComplement != null)
1047 SequenceGroup mappedGroup = MappingUtils.mapSequenceGroup(sg, av,
1049 if (mappedGroup.getSequences().size() > 0)
1051 codingComplement.getAlignment().addGroup(mappedGroup);
1052 for (SequenceI seq : mappedGroup.getSequences())
1054 codingComplement.setSequenceColour(seq, col.brighter());
1061 // notify the panel(s) to redo any group specific stuff.
1062 for (int a = 0; a < aps.length; a++)
1064 aps[a].updateAnnotation();
1065 // TODO: JAL-868 - need to ensure view colour change message is broadcast
1066 // to any Jmols listening in
1067 final AlignViewportI codingComplement = aps[a].av
1068 .getCodingComplement();
1069 if (codingComplement != null)
1071 ((AlignViewport) codingComplement).getAlignPanel()
1072 .updateAnnotation();
1083 public void setShowDistances(boolean state)
1085 this.showDistances = state;
1095 public void setShowBootstrap(boolean state)
1097 this.showBootstrap = state;
1107 public void setMarkPlaceholders(boolean state)
1109 this.markPlaceholders = state;
1113 AlignmentPanel[] getAssociatedPanels()
1115 if (applyToAllViews)
1117 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1121 return new AlignmentPanel[] { ap };