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.ResidueProperties;
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.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(NJTree 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 float scale, int width, int offx, int offy)
228 if ((node.left() == null) && (node.right() == null))
231 float height = node.height;
232 float dist = node.dist;
234 int xstart = (int) ((height - dist) * scale) + offx;
235 int xend = (int) (height * scale) + 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()) ? (PLACEHOLDER + node
283 .getName()) : node.getName();
285 int charWidth = fm.stringWidth(name) + 3;
286 int charHeight = font.getSize();
288 Rectangle rect = new Rectangle(xend + 10, ypos - charHeight / 2,
289 charWidth, charHeight);
291 nameHash.put(node.element(), rect);
293 // Colour selected leaves differently
294 SequenceGroup selected = av.getSelectionGroup();
296 if ((selected != null)
297 && selected.getSequences(null).contains(node.element()))
299 g.setColor(Color.gray);
301 g.fillRect(xend + 10, ypos - charHeight / 2, charWidth, charHeight);
302 g.setColor(Color.white);
305 g.drawString(name, xend + 10, ypos + fm.getDescent());
306 g.setColor(Color.black);
310 drawNode(g, (SequenceNode) node.left(), chunk, scale, width, offx,
312 drawNode(g, (SequenceNode) node.right(), chunk, scale, width, offx,
315 float height = node.height;
316 float dist = node.dist;
318 int xstart = (int) ((height - dist) * scale) + offx;
319 int xend = (int) (height * scale) + offx;
320 int ypos = (int) (node.ycount * chunk) + offy;
322 g.setColor(node.color.darker());
324 // Draw horizontal line
325 g.drawLine(xstart, ypos, xend, ypos);
326 if (node == highlightNode)
328 g.fillRect(xend - 3, ypos - 3, 6, 6);
332 g.fillRect(xend - 2, ypos - 2, 4, 4);
335 int ystart = (int) (((SequenceNode) node.left()).ycount * chunk)
337 int yend = (int) (((SequenceNode) node.right()).ycount * chunk)
340 Rectangle pos = new Rectangle(xend - 2, ypos - 2, 5, 5);
341 nodeHash.put(node, pos);
343 g.drawLine((int) (height * scale) + offx, ystart,
344 (int) (height * scale) + offx, yend);
346 String nodeLabel = "";
348 if (showDistances && (node.dist > 0))
350 nodeLabel = new Format("%-.2f").form(node.dist);
353 if (showBootstrap && node.bootstrap > -1)
357 nodeLabel = nodeLabel + " : ";
360 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
363 if (!nodeLabel.equals(""))
365 g.drawString(nodeLabel, xstart + 2, ypos - 2);
378 * @return DOCUMENT ME!
380 public Object findElement(int x, int y)
382 Enumeration keys = nameHash.keys();
384 while (keys.hasMoreElements())
386 Object ob = keys.nextElement();
387 Rectangle rect = (Rectangle) nameHash.get(ob);
389 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
390 && (y <= (rect.y + rect.height)))
396 keys = nodeHash.keys();
398 while (keys.hasMoreElements())
400 Object ob = keys.nextElement();
401 Rectangle rect = (Rectangle) nodeHash.get(ob);
403 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
404 && (y <= (rect.y + rect.height)))
419 public void pickNodes(Rectangle pickBox)
421 int width = getWidth();
422 int height = getHeight();
424 SequenceNode top = tree.getTopNode();
426 float wscale = (float) ((width * .8) - (offx * 2))
427 / tree.getMaxHeight();
431 top.count = ((SequenceNode) top.left()).count
432 + ((SequenceNode) top.right()).count;
435 float chunk = (float) (height - (offy)) / top.count;
437 pickNode(pickBox, top, chunk, wscale, width, offx, offy);
458 public void pickNode(Rectangle pickBox, SequenceNode node, float chunk,
459 float scale, int width, int offx, int offy)
466 if ((node.left() == null) && (node.right() == null))
468 float height = node.height;
469 float dist = node.dist;
471 int xstart = (int) ((height - dist) * scale) + offx;
472 int xend = (int) (height * scale) + offx;
474 int ypos = (int) (node.ycount * chunk) + offy;
476 if (pickBox.contains(new Point(xend, ypos)))
478 if (node.element() instanceof SequenceI)
480 SequenceI seq = (SequenceI) node.element();
481 SequenceGroup sg = av.getSelectionGroup();
485 sg.addOrRemove(seq, true);
492 pickNode(pickBox, (SequenceNode) node.left(), chunk, scale, width,
494 pickNode(pickBox, (SequenceNode) node.right(), chunk, scale, width,
507 public void setColor(SequenceNode node, Color c)
514 if ((node.left() == null) && (node.right() == null)) // TODO: internal node
518 if (node.element() instanceof SequenceI)
520 AlignmentPanel[] aps = getAssociatedPanels();
523 for (int a = 0; a < aps.length; a++)
525 final SequenceI seq = (SequenceI) node.element();
526 aps[a].av.setSequenceColour(seq, c);
534 setColor((SequenceNode) node.left(), c);
535 setColor((SequenceNode) node.right(), c);
544 Thread thread = new Thread(this);
548 // put printing in a thread to avoid painting problems
552 PrinterJob printJob = PrinterJob.getPrinterJob();
553 PageFormat pf = printJob.pageDialog(printJob.defaultPage());
555 printJob.setPrintable(this, pf);
557 if (printJob.printDialog())
562 } catch (Exception PrintException)
564 PrintException.printStackTrace();
579 * @return DOCUMENT ME!
581 * @throws PrinterException
585 public int print(Graphics pg, PageFormat pf, int pi)
586 throws PrinterException
589 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
591 int pwidth = (int) pf.getImageableWidth();
592 int pheight = (int) pf.getImageableHeight();
594 int noPages = getHeight() / pheight;
598 return Printable.NO_SUCH_PAGE;
601 if (pwidth > getWidth())
608 if (pheight > getHeight())
610 pheight = getHeight();
617 FontMetrics fm = pg.getFontMetrics(font);
618 int height = fm.getHeight() * nameHash.size();
619 pg.translate(0, -pi * pheight);
620 pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
622 // translate number of pages,
623 // height is screen size as this is the
624 // non overlapping text size
628 draw(pg, pwidth, pheight);
630 return Printable.PAGE_EXISTS;
640 public void paintComponent(Graphics g)
642 super.paintComponent(g);
647 g.drawString(MessageManager.getString("label.calculating_tree")
648 + "....", 20, getHeight() / 2);
652 fm = g.getFontMetrics(font);
654 if (nameHash.size() == 0)
660 || (!fitToWindow && (scrollPane.getHeight() > ((fm
661 .getHeight() * nameHash.size()) + offy))))
663 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
664 setPreferredSize(null);
668 setPreferredSize(new Dimension(scrollPane.getWidth(),
669 fm.getHeight() * nameHash.size()));
670 draw(g, scrollPane.getWidth(), fm.getHeight() * nameHash.size());
673 scrollPane.revalidate();
684 public void setFont(Font font)
700 public void draw(Graphics g1, int width, int height)
702 Graphics2D g2 = (Graphics2D) g1;
703 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
704 RenderingHints.VALUE_ANTIALIAS_ON);
705 g2.setColor(Color.white);
706 g2.fillRect(0, 0, width, height);
709 if (longestName == null || tree == null)
711 g2.drawString("Calculating tree.", 20, 20);
713 offy = font.getSize() + 10;
715 fm = g2.getFontMetrics(font);
717 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
719 float wscale = (width - labelLength - (offx * 2)) / 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)
817 treeSelectionChanged(seq);
822 PaintRefresher.Refresh(tp, av.getSequenceSetId());
827 * Offer the user the option to choose a colour for the highlighted node and
828 * its children; this colour is also applied to the corresponding sequence ids
831 void chooseSubtreeColour()
833 Color col = JColorChooser.showDialog(this,
834 MessageManager.getString("label.select_subtree_colour"),
835 highlightNode.color);
838 setColor(highlightNode, col);
839 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
845 public void mouseMoved(MouseEvent evt)
847 av.setCurrentTree(tree);
849 Object ob = findElement(evt.getX(), evt.getY());
851 if (ob instanceof SequenceNode)
853 highlightNode = (SequenceNode) ob;
854 this.setToolTipText("<html>"
855 + MessageManager.getString("label.highlightnode"));
861 if (highlightNode != null)
863 highlightNode = null;
864 setToolTipText(null);
871 public void mouseDragged(MouseEvent ect)
876 * Handles a mouse press on a sequence name or the tree background canvas
877 * (click on a node is handled in mouseClicked). The action is to create
878 * groups by partitioning the tree at the mouse position. Colours for the
879 * groups (and sequence names) are generated randomly.
884 public void mousePressed(MouseEvent e)
886 av.setCurrentTree(tree);
889 * isPopupTrigger is set for mousePressed (Mac)
890 * or mouseReleased (Windows)
892 if (e.isPopupTrigger())
894 if (highlightNode != null)
896 chooseSubtreeColour();
902 * defer right-click handling on Windows to
903 * mouseClicked; note isRightMouseButton
904 * also matches Cmd-click on Mac which should do
907 if (SwingUtilities.isRightMouseButton(e))
915 Object ob = findElement(x, y);
917 if (ob instanceof SequenceI)
919 treeSelectionChanged((Sequence) ob);
920 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
925 else if (!(ob instanceof SequenceNode))
928 if (tree.getMaxHeight() != 0)
930 threshold = (float) (x - offx)
931 / (float) (getWidth() - labelLength - (2 * offx));
933 tree.getGroups().removeAllElements();
934 tree.groupNodes(tree.getTopNode(), threshold);
935 setColor(tree.getTopNode(), Color.black);
937 AlignmentPanel[] aps = getAssociatedPanels();
939 // TODO push calls below into a single AlignViewportI method?
940 // see also AlignViewController.deleteGroups
941 for (int a = 0; a < aps.length; a++)
943 aps[a].av.setSelectionGroup(null);
944 aps[a].av.getAlignment().deleteAllGroups();
945 aps[a].av.clearSequenceColours();
946 if (aps[a].av.getCodingComplement() != null)
948 aps[a].av.getCodingComplement().setSelectionGroup(null);
949 aps[a].av.getCodingComplement().getAlignment()
951 aps[a].av.getCodingComplement().clearSequenceColours();
957 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
965 AlignmentPanel[] aps = getAssociatedPanels();
966 for (int i = 0; i < tree.getGroups().size(); i++)
968 Color col = new Color((int) (Math.random() * 255),
969 (int) (Math.random() * 255), (int) (Math.random() * 255));
970 setColor(tree.getGroups().elementAt(i), col.brighter());
972 Vector<SequenceNode> l = tree.findLeaves(tree
973 .getGroups().elementAt(i));
975 Vector<SequenceI> sequences = new Vector<SequenceI>();
977 for (int j = 0; j < l.size(); j++)
979 SequenceI s1 = (SequenceI) l.elementAt(j)
982 if (!sequences.contains(s1))
984 sequences.addElement(s1);
988 ColourSchemeI cs = null;
989 SequenceGroup sg = new SequenceGroup(sequences, null, cs, true, true,
990 false, 0, av.getAlignment().getWidth() - 1);
992 if (av.getGlobalColourScheme() != null)
994 if (av.getGlobalColourScheme() instanceof UserColourScheme)
996 cs = new UserColourScheme(
997 ((UserColourScheme) av.getGlobalColourScheme())
1003 cs = ColourSchemeProperty.getColour(sg, ColourSchemeProperty
1004 .getColourName(av.getGlobalColourScheme()));
1006 // cs is null if shading is an annotationColourGradient
1009 cs.setThreshold(av.getGlobalColourScheme().getThreshold(),
1010 av.isIgnoreGapsConsensus());
1014 // sg.recalcConservation();
1015 sg.setName("JTreeGroup:" + sg.hashCode());
1016 sg.setIdColour(col);
1018 for (int a = 0; a < aps.length; a++)
1020 if (aps[a].av.getGlobalColourScheme() != null
1021 && aps[a].av.getGlobalColourScheme().conservationApplied())
1023 Conservation c = new Conservation("Group",
1024 ResidueProperties.propHash, 3, sg.getSequences(null),
1025 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 };