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 float scale, int width, int offx, int offy)
227 if ((node.left() == null) && (node.right() == null))
230 float height = node.height;
231 float dist = node.dist;
233 int xstart = (int) ((height - dist) * scale) + offx;
234 int xend = (int) (height * scale) + 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, scale, width, offx,
311 drawNode(g, (SequenceNode) node.right(), chunk, scale, width, offx,
314 float height = node.height;
315 float dist = node.dist;
317 int xstart = (int) ((height - dist) * scale) + offx;
318 int xend = (int) (height * scale) + 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 * scale) + offx, ystart,
343 (int) (height * scale) + 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 float wscale = (float) ((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 float scale, int width, int offx, int offy)
465 if ((node.left() == null) && (node.right() == null))
467 float height = node.height;
468 float dist = node.dist;
470 int xstart = (int) ((height - dist) * scale) + offx;
471 int xend = (int) (height * scale) + 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, scale, width,
493 pickNode(pickBox, (SequenceNode) node.right(), chunk, scale, 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 float wscale = (width - labelLength - (offx * 2)) / tree.getMaxHeight();
720 SequenceNode top = tree.getTopNode();
724 top.count = ((SequenceNode) top.left()).count
725 + ((SequenceNode) top.right()).count;
728 float chunk = (float) (height - (offy)) / top.count;
730 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
734 if (av.getCurrentTree() == tree)
736 g2.setColor(Color.red);
740 g2.setColor(Color.gray);
743 int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx))) + offx);
745 g2.drawLine(x, 0, x, getHeight());
750 * Empty method to satisfy the MouseListener interface
755 public void mouseReleased(MouseEvent e)
758 * isPopupTrigger is set on mouseReleased on Windows
760 if (e.isPopupTrigger())
762 chooseSubtreeColour();
763 e.consume(); // prevent mouseClicked happening
768 * Empty method to satisfy the MouseListener interface
773 public void mouseEntered(MouseEvent e)
778 * Empty method to satisfy the MouseListener interface
783 public void mouseExited(MouseEvent e)
788 * Handles a mouse click on a tree node (clicks elsewhere are handled in
789 * mousePressed). Click selects the sub-tree, double-click swaps leaf nodes
790 * order, right-click opens a dialogue to choose colour for the sub-tree.
795 public void mouseClicked(MouseEvent evt)
797 if (highlightNode == null)
802 if (evt.getClickCount() > 1)
804 tree.swapNodes(highlightNode);
805 tree.reCount(tree.getTopNode());
806 tree.findHeight(tree.getTopNode());
810 Vector<SequenceNode> leaves = tree.findLeaves(highlightNode);
812 for (int i = 0; i < leaves.size(); i++)
814 SequenceI seq = (SequenceI) leaves.elementAt(i).element();
815 treeSelectionChanged(seq);
820 PaintRefresher.Refresh(tp, av.getSequenceSetId());
825 * Offer the user the option to choose a colour for the highlighted node and
826 * its children; this colour is also applied to the corresponding sequence ids
829 void chooseSubtreeColour()
831 Color col = JColorChooser.showDialog(this,
832 MessageManager.getString("label.select_subtree_colour"),
833 highlightNode.color);
836 setColor(highlightNode, col);
837 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
843 public void mouseMoved(MouseEvent evt)
845 av.setCurrentTree(tree);
847 Object ob = findElement(evt.getX(), evt.getY());
849 if (ob instanceof SequenceNode)
851 highlightNode = (SequenceNode) ob;
852 this.setToolTipText("<html>"
853 + MessageManager.getString("label.highlightnode"));
859 if (highlightNode != null)
861 highlightNode = null;
862 setToolTipText(null);
869 public void mouseDragged(MouseEvent ect)
874 * Handles a mouse press on a sequence name or the tree background canvas
875 * (click on a node is handled in mouseClicked). The action is to create
876 * groups by partitioning the tree at the mouse position. Colours for the
877 * groups (and sequence names) are generated randomly.
882 public void mousePressed(MouseEvent e)
884 av.setCurrentTree(tree);
887 * isPopupTrigger is set for mousePressed (Mac)
888 * or mouseReleased (Windows)
890 if (e.isPopupTrigger())
892 if (highlightNode != null)
894 chooseSubtreeColour();
900 * defer right-click handling on Windows to
901 * mouseClicked; note isRightMouseButton
902 * also matches Cmd-click on Mac which should do
905 if (SwingUtilities.isRightMouseButton(e))
913 Object ob = findElement(x, y);
915 if (ob instanceof SequenceI)
917 treeSelectionChanged((Sequence) ob);
918 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
923 else if (!(ob instanceof SequenceNode))
926 if (tree.getMaxHeight() != 0)
928 threshold = (float) (x - offx)
929 / (float) (getWidth() - labelLength - (2 * offx));
931 tree.getGroups().removeAllElements();
932 tree.groupNodes(tree.getTopNode(), threshold);
933 setColor(tree.getTopNode(), Color.black);
935 AlignmentPanel[] aps = getAssociatedPanels();
937 // TODO push calls below into a single AlignViewportI method?
938 // see also AlignViewController.deleteGroups
939 for (int a = 0; a < aps.length; a++)
941 aps[a].av.setSelectionGroup(null);
942 aps[a].av.getAlignment().deleteAllGroups();
943 aps[a].av.clearSequenceColours();
944 if (aps[a].av.getCodingComplement() != null)
946 aps[a].av.getCodingComplement().setSelectionGroup(null);
947 aps[a].av.getCodingComplement().getAlignment()
949 aps[a].av.getCodingComplement().clearSequenceColours();
955 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
963 AlignmentPanel[] aps = getAssociatedPanels();
964 for (int i = 0; i < tree.getGroups().size(); i++)
966 Color col = new Color((int) (Math.random() * 255),
967 (int) (Math.random() * 255), (int) (Math.random() * 255));
968 setColor(tree.getGroups().elementAt(i), col.brighter());
970 Vector<SequenceNode> l = tree.findLeaves(tree.getGroups()
973 Vector<SequenceI> sequences = new Vector<SequenceI>();
975 for (int j = 0; j < l.size(); j++)
977 SequenceI s1 = (SequenceI) l.elementAt(j).element();
979 if (!sequences.contains(s1))
981 sequences.addElement(s1);
985 ColourSchemeI cs = null;
986 SequenceGroup sg = new SequenceGroup(sequences, null, cs, true, true,
987 false, 0, av.getAlignment().getWidth() - 1);
989 if (av.getGlobalColourScheme() != null)
991 if (av.getGlobalColourScheme() instanceof UserColourScheme)
993 cs = new UserColourScheme(
994 ((UserColourScheme) av.getGlobalColourScheme())
1000 cs = ColourSchemeProperty.getColourScheme(sg,
1001 ColourSchemeProperty.getColourName(av
1002 .getGlobalColourScheme()));
1004 // cs is null if shading is an annotationColourGradient
1007 // cs.setThreshold(av.getViewportColourScheme().getThreshold(),
1008 // av.isIgnoreGapsConsensus());
1011 sg.setColourScheme(cs);
1012 sg.getGroupColourScheme().setThreshold(
1013 av.getResidueShading().getThreshold(),
1014 av.isIgnoreGapsConsensus());
1015 // sg.recalcConservation();
1016 sg.setName("JTreeGroup:" + sg.hashCode());
1017 sg.setIdColour(col);
1019 for (int a = 0; a < aps.length; a++)
1021 if (aps[a].av.getGlobalColourScheme() != null
1022 && aps[a].av.getResidueShading()
1023 .conservationApplied())
1025 Conservation c = new Conservation("Group", sg.getSequences(null),
1026 sg.getStartRes(), sg.getEndRes());
1028 c.verdict(false, aps[a].av.getConsPercGaps());
1029 sg.cs.setConservation(c);
1032 aps[a].av.getAlignment().addGroup(new SequenceGroup(sg));
1033 // TODO can we push all of the below into AlignViewportI?
1034 final AlignViewportI codingComplement = aps[a].av
1035 .getCodingComplement();
1036 if (codingComplement != null)
1038 SequenceGroup mappedGroup = MappingUtils.mapSequenceGroup(sg, av,
1040 if (mappedGroup.getSequences().size() > 0)
1042 codingComplement.getAlignment().addGroup(mappedGroup);
1043 for (SequenceI seq : mappedGroup.getSequences())
1045 codingComplement.setSequenceColour(seq, col.brighter());
1052 // notify the panel(s) to redo any group specific stuff.
1053 for (int a = 0; a < aps.length; a++)
1055 aps[a].updateAnnotation();
1056 // TODO: JAL-868 - need to ensure view colour change message is broadcast
1057 // to any Jmols listening in
1058 final AlignViewportI codingComplement = aps[a].av
1059 .getCodingComplement();
1060 if (codingComplement != null)
1062 ((AlignViewport) codingComplement).getAlignPanel()
1063 .updateAnnotation();
1074 public void setShowDistances(boolean state)
1076 this.showDistances = state;
1086 public void setShowBootstrap(boolean state)
1088 this.showBootstrap = state;
1098 public void setMarkPlaceholders(boolean state)
1100 this.markPlaceholders = state;
1104 AlignmentPanel[] getAssociatedPanels()
1106 if (applyToAllViews)
1108 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1112 return new AlignmentPanel[] { ap };