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 java.awt.Color;
24 import java.awt.Dimension;
26 import java.awt.FontMetrics;
27 import java.awt.Graphics;
28 import java.awt.Graphics2D;
29 import java.awt.Point;
30 import java.awt.Rectangle;
31 import java.awt.RenderingHints;
32 import java.awt.event.MouseEvent;
33 import java.awt.event.MouseListener;
34 import java.awt.event.MouseMotionListener;
35 import java.awt.print.PageFormat;
36 import java.awt.print.Printable;
37 import java.awt.print.PrinterException;
38 import java.awt.print.PrinterJob;
39 import java.util.Hashtable;
40 import java.util.List;
42 import java.util.Map.Entry;
43 import java.util.Vector;
45 import javax.swing.JPanel;
46 import javax.swing.JScrollPane;
47 import javax.swing.SwingUtilities;
48 import javax.swing.ToolTipManager;
50 import jalview.analysis.Conservation;
51 import jalview.analysis.TreeModel;
52 import jalview.api.AlignViewportI;
53 import jalview.datamodel.BinaryNode;
54 import jalview.datamodel.Sequence;
55 import jalview.datamodel.SequenceGroup;
56 import jalview.datamodel.SequenceI;
57 import jalview.datamodel.SequenceNode;
58 import jalview.gui.JalviewColourChooser.ColourChooserListener;
59 import jalview.schemes.ColourSchemeI;
60 import jalview.structure.SelectionSource;
61 import jalview.util.Format;
62 import jalview.util.MessageManager;
70 public class TreeCanvas extends JPanel implements MouseListener, Runnable,
71 Printable, MouseMotionListener, SelectionSource
74 public static final String PLACEHOLDER = " * ";
78 JScrollPane scrollPane;
82 private AlignViewport av;
84 private AlignmentPanel ap;
90 boolean fitToWindow = true;
92 boolean showDistances = false;
94 boolean showBootstrap = false;
96 boolean markPlaceholders = false;
102 private float threshold;
106 int labelLength = -1;
108 Map<Object, Rectangle> nameHash = new Hashtable<>();
110 Map<BinaryNode, Rectangle> nodeHash = new Hashtable<>();
112 BinaryNode highlightNode;
114 boolean applyToAllViews = false;
117 * Creates a new TreeCanvas object.
128 public TreeCanvas(TreePanel tp, AlignmentPanel ap, JScrollPane scroller)
132 this.setAssociatedPanel(ap);
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<BinaryNode> leaves = tree.findLeaves(tree.getTopNode());
178 boolean has_placeholders = false;
181 for (int i = 0; i < leaves.size(); i++)
183 BinaryNode lf = leaves.elementAt(i);
185 if (lf instanceof SequenceNode && ((SequenceNode)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, BinaryNode 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("%g").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 instanceof SequenceNode && ((SequenceNode)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, (BinaryNode) node.left(), chunk, wscale, width, offx,
312 drawNode(g, (BinaryNode) 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) (((BinaryNode) node.left()).ycount * chunk)) + offy;
337 int yend = (node.right() == null ? 0
338 : (int) (((BinaryNode) 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("%g").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 for (Entry<Object, Rectangle> entry : nameHash.entrySet())
385 Rectangle rect = entry.getValue();
387 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
388 && (y <= (rect.y + rect.height)))
390 return entry.getKey();
394 for (Entry<BinaryNode, Rectangle> entry : nodeHash.entrySet())
396 Rectangle rect = entry.getValue();
398 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
399 && (y <= (rect.y + rect.height)))
401 return entry.getKey();
414 public void pickNodes(Rectangle pickBox)
416 int width = getWidth();
417 int height = getHeight();
419 BinaryNode top = tree.getTopNode();
421 double wscale = ((width * .8) - (offx * 2)) / tree.getMaxHeight();
425 top.count = ((BinaryNode) top.left()).count
426 + ((BinaryNode) top.right()).count;
429 float chunk = (float) (height - (offy)) / top.count;
431 pickNode(pickBox, top, chunk, wscale, width, offx, offy);
452 public void pickNode(Rectangle pickBox, BinaryNode node, float chunk,
453 double wscale, int width, int offx, int offy)
460 if ((node.left() == null) && (node.right() == null))
462 double height = node.height;
463 // double dist = node.dist;
464 // int xstart = (int) ((height - dist) * wscale) + offx;
465 int xend = (int) (height * wscale) + offx;
467 int ypos = (int) (node.ycount * chunk) + offy;
469 if (pickBox.contains(new Point(xend, ypos)))
471 if (node.element() instanceof SequenceI)
473 SequenceI seq = (SequenceI) node.element();
474 SequenceGroup sg = av.getSelectionGroup();
478 sg.addOrRemove(seq, true);
485 pickNode(pickBox, (BinaryNode) node.left(), chunk, wscale, width,
487 pickNode(pickBox, (BinaryNode) node.right(), chunk, wscale, width,
500 public void setColor(BinaryNode node, Color c)
508 if (node.element() instanceof SequenceI)
510 final SequenceI seq = (SequenceI) node.element();
511 AlignmentPanel[] aps = getAssociatedPanels();
514 for (int a = 0; a < aps.length; a++)
516 aps[a].av.setSequenceColour(seq, c);
520 setColor((BinaryNode) node.left(), c);
521 setColor((BinaryNode) node.right(), c);
529 Thread thread = new Thread(this);
533 // put printing in a thread to avoid painting problems
537 PrinterJob printJob = PrinterJob.getPrinterJob();
538 PageFormat defaultPage = printJob.defaultPage();
539 PageFormat pf = printJob.pageDialog(defaultPage);
541 if (defaultPage == pf)
549 printJob.setPrintable(this, pf);
551 if (printJob.printDialog())
556 } catch (Exception PrintException)
558 PrintException.printStackTrace();
573 * @return DOCUMENT ME!
575 * @throws PrinterException
579 public int print(Graphics pg, PageFormat pf, int pi)
580 throws PrinterException
583 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
585 int pwidth = (int) pf.getImageableWidth();
586 int pheight = (int) pf.getImageableHeight();
588 int noPages = getHeight() / pheight;
592 return Printable.NO_SUCH_PAGE;
595 if (pwidth > getWidth())
602 if (pheight > getHeight())
604 pheight = getHeight();
611 FontMetrics fm = pg.getFontMetrics(font);
612 int height = fm.getHeight() * nameHash.size();
613 pg.translate(0, -pi * pheight);
614 pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
616 // translate number of pages,
617 // height is screen size as this is the
618 // non overlapping text size
622 draw(pg, pwidth, pheight);
624 return Printable.PAGE_EXISTS;
634 public void paintComponent(Graphics g)
636 super.paintComponent(g);
642 MessageManager.getString("label.calculating_tree") + "....",
643 20, getHeight() / 2);
647 fm = g.getFontMetrics(font);
649 int nameCount = nameHash.size();
655 if (fitToWindow || (!fitToWindow && (scrollPane
656 .getHeight() > ((fm.getHeight() * nameCount) + offy))))
658 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
659 setPreferredSize(null);
663 setPreferredSize(new Dimension(scrollPane.getWidth(),
664 fm.getHeight() * nameCount));
665 draw(g, scrollPane.getWidth(), fm.getHeight() * nameCount);
668 scrollPane.revalidate();
679 public void setFont(Font font)
695 public void draw(Graphics g1, int width, int height)
697 Graphics2D g2 = (Graphics2D) g1;
698 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
699 RenderingHints.VALUE_ANTIALIAS_ON);
700 g2.setColor(Color.white);
701 g2.fillRect(0, 0, width, height);
704 if (longestName == null || tree == null)
706 g2.drawString("Calculating tree.", 20, 20);
708 offy = font.getSize() + 10;
710 fm = g2.getFontMetrics(font);
712 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
714 double wscale = (width - labelLength - (offx * 2))
715 / tree.getMaxHeight();
717 BinaryNode top = tree.getTopNode();
721 top.count = ((BinaryNode) top.left()).count
722 + ((BinaryNode) top.right()).count;
725 float chunk = (float) (height - (offy)) / top.count;
727 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
731 if (av.getCurrentTree() == tree)
733 g2.setColor(Color.red);
737 g2.setColor(Color.gray);
740 int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx)))
743 g2.drawLine(x, 0, x, getHeight());
748 * Empty method to satisfy the MouseListener interface
753 public void mouseReleased(MouseEvent e)
756 * isPopupTrigger is set on mouseReleased on Windows
758 if (e.isPopupTrigger())
760 chooseSubtreeColour();
761 e.consume(); // prevent mouseClicked happening
766 * Empty method to satisfy the MouseListener interface
771 public void mouseEntered(MouseEvent e)
776 * Empty method to satisfy the MouseListener interface
781 public void mouseExited(MouseEvent e)
786 * Handles a mouse click on a tree node (clicks elsewhere are handled in
787 * mousePressed). Click selects the sub-tree, double-click swaps leaf nodes
788 * order, right-click opens a dialogue to choose colour for the sub-tree.
793 public void mouseClicked(MouseEvent evt)
795 if (highlightNode == null)
800 if (evt.getClickCount() > 1)
802 tree.swapNodes(highlightNode);
803 tree.reCount(tree.getTopNode());
804 tree.findHeight(tree.getTopNode());
808 Vector<BinaryNode> leaves = tree.findLeaves(highlightNode);
810 for (int i = 0; i < leaves.size(); i++)
812 SequenceI seq = (SequenceI) leaves.elementAt(i).element();
813 treeSelectionChanged(seq);
818 PaintRefresher.Refresh(tp, av.getSequenceSetId());
823 * Offer the user the option to choose a colour for the highlighted node and
824 * its children; this colour is also applied to the corresponding sequence ids
827 void chooseSubtreeColour()
829 String ttl = MessageManager.getString("label.select_subtree_colour");
830 ColourChooserListener listener = new ColourChooserListener()
833 public void colourSelected(Color c)
835 setColor(highlightNode, c);
836 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
840 JalviewColourChooser.showColourChooser(this, ttl, highlightNode.color,
845 public void mouseMoved(MouseEvent evt)
847 av.setCurrentTree(tree);
849 Object ob = findElement(evt.getX(), evt.getY());
851 if (ob instanceof BinaryNode)
853 highlightNode = (BinaryNode) ob;
855 "<html>" + 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,
921 getAssociatedPanel().av.getSequenceSetId());
926 else if (!(ob instanceof BinaryNode))
929 if (tree.getMaxHeight() != 0)
931 threshold = (float) (x - offx)
932 / (float) (getWidth() - labelLength - (2 * offx));
934 List<BinaryNode> groups = tree.groupNodes(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();
953 aps[a].av.setUpdateStructures(true);
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,
968 getAssociatedPanel().av.getSequenceSetId());
974 void colourGroups(List<BinaryNode> groups)
976 AlignmentPanel[] aps = getAssociatedPanels();
977 for (int i = 0; i < groups.size(); i++)
979 Color col = new Color((int) (Math.random() * 255),
980 (int) (Math.random() * 255), (int) (Math.random() * 255));
981 setColor(groups.get(i), col.brighter());
983 Vector<BinaryNode> l = tree.findLeaves(groups.get(i));
985 Vector<SequenceI> sequences = new Vector<>();
987 for (int j = 0; j < l.size(); j++)
989 SequenceI s1 = (SequenceI) l.elementAt(j).element();
991 if (!sequences.contains(s1))
993 sequences.addElement(s1);
997 ColourSchemeI cs = null;
998 SequenceGroup _sg = new SequenceGroup(sequences, null, cs, true, true,
999 false, 0, av.getAlignment().getWidth() - 1);
1001 _sg.setName("JTreeGroup:" + _sg.hashCode());
1002 _sg.setIdColour(col);
1004 for (int a = 0; a < aps.length; a++)
1006 SequenceGroup sg = new SequenceGroup(_sg);
1007 AlignViewport viewport = aps[a].av;
1009 // Propagate group colours in each view
1010 if (viewport.getGlobalColourScheme() != null)
1012 cs = viewport.getGlobalColourScheme().getInstance(viewport, sg);
1013 sg.setColourScheme(cs);
1014 sg.getGroupColourScheme().setThreshold(
1015 viewport.getResidueShading().getThreshold(),
1016 viewport.isIgnoreGapsConsensus());
1018 if (viewport.getResidueShading().conservationApplied())
1020 Conservation c = new Conservation("Group",
1021 sg.getSequences(null), sg.getStartRes(),
1024 c.verdict(false, viewport.getConsPercGaps());
1025 sg.cs.setConservation(c);
1028 // indicate that associated structure views will need an update
1029 viewport.setUpdateStructures(true);
1030 // propagate structure view update and sequence group to complement view
1031 viewport.addSequenceGroup(sg);
1035 // notify the panel(s) to redo any group specific stuff
1036 // also updates structure views if necessary
1037 for (int a = 0; a < aps.length; a++)
1039 aps[a].updateAnnotation();
1040 final AlignViewportI codingComplement = aps[a].av
1041 .getCodingComplement();
1042 if (codingComplement != null)
1044 ((AlignViewport) codingComplement).getAlignPanel()
1045 .updateAnnotation();
1056 public void setShowDistances(boolean state)
1058 this.showDistances = state;
1068 public void setShowBootstrap(boolean state)
1070 this.showBootstrap = state;
1080 public void setMarkPlaceholders(boolean state)
1082 this.markPlaceholders = state;
1086 AlignmentPanel[] getAssociatedPanels()
1088 if (applyToAllViews)
1090 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1094 return new AlignmentPanel[] { getAssociatedPanel() };
1098 public AlignmentPanel getAssociatedPanel()
1103 public void setAssociatedPanel(AlignmentPanel ap)
1108 public AlignViewport getViewport()
1113 public void setViewport(AlignViewport av)
1118 public float getThreshold()
1123 public void setThreshold(float threshold)
1125 this.threshold = threshold;
1128 public boolean isApplyToAllViews()
1130 return this.applyToAllViews;
1133 public void setApplyToAllViews(boolean applyToAllViews)
1135 this.applyToAllViews = applyToAllViews;