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.MessageManager;
37 import java.awt.Color;
38 import java.awt.Dimension;
40 import java.awt.FontMetrics;
41 import java.awt.Graphics;
42 import java.awt.Graphics2D;
43 import java.awt.Point;
44 import java.awt.Rectangle;
45 import java.awt.RenderingHints;
46 import java.awt.event.MouseEvent;
47 import java.awt.event.MouseListener;
48 import java.awt.event.MouseMotionListener;
49 import java.awt.print.PageFormat;
50 import java.awt.print.Printable;
51 import java.awt.print.PrinterException;
52 import java.awt.print.PrinterJob;
53 import java.util.Enumeration;
54 import java.util.Hashtable;
55 import java.util.List;
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(TreeModel 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())
282 ? (PLACEHOLDER + 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 = (node.left() == null ? 0
336 : (int) (((SequenceNode) node.left()).ycount * chunk)) + offy;
337 int yend = (node.right() == null ? 0
338 : (int) (((SequenceNode) node.right()).ycount * chunk))
341 Rectangle pos = new Rectangle(xend - 2, ypos - 2, 5, 5);
342 nodeHash.put(node, pos);
344 g.drawLine((int) (height * wscale) + offx, ystart,
345 (int) (height * wscale) + offx, yend);
347 String nodeLabel = "";
349 if (showDistances && (node.dist > 0))
351 nodeLabel = new Format("%-.2f").form(node.dist);
354 if (showBootstrap && node.bootstrap > -1)
358 nodeLabel = nodeLabel + " : ";
361 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
364 if (!nodeLabel.equals(""))
366 g.drawString(nodeLabel, xstart + 2, ypos - 2);
379 * @return DOCUMENT ME!
381 public Object findElement(int x, int y)
383 Enumeration keys = nameHash.keys();
385 while (keys.hasMoreElements())
387 Object ob = keys.nextElement();
388 Rectangle rect = (Rectangle) nameHash.get(ob);
390 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
391 && (y <= (rect.y + rect.height)))
397 keys = nodeHash.keys();
399 while (keys.hasMoreElements())
401 Object ob = keys.nextElement();
402 Rectangle rect = (Rectangle) nodeHash.get(ob);
404 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
405 && (y <= (rect.y + rect.height)))
420 public void pickNodes(Rectangle pickBox)
422 int width = getWidth();
423 int height = getHeight();
425 SequenceNode top = tree.getTopNode();
427 double wscale = ((width * .8) - (offx * 2)) / 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)
515 if (node.element() instanceof SequenceI)
517 final SequenceI seq = (SequenceI) node.element();
518 AlignmentPanel[] aps = getAssociatedPanels();
521 for (int a = 0; a < aps.length; a++)
523 aps[a].av.setSequenceColour(seq, c);
527 setColor((SequenceNode) node.left(), c);
528 setColor((SequenceNode) node.right(), c);
536 Thread thread = new Thread(this);
540 // put printing in a thread to avoid painting problems
544 PrinterJob printJob = PrinterJob.getPrinterJob();
545 PageFormat defaultPage = printJob.defaultPage();
546 PageFormat pf = printJob.pageDialog(defaultPage);
548 if (defaultPage == pf)
556 printJob.setPrintable(this, pf);
558 if (printJob.printDialog())
563 } catch (Exception PrintException)
565 PrintException.printStackTrace();
580 * @return DOCUMENT ME!
582 * @throws PrinterException
586 public int print(Graphics pg, PageFormat pf, int pi)
587 throws PrinterException
590 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
592 int pwidth = (int) pf.getImageableWidth();
593 int pheight = (int) pf.getImageableHeight();
595 int noPages = getHeight() / pheight;
599 return Printable.NO_SUCH_PAGE;
602 if (pwidth > getWidth())
609 if (pheight > getHeight())
611 pheight = getHeight();
618 FontMetrics fm = pg.getFontMetrics(font);
619 int height = fm.getHeight() * nameHash.size();
620 pg.translate(0, -pi * pheight);
621 pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
623 // translate number of pages,
624 // height is screen size as this is the
625 // non overlapping text size
629 draw(pg, pwidth, pheight);
631 return Printable.PAGE_EXISTS;
641 public void paintComponent(Graphics g)
643 super.paintComponent(g);
649 MessageManager.getString("label.calculating_tree") + "....",
650 20, getHeight() / 2);
654 fm = g.getFontMetrics(font);
656 if (nameHash.size() == 0)
661 if (fitToWindow || (!fitToWindow && (scrollPane
662 .getHeight() > ((fm.getHeight() * nameHash.size()) + offy))))
664 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
665 setPreferredSize(null);
669 setPreferredSize(new Dimension(scrollPane.getWidth(),
670 fm.getHeight() * nameHash.size()));
671 draw(g, scrollPane.getWidth(), fm.getHeight() * nameHash.size());
674 scrollPane.revalidate();
685 public void setFont(Font font)
701 public void draw(Graphics g1, int width, int height)
703 Graphics2D g2 = (Graphics2D) g1;
704 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
705 RenderingHints.VALUE_ANTIALIAS_ON);
706 g2.setColor(Color.white);
707 g2.fillRect(0, 0, width, height);
710 if (longestName == null || tree == null)
712 g2.drawString("Calculating tree.", 20, 20);
714 offy = font.getSize() + 10;
716 fm = g2.getFontMetrics(font);
718 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
720 double wscale = (width - labelLength - (offx * 2))
721 / tree.getMaxHeight();
723 SequenceNode top = tree.getTopNode();
727 top.count = ((SequenceNode) top.left()).count
728 + ((SequenceNode) top.right()).count;
731 float chunk = (float) (height - (offy)) / top.count;
733 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
737 if (av.getCurrentTree() == tree)
739 g2.setColor(Color.red);
743 g2.setColor(Color.gray);
746 int x = (int) ((threshold * (getWidth() - labelLength - (2 * 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).element();
819 treeSelectionChanged(seq);
824 PaintRefresher.Refresh(tp, av.getSequenceSetId());
829 * Offer the user the option to choose a colour for the highlighted node and
830 * its children; this colour is also applied to the corresponding sequence ids
833 void chooseSubtreeColour()
835 Color col = JColorChooser.showDialog(this,
836 MessageManager.getString("label.select_subtree_colour"),
837 highlightNode.color);
840 setColor(highlightNode, col);
841 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
847 public void mouseMoved(MouseEvent evt)
849 av.setCurrentTree(tree);
851 Object ob = findElement(evt.getX(), evt.getY());
853 if (ob instanceof SequenceNode)
855 highlightNode = (SequenceNode) ob;
857 "<html>" + MessageManager.getString("label.highlightnode"));
863 if (highlightNode != null)
865 highlightNode = null;
866 setToolTipText(null);
873 public void mouseDragged(MouseEvent ect)
878 * Handles a mouse press on a sequence name or the tree background canvas
879 * (click on a node is handled in mouseClicked). The action is to create
880 * groups by partitioning the tree at the mouse position. Colours for the
881 * groups (and sequence names) are generated randomly.
886 public void mousePressed(MouseEvent e)
888 av.setCurrentTree(tree);
891 * isPopupTrigger is set for mousePressed (Mac)
892 * or mouseReleased (Windows)
894 if (e.isPopupTrigger())
896 if (highlightNode != null)
898 chooseSubtreeColour();
904 * defer right-click handling on Windows to
905 * mouseClicked; note isRightMouseButton
906 * also matches Cmd-click on Mac which should do
909 if (SwingUtilities.isRightMouseButton(e))
917 Object ob = findElement(x, y);
919 if (ob instanceof SequenceI)
921 treeSelectionChanged((Sequence) ob);
922 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
927 else if (!(ob instanceof SequenceNode))
930 if (tree.getMaxHeight() != 0)
932 threshold = (float) (x - offx)
933 / (float) (getWidth() - labelLength - (2 * offx));
935 List<SequenceNode> groups = tree.groupNodes(threshold);
936 setColor(tree.getTopNode(), Color.black);
938 AlignmentPanel[] aps = getAssociatedPanels();
940 // TODO push calls below into a single AlignViewportI method?
941 // see also AlignViewController.deleteGroups
942 for (int a = 0; a < aps.length; a++)
944 aps[a].av.setSelectionGroup(null);
945 aps[a].av.getAlignment().deleteAllGroups();
946 aps[a].av.clearSequenceColours();
947 if (aps[a].av.getCodingComplement() != null)
949 aps[a].av.getCodingComplement().setSelectionGroup(null);
950 aps[a].av.getCodingComplement().getAlignment()
952 aps[a].av.getCodingComplement().clearSequenceColours();
955 colourGroups(groups);
958 * clear partition (don't show vertical line) if
959 * it is to the right of all nodes
961 if (groups.isEmpty())
967 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
973 void colourGroups(List<SequenceNode> groups)
975 AlignmentPanel[] aps = getAssociatedPanels();
976 for (int i = 0; i < groups.size(); i++)
978 Color col = new Color((int) (Math.random() * 255),
979 (int) (Math.random() * 255), (int) (Math.random() * 255));
980 setColor(groups.get(i), col.brighter());
982 Vector<SequenceNode> l = tree.findLeaves(groups.get(i));
984 Vector<SequenceI> sequences = new Vector<>();
986 for (int j = 0; j < l.size(); j++)
988 SequenceI s1 = (SequenceI) l.elementAt(j).element();
990 if (!sequences.contains(s1))
992 sequences.addElement(s1);
996 ColourSchemeI cs = null;
997 SequenceGroup sg = new SequenceGroup(sequences, null, cs, true, true,
998 false, 0, av.getAlignment().getWidth() - 1);
1000 if (av.getGlobalColourScheme() != null)
1002 if (av.getGlobalColourScheme() instanceof UserColourScheme)
1004 cs = new UserColourScheme(
1005 ((UserColourScheme) av.getGlobalColourScheme())
1011 cs = ColourSchemeProperty.getColourScheme(av, sg,
1012 ColourSchemeProperty
1013 .getColourName(av.getGlobalColourScheme()));
1015 // cs is null if shading is an annotationColourGradient
1018 // cs.setThreshold(av.getViewportColourScheme().getThreshold(),
1019 // av.isIgnoreGapsConsensus());
1022 sg.setColourScheme(cs);
1023 sg.getGroupColourScheme().setThreshold(
1024 av.getResidueShading().getThreshold(),
1025 av.isIgnoreGapsConsensus());
1026 // sg.recalcConservation();
1027 sg.setName("JTreeGroup:" + sg.hashCode());
1028 sg.setIdColour(col);
1030 for (int a = 0; a < aps.length; a++)
1032 if (aps[a].av.getGlobalColourScheme() != null
1033 && aps[a].av.getResidueShading().conservationApplied())
1035 Conservation c = new Conservation("Group", sg.getSequences(null),
1036 sg.getStartRes(), sg.getEndRes());
1038 c.verdict(false, aps[a].av.getConsPercGaps());
1039 sg.cs.setConservation(c);
1041 // indicate that associated structure views will need an update
1042 aps[a].av.setUpdateStructures(true);
1043 // propagate structure view update and sequence group to complement view
1044 aps[a].av.addSequenceGroup(new SequenceGroup(sg));
1048 // notify the panel(s) to redo any group specific stuff
1049 // also updates structure views if necessary
1050 for (int a = 0; a < aps.length; a++)
1052 aps[a].updateAnnotation();
1053 final AlignViewportI codingComplement = aps[a].av
1054 .getCodingComplement();
1055 if (codingComplement != null)
1057 ((AlignViewport) codingComplement).getAlignPanel()
1058 .updateAnnotation();
1069 public void setShowDistances(boolean state)
1071 this.showDistances = state;
1081 public void setShowBootstrap(boolean state)
1083 this.showBootstrap = state;
1093 public void setMarkPlaceholders(boolean state)
1095 this.markPlaceholders = state;
1099 AlignmentPanel[] getAssociatedPanels()
1101 if (applyToAllViews)
1103 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1107 return new AlignmentPanel[] { ap };