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.BitSet;
40 import java.util.Hashtable;
41 import java.util.List;
43 import java.util.Map.Entry;
44 import java.util.Vector;
46 import javax.swing.JPanel;
47 import javax.swing.JScrollPane;
48 import javax.swing.SwingUtilities;
49 import javax.swing.ToolTipManager;
51 import jalview.analysis.Conservation;
52 import jalview.analysis.TreeModel;
53 import jalview.api.AlignViewportI;
54 import jalview.datamodel.BinaryNode;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.HiddenColumns;
57 import jalview.datamodel.Sequence;
58 import jalview.datamodel.SequenceGroup;
59 import jalview.datamodel.SequenceI;
60 import jalview.datamodel.SequenceNode;
61 import jalview.gui.JalviewColourChooser.ColourChooserListener;
62 import jalview.schemes.ColourSchemeI;
63 import jalview.structure.SelectionSource;
64 import jalview.util.Format;
65 import jalview.util.MessageManager;
73 public class TreeCanvas extends JPanel implements MouseListener, Runnable,
74 Printable, MouseMotionListener, SelectionSource
77 public static final String PLACEHOLDER = " * ";
81 JScrollPane scrollPane;
85 private AlignViewport av;
87 private AlignmentPanel ap;
93 boolean fitToWindow = true;
95 boolean showDistances = false;
97 boolean showBootstrap = false;
99 boolean markPlaceholders = false;
105 private float threshold;
109 int labelLength = -1;
111 Map<Object, Rectangle> nameHash = new Hashtable<>();
113 Map<BinaryNode, Rectangle> nodeHash = new Hashtable<>();
115 BinaryNode highlightNode;
117 boolean applyToAllViews = false;
120 * Creates a new TreeCanvas object.
131 public TreeCanvas(TreePanel tp, AlignmentPanel ap, JScrollPane scroller)
135 this.setAssociatedPanel(ap);
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(TreeModel tree)
177 tree.findHeight(tree.getTopNode());
179 // Now have to calculate longest name based on the leaves
180 Vector<BinaryNode> leaves = tree.findLeaves(tree.getTopNode());
181 boolean has_placeholders = false;
184 for (int i = 0; i < leaves.size(); i++)
186 BinaryNode lf = leaves.elementAt(i);
188 if (lf instanceof SequenceNode && ((SequenceNode)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, BinaryNode node, float chunk,
223 double wscale, int width, int offx, int offy)
230 if ((node.left() == null) && (node.right() == null))
233 double height = node.height;
234 double dist = node.dist;
236 int xstart = (int) ((height - dist) * wscale) + offx;
237 int xend = (int) (height * wscale) + 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(av.getSequenceColour(seq).darker());
256 g.setColor(Color.black);
259 // Draw horizontal line
260 g.drawLine(xstart, ypos, xend, ypos);
262 String nodeLabel = "";
264 if (showDistances && (node.dist > 0))
266 nodeLabel = new Format("%g").form(node.dist);
269 if (showBootstrap && node.bootstrap > -1)
273 nodeLabel = nodeLabel + " : ";
276 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
279 if (!nodeLabel.equals(""))
281 g.drawString(nodeLabel, xstart + 2, ypos - 2);
284 String name = (markPlaceholders && ((node instanceof SequenceNode && ((SequenceNode)node).isPlaceholder())))
285 ? (PLACEHOLDER + 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 boolean isSelected = false;
298 if (tp.isColumnWise())
300 isSelected = isColumnForNodeSelected(node);
304 SequenceGroup selected = av.getSelectionGroup();
306 if ((selected != null)
307 && selected.getSequences(null).contains(node.element()))
314 g.setColor(Color.gray);
316 g.fillRect(xend + 10, ypos - charHeight / 2, charWidth, charHeight);
317 g.setColor(Color.white);
320 g.drawString(name, xend + 10, ypos + fm.getDescent());
321 g.setColor(Color.black);
325 drawNode(g, (BinaryNode) node.left(), chunk, wscale, width, offx,
327 drawNode(g, (BinaryNode) node.right(), chunk, wscale, width, offx,
330 double height = node.height;
331 double dist = node.dist;
333 int xstart = (int) ((height - dist) * wscale) + offx;
334 int xend = (int) (height * wscale) + offx;
335 int ypos = (int) (node.ycount * chunk) + offy;
337 g.setColor(node.color.darker());
339 // Draw horizontal line
340 g.drawLine(xstart, ypos, xend, ypos);
341 if (node == highlightNode)
343 g.fillRect(xend - 3, ypos - 3, 6, 6);
347 g.fillRect(xend - 2, ypos - 2, 4, 4);
350 int ystart = (node.left() == null ? 0
351 : (int) (((BinaryNode) node.left()).ycount * chunk)) + offy;
352 int yend = (node.right() == null ? 0
353 : (int) (((BinaryNode) node.right()).ycount * chunk))
356 Rectangle pos = new Rectangle(xend - 2, ypos - 2, 5, 5);
357 nodeHash.put(node, pos);
359 g.drawLine((int) (height * wscale) + offx, ystart,
360 (int) (height * wscale) + offx, yend);
362 String nodeLabel = "";
364 if (showDistances && (node.dist > 0))
366 nodeLabel = new Format("%g").form(node.dist);
369 if (showBootstrap && node.bootstrap > -1)
373 nodeLabel = nodeLabel + " : ";
376 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
379 if (!nodeLabel.equals(""))
381 g.drawString(nodeLabel, xstart + 2, ypos - 2);
394 * @return DOCUMENT ME!
396 public Object findElement(int x, int y)
398 for (Entry<Object, Rectangle> entry : nameHash.entrySet())
400 Rectangle rect = entry.getValue();
402 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
403 && (y <= (rect.y + rect.height)))
405 return entry.getKey();
409 for (Entry<BinaryNode, Rectangle> entry : nodeHash.entrySet())
411 Rectangle rect = entry.getValue();
413 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
414 && (y <= (rect.y + rect.height)))
416 return entry.getKey();
429 public void pickNodes(Rectangle pickBox)
431 int width = getWidth();
432 int height = getHeight();
434 BinaryNode top = tree.getTopNode();
436 double wscale = ((width * .8) - (offx * 2)) / tree.getMaxHeight();
440 top.count = ((BinaryNode) top.left()).count
441 + ((BinaryNode) top.right()).count;
444 float chunk = (float) (height - (offy)) / top.count;
446 pickNode(pickBox, top, chunk, wscale, width, offx, offy);
467 public void pickNode(Rectangle pickBox, BinaryNode node, float chunk,
468 double wscale, int width, int offx, int offy)
475 if ((node.left() == null) && (node.right() == null))
477 double height = node.height;
478 // double dist = node.dist;
479 // int xstart = (int) ((height - dist) * wscale) + offx;
480 int xend = (int) (height * wscale) + offx;
482 int ypos = (int) (node.ycount * chunk) + offy;
484 if (pickBox.contains(new Point(xend, ypos)))
486 if (node.element() instanceof SequenceI)
488 SequenceI seq = (SequenceI) node.element();
489 SequenceGroup sg = av.getSelectionGroup();
493 sg.addOrRemove(seq, true);
500 pickNode(pickBox, (BinaryNode) node.left(), chunk, wscale, width,
502 pickNode(pickBox, (BinaryNode) node.right(), chunk, wscale, width,
515 public void setColor(BinaryNode node, Color c)
523 if (node.element() instanceof SequenceI)
525 final SequenceI seq = (SequenceI) node.element();
526 AlignmentPanel[] aps = getAssociatedPanels();
529 for (int a = 0; a < aps.length; a++)
531 aps[a].av.setSequenceColour(seq, c);
535 setColor((BinaryNode) node.left(), c);
536 setColor((BinaryNode) 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);
657 MessageManager.getString("label.calculating_tree") + "....",
658 20, getHeight() / 2);
662 fm = g.getFontMetrics(font);
664 int nameCount = nameHash.size();
670 if (fitToWindow || (!fitToWindow && (scrollPane
671 .getHeight() > ((fm.getHeight() * nameCount) + offy))))
673 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
674 setPreferredSize(null);
678 setPreferredSize(new Dimension(scrollPane.getWidth(),
679 fm.getHeight() * nameCount));
680 draw(g, scrollPane.getWidth(), fm.getHeight() * nameCount);
683 scrollPane.revalidate();
694 public void setFont(Font font)
710 public void draw(Graphics g1, int width, int height)
712 Graphics2D g2 = (Graphics2D) g1;
713 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
714 RenderingHints.VALUE_ANTIALIAS_ON);
715 g2.setColor(Color.white);
716 g2.fillRect(0, 0, width, height);
719 if (longestName == null || tree == null)
721 g2.drawString("Calculating tree.", 20, 20);
724 offy = font.getSize() + 10;
726 fm = g2.getFontMetrics(font);
728 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
730 double wscale = (width - labelLength - (offx * 2))
731 / tree.getMaxHeight();
733 BinaryNode top = tree.getTopNode();
737 top.count = ((BinaryNode) top.left()).count
738 + ((BinaryNode) top.right()).count;
741 float chunk = (float) (height - (offy)) / top.count;
743 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
747 if (av.getCurrentTree() == tree)
749 g2.setColor(Color.red);
753 g2.setColor(Color.gray);
756 int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx)))
759 g2.drawLine(x, 0, x, getHeight());
764 * Empty method to satisfy the MouseListener interface
769 public void mouseReleased(MouseEvent e)
772 * isPopupTrigger is set on mouseReleased on Windows
774 if (e.isPopupTrigger())
776 chooseSubtreeColour();
777 e.consume(); // prevent mouseClicked happening
782 * Empty method to satisfy the MouseListener interface
787 public void mouseEntered(MouseEvent e)
792 * Empty method to satisfy the MouseListener interface
797 public void mouseExited(MouseEvent e)
802 * Handles a mouse click on a tree node (clicks elsewhere are handled in
803 * mousePressed). Click selects the sub-tree, double-click swaps leaf nodes
804 * order, right-click opens a dialogue to choose colour for the sub-tree.
809 public void mouseClicked(MouseEvent evt)
811 if (highlightNode == null)
816 if (evt.getClickCount() > 1)
818 tree.swapNodes(highlightNode);
819 tree.reCount(tree.getTopNode());
820 tree.findHeight(tree.getTopNode());
824 Vector<BinaryNode> leaves = tree.findLeaves(highlightNode);
825 if (tp.isColumnWise()) {
826 markColumnsFor(getAssociatedPanels(), leaves, Color.red);
828 for (int i = 0; i < leaves.size(); i++)
830 SequenceI seq = (SequenceI) leaves.elementAt(i).element();
831 treeSelectionChanged(seq);
837 PaintRefresher.Refresh(tp, av.getSequenceSetId());
842 * Offer the user the option to choose a colour for the highlighted node and
843 * its children; this colour is also applied to the corresponding sequence ids
846 void chooseSubtreeColour()
848 String ttl = MessageManager.getString("label.select_subtree_colour");
849 ColourChooserListener listener = new ColourChooserListener()
852 public void colourSelected(Color c)
854 setColor(highlightNode, c);
855 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
859 JalviewColourChooser.showColourChooser(this, ttl, highlightNode.color,
864 public void mouseMoved(MouseEvent evt)
866 av.setCurrentTree(tree);
868 Object ob = findElement(evt.getX(), evt.getY());
870 if (ob instanceof BinaryNode)
872 highlightNode = (BinaryNode) ob;
874 "<html>" + MessageManager.getString("label.highlightnode"));
880 if (highlightNode != null)
882 highlightNode = null;
883 setToolTipText(null);
890 public void mouseDragged(MouseEvent ect)
895 * Handles a mouse press on a sequence name or the tree background canvas
896 * (click on a node is handled in mouseClicked). The action is to create
897 * groups by partitioning the tree at the mouse position. Colours for the
898 * groups (and sequence names) are generated randomly.
903 public void mousePressed(MouseEvent e)
905 av.setCurrentTree(tree);
908 * isPopupTrigger is set for mousePressed (Mac)
909 * or mouseReleased (Windows)
911 if (e.isPopupTrigger())
913 if (highlightNode != null)
915 chooseSubtreeColour();
921 * defer right-click handling on Windows to
922 * mouseClicked; note isRightMouseButton
923 * also matches Cmd-click on Mac which should do
926 if (SwingUtilities.isRightMouseButton(e))
934 Object ob = findElement(x, y);
936 if (ob instanceof SequenceI)
938 treeSelectionChanged((Sequence) ob);
939 PaintRefresher.Refresh(tp,
940 getAssociatedPanel().av.getSequenceSetId());
945 else if (!(ob instanceof BinaryNode))
948 if (tree.getMaxHeight() != 0)
950 threshold = (float) (x - offx)
951 / (float) (getWidth() - labelLength - (2 * offx));
953 List<BinaryNode> groups = tree.groupNodes(threshold);
954 setColor(tree.getTopNode(), Color.black);
956 AlignmentPanel[] aps = getAssociatedPanels();
958 // TODO push calls below into a single AlignViewportI method?
959 // see also AlignViewController.deleteGroups
960 for (int a = 0; a < aps.length; a++)
962 aps[a].av.setSelectionGroup(null);
963 aps[a].av.getAlignment().deleteAllGroups();
964 aps[a].av.clearSequenceColours();
965 if (aps[a].av.getCodingComplement() != null)
967 aps[a].av.getCodingComplement().setSelectionGroup(null);
968 aps[a].av.getCodingComplement().getAlignment()
970 aps[a].av.getCodingComplement().clearSequenceColours();
972 aps[a].av.setUpdateStructures(true);
974 colourGroups(groups);
977 * clear partition (don't show vertical line) if
978 * it is to the right of all nodes
980 if (groups.isEmpty())
986 PaintRefresher.Refresh(tp,
987 getAssociatedPanel().av.getSequenceSetId());
993 void colourGroups(List<BinaryNode> groups)
995 AlignmentPanel[] aps = getAssociatedPanels();
996 for (int i = 0; i < groups.size(); i++)
998 Color col = new Color((int) (Math.random() * 255),
999 (int) (Math.random() * 255), (int) (Math.random() * 255));
1000 setColor(groups.get(i), col.brighter());
1002 Vector<BinaryNode> l = tree.findLeaves(groups.get(i));
1003 if (!tp.isColumnWise()) {
1004 createSeqGroupFor(aps, l, col);
1006 markColumnsFor(aps,l,col);
1010 // notify the panel(s) to redo any group specific stuff
1011 // also updates structure views if necessary
1012 for (int a = 0; a < aps.length; a++)
1014 aps[a].updateAnnotation();
1015 final AlignViewportI codingComplement = aps[a].av
1016 .getCodingComplement();
1017 if (codingComplement != null)
1019 ((AlignViewport) codingComplement).getAlignPanel()
1020 .updateAnnotation();
1025 private boolean isColumnForNodeSelected(BinaryNode bn)
1027 SequenceI rseq = tp.assocAnnotation.sequenceRef;
1031 colm = Integer.parseInt(
1032 bn.getName().substring(bn.getName().indexOf("c") + 1));
1033 } catch (Exception e)
1037 if (av==null||av.getAlignment()==null)
1039 // alignment is closed
1042 ColumnSelection cs = av.getColumnSelection();
1044 HiddenColumns hc = av.getAlignment().getHiddenColumns();
1045 int offp = (rseq != null) ? rseq.findIndex(rseq.getStart() + colm)
1048 if (!av.hasHiddenColumns())
1050 return cs.contains(offp-1);
1052 if (hc.isVisible(offp-1))
1054 return cs.contains(offp-1);
1055 // return cs.contains(hc.absoluteToVisibleColumn(offp));
1060 private void markColumnsFor(AlignmentPanel[] aps, Vector<BinaryNode> l,
1063 SequenceI rseq = tp.assocAnnotation.sequenceRef;
1064 if (av==null||av.getAlignment()==null)
1066 // alignment is closed
1070 for (BinaryNode bn:l)
1074 colm = Integer.parseInt(bn.getName().substring(bn.getName().indexOf("c")+1));
1075 } catch (Exception e)
1079 ColumnSelection cs = av.getColumnSelection();
1080 HiddenColumns hc = av.getAlignment().getHiddenColumns();
1082 int offp = (rseq!=null) ? rseq.findIndex(rseq.getStart()-1+colm) : colm;
1084 if (!av.hasHiddenColumns() || hc.isVisible(offp))
1086 if (cs.contains(offp))
1088 cs.removeElement(offp);
1090 cs.addElement(offp);
1097 public void createSeqGroupFor(AlignmentPanel[] aps, Vector<BinaryNode> l,
1101 Vector<SequenceI> sequences = new Vector<>();
1103 for (int j = 0; j < l.size(); j++)
1105 SequenceI s1 = (SequenceI) l.elementAt(j).element();
1107 if (!sequences.contains(s1))
1109 sequences.addElement(s1);
1113 ColourSchemeI cs = null;
1114 SequenceGroup _sg = new SequenceGroup(sequences, null, cs, true, true,
1115 false, 0, av.getAlignment().getWidth() - 1);
1117 _sg.setName("JTreeGroup:" + _sg.hashCode());
1118 _sg.setIdColour(col);
1120 for (int a = 0; a < aps.length; a++)
1122 SequenceGroup sg = new SequenceGroup(_sg);
1123 AlignViewport viewport = aps[a].av;
1125 // Propagate group colours in each view
1126 if (viewport.getGlobalColourScheme() != null)
1128 cs = viewport.getGlobalColourScheme().getInstance(viewport, sg);
1129 sg.setColourScheme(cs);
1130 sg.getGroupColourScheme().setThreshold(
1131 viewport.getResidueShading().getThreshold(),
1132 viewport.isIgnoreGapsConsensus());
1134 if (viewport.getResidueShading().conservationApplied())
1136 Conservation c = new Conservation("Group", sg.getSequences(null),
1137 sg.getStartRes(), sg.getEndRes());
1139 c.verdict(false, viewport.getConsPercGaps());
1140 sg.cs.setConservation(c);
1143 // indicate that associated structure views will need an update
1144 viewport.setUpdateStructures(true);
1145 // propagate structure view update and sequence group to complement view
1146 viewport.addSequenceGroup(sg);
1156 public void setShowDistances(boolean state)
1158 this.showDistances = state;
1168 public void setShowBootstrap(boolean state)
1170 this.showBootstrap = state;
1180 public void setMarkPlaceholders(boolean state)
1182 this.markPlaceholders = state;
1186 AlignmentPanel[] getAssociatedPanels()
1188 if (applyToAllViews)
1190 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1194 return new AlignmentPanel[] { getAssociatedPanel() };
1198 public AlignmentPanel getAssociatedPanel()
1203 public void setAssociatedPanel(AlignmentPanel ap)
1208 public AlignViewport getViewport()
1213 public void setViewport(AlignViewport av)
1218 public float getThreshold()
1223 public void setThreshold(float threshold)
1225 this.threshold = threshold;
1228 public boolean isApplyToAllViews()
1230 return this.applyToAllViews;
1233 public void setApplyToAllViews(boolean applyToAllViews)
1235 this.applyToAllViews = applyToAllViews;