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.gui.JalviewColourChooser.ColourChooserListener;
31 import jalview.schemes.ColourSchemeI;
32 import jalview.structure.SelectionSource;
33 import jalview.util.Format;
34 import jalview.util.MessageManager;
36 import java.awt.Color;
37 import java.awt.Dimension;
39 import java.awt.FontMetrics;
40 import java.awt.Graphics;
41 import java.awt.Graphics2D;
42 import java.awt.Point;
43 import java.awt.Rectangle;
44 import java.awt.RenderingHints;
45 import java.awt.event.MouseEvent;
46 import java.awt.event.MouseListener;
47 import java.awt.event.MouseMotionListener;
48 import java.awt.print.PageFormat;
49 import java.awt.print.Printable;
50 import java.awt.print.PrinterException;
51 import java.awt.print.PrinterJob;
52 import java.util.Enumeration;
53 import java.util.Hashtable;
54 import java.util.List;
55 import java.util.Vector;
57 import javax.swing.JPanel;
58 import javax.swing.JScrollPane;
59 import javax.swing.SwingUtilities;
60 import javax.swing.ToolTipManager;
68 public class TreeCanvas extends JPanel implements MouseListener, Runnable,
69 Printable, MouseMotionListener, SelectionSource
72 public static final String PLACEHOLDER = " * ";
76 JScrollPane scrollPane;
80 private AlignViewport av;
82 private AlignmentPanel ap;
88 boolean fitToWindow = true;
90 boolean showDistances = false;
92 boolean showBootstrap = false;
94 boolean markPlaceholders = false;
100 private float threshold;
104 int labelLength = -1;
106 Hashtable nameHash = new Hashtable();
108 Hashtable nodeHash = new Hashtable();
110 SequenceNode highlightNode;
112 boolean applyToAllViews = false;
115 * Creates a new TreeCanvas object.
126 public TreeCanvas(TreePanel tp, AlignmentPanel ap, JScrollPane scroller)
130 this.setAssociatedPanel(ap);
132 scrollPane = scroller;
133 addMouseListener(this);
134 addMouseMotionListener(this);
135 ToolTipManager.sharedInstance().registerComponent(this);
144 public void treeSelectionChanged(SequenceI sequence)
146 AlignmentPanel[] aps = getAssociatedPanels();
148 for (int a = 0; a < aps.length; a++)
150 SequenceGroup selected = aps[a].av.getSelectionGroup();
152 if (selected == null)
154 selected = new SequenceGroup();
155 aps[a].av.setSelectionGroup(selected);
158 selected.setEndRes(aps[a].av.getAlignment().getWidth() - 1);
159 selected.addOrRemove(sequence, true);
169 public void setTree(TreeModel tree)
172 tree.findHeight(tree.getTopNode());
174 // Now have to calculate longest name based on the leaves
175 Vector<SequenceNode> leaves = tree.findLeaves(tree.getTopNode());
176 boolean has_placeholders = false;
179 for (int i = 0; i < leaves.size(); i++)
181 SequenceNode lf = leaves.elementAt(i);
183 if (lf.isPlaceholder())
185 has_placeholders = true;
188 if (longestName.length() < ((Sequence) lf.element()).getName()
191 longestName = TreeCanvas.PLACEHOLDER
192 + ((Sequence) lf.element()).getName();
196 setMarkPlaceholders(has_placeholders);
217 public void drawNode(Graphics g, SequenceNode node, float chunk,
218 double wscale, int width, int offx, int offy)
225 if ((node.left() == null) && (node.right() == null))
228 double height = node.height;
229 double dist = node.dist;
231 int xstart = (int) ((height - dist) * wscale) + offx;
232 int xend = (int) (height * wscale) + offx;
234 int ypos = (int) (node.ycount * chunk) + offy;
236 if (node.element() instanceof SequenceI)
238 SequenceI seq = (SequenceI) node.element();
240 if (av.getSequenceColour(seq) == Color.white)
242 g.setColor(Color.black);
246 g.setColor(av.getSequenceColour(seq).darker());
251 g.setColor(Color.black);
254 // Draw horizontal line
255 g.drawLine(xstart, ypos, xend, ypos);
257 String nodeLabel = "";
259 if (showDistances && (node.dist > 0))
261 nodeLabel = new Format("%-.2f").form(node.dist);
264 if (showBootstrap && node.bootstrap > -1)
268 nodeLabel = nodeLabel + " : ";
271 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
274 if (!nodeLabel.equals(""))
276 g.drawString(nodeLabel, xstart + 2, ypos - 2);
279 String name = (markPlaceholders && node.isPlaceholder())
280 ? (PLACEHOLDER + node.getName())
283 int charWidth = fm.stringWidth(name) + 3;
284 int charHeight = font.getSize();
286 Rectangle rect = new Rectangle(xend + 10, ypos - charHeight / 2,
287 charWidth, charHeight);
289 nameHash.put(node.element(), rect);
291 // Colour selected leaves differently
292 SequenceGroup selected = av.getSelectionGroup();
294 if ((selected != null)
295 && selected.getSequences(null).contains(node.element()))
297 g.setColor(Color.gray);
299 g.fillRect(xend + 10, ypos - charHeight / 2, charWidth, charHeight);
300 g.setColor(Color.white);
303 g.drawString(name, xend + 10, ypos + fm.getDescent());
304 g.setColor(Color.black);
308 drawNode(g, (SequenceNode) node.left(), chunk, wscale, width, offx,
310 drawNode(g, (SequenceNode) node.right(), chunk, wscale, width, offx,
313 double height = node.height;
314 double dist = node.dist;
316 int xstart = (int) ((height - dist) * wscale) + offx;
317 int xend = (int) (height * wscale) + offx;
318 int ypos = (int) (node.ycount * chunk) + offy;
320 g.setColor(node.color.darker());
322 // Draw horizontal line
323 g.drawLine(xstart, ypos, xend, ypos);
324 if (node == highlightNode)
326 g.fillRect(xend - 3, ypos - 3, 6, 6);
330 g.fillRect(xend - 2, ypos - 2, 4, 4);
333 int ystart = (node.left() == null ? 0
334 : (int) (((SequenceNode) node.left()).ycount * chunk)) + offy;
335 int yend = (node.right() == null ? 0
336 : (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 * wscale) + offx, ystart,
343 (int) (height * wscale) + 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 double wscale = ((width * .8) - (offx * 2)) / tree.getMaxHeight();
429 top.count = ((SequenceNode) top.left()).count
430 + ((SequenceNode) top.right()).count;
433 float chunk = (float) (height - (offy)) / top.count;
435 pickNode(pickBox, top, chunk, wscale, width, offx, offy);
456 public void pickNode(Rectangle pickBox, SequenceNode node, float chunk,
457 double wscale, int width, int offx, int offy)
464 if ((node.left() == null) && (node.right() == null))
466 double height = node.height;
467 double dist = node.dist;
469 int xstart = (int) ((height - dist) * wscale) + offx;
470 int xend = (int) (height * wscale) + offx;
472 int ypos = (int) (node.ycount * chunk) + offy;
474 if (pickBox.contains(new Point(xend, ypos)))
476 if (node.element() instanceof SequenceI)
478 SequenceI seq = (SequenceI) node.element();
479 SequenceGroup sg = av.getSelectionGroup();
483 sg.addOrRemove(seq, true);
490 pickNode(pickBox, (SequenceNode) node.left(), chunk, wscale, width,
492 pickNode(pickBox, (SequenceNode) node.right(), chunk, wscale, width,
505 public void setColor(SequenceNode node, Color c)
513 if (node.element() instanceof SequenceI)
515 final SequenceI seq = (SequenceI) node.element();
516 AlignmentPanel[] aps = getAssociatedPanels();
519 for (int a = 0; a < aps.length; a++)
521 aps[a].av.setSequenceColour(seq, c);
525 setColor((SequenceNode) node.left(), c);
526 setColor((SequenceNode) node.right(), c);
534 Thread thread = new Thread(this);
538 // put printing in a thread to avoid painting problems
542 PrinterJob printJob = PrinterJob.getPrinterJob();
543 PageFormat defaultPage = printJob.defaultPage();
544 PageFormat pf = printJob.pageDialog(defaultPage);
546 if (defaultPage == pf)
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 int pwidth = (int) pf.getImageableWidth();
589 int pheight = (int) pf.getImageableHeight();
591 int noPages = getHeight() / pheight;
595 return Printable.NO_SUCH_PAGE;
598 if (pwidth > getWidth())
605 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
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 // BH 2020.03.19 avoiding setClip here
622 pg.clipRect(0, pi * pheight, pwidth, (pi * pheight) + pheight);
624 // translate number of pages,
625 // height is screen size as this is the
626 // non overlapping text size
630 draw(pg, pwidth, pheight);
634 return Printable.PAGE_EXISTS;
644 public void paintComponent(Graphics g)
646 super.paintComponent(g);
652 MessageManager.getString("label.calculating_tree") + "....",
653 20, getHeight() / 2);
657 fm = g.getFontMetrics(font);
659 if (nameHash.size() == 0)
664 if (fitToWindow || (!fitToWindow && (scrollPane
665 .getHeight() > ((fm.getHeight() * nameHash.size()) + offy))))
667 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
668 setPreferredSize(null);
672 setPreferredSize(new Dimension(scrollPane.getWidth(),
673 fm.getHeight() * nameHash.size()));
674 draw(g, scrollPane.getWidth(), fm.getHeight() * nameHash.size());
677 scrollPane.revalidate();
688 public void setFont(Font font)
704 public void draw(Graphics g1, int width, int height)
706 Graphics2D g2 = (Graphics2D) g1;
707 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
708 RenderingHints.VALUE_ANTIALIAS_ON);
709 g2.setColor(Color.white);
710 g2.fillRect(0, 0, width, height);
713 if (longestName == null || tree == null)
715 g2.drawString("Calculating tree.", 20, 20);
717 offy = font.getSize() + 10;
719 fm = g2.getFontMetrics(font);
721 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
723 double wscale = (width - labelLength - (offx * 2))
724 / tree.getMaxHeight();
726 SequenceNode top = tree.getTopNode();
730 top.count = ((SequenceNode) top.left()).count
731 + ((SequenceNode) top.right()).count;
734 float chunk = (float) (height - (offy)) / top.count;
736 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
740 if (av.getCurrentTree() == tree)
742 g2.setColor(Color.red);
746 g2.setColor(Color.gray);
749 int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx)))
752 g2.drawLine(x, 0, x, getHeight());
757 * Empty method to satisfy the MouseListener interface
762 public void mouseReleased(MouseEvent e)
765 * isPopupTrigger is set on mouseReleased on Windows
767 if (e.isPopupTrigger())
769 chooseSubtreeColour();
770 e.consume(); // prevent mouseClicked happening
775 * Empty method to satisfy the MouseListener interface
780 public void mouseEntered(MouseEvent e)
785 * Empty method to satisfy the MouseListener interface
790 public void mouseExited(MouseEvent e)
795 * Handles a mouse click on a tree node (clicks elsewhere are handled in
796 * mousePressed). Click selects the sub-tree, double-click swaps leaf nodes
797 * order, right-click opens a dialogue to choose colour for the sub-tree.
802 public void mouseClicked(MouseEvent evt)
804 if (highlightNode == null)
809 if (evt.getClickCount() > 1)
811 tree.swapNodes(highlightNode);
812 tree.reCount(tree.getTopNode());
813 tree.findHeight(tree.getTopNode());
817 Vector<SequenceNode> leaves = tree.findLeaves(highlightNode);
819 for (int i = 0; i < leaves.size(); i++)
821 SequenceI seq = (SequenceI) leaves.elementAt(i).element();
822 treeSelectionChanged(seq);
827 PaintRefresher.Refresh(tp, av.getSequenceSetId());
832 * Offer the user the option to choose a colour for the highlighted node and
833 * its children; this colour is also applied to the corresponding sequence ids
836 void chooseSubtreeColour()
838 String ttl = MessageManager.getString("label.select_subtree_colour");
839 ColourChooserListener listener = new ColourChooserListener() {
841 public void colourSelected(Color c)
843 setColor(highlightNode, c);
844 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
848 JalviewColourChooser.showColourChooser(this, ttl, highlightNode.color, listener);
852 public void mouseMoved(MouseEvent evt)
854 av.setCurrentTree(tree);
856 Object ob = findElement(evt.getX(), evt.getY());
858 if (ob instanceof SequenceNode)
860 highlightNode = (SequenceNode) ob;
862 "<html>" + MessageManager.getString("label.highlightnode"));
868 if (highlightNode != null)
870 highlightNode = null;
871 setToolTipText(null);
878 public void mouseDragged(MouseEvent ect)
883 * Handles a mouse press on a sequence name or the tree background canvas
884 * (click on a node is handled in mouseClicked). The action is to create
885 * groups by partitioning the tree at the mouse position. Colours for the
886 * groups (and sequence names) are generated randomly.
891 public void mousePressed(MouseEvent e)
893 av.setCurrentTree(tree);
896 * isPopupTrigger is set for mousePressed (Mac)
897 * or mouseReleased (Windows)
899 if (e.isPopupTrigger())
901 if (highlightNode != null)
903 chooseSubtreeColour();
909 * defer right-click handling on Windows to
910 * mouseClicked; note isRightMouseButton
911 * also matches Cmd-click on Mac which should do
914 if (SwingUtilities.isRightMouseButton(e))
922 Object ob = findElement(x, y);
924 if (ob instanceof SequenceI)
926 treeSelectionChanged((Sequence) ob);
927 PaintRefresher.Refresh(tp, getAssociatedPanel().av.getSequenceSetId());
932 else if (!(ob instanceof SequenceNode))
935 if (tree.getMaxHeight() != 0)
937 threshold = (float) (x - offx)
938 / (float) (getWidth() - labelLength - (2 * offx));
940 List<SequenceNode> groups = tree.groupNodes(threshold);
941 setColor(tree.getTopNode(), Color.black);
943 AlignmentPanel[] aps = getAssociatedPanels();
945 // TODO push calls below into a single AlignViewportI method?
946 // see also AlignViewController.deleteGroups
947 for (int a = 0; a < aps.length; a++)
949 aps[a].av.setSelectionGroup(null);
950 aps[a].av.getAlignment().deleteAllGroups();
951 aps[a].av.clearSequenceColours();
952 if (aps[a].av.getCodingComplement() != null)
954 aps[a].av.getCodingComplement().setSelectionGroup(null);
955 aps[a].av.getCodingComplement().getAlignment()
957 aps[a].av.getCodingComplement().clearSequenceColours();
959 aps[a].av.setUpdateStructures(true);
961 colourGroups(groups);
964 * clear partition (don't show vertical line) if
965 * it is to the right of all nodes
967 if (groups.isEmpty())
973 PaintRefresher.Refresh(tp, getAssociatedPanel().av.getSequenceSetId());
979 void colourGroups(List<SequenceNode> groups)
981 AlignmentPanel[] aps = getAssociatedPanels();
982 for (int i = 0; i < groups.size(); i++)
984 Color col = new Color((int) (Math.random() * 255),
985 (int) (Math.random() * 255), (int) (Math.random() * 255));
986 setColor(groups.get(i), col.brighter());
988 Vector<SequenceNode> l = tree.findLeaves(groups.get(i));
990 Vector<SequenceI> sequences = new Vector<>();
992 for (int j = 0; j < l.size(); j++)
994 SequenceI s1 = (SequenceI) l.elementAt(j).element();
996 if (!sequences.contains(s1))
998 sequences.addElement(s1);
1002 ColourSchemeI cs = null;
1003 SequenceGroup _sg = new SequenceGroup(sequences, null, cs, true, true,
1004 false, 0, av.getAlignment().getWidth() - 1);
1006 _sg.setName("JTreeGroup:" + _sg.hashCode());
1007 _sg.setIdColour(col);
1009 for (int a = 0; a < aps.length; a++)
1011 SequenceGroup sg = new SequenceGroup(_sg);
1012 AlignViewport viewport = aps[a].av;
1014 // Propagate group colours in each view
1015 if (viewport.getGlobalColourScheme() != null)
1017 cs = viewport.getGlobalColourScheme().getInstance(viewport, sg);
1018 sg.setColourScheme(cs);
1019 sg.getGroupColourScheme().setThreshold(
1020 viewport.getResidueShading().getThreshold(),
1021 viewport.isIgnoreGapsConsensus());
1023 if (viewport.getResidueShading().conservationApplied())
1025 Conservation c = new Conservation("Group",
1026 sg.getSequences(null), sg.getStartRes(),
1029 c.verdict(false, viewport.getConsPercGaps());
1030 sg.cs.setConservation(c);
1033 // indicate that associated structure views will need an update
1034 viewport.setUpdateStructures(true);
1035 // propagate structure view update and sequence group to complement view
1036 viewport.addSequenceGroup(sg);
1040 // notify the panel(s) to redo any group specific stuff
1041 // also updates structure views if necessary
1042 for (int a = 0; a < aps.length; a++)
1044 aps[a].updateAnnotation();
1045 final AlignViewportI codingComplement = aps[a].av
1046 .getCodingComplement();
1047 if (codingComplement != null)
1049 ((AlignViewport) codingComplement).getAlignPanel()
1050 .updateAnnotation();
1061 public void setShowDistances(boolean state)
1063 this.showDistances = state;
1073 public void setShowBootstrap(boolean state)
1075 this.showBootstrap = state;
1085 public void setMarkPlaceholders(boolean state)
1087 this.markPlaceholders = state;
1091 AlignmentPanel[] getAssociatedPanels()
1093 if (applyToAllViews)
1095 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1099 return new AlignmentPanel[] { getAssociatedPanel() };
1103 public AlignmentPanel getAssociatedPanel()
1108 public void setAssociatedPanel(AlignmentPanel ap)
1113 public AlignViewport getViewport()
1118 public void setViewport(AlignViewport av)
1123 public float getThreshold()
1128 public void setThreshold(float threshold)
1130 this.threshold = threshold;
1133 public boolean isApplyToAllViews()
1135 return this.applyToAllViews;
1138 public void setApplyToAllViews(boolean applyToAllViews)
1140 this.applyToAllViews = applyToAllViews;