2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 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.NJTree;
25 import jalview.datamodel.Sequence;
26 import jalview.datamodel.SequenceGroup;
27 import jalview.datamodel.SequenceI;
28 import jalview.datamodel.SequenceNode;
29 import jalview.schemes.ColourSchemeI;
30 import jalview.schemes.ColourSchemeProperty;
31 import jalview.schemes.ResidueProperties;
32 import jalview.schemes.UserColourScheme;
33 import jalview.structure.SelectionSource;
34 import jalview.util.Format;
35 import jalview.util.MappingUtils;
36 import jalview.util.MessageManager;
38 import java.awt.Color;
39 import java.awt.Dimension;
41 import java.awt.FontMetrics;
42 import java.awt.Graphics;
43 import java.awt.Graphics2D;
44 import java.awt.Point;
45 import java.awt.Rectangle;
46 import java.awt.RenderingHints;
47 import java.awt.event.MouseEvent;
48 import java.awt.event.MouseListener;
49 import java.awt.event.MouseMotionListener;
50 import java.awt.print.PageFormat;
51 import java.awt.print.Printable;
52 import java.awt.print.PrinterException;
53 import java.awt.print.PrinterJob;
54 import java.util.Enumeration;
55 import java.util.Hashtable;
56 import java.util.Vector;
58 import javax.swing.JColorChooser;
59 import javax.swing.JPanel;
60 import javax.swing.JScrollPane;
61 import javax.swing.SwingUtilities;
62 import javax.swing.ToolTipManager;
70 public class TreeCanvas extends JPanel implements MouseListener, Runnable,
71 Printable, MouseMotionListener, SelectionSource
74 public static final String PLACEHOLDER = " * ";
78 JScrollPane scrollPane;
90 boolean fitToWindow = true;
92 boolean showDistances = false;
94 boolean showBootstrap = false;
96 boolean markPlaceholders = false;
106 int labelLength = -1;
108 Hashtable nameHash = new Hashtable();
110 Hashtable nodeHash = new Hashtable();
112 SequenceNode highlightNode;
114 boolean applyToAllViews = false;
117 * Creates a new TreeCanvas object.
128 public TreeCanvas(TreePanel tp, AlignmentPanel ap, JScrollPane scroller)
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(NJTree tree)
174 tree.findHeight(tree.getTopNode());
176 // Now have to calculate longest name based on the leaves
177 Vector leaves = tree.findLeaves(tree.getTopNode(), new Vector());
178 boolean has_placeholders = false;
181 for (int i = 0; i < leaves.size(); i++)
183 SequenceNode lf = (SequenceNode) leaves.elementAt(i);
185 if (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, SequenceNode node, float chunk,
220 float scale, int width, int offx, int offy)
227 if ((node.left() == null) && (node.right() == null))
230 float height = node.height;
231 float dist = node.dist;
233 int xstart = (int) ((height - dist) * scale) + offx;
234 int xend = (int) (height * scale) + 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("%-.2f").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.isPlaceholder()) ? (PLACEHOLDER + node
282 .getName()) : node.getName();
284 int charWidth = fm.stringWidth(name) + 3;
285 int charHeight = font.getSize();
287 Rectangle rect = new Rectangle(xend + 10, ypos - charHeight / 2,
288 charWidth, charHeight);
290 nameHash.put(node.element(), rect);
292 // Colour selected leaves differently
293 SequenceGroup selected = av.getSelectionGroup();
295 if ((selected != null)
296 && selected.getSequences(null).contains(
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, (SequenceNode) node.left(), chunk, scale, width, offx,
312 drawNode(g, (SequenceNode) node.right(), chunk, scale, width, offx,
315 float height = node.height;
316 float dist = node.dist;
318 int xstart = (int) ((height - dist) * scale) + offx;
319 int xend = (int) (height * scale) + 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 = (int) (((SequenceNode) node.left()).ycount * chunk)
337 int yend = (int) (((SequenceNode) node.right()).ycount * chunk)
340 Rectangle pos = new Rectangle(xend - 2, ypos - 2, 5, 5);
341 nodeHash.put(node, pos);
343 g.drawLine((int) (height * scale) + offx, ystart,
344 (int) (height * scale) + offx, yend);
346 String nodeLabel = "";
348 if (showDistances && (node.dist > 0))
350 nodeLabel = new Format("%-.2f").form(node.dist);
353 if (showBootstrap && node.bootstrap > -1)
357 nodeLabel = nodeLabel + " : ";
360 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
363 if (!nodeLabel.equals(""))
365 g.drawString(nodeLabel, xstart + 2, ypos - 2);
378 * @return DOCUMENT ME!
380 public Object findElement(int x, int y)
382 Enumeration keys = nameHash.keys();
384 while (keys.hasMoreElements())
386 Object ob = keys.nextElement();
387 Rectangle rect = (Rectangle) nameHash.get(ob);
389 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
390 && (y <= (rect.y + rect.height)))
396 keys = nodeHash.keys();
398 while (keys.hasMoreElements())
400 Object ob = keys.nextElement();
401 Rectangle rect = (Rectangle) nodeHash.get(ob);
403 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
404 && (y <= (rect.y + rect.height)))
419 public void pickNodes(Rectangle pickBox)
421 int width = getWidth();
422 int height = getHeight();
424 SequenceNode top = tree.getTopNode();
426 float wscale = (float) ((width * .8) - (offx * 2))
427 / tree.getMaxHeight();
431 top.count = ((SequenceNode) top.left()).count
432 + ((SequenceNode) top.right()).count;
435 float chunk = (float) (height - (offy)) / top.count;
437 pickNode(pickBox, top, chunk, wscale, width, offx, offy);
458 public void pickNode(Rectangle pickBox, SequenceNode node, float chunk,
459 float scale, int width, int offx, int offy)
466 if ((node.left() == null) && (node.right() == null))
468 float height = node.height;
469 float dist = node.dist;
471 int xstart = (int) ((height - dist) * scale) + offx;
472 int xend = (int) (height * scale) + offx;
474 int ypos = (int) (node.ycount * chunk) + offy;
476 if (pickBox.contains(new Point(xend, ypos)))
478 if (node.element() instanceof SequenceI)
480 SequenceI seq = (SequenceI) node.element();
481 SequenceGroup sg = av.getSelectionGroup();
485 sg.addOrRemove(seq, true);
492 pickNode(pickBox, (SequenceNode) node.left(), chunk, scale, width,
494 pickNode(pickBox, (SequenceNode) node.right(), chunk, scale, width,
507 public void setColor(SequenceNode node, Color c)
514 if ((node.left() == null) && (node.right() == null)) // TODO: internal node
518 if (node.element() instanceof SequenceI)
520 AlignmentPanel[] aps = getAssociatedPanels();
523 for (int a = 0; a < aps.length; a++)
525 final SequenceI seq = (SequenceI) node.element();
526 aps[a].av.setSequenceColour(seq, c);
534 setColor((SequenceNode) node.left(), c);
535 setColor((SequenceNode) node.right(), c);
544 Thread thread = new Thread(this);
548 // put printing in a thread to avoid painting problems
551 PrinterJob printJob = PrinterJob.getPrinterJob();
552 PageFormat pf = printJob.pageDialog(printJob.defaultPage());
554 printJob.setPrintable(this, pf);
556 if (printJob.printDialog())
561 } catch (Exception PrintException)
563 PrintException.printStackTrace();
578 * @return DOCUMENT ME!
580 * @throws PrinterException
583 public int print(Graphics pg, PageFormat pf, int pi)
584 throws PrinterException
587 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
589 int pwidth = (int) pf.getImageableWidth();
590 int pheight = (int) pf.getImageableHeight();
592 int noPages = getHeight() / pheight;
596 return Printable.NO_SUCH_PAGE;
599 if (pwidth > getWidth())
606 if (pheight > getHeight())
608 pheight = getHeight();
615 FontMetrics fm = pg.getFontMetrics(font);
616 int height = fm.getHeight() * nameHash.size();
617 pg.translate(0, -pi * pheight);
618 pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
620 // translate number of pages,
621 // height is screen size as this is the
622 // non overlapping text size
626 draw(pg, pwidth, pheight);
628 return Printable.PAGE_EXISTS;
637 public void paintComponent(Graphics g)
639 super.paintComponent(g);
644 g.drawString(MessageManager.getString("label.calculating_tree")
645 + "....", 20, getHeight() / 2);
649 fm = g.getFontMetrics(font);
651 if (nameHash.size() == 0)
657 || (!fitToWindow && (scrollPane.getHeight() > ((fm
658 .getHeight() * nameHash.size()) + offy))))
660 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
661 setPreferredSize(null);
665 setPreferredSize(new Dimension(scrollPane.getWidth(),
666 fm.getHeight() * nameHash.size()));
667 draw(g, scrollPane.getWidth(), fm.getHeight() * nameHash.size());
670 scrollPane.revalidate();
680 public void setFont(Font font)
696 public void draw(Graphics g1, int width, int height)
698 Graphics2D g2 = (Graphics2D) g1;
699 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
700 RenderingHints.VALUE_ANTIALIAS_ON);
701 g2.setColor(Color.white);
702 g2.fillRect(0, 0, width, height);
705 if (longestName == null || tree == null)
707 g2.drawString("Calculating tree.", 20, 20);
709 offy = font.getSize() + 10;
711 fm = g2.getFontMetrics(font);
713 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
715 float wscale = (width - labelLength - (offx * 2))
716 / tree.getMaxHeight();
718 SequenceNode top = tree.getTopNode();
722 top.count = ((SequenceNode) top.left()).count
723 + ((SequenceNode) top.right()).count;
726 float chunk = (float) (height - (offy)) / top.count;
728 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
732 if (av.getCurrentTree() == tree)
734 g2.setColor(Color.red);
738 g2.setColor(Color.gray);
741 int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx))) + offx);
743 g2.drawLine(x, 0, x, getHeight());
753 public void mouseReleased(MouseEvent e)
763 public void mouseEntered(MouseEvent e)
773 public void mouseExited(MouseEvent e)
783 public void mouseClicked(MouseEvent evt)
785 if (highlightNode != null)
787 if (SwingUtilities.isRightMouseButton(evt))
789 Color col = JColorChooser.showDialog(this,
790 MessageManager.getString("label.select_subtree_colour"), highlightNode.color);
793 setColor(highlightNode, col);
796 else if (evt.getClickCount() > 1)
798 tree.swapNodes(highlightNode);
799 tree.reCount(tree.getTopNode());
800 tree.findHeight(tree.getTopNode());
804 Vector leaves = new Vector();
805 tree.findLeaves(highlightNode, leaves);
807 for (int i = 0; i < leaves.size(); i++)
809 SequenceI seq = (SequenceI) ((SequenceNode) leaves.elementAt(i))
811 treeSelectionChanged(seq);
816 PaintRefresher.Refresh(tp, av.getSequenceSetId());
821 public void mouseMoved(MouseEvent evt)
823 av.setCurrentTree(tree);
825 Object ob = findElement(evt.getX(), evt.getY());
827 if (ob instanceof SequenceNode)
829 highlightNode = (SequenceNode) ob;
830 this.setToolTipText("<html>"
831 + MessageManager.getString("label.highlightnode"));
837 if (highlightNode != null)
839 highlightNode = null;
840 setToolTipText(null);
846 public void mouseDragged(MouseEvent ect)
856 public void mousePressed(MouseEvent e)
858 av.setCurrentTree(tree);
863 Object ob = findElement(x, y);
865 if (ob instanceof SequenceI)
867 treeSelectionChanged((Sequence) ob);
868 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
873 else if (!(ob instanceof SequenceNode))
876 if (tree.getMaxHeight() != 0)
878 threshold = (float) (x - offx)
879 / (float) (getWidth() - labelLength - (2 * offx));
881 tree.getGroups().removeAllElements();
882 tree.groupNodes(tree.getTopNode(), threshold);
883 setColor(tree.getTopNode(), Color.black);
885 AlignmentPanel[] aps = getAssociatedPanels();
887 // TODO push calls below into a single AlignViewportI method?
888 // see also AlignViewController.deleteGroups
889 for (int a = 0; a < aps.length; a++)
891 aps[a].av.setSelectionGroup(null);
892 aps[a].av.getAlignment().deleteAllGroups();
893 aps[a].av.clearSequenceColours();
895 if (av.getSlave() != null)
897 av.getSlave().setSelectionGroup(null);
898 av.getSlave().getAlignment().deleteAllGroups();
899 av.getSlave().clearSequenceColours();
904 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
912 AlignmentPanel[] aps = getAssociatedPanels();
913 for (int i = 0; i < tree.getGroups().size(); i++)
915 Color col = new Color((int) (Math.random() * 255),
916 (int) (Math.random() * 255), (int) (Math.random() * 255));
917 setColor((SequenceNode) tree.getGroups().elementAt(i), col.brighter());
919 Vector l = tree.findLeaves(
920 (SequenceNode) tree.getGroups().elementAt(i), new Vector());
922 Vector sequences = new Vector();
924 for (int j = 0; j < l.size(); j++)
926 SequenceI s1 = (SequenceI) ((SequenceNode) l.elementAt(j))
929 if (!sequences.contains(s1))
931 sequences.addElement(s1);
935 ColourSchemeI cs = null;
936 SequenceGroup sg = new SequenceGroup(sequences, null, cs, true, true,
937 false, 0, av.getAlignment().getWidth() - 1);
939 if (av.getGlobalColourScheme() != null)
941 if (av.getGlobalColourScheme() instanceof UserColourScheme)
943 cs = new UserColourScheme(
944 ((UserColourScheme) av.getGlobalColourScheme())
950 cs = ColourSchemeProperty.getColour(sg, ColourSchemeProperty
951 .getColourName(av.getGlobalColourScheme()));
953 // cs is null if shading is an annotationColourGradient
956 cs.setThreshold(av.getGlobalColourScheme().getThreshold(),
957 av.getIgnoreGapsConsensus());
961 // sg.recalcConservation();
962 sg.setName("JTreeGroup:" + sg.hashCode());
965 for (int a = 0; a < aps.length; a++)
967 if (aps[a].av.getGlobalColourScheme() != null
968 && aps[a].av.getGlobalColourScheme().conservationApplied())
970 Conservation c = new Conservation("Group",
971 ResidueProperties.propHash, 3, sg.getSequences(null),
972 sg.getStartRes(), sg.getEndRes());
975 c.verdict(false, aps[a].av.getConsPercGaps());
976 sg.cs.setConservation(c);
979 aps[a].av.getAlignment().addGroup(new SequenceGroup(sg));
982 // TODO can we push all of the below into AlignViewportI?
983 av.getAlignment().addGroup(sg);
984 if (av.getSlave() != null)
986 SequenceGroup mappedGroup = MappingUtils.mapSequenceGroup(sg, av,
988 if (mappedGroup.getSequences().size() > 0)
990 av.getSlave().getAlignment().addGroup(mappedGroup);
991 for (SequenceI seq : mappedGroup.getSequences())
993 av.getSlave().setSequenceColour(seq,
994 mappedGroup.getIdColour().brighter());
1001 // notify the panel to redo any group specific stuff.
1002 for (int a = 0; a < aps.length; a++)
1004 aps[a].updateAnnotation();
1005 // TODO: JAL-868 - need to ensure view colour change message is broadcast
1006 // to any Jmols listening in
1009 if (av.getSlave() != null)
1011 ((AlignViewport) av.getSlave()).getAlignPanel().updateAnnotation();
1013 * idPanel. repaint ()
1024 public void setShowDistances(boolean state)
1026 this.showDistances = state;
1036 public void setShowBootstrap(boolean state)
1038 this.showBootstrap = state;
1048 public void setMarkPlaceholders(boolean state)
1050 this.markPlaceholders = state;
1054 AlignmentPanel[] getAssociatedPanels()
1056 if (applyToAllViews)
1058 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1062 return new AlignmentPanel[]