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 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
590 int pwidth = (int) pf.getImageableWidth();
591 int pheight = (int) pf.getImageableHeight();
593 int noPages = getHeight() / pheight;
597 return Printable.NO_SUCH_PAGE;
600 if (pwidth > getWidth())
607 if (pheight > getHeight())
609 pheight = getHeight();
616 FontMetrics fm = pg.getFontMetrics(font);
617 int height = fm.getHeight() * nameHash.size();
618 pg.translate(0, -pi * pheight);
619 pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
621 // translate number of pages,
622 // height is screen size as this is the
623 // non overlapping text size
627 draw(pg, pwidth, pheight);
629 return Printable.PAGE_EXISTS;
639 public void paintComponent(Graphics g)
641 super.paintComponent(g);
647 MessageManager.getString("label.calculating_tree") + "....",
648 20, getHeight() / 2);
652 fm = g.getFontMetrics(font);
654 if (nameHash.size() == 0)
659 if (fitToWindow || (!fitToWindow && (scrollPane
660 .getHeight() > ((fm.getHeight() * nameHash.size()) + offy))))
662 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
663 setPreferredSize(null);
667 setPreferredSize(new Dimension(scrollPane.getWidth(),
668 fm.getHeight() * nameHash.size()));
669 draw(g, scrollPane.getWidth(), fm.getHeight() * nameHash.size());
672 scrollPane.revalidate();
683 public void setFont(Font font)
699 public void draw(Graphics g1, int width, int height)
701 Graphics2D g2 = (Graphics2D) g1;
702 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
703 RenderingHints.VALUE_ANTIALIAS_ON);
704 g2.setColor(Color.white);
705 g2.fillRect(0, 0, width, height);
708 if (longestName == null || tree == null)
710 g2.drawString("Calculating tree.", 20, 20);
712 offy = font.getSize() + 10;
714 fm = g2.getFontMetrics(font);
716 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
718 double wscale = (width - labelLength - (offx * 2))
719 / tree.getMaxHeight();
721 SequenceNode top = tree.getTopNode();
725 top.count = ((SequenceNode) top.left()).count
726 + ((SequenceNode) top.right()).count;
729 float chunk = (float) (height - (offy)) / top.count;
731 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
735 if (av.getCurrentTree() == tree)
737 g2.setColor(Color.red);
741 g2.setColor(Color.gray);
744 int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx)))
747 g2.drawLine(x, 0, x, getHeight());
752 * Empty method to satisfy the MouseListener interface
757 public void mouseReleased(MouseEvent e)
760 * isPopupTrigger is set on mouseReleased on Windows
762 if (e.isPopupTrigger())
764 if (highlightNode != null) {
765 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 String ttl = MessageManager.getString("label.select_subtree_colour");
836 ColourChooserListener listener = new ColourChooserListener() {
838 public void colourSelected(Color c)
840 setColor(highlightNode, c);
841 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
845 JalviewColourChooser.showColourChooser(this, ttl, highlightNode.color, listener);
849 public void mouseMoved(MouseEvent evt)
851 av.setCurrentTree(tree);
853 Object ob = findElement(evt.getX(), evt.getY());
855 if (ob instanceof SequenceNode)
857 highlightNode = (SequenceNode) ob;
859 "<html>" + MessageManager.getString("label.highlightnode"));
865 if (highlightNode != null)
867 highlightNode = null;
868 setToolTipText(null);
875 public void mouseDragged(MouseEvent ect)
880 * Handles a mouse press on a sequence name or the tree background canvas
881 * (click on a node is handled in mouseClicked). The action is to create
882 * groups by partitioning the tree at the mouse position. Colours for the
883 * groups (and sequence names) are generated randomly.
888 public void mousePressed(MouseEvent e)
890 av.setCurrentTree(tree);
893 * isPopupTrigger is set for mousePressed (Mac)
894 * or mouseReleased (Windows)
896 if (e.isPopupTrigger())
898 if (highlightNode != null)
900 chooseSubtreeColour();
906 * defer right-click handling on Windows to
907 * mouseClicked; note isRightMouseButton
908 * also matches Cmd-click on Mac which should do
911 if (SwingUtilities.isRightMouseButton(e))
919 Object ob = findElement(x, y);
921 if (ob instanceof SequenceI)
923 treeSelectionChanged((Sequence) ob);
924 PaintRefresher.Refresh(tp, getAssociatedPanel().av.getSequenceSetId());
929 else if (!(ob instanceof SequenceNode))
932 if (tree.getMaxHeight() != 0)
934 threshold = (float) (x - offx)
935 / (float) (getWidth() - labelLength - (2 * offx));
937 List<SequenceNode> groups = tree.groupNodes(threshold);
938 setColor(tree.getTopNode(), Color.black);
940 AlignmentPanel[] aps = getAssociatedPanels();
942 // TODO push calls below into a single AlignViewportI method?
943 // see also AlignViewController.deleteGroups
944 for (int a = 0; a < aps.length; a++)
946 aps[a].av.setSelectionGroup(null);
947 aps[a].av.getAlignment().deleteAllGroups();
948 aps[a].av.clearSequenceColours();
949 if (aps[a].av.getCodingComplement() != null)
951 aps[a].av.getCodingComplement().setSelectionGroup(null);
952 aps[a].av.getCodingComplement().getAlignment()
954 aps[a].av.getCodingComplement().clearSequenceColours();
956 aps[a].av.setUpdateStructures(true);
958 colourGroups(groups);
961 * clear partition (don't show vertical line) if
962 * it is to the right of all nodes
964 if (groups.isEmpty())
970 PaintRefresher.Refresh(tp, getAssociatedPanel().av.getSequenceSetId());
976 void colourGroups(List<SequenceNode> groups)
978 AlignmentPanel[] aps = getAssociatedPanels();
979 for (int i = 0; i < groups.size(); i++)
981 Color col = new Color((int) (Math.random() * 255),
982 (int) (Math.random() * 255), (int) (Math.random() * 255));
983 setColor(groups.get(i), col.brighter());
985 Vector<SequenceNode> l = tree.findLeaves(groups.get(i));
987 Vector<SequenceI> sequences = new Vector<>();
989 for (int j = 0; j < l.size(); j++)
991 SequenceI s1 = (SequenceI) l.elementAt(j).element();
993 if (!sequences.contains(s1))
995 sequences.addElement(s1);
999 ColourSchemeI cs = null;
1000 SequenceGroup _sg = new SequenceGroup(sequences, null, cs, true, true,
1001 false, 0, av.getAlignment().getWidth() - 1);
1003 _sg.setName("JTreeGroup:" + _sg.hashCode());
1004 _sg.setIdColour(col);
1006 for (int a = 0; a < aps.length; a++)
1008 SequenceGroup sg = new SequenceGroup(_sg);
1009 AlignViewport viewport = aps[a].av;
1011 // Propagate group colours in each view
1012 if (viewport.getGlobalColourScheme() != null)
1014 cs = viewport.getGlobalColourScheme().getInstance(viewport, sg);
1015 sg.setColourScheme(cs);
1016 sg.getGroupColourScheme().setThreshold(
1017 viewport.getResidueShading().getThreshold(),
1018 viewport.isIgnoreGapsConsensus());
1020 if (viewport.getResidueShading().conservationApplied())
1022 Conservation c = new Conservation("Group",
1023 sg.getSequences(null), sg.getStartRes(),
1026 c.verdict(false, viewport.getConsPercGaps());
1027 sg.cs.setConservation(c);
1030 // indicate that associated structure views will need an update
1031 viewport.setUpdateStructures(true);
1032 // propagate structure view update and sequence group to complement view
1033 viewport.addSequenceGroup(sg);
1037 // notify the panel(s) to redo any group specific stuff
1038 // also updates structure views if necessary
1039 for (int a = 0; a < aps.length; a++)
1041 aps[a].updateAnnotation();
1042 final AlignViewportI codingComplement = aps[a].av
1043 .getCodingComplement();
1044 if (codingComplement != null)
1046 ((AlignViewport) codingComplement).getAlignPanel()
1047 .updateAnnotation();
1058 public void setShowDistances(boolean state)
1060 this.showDistances = state;
1070 public void setShowBootstrap(boolean state)
1072 this.showBootstrap = state;
1082 public void setMarkPlaceholders(boolean state)
1084 this.markPlaceholders = state;
1088 AlignmentPanel[] getAssociatedPanels()
1090 if (applyToAllViews)
1092 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1096 return new AlignmentPanel[] { getAssociatedPanel() };
1100 public AlignmentPanel getAssociatedPanel()
1105 public void setAssociatedPanel(AlignmentPanel ap)
1110 public AlignViewport getViewport()
1115 public void setViewport(AlignViewport av)
1120 public float getThreshold()
1125 public void setThreshold(float threshold)
1127 this.threshold = threshold;
1130 public boolean isApplyToAllViews()
1132 return this.applyToAllViews;
1135 public void setApplyToAllViews(boolean applyToAllViews)
1137 this.applyToAllViews = applyToAllViews;