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.NJTree;
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.Vector;
58 import javax.swing.JColorChooser;
59 import javax.swing.JPanel;
60 import javax.swing.JScrollPane;
61 import javax.swing.SwingUtilities;
62 import javax.swing.ToolTipManager;
70 public class TreeCanvas extends JPanel implements MouseListener, Runnable,
71 Printable, MouseMotionListener, SelectionSource
74 public static final String PLACEHOLDER = " * ";
78 JScrollPane scrollPane;
90 boolean fitToWindow = true;
92 boolean showDistances = false;
94 boolean showBootstrap = false;
96 boolean markPlaceholders = false;
106 int labelLength = -1;
108 Hashtable nameHash = new Hashtable();
110 Hashtable nodeHash = new Hashtable();
112 SequenceNode highlightNode;
114 boolean applyToAllViews = false;
117 * Creates a new TreeCanvas object.
128 public TreeCanvas(TreePanel tp, AlignmentPanel ap, JScrollPane scroller)
134 scrollPane = scroller;
135 addMouseListener(this);
136 addMouseMotionListener(this);
137 ToolTipManager.sharedInstance().registerComponent(this);
146 public void treeSelectionChanged(SequenceI sequence)
148 AlignmentPanel[] aps = getAssociatedPanels();
150 for (int a = 0; a < aps.length; a++)
152 SequenceGroup selected = aps[a].av.getSelectionGroup();
154 if (selected == null)
156 selected = new SequenceGroup();
157 aps[a].av.setSelectionGroup(selected);
160 selected.setEndRes(aps[a].av.getAlignment().getWidth() - 1);
161 selected.addOrRemove(sequence, true);
171 public void setTree(NJTree tree)
174 tree.findHeight(tree.getTopNode());
176 // Now have to calculate longest name based on the leaves
177 Vector<SequenceNode> leaves = tree.findLeaves(tree.getTopNode());
178 boolean has_placeholders = false;
181 for (int i = 0; i < leaves.size(); i++)
183 SequenceNode lf = leaves.elementAt(i);
185 if (lf.isPlaceholder())
187 has_placeholders = true;
190 if (longestName.length() < ((Sequence) lf.element()).getName()
193 longestName = TreeCanvas.PLACEHOLDER
194 + ((Sequence) lf.element()).getName();
198 setMarkPlaceholders(has_placeholders);
219 public void drawNode(Graphics g, SequenceNode node, float chunk,
220 double wscale, int width, int offx, int offy)
227 if ((node.left() == null) && (node.right() == null))
230 double height = node.height;
231 double dist = node.dist;
233 int xstart = (int) ((height - dist) * wscale) + offx;
234 int xend = (int) (height * wscale) + offx;
236 int ypos = (int) (node.ycount * chunk) + offy;
238 if (node.element() instanceof SequenceI)
240 SequenceI seq = (SequenceI) node.element();
242 if (av.getSequenceColour(seq) == Color.white)
244 g.setColor(Color.black);
248 g.setColor(av.getSequenceColour(seq).darker());
253 g.setColor(Color.black);
256 // Draw horizontal line
257 g.drawLine(xstart, ypos, xend, ypos);
259 String nodeLabel = "";
261 if (showDistances && (node.dist > 0))
263 nodeLabel = new Format("%-.2f").form(node.dist);
266 if (showBootstrap && node.bootstrap > -1)
270 nodeLabel = nodeLabel + " : ";
273 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
276 if (!nodeLabel.equals(""))
278 g.drawString(nodeLabel, xstart + 2, ypos - 2);
281 String name = (markPlaceholders && node.isPlaceholder()) ? (PLACEHOLDER + node
282 .getName()) : node.getName();
284 int charWidth = fm.stringWidth(name) + 3;
285 int charHeight = font.getSize();
287 Rectangle rect = new Rectangle(xend + 10, ypos - charHeight / 2,
288 charWidth, charHeight);
290 nameHash.put(node.element(), rect);
292 // Colour selected leaves differently
293 SequenceGroup selected = av.getSelectionGroup();
295 if ((selected != null)
296 && selected.getSequences(null).contains(node.element()))
298 g.setColor(Color.gray);
300 g.fillRect(xend + 10, ypos - charHeight / 2, charWidth, charHeight);
301 g.setColor(Color.white);
304 g.drawString(name, xend + 10, ypos + fm.getDescent());
305 g.setColor(Color.black);
309 drawNode(g, (SequenceNode) node.left(), chunk, wscale, width, offx,
311 drawNode(g, (SequenceNode) node.right(), chunk, wscale, width, offx,
314 double height = node.height;
315 double dist = node.dist;
317 int xstart = (int) ((height - dist) * wscale) + offx;
318 int xend = (int) (height * wscale) + offx;
319 int ypos = (int) (node.ycount * chunk) + offy;
321 g.setColor(node.color.darker());
323 // Draw horizontal line
324 g.drawLine(xstart, ypos, xend, ypos);
325 if (node == highlightNode)
327 g.fillRect(xend - 3, ypos - 3, 6, 6);
331 g.fillRect(xend - 2, ypos - 2, 4, 4);
334 int ystart = (int) (((SequenceNode) node.left()).ycount * chunk)
336 int yend = (int) (((SequenceNode) node.right()).ycount * chunk)
339 Rectangle pos = new Rectangle(xend - 2, ypos - 2, 5, 5);
340 nodeHash.put(node, pos);
342 g.drawLine((int) (height * wscale) + offx, ystart,
343 (int) (height * wscale) + offx, yend);
345 String nodeLabel = "";
347 if (showDistances && (node.dist > 0))
349 nodeLabel = new Format("%-.2f").form(node.dist);
352 if (showBootstrap && node.bootstrap > -1)
356 nodeLabel = nodeLabel + " : ";
359 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
362 if (!nodeLabel.equals(""))
364 g.drawString(nodeLabel, xstart + 2, ypos - 2);
377 * @return DOCUMENT ME!
379 public Object findElement(int x, int y)
381 Enumeration keys = nameHash.keys();
383 while (keys.hasMoreElements())
385 Object ob = keys.nextElement();
386 Rectangle rect = (Rectangle) nameHash.get(ob);
388 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
389 && (y <= (rect.y + rect.height)))
395 keys = nodeHash.keys();
397 while (keys.hasMoreElements())
399 Object ob = keys.nextElement();
400 Rectangle rect = (Rectangle) nodeHash.get(ob);
402 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
403 && (y <= (rect.y + rect.height)))
418 public void pickNodes(Rectangle pickBox)
420 int width = getWidth();
421 int height = getHeight();
423 SequenceNode top = tree.getTopNode();
425 double wscale = ((width * .8) - (offx * 2))
426 / tree.getMaxHeight();
430 top.count = ((SequenceNode) top.left()).count
431 + ((SequenceNode) top.right()).count;
434 float chunk = (float) (height - (offy)) / top.count;
436 pickNode(pickBox, top, chunk, wscale, width, offx, offy);
457 public void pickNode(Rectangle pickBox, SequenceNode node, float chunk,
458 double wscale, int width, int offx, int offy)
465 if ((node.left() == null) && (node.right() == null))
467 double height = node.height;
468 double dist = node.dist;
470 int xstart = (int) ((height - dist) * wscale) + offx;
471 int xend = (int) (height * wscale) + offx;
473 int ypos = (int) (node.ycount * chunk) + offy;
475 if (pickBox.contains(new Point(xend, ypos)))
477 if (node.element() instanceof SequenceI)
479 SequenceI seq = (SequenceI) node.element();
480 SequenceGroup sg = av.getSelectionGroup();
484 sg.addOrRemove(seq, true);
491 pickNode(pickBox, (SequenceNode) node.left(), chunk, wscale, width,
493 pickNode(pickBox, (SequenceNode) node.right(), chunk, wscale, width,
506 public void setColor(SequenceNode node, Color c)
513 if ((node.left() == null) && (node.right() == null)) // TODO: internal node
517 if (node.element() instanceof SequenceI)
519 AlignmentPanel[] aps = getAssociatedPanels();
522 for (int a = 0; a < aps.length; a++)
524 final SequenceI seq = (SequenceI) node.element();
525 aps[a].av.setSequenceColour(seq, c);
533 setColor((SequenceNode) node.left(), c);
534 setColor((SequenceNode) node.right(), c);
543 Thread thread = new Thread(this);
547 // put printing in a thread to avoid painting problems
551 PrinterJob printJob = PrinterJob.getPrinterJob();
552 PageFormat pf = printJob.pageDialog(printJob.defaultPage());
554 printJob.setPrintable(this, pf);
556 if (printJob.printDialog())
561 } catch (Exception PrintException)
563 PrintException.printStackTrace();
578 * @return DOCUMENT ME!
580 * @throws PrinterException
584 public int print(Graphics pg, PageFormat pf, int pi)
585 throws PrinterException
588 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
590 int pwidth = (int) pf.getImageableWidth();
591 int pheight = (int) pf.getImageableHeight();
593 int noPages = getHeight() / pheight;
597 return Printable.NO_SUCH_PAGE;
600 if (pwidth > getWidth())
607 if (pheight > getHeight())
609 pheight = getHeight();
616 FontMetrics fm = pg.getFontMetrics(font);
617 int height = fm.getHeight() * nameHash.size();
618 pg.translate(0, -pi * pheight);
619 pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
621 // translate number of pages,
622 // height is screen size as this is the
623 // non overlapping text size
627 draw(pg, pwidth, pheight);
629 return Printable.PAGE_EXISTS;
639 public void paintComponent(Graphics g)
641 super.paintComponent(g);
646 g.drawString(MessageManager.getString("label.calculating_tree")
647 + "....", 20, getHeight() / 2);
651 fm = g.getFontMetrics(font);
653 if (nameHash.size() == 0)
659 || (!fitToWindow && (scrollPane.getHeight() > ((fm
660 .getHeight() * nameHash.size()) + offy))))
662 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
663 setPreferredSize(null);
667 setPreferredSize(new Dimension(scrollPane.getWidth(),
668 fm.getHeight() * nameHash.size()));
669 draw(g, scrollPane.getWidth(), fm.getHeight() * nameHash.size());
672 scrollPane.revalidate();
683 public void setFont(Font font)
699 public void draw(Graphics g1, int width, int height)
701 Graphics2D g2 = (Graphics2D) g1;
702 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
703 RenderingHints.VALUE_ANTIALIAS_ON);
704 g2.setColor(Color.white);
705 g2.fillRect(0, 0, width, height);
708 if (longestName == null || tree == null)
710 g2.drawString("Calculating tree.", 20, 20);
712 offy = font.getSize() + 10;
714 fm = g2.getFontMetrics(font);
716 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
718 double wscale = (width - labelLength - (offx * 2))
719 / tree.getMaxHeight();
721 SequenceNode top = tree.getTopNode();
725 top.count = ((SequenceNode) top.left()).count
726 + ((SequenceNode) top.right()).count;
729 float chunk = (float) (height - (offy)) / top.count;
731 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
735 if (av.getCurrentTree() == tree)
737 g2.setColor(Color.red);
741 g2.setColor(Color.gray);
744 int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx))) + offx);
746 g2.drawLine(x, 0, x, getHeight());
751 * Empty method to satisfy the MouseListener interface
756 public void mouseReleased(MouseEvent e)
759 * isPopupTrigger is set on mouseReleased on Windows
761 if (e.isPopupTrigger())
763 chooseSubtreeColour();
764 e.consume(); // prevent mouseClicked happening
769 * Empty method to satisfy the MouseListener interface
774 public void mouseEntered(MouseEvent e)
779 * Empty method to satisfy the MouseListener interface
784 public void mouseExited(MouseEvent e)
789 * Handles a mouse click on a tree node (clicks elsewhere are handled in
790 * mousePressed). Click selects the sub-tree, double-click swaps leaf nodes
791 * order, right-click opens a dialogue to choose colour for the sub-tree.
796 public void mouseClicked(MouseEvent evt)
798 if (highlightNode == null)
803 if (evt.getClickCount() > 1)
805 tree.swapNodes(highlightNode);
806 tree.reCount(tree.getTopNode());
807 tree.findHeight(tree.getTopNode());
811 Vector<SequenceNode> leaves = tree.findLeaves(highlightNode);
813 for (int i = 0; i < leaves.size(); i++)
815 SequenceI seq = (SequenceI) leaves.elementAt(i).element();
816 treeSelectionChanged(seq);
821 PaintRefresher.Refresh(tp, av.getSequenceSetId());
826 * Offer the user the option to choose a colour for the highlighted node and
827 * its children; this colour is also applied to the corresponding sequence ids
830 void chooseSubtreeColour()
832 Color col = JColorChooser.showDialog(this,
833 MessageManager.getString("label.select_subtree_colour"),
834 highlightNode.color);
837 setColor(highlightNode, col);
838 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
844 public void mouseMoved(MouseEvent evt)
846 av.setCurrentTree(tree);
848 Object ob = findElement(evt.getX(), evt.getY());
850 if (ob instanceof SequenceNode)
852 highlightNode = (SequenceNode) ob;
853 this.setToolTipText("<html>"
854 + MessageManager.getString("label.highlightnode"));
860 if (highlightNode != null)
862 highlightNode = null;
863 setToolTipText(null);
870 public void mouseDragged(MouseEvent ect)
875 * Handles a mouse press on a sequence name or the tree background canvas
876 * (click on a node is handled in mouseClicked). The action is to create
877 * groups by partitioning the tree at the mouse position. Colours for the
878 * groups (and sequence names) are generated randomly.
883 public void mousePressed(MouseEvent e)
885 av.setCurrentTree(tree);
888 * isPopupTrigger is set for mousePressed (Mac)
889 * or mouseReleased (Windows)
891 if (e.isPopupTrigger())
893 if (highlightNode != null)
895 chooseSubtreeColour();
901 * defer right-click handling on Windows to
902 * mouseClicked; note isRightMouseButton
903 * also matches Cmd-click on Mac which should do
906 if (SwingUtilities.isRightMouseButton(e))
914 Object ob = findElement(x, y);
916 if (ob instanceof SequenceI)
918 treeSelectionChanged((Sequence) ob);
919 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
924 else if (!(ob instanceof SequenceNode))
927 if (tree.getMaxHeight() != 0)
929 threshold = (float) (x - offx)
930 / (float) (getWidth() - labelLength - (2 * offx));
932 tree.getGroups().removeAllElements();
933 tree.groupNodes(tree.getTopNode(), threshold);
934 setColor(tree.getTopNode(), Color.black);
936 AlignmentPanel[] aps = getAssociatedPanels();
938 // TODO push calls below into a single AlignViewportI method?
939 // see also AlignViewController.deleteGroups
940 for (int a = 0; a < aps.length; a++)
942 aps[a].av.setSelectionGroup(null);
943 aps[a].av.getAlignment().deleteAllGroups();
944 aps[a].av.clearSequenceColours();
945 if (aps[a].av.getCodingComplement() != null)
947 aps[a].av.getCodingComplement().setSelectionGroup(null);
948 aps[a].av.getCodingComplement().getAlignment()
950 aps[a].av.getCodingComplement().clearSequenceColours();
956 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
964 AlignmentPanel[] aps = getAssociatedPanels();
965 for (int i = 0; i < tree.getGroups().size(); i++)
967 Color col = new Color((int) (Math.random() * 255),
968 (int) (Math.random() * 255), (int) (Math.random() * 255));
969 setColor(tree.getGroups().elementAt(i), col.brighter());
971 Vector<SequenceNode> l = tree.findLeaves(tree.getGroups()
974 Vector<SequenceI> sequences = new Vector<SequenceI>();
976 for (int j = 0; j < l.size(); j++)
978 SequenceI s1 = (SequenceI) l.elementAt(j).element();
980 if (!sequences.contains(s1))
982 sequences.addElement(s1);
986 ColourSchemeI cs = null;
987 SequenceGroup sg = new SequenceGroup(sequences, null, cs, true, true,
988 false, 0, av.getAlignment().getWidth() - 1);
990 if (av.getGlobalColourScheme() != null)
992 if (av.getGlobalColourScheme() instanceof UserColourScheme)
994 cs = new UserColourScheme(
995 ((UserColourScheme) av.getGlobalColourScheme())
1001 cs = ColourSchemeProperty.getColourScheme(sg,
1002 ColourSchemeProperty.getColourName(av
1003 .getGlobalColourScheme()));
1005 // cs is null if shading is an annotationColourGradient
1008 // cs.setThreshold(av.getViewportColourScheme().getThreshold(),
1009 // av.isIgnoreGapsConsensus());
1012 sg.setColourScheme(cs);
1013 sg.getGroupColourScheme().setThreshold(
1014 av.getResidueShading().getThreshold(),
1015 av.isIgnoreGapsConsensus());
1016 // sg.recalcConservation();
1017 sg.setName("JTreeGroup:" + sg.hashCode());
1018 sg.setIdColour(col);
1020 for (int a = 0; a < aps.length; a++)
1022 if (aps[a].av.getGlobalColourScheme() != null
1023 && aps[a].av.getResidueShading()
1024 .conservationApplied())
1026 Conservation c = new Conservation("Group", sg.getSequences(null),
1027 sg.getStartRes(), sg.getEndRes());
1029 c.verdict(false, aps[a].av.getConsPercGaps());
1030 sg.cs.setConservation(c);
1033 aps[a].av.getAlignment().addGroup(new SequenceGroup(sg));
1034 // TODO can we push all of the below into AlignViewportI?
1035 final AlignViewportI codingComplement = aps[a].av
1036 .getCodingComplement();
1037 if (codingComplement != null)
1039 SequenceGroup mappedGroup = MappingUtils.mapSequenceGroup(sg, av,
1041 if (mappedGroup.getSequences().size() > 0)
1043 codingComplement.getAlignment().addGroup(mappedGroup);
1044 for (SequenceI seq : mappedGroup.getSequences())
1046 codingComplement.setSequenceColour(seq, col.brighter());
1053 // notify the panel(s) to redo any group specific stuff.
1054 for (int a = 0; a < aps.length; a++)
1056 aps[a].updateAnnotation();
1057 // TODO: JAL-868 - need to ensure view colour change message is broadcast
1058 // to any Jmols listening in
1059 final AlignViewportI codingComplement = aps[a].av
1060 .getCodingComplement();
1061 if (codingComplement != null)
1063 ((AlignViewport) codingComplement).getAlignPanel()
1064 .updateAnnotation();
1075 public void setShowDistances(boolean state)
1077 this.showDistances = state;
1087 public void setShowBootstrap(boolean state)
1089 this.showBootstrap = state;
1099 public void setMarkPlaceholders(boolean state)
1101 this.markPlaceholders = state;
1105 AlignmentPanel[] getAssociatedPanels()
1107 if (applyToAllViews)
1109 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1113 return new AlignmentPanel[] { ap };