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.Colour;
31 import jalview.schemes.ColourSchemeI;
32 import jalview.schemes.ColourSchemeProperty;
33 import jalview.schemes.ResidueProperties;
34 import jalview.schemes.UserColourScheme;
35 import jalview.structure.SelectionSource;
36 import jalview.util.ColorUtils;
37 import jalview.util.Format;
38 import jalview.util.MappingUtils;
39 import jalview.util.MessageManager;
41 import java.awt.Color;
42 import java.awt.Dimension;
44 import java.awt.FontMetrics;
45 import java.awt.Graphics;
46 import java.awt.Graphics2D;
47 import java.awt.Point;
48 import java.awt.Rectangle;
49 import java.awt.RenderingHints;
50 import java.awt.event.MouseEvent;
51 import java.awt.event.MouseListener;
52 import java.awt.event.MouseMotionListener;
53 import java.awt.print.PageFormat;
54 import java.awt.print.Printable;
55 import java.awt.print.PrinterException;
56 import java.awt.print.PrinterJob;
57 import java.util.Enumeration;
58 import java.util.Hashtable;
59 import java.util.Vector;
61 import javax.swing.JColorChooser;
62 import javax.swing.JPanel;
63 import javax.swing.JScrollPane;
64 import javax.swing.SwingUtilities;
65 import javax.swing.ToolTipManager;
73 public class TreeCanvas extends JPanel implements MouseListener, Runnable,
74 Printable, MouseMotionListener, SelectionSource
77 public static final String PLACEHOLDER = " * ";
81 JScrollPane scrollPane;
93 boolean fitToWindow = true;
95 boolean showDistances = false;
97 boolean showBootstrap = false;
99 boolean markPlaceholders = false;
109 int labelLength = -1;
111 Hashtable nameHash = new Hashtable();
113 Hashtable nodeHash = new Hashtable();
115 SequenceNode highlightNode;
117 boolean applyToAllViews = false;
120 * Creates a new TreeCanvas object.
131 public TreeCanvas(TreePanel tp, AlignmentPanel ap, JScrollPane scroller)
137 scrollPane = scroller;
138 addMouseListener(this);
139 addMouseMotionListener(this);
140 ToolTipManager.sharedInstance().registerComponent(this);
149 public void treeSelectionChanged(SequenceI sequence)
151 AlignmentPanel[] aps = getAssociatedPanels();
153 for (int a = 0; a < aps.length; a++)
155 SequenceGroup selected = aps[a].av.getSelectionGroup();
157 if (selected == null)
159 selected = new SequenceGroup();
160 aps[a].av.setSelectionGroup(selected);
163 selected.setEndRes(aps[a].av.getAlignment().getWidth() - 1);
164 selected.addOrRemove(sequence, true);
174 public void setTree(NJTree tree)
177 tree.findHeight(tree.getTopNode());
179 // Now have to calculate longest name based on the leaves
180 Vector<SequenceNode> leaves = tree.findLeaves(tree.getTopNode());
181 boolean has_placeholders = false;
184 for (int i = 0; i < leaves.size(); i++)
186 SequenceNode lf = leaves.elementAt(i);
188 if (lf.isPlaceholder())
190 has_placeholders = true;
193 if (longestName.length() < ((Sequence) lf.element()).getName()
196 longestName = TreeCanvas.PLACEHOLDER
197 + ((Sequence) lf.element()).getName();
201 setMarkPlaceholders(has_placeholders);
222 public void drawNode(Graphics g, SequenceNode node, float chunk,
223 float scale, int width, int offx, int offy)
230 if ((node.left() == null) && (node.right() == null))
233 float height = node.height;
234 float dist = node.dist;
236 int xstart = (int) ((height - dist) * scale) + offx;
237 int xend = (int) (height * scale) + offx;
239 int ypos = (int) (node.ycount * chunk) + offy;
241 if (node.element() instanceof SequenceI)
243 SequenceI seq = (SequenceI) node.element();
245 if (av.getSequenceColour(seq) == Color.white)
247 g.setColor(Color.black);
251 g.setColor(ColorUtils.getColor(av.getSequenceColour(seq))
257 g.setColor(Color.black);
260 // Draw horizontal line
261 g.drawLine(xstart, ypos, xend, ypos);
263 String nodeLabel = "";
265 if (showDistances && (node.dist > 0))
267 nodeLabel = new Format("%-.2f").form(node.dist);
270 if (showBootstrap && node.bootstrap > -1)
274 nodeLabel = nodeLabel + " : ";
277 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
280 if (!nodeLabel.equals(""))
282 g.drawString(nodeLabel, xstart + 2, ypos - 2);
285 String name = (markPlaceholders && node.isPlaceholder()) ? (PLACEHOLDER + node
286 .getName()) : node.getName();
288 int charWidth = fm.stringWidth(name) + 3;
289 int charHeight = font.getSize();
291 Rectangle rect = new Rectangle(xend + 10, ypos - charHeight / 2,
292 charWidth, charHeight);
294 nameHash.put(node.element(), rect);
296 // Colour selected leaves differently
297 SequenceGroup selected = av.getSelectionGroup();
299 if ((selected != null)
300 && selected.getSequences(null).contains(node.element()))
302 g.setColor(Color.gray);
304 g.fillRect(xend + 10, ypos - charHeight / 2, charWidth, charHeight);
305 g.setColor(Color.white);
308 g.drawString(name, xend + 10, ypos + fm.getDescent());
309 g.setColor(Color.black);
313 drawNode(g, (SequenceNode) node.left(), chunk, scale, width, offx,
315 drawNode(g, (SequenceNode) node.right(), chunk, scale, width, offx,
318 float height = node.height;
319 float dist = node.dist;
321 int xstart = (int) ((height - dist) * scale) + offx;
322 int xend = (int) (height * scale) + offx;
323 int ypos = (int) (node.ycount * chunk) + offy;
325 g.setColor(node.color.darker());
327 // Draw horizontal line
328 g.drawLine(xstart, ypos, xend, ypos);
329 if (node == highlightNode)
331 g.fillRect(xend - 3, ypos - 3, 6, 6);
335 g.fillRect(xend - 2, ypos - 2, 4, 4);
338 int ystart = (int) (((SequenceNode) node.left()).ycount * chunk)
340 int yend = (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 * scale) + offx, ystart,
347 (int) (height * scale) + 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 float wscale = (float) ((width * .8) - (offx * 2))
430 / tree.getMaxHeight();
434 top.count = ((SequenceNode) top.left()).count
435 + ((SequenceNode) top.right()).count;
438 float chunk = (float) (height - (offy)) / top.count;
440 pickNode(pickBox, top, chunk, wscale, width, offx, offy);
461 public void pickNode(Rectangle pickBox, SequenceNode node, float chunk,
462 float scale, int width, int offx, int offy)
469 if ((node.left() == null) && (node.right() == null))
471 float height = node.height;
472 float dist = node.dist;
474 int xstart = (int) ((height - dist) * scale) + offx;
475 int xend = (int) (height * scale) + offx;
477 int ypos = (int) (node.ycount * chunk) + offy;
479 if (pickBox.contains(new Point(xend, ypos)))
481 if (node.element() instanceof SequenceI)
483 SequenceI seq = (SequenceI) node.element();
484 SequenceGroup sg = av.getSelectionGroup();
488 sg.addOrRemove(seq, true);
495 pickNode(pickBox, (SequenceNode) node.left(), chunk, scale, width,
497 pickNode(pickBox, (SequenceNode) node.right(), chunk, scale, width,
510 public void setColor(SequenceNode node, Color c)
517 if ((node.left() == null) && (node.right() == null)) // TODO: internal node
521 if (node.element() instanceof SequenceI)
523 AlignmentPanel[] aps = getAssociatedPanels();
526 for (int a = 0; a < aps.length; a++)
528 final SequenceI seq = (SequenceI) node.element();
529 aps[a].av.setSequenceColour(seq, new Colour(c));
537 setColor((SequenceNode) node.left(), c);
538 setColor((SequenceNode) node.right(), c);
547 Thread thread = new Thread(this);
551 // put printing in a thread to avoid painting problems
555 PrinterJob printJob = PrinterJob.getPrinterJob();
556 PageFormat pf = printJob.pageDialog(printJob.defaultPage());
558 printJob.setPrintable(this, pf);
560 if (printJob.printDialog())
565 } catch (Exception PrintException)
567 PrintException.printStackTrace();
582 * @return DOCUMENT ME!
584 * @throws PrinterException
588 public int print(Graphics pg, PageFormat pf, int pi)
589 throws PrinterException
592 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
594 int pwidth = (int) pf.getImageableWidth();
595 int pheight = (int) pf.getImageableHeight();
597 int noPages = getHeight() / pheight;
601 return Printable.NO_SUCH_PAGE;
604 if (pwidth > getWidth())
611 if (pheight > getHeight())
613 pheight = getHeight();
620 FontMetrics fm = pg.getFontMetrics(font);
621 int height = fm.getHeight() * nameHash.size();
622 pg.translate(0, -pi * pheight);
623 pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
625 // translate number of pages,
626 // height is screen size as this is the
627 // non overlapping text size
631 draw(pg, pwidth, pheight);
633 return Printable.PAGE_EXISTS;
643 public void paintComponent(Graphics g)
645 super.paintComponent(g);
650 g.drawString(MessageManager.getString("label.calculating_tree")
651 + "....", 20, getHeight() / 2);
655 fm = g.getFontMetrics(font);
657 if (nameHash.size() == 0)
663 || (!fitToWindow && (scrollPane.getHeight() > ((fm
664 .getHeight() * nameHash.size()) + offy))))
666 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
667 setPreferredSize(null);
671 setPreferredSize(new Dimension(scrollPane.getWidth(),
672 fm.getHeight() * nameHash.size()));
673 draw(g, scrollPane.getWidth(), fm.getHeight() * nameHash.size());
676 scrollPane.revalidate();
687 public void setFont(Font font)
703 public void draw(Graphics g1, int width, int height)
705 Graphics2D g2 = (Graphics2D) g1;
706 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
707 RenderingHints.VALUE_ANTIALIAS_ON);
708 g2.setColor(Color.white);
709 g2.fillRect(0, 0, width, height);
712 if (longestName == null || tree == null)
714 g2.drawString("Calculating tree.", 20, 20);
716 offy = font.getSize() + 10;
718 fm = g2.getFontMetrics(font);
720 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
722 float wscale = (width - labelLength - (offx * 2)) / tree.getMaxHeight();
724 SequenceNode top = tree.getTopNode();
728 top.count = ((SequenceNode) top.left()).count
729 + ((SequenceNode) top.right()).count;
732 float chunk = (float) (height - (offy)) / top.count;
734 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
738 if (av.getCurrentTree() == tree)
740 g2.setColor(Color.red);
744 g2.setColor(Color.gray);
747 int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx))) + offx);
749 g2.drawLine(x, 0, x, getHeight());
754 * Empty method to satisfy the MouseListener interface
759 public void mouseReleased(MouseEvent e)
762 * isPopupTrigger is set on mouseReleased on Windows
764 if (e.isPopupTrigger())
766 chooseSubtreeColour();
767 e.consume(); // prevent mouseClicked happening
772 * Empty method to satisfy the MouseListener interface
777 public void mouseEntered(MouseEvent e)
782 * Empty method to satisfy the MouseListener interface
787 public void mouseExited(MouseEvent e)
792 * Handles a mouse click on a tree node (clicks elsewhere are handled in
793 * mousePressed). Click selects the sub-tree, double-click swaps leaf nodes
794 * order, right-click opens a dialogue to choose colour for the sub-tree.
799 public void mouseClicked(MouseEvent evt)
801 if (highlightNode == null)
806 if (evt.getClickCount() > 1)
808 tree.swapNodes(highlightNode);
809 tree.reCount(tree.getTopNode());
810 tree.findHeight(tree.getTopNode());
814 Vector<SequenceNode> leaves = tree.findLeaves(highlightNode);
816 for (int i = 0; i < leaves.size(); i++)
818 SequenceI seq = (SequenceI) leaves.elementAt(i)
820 treeSelectionChanged(seq);
825 PaintRefresher.Refresh(tp, av.getSequenceSetId());
830 * Offer the user the option to choose a colour for the highlighted node and
831 * its children; this colour is also applied to the corresponding sequence ids
834 void chooseSubtreeColour()
836 Color col = JColorChooser.showDialog(this,
837 MessageManager.getString("label.select_subtree_colour"),
838 highlightNode.color);
841 setColor(highlightNode, col);
842 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
848 public void mouseMoved(MouseEvent evt)
850 av.setCurrentTree(tree);
852 Object ob = findElement(evt.getX(), evt.getY());
854 if (ob instanceof SequenceNode)
856 highlightNode = (SequenceNode) ob;
857 this.setToolTipText("<html>"
858 + MessageManager.getString("label.highlightnode"));
864 if (highlightNode != null)
866 highlightNode = null;
867 setToolTipText(null);
874 public void mouseDragged(MouseEvent ect)
879 * Handles a mouse press on a sequence name or the tree background canvas
880 * (click on a node is handled in mouseClicked). The action is to create
881 * groups by partitioning the tree at the mouse position. Colours for the
882 * groups (and sequence names) are generated randomly.
887 public void mousePressed(MouseEvent e)
889 av.setCurrentTree(tree);
892 * isPopupTrigger is set for mousePressed (Mac)
893 * or mouseReleased (Windows)
895 if (e.isPopupTrigger())
897 if (highlightNode != null)
899 chooseSubtreeColour();
905 * defer right-click handling on Windows to
906 * mouseClicked; note isRightMouseButton
907 * also matches Cmd-click on Mac which should do
910 if (SwingUtilities.isRightMouseButton(e))
918 Object ob = findElement(x, y);
920 if (ob instanceof SequenceI)
922 treeSelectionChanged((Sequence) ob);
923 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
928 else if (!(ob instanceof SequenceNode))
931 if (tree.getMaxHeight() != 0)
933 threshold = (float) (x - offx)
934 / (float) (getWidth() - labelLength - (2 * offx));
936 tree.getGroups().removeAllElements();
937 tree.groupNodes(tree.getTopNode(), threshold);
938 setColor(tree.getTopNode(), Color.black);
940 AlignmentPanel[] aps = getAssociatedPanels();
942 // TODO push calls below into a single AlignViewportI method?
943 // see also AlignViewController.deleteGroups
944 for (int a = 0; a < aps.length; a++)
946 aps[a].av.setSelectionGroup(null);
947 aps[a].av.getAlignment().deleteAllGroups();
948 aps[a].av.clearSequenceColours();
949 if (aps[a].av.getCodingComplement() != null)
951 aps[a].av.getCodingComplement().setSelectionGroup(null);
952 aps[a].av.getCodingComplement().getAlignment()
954 aps[a].av.getCodingComplement().clearSequenceColours();
960 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
968 AlignmentPanel[] aps = getAssociatedPanels();
969 for (int i = 0; i < tree.getGroups().size(); i++)
971 Color col = new Color((int) (Math.random() * 255),
972 (int) (Math.random() * 255), (int) (Math.random() * 255));
973 setColor(tree.getGroups().elementAt(i), col.brighter());
975 Vector<SequenceNode> l = tree.findLeaves(tree
976 .getGroups().elementAt(i));
978 Vector<SequenceI> sequences = new Vector<SequenceI>();
980 for (int j = 0; j < l.size(); j++)
982 SequenceI s1 = (SequenceI) l.elementAt(j)
985 if (!sequences.contains(s1))
987 sequences.addElement(s1);
991 ColourSchemeI cs = null;
992 SequenceGroup sg = new SequenceGroup(sequences, null, cs, true, true,
993 false, 0, av.getAlignment().getWidth() - 1);
995 if (av.getGlobalColourScheme() != null)
997 if (av.getGlobalColourScheme() instanceof UserColourScheme)
999 cs = new UserColourScheme(
1000 ((UserColourScheme) av.getGlobalColourScheme())
1006 cs = ColourSchemeProperty.getColour(sg, ColourSchemeProperty
1007 .getColourName(av.getGlobalColourScheme()));
1009 // cs is null if shading is an annotationColourGradient
1012 cs.setThreshold(av.getGlobalColourScheme().getThreshold(),
1013 av.isIgnoreGapsConsensus());
1017 // sg.recalcConservation();
1018 sg.setName("JTreeGroup:" + sg.hashCode());
1019 sg.setIdColour(col);
1021 for (int a = 0; a < aps.length; a++)
1023 if (aps[a].av.getGlobalColourScheme() != null
1024 && aps[a].av.getGlobalColourScheme().conservationApplied())
1026 Conservation c = new Conservation("Group",
1027 ResidueProperties.propHash, 3, sg.getSequences(null),
1028 sg.getStartRes(), sg.getEndRes());
1031 c.verdict(false, aps[a].av.getConsPercGaps());
1032 sg.cs.setConservation(c);
1035 aps[a].av.getAlignment().addGroup(new SequenceGroup(sg));
1036 // TODO can we push all of the below into AlignViewportI?
1037 final AlignViewportI codingComplement = aps[a].av
1038 .getCodingComplement();
1039 if (codingComplement != null)
1041 SequenceGroup mappedGroup = MappingUtils.mapSequenceGroup(sg, av,
1043 if (mappedGroup.getSequences().size() > 0)
1045 codingComplement.getAlignment().addGroup(mappedGroup);
1046 for (SequenceI seq : mappedGroup.getSequences())
1048 codingComplement.setSequenceColour(seq,
1049 new Colour(col.brighter()));
1056 // notify the panel(s) to redo any group specific stuff.
1057 for (int a = 0; a < aps.length; a++)
1059 aps[a].updateAnnotation();
1060 // TODO: JAL-868 - need to ensure view colour change message is broadcast
1061 // to any Jmols listening in
1062 final AlignViewportI codingComplement = aps[a].av
1063 .getCodingComplement();
1064 if (codingComplement != null)
1066 ((AlignViewport) codingComplement).getAlignPanel()
1067 .updateAnnotation();
1078 public void setShowDistances(boolean state)
1080 this.showDistances = state;
1090 public void setShowBootstrap(boolean state)
1092 this.showBootstrap = state;
1102 public void setMarkPlaceholders(boolean state)
1104 this.markPlaceholders = state;
1108 AlignmentPanel[] getAssociatedPanels()
1110 if (applyToAllViews)
1112 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1116 return new AlignmentPanel[] { ap };