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.NJTree;
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.schemes.Colour;
31 import jalview.schemes.ColourSchemeI;
32 import jalview.schemes.ColourSchemeProperty;
33 import jalview.schemes.ResidueProperties;
34 import jalview.schemes.UserColourScheme;
35 import jalview.structure.SelectionSource;
36 import jalview.util.ColorUtils;
37 import jalview.util.Format;
38 import jalview.util.MappingUtils;
39 import jalview.util.MessageManager;
41 import java.awt.Color;
42 import java.awt.Dimension;
44 import java.awt.FontMetrics;
45 import java.awt.Graphics;
46 import java.awt.Graphics2D;
47 import java.awt.Point;
48 import java.awt.Rectangle;
49 import java.awt.RenderingHints;
50 import java.awt.event.MouseEvent;
51 import java.awt.event.MouseListener;
52 import java.awt.event.MouseMotionListener;
53 import java.awt.print.PageFormat;
54 import java.awt.print.Printable;
55 import java.awt.print.PrinterException;
56 import java.awt.print.PrinterJob;
57 import java.util.Enumeration;
58 import java.util.Hashtable;
59 import java.util.Vector;
61 import javax.swing.JColorChooser;
62 import javax.swing.JPanel;
63 import javax.swing.JScrollPane;
64 import javax.swing.ToolTipManager;
72 public class TreeCanvas extends JPanel implements MouseListener, Runnable,
73 Printable, MouseMotionListener, SelectionSource
76 public static final String PLACEHOLDER = " * ";
80 JScrollPane scrollPane;
92 boolean fitToWindow = true;
94 boolean showDistances = false;
96 boolean showBootstrap = false;
98 boolean markPlaceholders = false;
108 int labelLength = -1;
110 Hashtable nameHash = new Hashtable();
112 Hashtable nodeHash = new Hashtable();
114 SequenceNode highlightNode;
116 boolean applyToAllViews = false;
119 * Creates a new TreeCanvas object.
130 public TreeCanvas(TreePanel tp, AlignmentPanel ap, JScrollPane scroller)
136 scrollPane = scroller;
137 addMouseListener(this);
138 addMouseMotionListener(this);
139 ToolTipManager.sharedInstance().registerComponent(this);
148 public void treeSelectionChanged(SequenceI sequence)
150 AlignmentPanel[] aps = getAssociatedPanels();
152 for (int a = 0; a < aps.length; a++)
154 SequenceGroup selected = aps[a].av.getSelectionGroup();
156 if (selected == null)
158 selected = new SequenceGroup();
159 aps[a].av.setSelectionGroup(selected);
162 selected.setEndRes(aps[a].av.getAlignment().getWidth() - 1);
163 selected.addOrRemove(sequence, true);
173 public void setTree(NJTree tree)
176 tree.findHeight(tree.getTopNode());
178 // Now have to calculate longest name based on the leaves
179 Vector leaves = tree.findLeaves(tree.getTopNode(), new Vector());
180 boolean has_placeholders = false;
183 for (int i = 0; i < leaves.size(); i++)
185 SequenceNode lf = (SequenceNode) leaves.elementAt(i);
187 if (lf.isPlaceholder())
189 has_placeholders = true;
192 if (longestName.length() < ((Sequence) lf.element()).getName()
195 longestName = TreeCanvas.PLACEHOLDER
196 + ((Sequence) lf.element()).getName();
200 setMarkPlaceholders(has_placeholders);
221 public void drawNode(Graphics g, SequenceNode node, float chunk,
222 float scale, int width, int offx, int offy)
229 if ((node.left() == null) && (node.right() == null))
232 float height = node.height;
233 float dist = node.dist;
235 int xstart = (int) ((height - dist) * scale) + offx;
236 int xend = (int) (height * scale) + offx;
238 int ypos = (int) (node.ycount * chunk) + offy;
240 if (node.element() instanceof SequenceI)
242 SequenceI seq = (SequenceI) node.element();
244 if (av.getSequenceColour(seq) == Color.white)
246 g.setColor(Color.black);
250 g.setColor(ColorUtils.getColor(av.getSequenceColour(seq))
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("%-.2f").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.isPlaceholder()) ? (PLACEHOLDER + node
285 .getName()) : node.getName();
287 int charWidth = fm.stringWidth(name) + 3;
288 int charHeight = font.getSize();
290 Rectangle rect = new Rectangle(xend + 10, ypos - charHeight / 2,
291 charWidth, charHeight);
293 nameHash.put(node.element(), rect);
295 // Colour selected leaves differently
296 SequenceGroup selected = av.getSelectionGroup();
298 if ((selected != null)
299 && selected.getSequences(null).contains(node.element()))
301 g.setColor(Color.gray);
303 g.fillRect(xend + 10, ypos - charHeight / 2, charWidth, charHeight);
304 g.setColor(Color.white);
307 g.drawString(name, xend + 10, ypos + fm.getDescent());
308 g.setColor(Color.black);
312 drawNode(g, (SequenceNode) node.left(), chunk, scale, width, offx,
314 drawNode(g, (SequenceNode) node.right(), chunk, scale, width, offx,
317 float height = node.height;
318 float dist = node.dist;
320 int xstart = (int) ((height - dist) * scale) + offx;
321 int xend = (int) (height * scale) + offx;
322 int ypos = (int) (node.ycount * chunk) + offy;
324 g.setColor(node.color.darker());
326 // Draw horizontal line
327 g.drawLine(xstart, ypos, xend, ypos);
328 if (node == highlightNode)
330 g.fillRect(xend - 3, ypos - 3, 6, 6);
334 g.fillRect(xend - 2, ypos - 2, 4, 4);
337 int ystart = (int) (((SequenceNode) node.left()).ycount * chunk)
339 int yend = (int) (((SequenceNode) node.right()).ycount * chunk)
342 Rectangle pos = new Rectangle(xend - 2, ypos - 2, 5, 5);
343 nodeHash.put(node, pos);
345 g.drawLine((int) (height * scale) + offx, ystart,
346 (int) (height * scale) + offx, yend);
348 String nodeLabel = "";
350 if (showDistances && (node.dist > 0))
352 nodeLabel = new Format("%-.2f").form(node.dist);
355 if (showBootstrap && node.bootstrap > -1)
359 nodeLabel = nodeLabel + " : ";
362 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
365 if (!nodeLabel.equals(""))
367 g.drawString(nodeLabel, xstart + 2, ypos - 2);
380 * @return DOCUMENT ME!
382 public Object findElement(int x, int y)
384 Enumeration keys = nameHash.keys();
386 while (keys.hasMoreElements())
388 Object ob = keys.nextElement();
389 Rectangle rect = (Rectangle) nameHash.get(ob);
391 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
392 && (y <= (rect.y + rect.height)))
398 keys = nodeHash.keys();
400 while (keys.hasMoreElements())
402 Object ob = keys.nextElement();
403 Rectangle rect = (Rectangle) nodeHash.get(ob);
405 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
406 && (y <= (rect.y + rect.height)))
421 public void pickNodes(Rectangle pickBox)
423 int width = getWidth();
424 int height = getHeight();
426 SequenceNode top = tree.getTopNode();
428 float wscale = (float) ((width * .8) - (offx * 2))
429 / tree.getMaxHeight();
433 top.count = ((SequenceNode) top.left()).count
434 + ((SequenceNode) top.right()).count;
437 float chunk = (float) (height - (offy)) / top.count;
439 pickNode(pickBox, top, chunk, wscale, width, offx, offy);
460 public void pickNode(Rectangle pickBox, SequenceNode node, float chunk,
461 float scale, int width, int offx, int offy)
468 if ((node.left() == null) && (node.right() == null))
470 float height = node.height;
471 float dist = node.dist;
473 int xstart = (int) ((height - dist) * scale) + offx;
474 int xend = (int) (height * scale) + offx;
476 int ypos = (int) (node.ycount * chunk) + offy;
478 if (pickBox.contains(new Point(xend, ypos)))
480 if (node.element() instanceof SequenceI)
482 SequenceI seq = (SequenceI) node.element();
483 SequenceGroup sg = av.getSelectionGroup();
487 sg.addOrRemove(seq, true);
494 pickNode(pickBox, (SequenceNode) node.left(), chunk, scale, width,
496 pickNode(pickBox, (SequenceNode) node.right(), chunk, scale, width,
509 public void setColor(SequenceNode node, Color c)
516 if ((node.left() == null) && (node.right() == null)) // TODO: internal node
520 if (node.element() instanceof SequenceI)
522 AlignmentPanel[] aps = getAssociatedPanels();
525 for (int a = 0; a < aps.length; a++)
527 final SequenceI seq = (SequenceI) node.element();
528 aps[a].av.setSequenceColour(seq, new Colour(c));
536 setColor((SequenceNode) node.left(), c);
537 setColor((SequenceNode) node.right(), c);
546 Thread thread = new Thread(this);
550 // put printing in a thread to avoid painting problems
554 PrinterJob printJob = PrinterJob.getPrinterJob();
555 PageFormat pf = printJob.pageDialog(printJob.defaultPage());
557 printJob.setPrintable(this, pf);
559 if (printJob.printDialog())
564 } catch (Exception PrintException)
566 PrintException.printStackTrace();
581 * @return DOCUMENT ME!
583 * @throws PrinterException
587 public int print(Graphics pg, PageFormat pf, int pi)
588 throws PrinterException
591 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
593 int pwidth = (int) pf.getImageableWidth();
594 int pheight = (int) pf.getImageableHeight();
596 int noPages = getHeight() / pheight;
600 return Printable.NO_SUCH_PAGE;
603 if (pwidth > getWidth())
610 if (pheight > getHeight())
612 pheight = getHeight();
619 FontMetrics fm = pg.getFontMetrics(font);
620 int height = fm.getHeight() * nameHash.size();
621 pg.translate(0, -pi * pheight);
622 pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
624 // translate number of pages,
625 // height is screen size as this is the
626 // non overlapping text size
630 draw(pg, pwidth, pheight);
632 return Printable.PAGE_EXISTS;
642 public void paintComponent(Graphics g)
644 super.paintComponent(g);
649 g.drawString(MessageManager.getString("label.calculating_tree")
650 + "....", 20, getHeight() / 2);
654 fm = g.getFontMetrics(font);
656 if (nameHash.size() == 0)
662 || (!fitToWindow && (scrollPane.getHeight() > ((fm
663 .getHeight() * nameHash.size()) + offy))))
665 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
666 setPreferredSize(null);
670 setPreferredSize(new Dimension(scrollPane.getWidth(),
671 fm.getHeight() * nameHash.size()));
672 draw(g, scrollPane.getWidth(), fm.getHeight() * nameHash.size());
675 scrollPane.revalidate();
686 public void setFont(Font font)
702 public void draw(Graphics g1, int width, int height)
704 Graphics2D g2 = (Graphics2D) g1;
705 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
706 RenderingHints.VALUE_ANTIALIAS_ON);
707 g2.setColor(Color.white);
708 g2.fillRect(0, 0, width, height);
711 if (longestName == null || tree == null)
713 g2.drawString("Calculating tree.", 20, 20);
715 offy = font.getSize() + 10;
717 fm = g2.getFontMetrics(font);
719 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
721 float wscale = (width - labelLength - (offx * 2)) / tree.getMaxHeight();
723 SequenceNode top = tree.getTopNode();
727 top.count = ((SequenceNode) top.left()).count
728 + ((SequenceNode) top.right()).count;
731 float chunk = (float) (height - (offy)) / top.count;
733 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
737 if (av.getCurrentTree() == tree)
739 g2.setColor(Color.red);
743 g2.setColor(Color.gray);
746 int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx))) + offx);
748 g2.drawLine(x, 0, x, getHeight());
759 public void mouseReleased(MouseEvent e)
770 public void mouseEntered(MouseEvent e)
781 public void mouseExited(MouseEvent e)
792 public void mouseClicked(MouseEvent evt)
794 if (highlightNode != null)
796 if (evt.isPopupTrigger())
798 Color col = JColorChooser.showDialog(this,
799 MessageManager.getString("label.select_subtree_colour"),
800 highlightNode.color);
803 setColor(highlightNode, col);
806 else if (evt.getClickCount() > 1)
808 tree.swapNodes(highlightNode);
809 tree.reCount(tree.getTopNode());
810 tree.findHeight(tree.getTopNode());
814 Vector leaves = new Vector();
815 tree.findLeaves(highlightNode, leaves);
817 for (int i = 0; i < leaves.size(); i++)
819 SequenceI seq = (SequenceI) ((SequenceNode) leaves.elementAt(i))
821 treeSelectionChanged(seq);
826 PaintRefresher.Refresh(tp, av.getSequenceSetId());
832 public void mouseMoved(MouseEvent evt)
834 av.setCurrentTree(tree);
836 Object ob = findElement(evt.getX(), evt.getY());
838 if (ob instanceof SequenceNode)
840 highlightNode = (SequenceNode) ob;
841 this.setToolTipText("<html>"
842 + MessageManager.getString("label.highlightnode"));
848 if (highlightNode != null)
850 highlightNode = null;
851 setToolTipText(null);
858 public void mouseDragged(MouseEvent ect)
869 public void mousePressed(MouseEvent e)
871 av.setCurrentTree(tree);
876 Object ob = findElement(x, y);
878 if (ob instanceof SequenceI)
880 treeSelectionChanged((Sequence) ob);
881 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
886 else if (!(ob instanceof SequenceNode))
889 if (tree.getMaxHeight() != 0)
891 threshold = (float) (x - offx)
892 / (float) (getWidth() - labelLength - (2 * offx));
894 tree.getGroups().removeAllElements();
895 tree.groupNodes(tree.getTopNode(), threshold);
896 setColor(tree.getTopNode(), Color.black);
898 AlignmentPanel[] aps = getAssociatedPanels();
900 // TODO push calls below into a single AlignViewportI method?
901 // see also AlignViewController.deleteGroups
902 for (int a = 0; a < aps.length; a++)
904 aps[a].av.setSelectionGroup(null);
905 aps[a].av.getAlignment().deleteAllGroups();
906 aps[a].av.clearSequenceColours();
907 if (aps[a].av.getCodingComplement() != null)
909 aps[a].av.getCodingComplement().setSelectionGroup(null);
910 aps[a].av.getCodingComplement().getAlignment()
912 aps[a].av.getCodingComplement().clearSequenceColours();
918 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
926 AlignmentPanel[] aps = getAssociatedPanels();
927 for (int i = 0; i < tree.getGroups().size(); i++)
929 Color col = new Color((int) (Math.random() * 255),
930 (int) (Math.random() * 255), (int) (Math.random() * 255));
931 setColor((SequenceNode) tree.getGroups().elementAt(i), col.brighter());
933 Vector l = tree.findLeaves(
934 (SequenceNode) tree.getGroups().elementAt(i), new Vector());
936 Vector sequences = new Vector();
938 for (int j = 0; j < l.size(); j++)
940 SequenceI s1 = (SequenceI) ((SequenceNode) l.elementAt(j))
943 if (!sequences.contains(s1))
945 sequences.addElement(s1);
949 ColourSchemeI cs = null;
950 SequenceGroup sg = new SequenceGroup(sequences, null, cs, true, true,
951 false, 0, av.getAlignment().getWidth() - 1);
953 if (av.getGlobalColourScheme() != null)
955 if (av.getGlobalColourScheme() instanceof UserColourScheme)
957 cs = new UserColourScheme(
958 ((UserColourScheme) av.getGlobalColourScheme())
964 cs = ColourSchemeProperty.getColour(sg, ColourSchemeProperty
965 .getColourName(av.getGlobalColourScheme()));
967 // cs is null if shading is an annotationColourGradient
970 cs.setThreshold(av.getGlobalColourScheme().getThreshold(),
971 av.isIgnoreGapsConsensus());
975 // sg.recalcConservation();
976 sg.setName("JTreeGroup:" + sg.hashCode());
979 for (int a = 0; a < aps.length; a++)
981 if (aps[a].av.getGlobalColourScheme() != null
982 && aps[a].av.getGlobalColourScheme().conservationApplied())
984 Conservation c = new Conservation("Group",
985 ResidueProperties.propHash, 3, sg.getSequences(null),
986 sg.getStartRes(), sg.getEndRes());
989 c.verdict(false, aps[a].av.getConsPercGaps());
990 sg.cs.setConservation(c);
993 aps[a].av.getAlignment().addGroup(new SequenceGroup(sg));
994 // TODO can we push all of the below into AlignViewportI?
995 final AlignViewportI codingComplement = aps[a].av
996 .getCodingComplement();
997 if (codingComplement != null)
999 if (codingComplement != null)
1001 SequenceGroup mappedGroup = MappingUtils.mapSequenceGroup(sg,
1002 av, codingComplement);
1003 if (mappedGroup.getSequences().size() > 0)
1005 codingComplement.getAlignment().addGroup(mappedGroup);
1006 for (SequenceI seq : mappedGroup.getSequences())
1008 codingComplement.setSequenceColour(seq,
1009 new Colour(col.brighter()));
1017 // notify the panel(s) to redo any group specific stuff.
1018 for (int a = 0; a < aps.length; a++)
1020 aps[a].updateAnnotation();
1021 // TODO: JAL-868 - need to ensure view colour change message is broadcast
1022 // to any Jmols listening in
1023 final AlignViewportI codingComplement = aps[a].av
1024 .getCodingComplement();
1025 if (codingComplement != null)
1027 ((AlignViewport) codingComplement).getAlignPanel()
1028 .updateAnnotation();
1042 public void setShowDistances(boolean state)
1044 this.showDistances = state;
1054 public void setShowBootstrap(boolean state)
1056 this.showBootstrap = state;
1066 public void setMarkPlaceholders(boolean state)
1068 this.markPlaceholders = state;
1072 AlignmentPanel[] getAssociatedPanels()
1074 if (applyToAllViews)
1076 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1080 return new AlignmentPanel[] { ap };