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()) ? (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, wscale, width, offx,
312 drawNode(g, (SequenceNode) node.right(), chunk, wscale, width, offx,
315 double height = node.height;
316 double dist = node.dist;
318 int xstart = (int) ((height - dist) * wscale) + offx;
319 int xend = (int) (height * wscale) + 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 * wscale) + offx, ystart,
344 (int) (height * wscale) + 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 double wscale = ((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 double wscale, int width, int offx, int offy)
466 if ((node.left() == null) && (node.right() == null))
468 double height = node.height;
469 double dist = node.dist;
471 int xstart = (int) ((height - dist) * wscale) + offx;
472 int xend = (int) (height * wscale) + 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, wscale, width,
494 pickNode(pickBox, (SequenceNode) node.right(), chunk, wscale, 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 defaultPage = printJob.defaultPage();
554 PageFormat pf = printJob.pageDialog(defaultPage);
556 if (defaultPage == pf)
564 printJob.setPrintable(this, pf);
566 if (printJob.printDialog())
571 } catch (Exception PrintException)
573 PrintException.printStackTrace();
588 * @return DOCUMENT ME!
590 * @throws PrinterException
594 public int print(Graphics pg, PageFormat pf, int pi)
595 throws PrinterException
598 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
600 int pwidth = (int) pf.getImageableWidth();
601 int pheight = (int) pf.getImageableHeight();
603 int noPages = getHeight() / pheight;
607 return Printable.NO_SUCH_PAGE;
610 if (pwidth > getWidth())
617 if (pheight > getHeight())
619 pheight = getHeight();
626 FontMetrics fm = pg.getFontMetrics(font);
627 int height = fm.getHeight() * nameHash.size();
628 pg.translate(0, -pi * pheight);
629 pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
631 // translate number of pages,
632 // height is screen size as this is the
633 // non overlapping text size
637 draw(pg, pwidth, pheight);
639 return Printable.PAGE_EXISTS;
649 public void paintComponent(Graphics g)
651 super.paintComponent(g);
656 g.drawString(MessageManager.getString("label.calculating_tree")
657 + "....", 20, getHeight() / 2);
661 fm = g.getFontMetrics(font);
663 if (nameHash.size() == 0)
669 || (!fitToWindow && (scrollPane.getHeight() > ((fm
670 .getHeight() * nameHash.size()) + offy))))
672 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
673 setPreferredSize(null);
677 setPreferredSize(new Dimension(scrollPane.getWidth(),
678 fm.getHeight() * nameHash.size()));
679 draw(g, scrollPane.getWidth(), fm.getHeight() * nameHash.size());
682 scrollPane.revalidate();
693 public void setFont(Font font)
709 public void draw(Graphics g1, int width, int height)
711 Graphics2D g2 = (Graphics2D) g1;
712 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
713 RenderingHints.VALUE_ANTIALIAS_ON);
714 g2.setColor(Color.white);
715 g2.fillRect(0, 0, width, height);
718 if (longestName == null || tree == null)
720 g2.drawString("Calculating tree.", 20, 20);
722 offy = font.getSize() + 10;
724 fm = g2.getFontMetrics(font);
726 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
728 double wscale = (width - labelLength - (offx * 2))
729 / tree.getMaxHeight();
731 SequenceNode top = tree.getTopNode();
735 top.count = ((SequenceNode) top.left()).count
736 + ((SequenceNode) top.right()).count;
739 float chunk = (float) (height - (offy)) / top.count;
741 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
745 if (av.getCurrentTree() == tree)
747 g2.setColor(Color.red);
751 g2.setColor(Color.gray);
754 int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx))) + offx);
756 g2.drawLine(x, 0, x, getHeight());
761 * Empty method to satisfy the MouseListener interface
766 public void mouseReleased(MouseEvent e)
769 * isPopupTrigger is set on mouseReleased on Windows
771 if (e.isPopupTrigger())
773 chooseSubtreeColour();
774 e.consume(); // prevent mouseClicked happening
779 * Empty method to satisfy the MouseListener interface
784 public void mouseEntered(MouseEvent e)
789 * Empty method to satisfy the MouseListener interface
794 public void mouseExited(MouseEvent e)
799 * Handles a mouse click on a tree node (clicks elsewhere are handled in
800 * mousePressed). Click selects the sub-tree, double-click swaps leaf nodes
801 * order, right-click opens a dialogue to choose colour for the sub-tree.
806 public void mouseClicked(MouseEvent evt)
808 if (highlightNode == null)
813 if (evt.getClickCount() > 1)
815 tree.swapNodes(highlightNode);
816 tree.reCount(tree.getTopNode());
817 tree.findHeight(tree.getTopNode());
821 Vector<SequenceNode> leaves = tree.findLeaves(highlightNode);
823 for (int i = 0; i < leaves.size(); i++)
825 SequenceI seq = (SequenceI) leaves.elementAt(i).element();
826 treeSelectionChanged(seq);
831 PaintRefresher.Refresh(tp, av.getSequenceSetId());
836 * Offer the user the option to choose a colour for the highlighted node and
837 * its children; this colour is also applied to the corresponding sequence ids
840 void chooseSubtreeColour()
842 Color col = JColorChooser.showDialog(this,
843 MessageManager.getString("label.select_subtree_colour"),
844 highlightNode.color);
847 setColor(highlightNode, col);
848 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
854 public void mouseMoved(MouseEvent evt)
856 av.setCurrentTree(tree);
858 Object ob = findElement(evt.getX(), evt.getY());
860 if (ob instanceof SequenceNode)
862 highlightNode = (SequenceNode) ob;
863 this.setToolTipText("<html>"
864 + MessageManager.getString("label.highlightnode"));
870 if (highlightNode != null)
872 highlightNode = null;
873 setToolTipText(null);
880 public void mouseDragged(MouseEvent ect)
885 * Handles a mouse press on a sequence name or the tree background canvas
886 * (click on a node is handled in mouseClicked). The action is to create
887 * groups by partitioning the tree at the mouse position. Colours for the
888 * groups (and sequence names) are generated randomly.
893 public void mousePressed(MouseEvent e)
895 av.setCurrentTree(tree);
898 * isPopupTrigger is set for mousePressed (Mac)
899 * or mouseReleased (Windows)
901 if (e.isPopupTrigger())
903 if (highlightNode != null)
905 chooseSubtreeColour();
911 * defer right-click handling on Windows to
912 * mouseClicked; note isRightMouseButton
913 * also matches Cmd-click on Mac which should do
916 if (SwingUtilities.isRightMouseButton(e))
924 Object ob = findElement(x, y);
926 if (ob instanceof SequenceI)
928 treeSelectionChanged((Sequence) ob);
929 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
934 else if (!(ob instanceof SequenceNode))
937 if (tree.getMaxHeight() != 0)
939 threshold = (float) (x - offx)
940 / (float) (getWidth() - labelLength - (2 * offx));
942 List<SequenceNode> groups = tree.groupNodes(threshold);
943 setColor(tree.getTopNode(), Color.black);
945 AlignmentPanel[] aps = getAssociatedPanels();
947 // TODO push calls below into a single AlignViewportI method?
948 // see also AlignViewController.deleteGroups
949 for (int a = 0; a < aps.length; a++)
951 aps[a].av.setSelectionGroup(null);
952 aps[a].av.getAlignment().deleteAllGroups();
953 aps[a].av.clearSequenceColours();
954 if (aps[a].av.getCodingComplement() != null)
956 aps[a].av.getCodingComplement().setSelectionGroup(null);
957 aps[a].av.getCodingComplement().getAlignment()
959 aps[a].av.getCodingComplement().clearSequenceColours();
962 colourGroups(groups);
965 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
971 void colourGroups(List<SequenceNode> groups)
973 AlignmentPanel[] aps = getAssociatedPanels();
974 for (int i = 0; i < groups.size(); i++)
976 Color col = new Color((int) (Math.random() * 255),
977 (int) (Math.random() * 255), (int) (Math.random() * 255));
978 setColor(groups.get(i), col.brighter());
980 Vector<SequenceNode> l = tree.findLeaves(groups.get(i));
982 Vector<SequenceI> sequences = new Vector<SequenceI>();
984 for (int j = 0; j < l.size(); j++)
986 SequenceI s1 = (SequenceI) l.elementAt(j).element();
988 if (!sequences.contains(s1))
990 sequences.addElement(s1);
994 ColourSchemeI cs = null;
995 SequenceGroup sg = new SequenceGroup(sequences, null, cs, true, true,
996 false, 0, av.getAlignment().getWidth() - 1);
998 if (av.getGlobalColourScheme() != null)
1000 if (av.getGlobalColourScheme() instanceof UserColourScheme)
1002 cs = new UserColourScheme(
1003 ((UserColourScheme) av.getGlobalColourScheme())
1009 cs = ColourSchemeProperty.getColourScheme(sg,
1010 ColourSchemeProperty.getColourName(av
1011 .getGlobalColourScheme()));
1013 // cs is null if shading is an annotationColourGradient
1016 // cs.setThreshold(av.getViewportColourScheme().getThreshold(),
1017 // av.isIgnoreGapsConsensus());
1020 sg.setColourScheme(cs);
1021 sg.getGroupColourScheme().setThreshold(
1022 av.getResidueShading().getThreshold(),
1023 av.isIgnoreGapsConsensus());
1024 // sg.recalcConservation();
1025 sg.setName("JTreeGroup:" + sg.hashCode());
1026 sg.setIdColour(col);
1028 for (int a = 0; a < aps.length; a++)
1030 if (aps[a].av.getGlobalColourScheme() != null
1031 && aps[a].av.getResidueShading()
1032 .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 };