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 SequenceGroup selected = av.getSelectionGroup();
299 if ((selected != null)
300 && selected.getSequences(null).contains(node.element()))
302 g.setColor(Color.gray);
304 g.fillRect(xend + 10, ypos - charHeight / 2, charWidth, charHeight);
305 g.setColor(Color.white);
308 g.drawString(name, xend + 10, ypos + fm.getDescent());
309 g.setColor(Color.black);
313 drawNode(g, (BinaryNode) node.left(), chunk, wscale, width, offx,
315 drawNode(g, (BinaryNode) node.right(), chunk, wscale, width, offx,
318 double height = node.height;
319 double dist = node.dist;
321 int xstart = (int) ((height - dist) * wscale) + offx;
322 int xend = (int) (height * wscale) + offx;
323 int ypos = (int) (node.ycount * chunk) + offy;
325 g.setColor(node.color.darker());
327 // Draw horizontal line
328 g.drawLine(xstart, ypos, xend, ypos);
329 if (node == highlightNode)
331 g.fillRect(xend - 3, ypos - 3, 6, 6);
335 g.fillRect(xend - 2, ypos - 2, 4, 4);
338 int ystart = (node.left() == null ? 0
339 : (int) (((BinaryNode) node.left()).ycount * chunk)) + offy;
340 int yend = (node.right() == null ? 0
341 : (int) (((BinaryNode) node.right()).ycount * chunk))
344 Rectangle pos = new Rectangle(xend - 2, ypos - 2, 5, 5);
345 nodeHash.put(node, pos);
347 g.drawLine((int) (height * wscale) + offx, ystart,
348 (int) (height * wscale) + offx, yend);
350 String nodeLabel = "";
352 if (showDistances && (node.dist > 0))
354 nodeLabel = new Format("%g").form(node.dist);
357 if (showBootstrap && node.bootstrap > -1)
361 nodeLabel = nodeLabel + " : ";
364 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
367 if (!nodeLabel.equals(""))
369 g.drawString(nodeLabel, xstart + 2, ypos - 2);
382 * @return DOCUMENT ME!
384 public Object findElement(int x, int y)
386 for (Entry<Object, Rectangle> entry : nameHash.entrySet())
388 Rectangle rect = entry.getValue();
390 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
391 && (y <= (rect.y + rect.height)))
393 return entry.getKey();
397 for (Entry<BinaryNode, Rectangle> entry : nodeHash.entrySet())
399 Rectangle rect = entry.getValue();
401 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
402 && (y <= (rect.y + rect.height)))
404 return entry.getKey();
417 public void pickNodes(Rectangle pickBox)
419 int width = getWidth();
420 int height = getHeight();
422 BinaryNode top = tree.getTopNode();
424 double wscale = ((width * .8) - (offx * 2)) / tree.getMaxHeight();
428 top.count = ((BinaryNode) top.left()).count
429 + ((BinaryNode) top.right()).count;
432 float chunk = (float) (height - (offy)) / top.count;
434 pickNode(pickBox, top, chunk, wscale, width, offx, offy);
455 public void pickNode(Rectangle pickBox, BinaryNode node, float chunk,
456 double wscale, int width, int offx, int offy)
463 if ((node.left() == null) && (node.right() == null))
465 double height = node.height;
466 // double dist = node.dist;
467 // int xstart = (int) ((height - dist) * wscale) + offx;
468 int xend = (int) (height * wscale) + offx;
470 int ypos = (int) (node.ycount * chunk) + offy;
472 if (pickBox.contains(new Point(xend, ypos)))
474 if (node.element() instanceof SequenceI)
476 SequenceI seq = (SequenceI) node.element();
477 SequenceGroup sg = av.getSelectionGroup();
481 sg.addOrRemove(seq, true);
488 pickNode(pickBox, (BinaryNode) node.left(), chunk, wscale, width,
490 pickNode(pickBox, (BinaryNode) node.right(), chunk, wscale, width,
503 public void setColor(BinaryNode node, Color c)
511 if (node.element() instanceof SequenceI)
513 final SequenceI seq = (SequenceI) node.element();
514 AlignmentPanel[] aps = getAssociatedPanels();
517 for (int a = 0; a < aps.length; a++)
519 aps[a].av.setSequenceColour(seq, c);
523 setColor((BinaryNode) node.left(), c);
524 setColor((BinaryNode) node.right(), c);
532 Thread thread = new Thread(this);
536 // put printing in a thread to avoid painting problems
540 PrinterJob printJob = PrinterJob.getPrinterJob();
541 PageFormat defaultPage = printJob.defaultPage();
542 PageFormat pf = printJob.pageDialog(defaultPage);
544 if (defaultPage == pf)
552 printJob.setPrintable(this, pf);
554 if (printJob.printDialog())
559 } catch (Exception PrintException)
561 PrintException.printStackTrace();
576 * @return DOCUMENT ME!
578 * @throws PrinterException
582 public int print(Graphics pg, PageFormat pf, int pi)
583 throws PrinterException
586 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
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 if (pheight > getHeight())
607 pheight = getHeight();
614 FontMetrics fm = pg.getFontMetrics(font);
615 int height = fm.getHeight() * nameHash.size();
616 pg.translate(0, -pi * pheight);
617 pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
619 // translate number of pages,
620 // height is screen size as this is the
621 // non overlapping text size
625 draw(pg, pwidth, pheight);
627 return Printable.PAGE_EXISTS;
637 public void paintComponent(Graphics g)
639 super.paintComponent(g);
645 MessageManager.getString("label.calculating_tree") + "....",
646 20, getHeight() / 2);
650 fm = g.getFontMetrics(font);
652 int nameCount = nameHash.size();
658 if (fitToWindow || (!fitToWindow && (scrollPane
659 .getHeight() > ((fm.getHeight() * nameCount) + offy))))
661 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
662 setPreferredSize(null);
666 setPreferredSize(new Dimension(scrollPane.getWidth(),
667 fm.getHeight() * nameCount));
668 draw(g, scrollPane.getWidth(), fm.getHeight() * nameCount);
671 scrollPane.revalidate();
682 public void setFont(Font font)
698 public void draw(Graphics g1, int width, int height)
700 Graphics2D g2 = (Graphics2D) g1;
701 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
702 RenderingHints.VALUE_ANTIALIAS_ON);
703 g2.setColor(Color.white);
704 g2.fillRect(0, 0, width, height);
707 if (longestName == null || tree == null)
709 g2.drawString("Calculating tree.", 20, 20);
711 offy = font.getSize() + 10;
713 fm = g2.getFontMetrics(font);
715 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
717 double wscale = (width - labelLength - (offx * 2))
718 / tree.getMaxHeight();
720 BinaryNode top = tree.getTopNode();
724 top.count = ((BinaryNode) top.left()).count
725 + ((BinaryNode) top.right()).count;
728 float chunk = (float) (height - (offy)) / top.count;
730 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
734 if (av.getCurrentTree() == tree)
736 g2.setColor(Color.red);
740 g2.setColor(Color.gray);
743 int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx)))
746 g2.drawLine(x, 0, x, getHeight());
751 * Empty method to satisfy the MouseListener interface
756 public void mouseReleased(MouseEvent e)
759 * isPopupTrigger is set on mouseReleased on Windows
761 if (e.isPopupTrigger())
763 chooseSubtreeColour();
764 e.consume(); // prevent mouseClicked happening
769 * Empty method to satisfy the MouseListener interface
774 public void mouseEntered(MouseEvent e)
779 * Empty method to satisfy the MouseListener interface
784 public void mouseExited(MouseEvent e)
789 * Handles a mouse click on a tree node (clicks elsewhere are handled in
790 * mousePressed). Click selects the sub-tree, double-click swaps leaf nodes
791 * order, right-click opens a dialogue to choose colour for the sub-tree.
796 public void mouseClicked(MouseEvent evt)
798 if (highlightNode == null)
803 if (evt.getClickCount() > 1)
805 tree.swapNodes(highlightNode);
806 tree.reCount(tree.getTopNode());
807 tree.findHeight(tree.getTopNode());
811 Vector<BinaryNode> leaves = tree.findLeaves(highlightNode);
812 if (tp.getColumnWise()) {
813 markColumnsFor(getAssociatedPanels(), leaves, Color.red);
815 for (int i = 0; i < leaves.size(); i++)
817 SequenceI seq = (SequenceI) leaves.elementAt(i).element();
818 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 String ttl = MessageManager.getString("label.select_subtree_colour");
836 ColourChooserListener listener = new ColourChooserListener()
839 public void colourSelected(Color c)
841 setColor(highlightNode, c);
842 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
846 JalviewColourChooser.showColourChooser(this, ttl, highlightNode.color,
851 public void mouseMoved(MouseEvent evt)
853 av.setCurrentTree(tree);
855 Object ob = findElement(evt.getX(), evt.getY());
857 if (ob instanceof BinaryNode)
859 highlightNode = (BinaryNode) ob;
861 "<html>" + MessageManager.getString("label.highlightnode"));
867 if (highlightNode != null)
869 highlightNode = null;
870 setToolTipText(null);
877 public void mouseDragged(MouseEvent ect)
882 * Handles a mouse press on a sequence name or the tree background canvas
883 * (click on a node is handled in mouseClicked). The action is to create
884 * groups by partitioning the tree at the mouse position. Colours for the
885 * groups (and sequence names) are generated randomly.
890 public void mousePressed(MouseEvent e)
892 av.setCurrentTree(tree);
895 * isPopupTrigger is set for mousePressed (Mac)
896 * or mouseReleased (Windows)
898 if (e.isPopupTrigger())
900 if (highlightNode != null)
902 chooseSubtreeColour();
908 * defer right-click handling on Windows to
909 * mouseClicked; note isRightMouseButton
910 * also matches Cmd-click on Mac which should do
913 if (SwingUtilities.isRightMouseButton(e))
921 Object ob = findElement(x, y);
923 if (ob instanceof SequenceI)
925 treeSelectionChanged((Sequence) ob);
926 PaintRefresher.Refresh(tp,
927 getAssociatedPanel().av.getSequenceSetId());
932 else if (!(ob instanceof BinaryNode))
935 if (tree.getMaxHeight() != 0)
937 threshold = (float) (x - offx)
938 / (float) (getWidth() - labelLength - (2 * offx));
940 List<BinaryNode> 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,
974 getAssociatedPanel().av.getSequenceSetId());
980 void colourGroups(List<BinaryNode> groups)
982 AlignmentPanel[] aps = getAssociatedPanels();
983 for (int i = 0; i < groups.size(); i++)
985 Color col = new Color((int) (Math.random() * 255),
986 (int) (Math.random() * 255), (int) (Math.random() * 255));
987 setColor(groups.get(i), col.brighter());
989 Vector<BinaryNode> l = tree.findLeaves(groups.get(i));
990 if (!tp.getColumnWise()) {
991 createSeqGroupFor(aps, l, col);
993 markColumnsFor(aps,l,col);
997 // notify the panel(s) to redo any group specific stuff
998 // also updates structure views if necessary
999 for (int a = 0; a < aps.length; a++)
1001 aps[a].updateAnnotation();
1002 final AlignViewportI codingComplement = aps[a].av
1003 .getCodingComplement();
1004 if (codingComplement != null)
1006 ((AlignViewport) codingComplement).getAlignPanel()
1007 .updateAnnotation();
1012 private void markColumnsFor(AlignmentPanel[] aps, Vector<BinaryNode> l,
1015 SequenceI rseq = tp.assocAnnotation.sequenceRef;
1016 for (BinaryNode bn:l)
1020 colm = Integer.parseInt(bn.getName().substring(bn.getName().indexOf("c")+1));
1021 } catch (Exception e)
1025 ColumnSelection cs = av.getColumnSelection();
1026 HiddenColumns hc = av.getAlignment().getHiddenColumns();
1028 int offp = (rseq!=null) ? rseq.findIndex(rseq.getStart()-1+colm) : colm;
1030 if (!av.hasHiddenColumns() || hc.isVisible(offp))
1032 if (cs.contains(offp))
1034 cs.removeElement(offp);
1036 cs.addElement(offp);
1043 public void createSeqGroupFor(AlignmentPanel[] aps, Vector<BinaryNode> l,
1047 Vector<SequenceI> sequences = new Vector<>();
1049 for (int j = 0; j < l.size(); j++)
1051 SequenceI s1 = (SequenceI) l.elementAt(j).element();
1053 if (!sequences.contains(s1))
1055 sequences.addElement(s1);
1059 ColourSchemeI cs = null;
1060 SequenceGroup _sg = new SequenceGroup(sequences, null, cs, true, true,
1061 false, 0, av.getAlignment().getWidth() - 1);
1063 _sg.setName("JTreeGroup:" + _sg.hashCode());
1064 _sg.setIdColour(col);
1066 for (int a = 0; a < aps.length; a++)
1068 SequenceGroup sg = new SequenceGroup(_sg);
1069 AlignViewport viewport = aps[a].av;
1071 // Propagate group colours in each view
1072 if (viewport.getGlobalColourScheme() != null)
1074 cs = viewport.getGlobalColourScheme().getInstance(viewport, sg);
1075 sg.setColourScheme(cs);
1076 sg.getGroupColourScheme().setThreshold(
1077 viewport.getResidueShading().getThreshold(),
1078 viewport.isIgnoreGapsConsensus());
1080 if (viewport.getResidueShading().conservationApplied())
1082 Conservation c = new Conservation("Group", sg.getSequences(null),
1083 sg.getStartRes(), sg.getEndRes());
1085 c.verdict(false, viewport.getConsPercGaps());
1086 sg.cs.setConservation(c);
1089 // indicate that associated structure views will need an update
1090 viewport.setUpdateStructures(true);
1091 // propagate structure view update and sequence group to complement view
1092 viewport.addSequenceGroup(sg);
1102 public void setShowDistances(boolean state)
1104 this.showDistances = state;
1114 public void setShowBootstrap(boolean state)
1116 this.showBootstrap = state;
1126 public void setMarkPlaceholders(boolean state)
1128 this.markPlaceholders = state;
1132 AlignmentPanel[] getAssociatedPanels()
1134 if (applyToAllViews)
1136 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1140 return new AlignmentPanel[] { getAssociatedPanel() };
1144 public AlignmentPanel getAssociatedPanel()
1149 public void setAssociatedPanel(AlignmentPanel ap)
1154 public AlignViewport getViewport()
1159 public void setViewport(AlignViewport av)
1164 public float getThreshold()
1169 public void setThreshold(float threshold)
1171 this.threshold = threshold;
1174 public boolean isApplyToAllViews()
1176 return this.applyToAllViews;
1179 public void setApplyToAllViews(boolean applyToAllViews)
1181 this.applyToAllViews = applyToAllViews;