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.ColourSchemeI;
31 import jalview.schemes.ColourSchemeProperty;
32 import jalview.schemes.ResidueProperties;
33 import jalview.schemes.UserColourScheme;
34 import jalview.structure.SelectionSource;
35 import jalview.util.Format;
36 import jalview.util.MappingUtils;
37 import jalview.util.MessageManager;
39 import java.awt.Color;
40 import java.awt.Dimension;
42 import java.awt.FontMetrics;
43 import java.awt.Graphics;
44 import java.awt.Graphics2D;
45 import java.awt.Point;
46 import java.awt.Rectangle;
47 import java.awt.RenderingHints;
48 import java.awt.event.MouseEvent;
49 import java.awt.event.MouseListener;
50 import java.awt.event.MouseMotionListener;
51 import java.awt.print.PageFormat;
52 import java.awt.print.Printable;
53 import java.awt.print.PrinterException;
54 import java.awt.print.PrinterJob;
55 import java.util.Enumeration;
56 import java.util.Hashtable;
57 import java.util.Vector;
59 import javax.swing.JColorChooser;
60 import javax.swing.JPanel;
61 import javax.swing.JScrollPane;
62 import javax.swing.SwingUtilities;
63 import javax.swing.ToolTipManager;
71 public class TreeCanvas extends JPanel implements MouseListener, Runnable,
72 Printable, MouseMotionListener, SelectionSource
75 public static final String PLACEHOLDER = " * ";
79 JScrollPane scrollPane;
91 boolean fitToWindow = true;
93 boolean showDistances = false;
95 boolean showBootstrap = false;
97 boolean markPlaceholders = false;
107 int labelLength = -1;
109 Hashtable nameHash = new Hashtable();
111 Hashtable nodeHash = new Hashtable();
113 SequenceNode highlightNode;
115 boolean applyToAllViews = false;
118 * Creates a new TreeCanvas object.
129 public TreeCanvas(TreePanel tp, AlignmentPanel ap, JScrollPane scroller)
135 scrollPane = scroller;
136 addMouseListener(this);
137 addMouseMotionListener(this);
138 ToolTipManager.sharedInstance().registerComponent(this);
147 public void treeSelectionChanged(SequenceI sequence)
149 AlignmentPanel[] aps = getAssociatedPanels();
151 for (int a = 0; a < aps.length; a++)
153 SequenceGroup selected = aps[a].av.getSelectionGroup();
155 if (selected == null)
157 selected = new SequenceGroup();
158 aps[a].av.setSelectionGroup(selected);
161 selected.setEndRes(aps[a].av.getAlignment().getWidth() - 1);
162 selected.addOrRemove(sequence, true);
172 public void setTree(NJTree tree)
175 tree.findHeight(tree.getTopNode());
177 // Now have to calculate longest name based on the leaves
178 Vector leaves = tree.findLeaves(tree.getTopNode(), new Vector());
179 boolean has_placeholders = false;
182 for (int i = 0; i < leaves.size(); i++)
184 SequenceNode lf = (SequenceNode) leaves.elementAt(i);
186 if (lf.isPlaceholder())
188 has_placeholders = true;
191 if (longestName.length() < ((Sequence) lf.element()).getName()
194 longestName = TreeCanvas.PLACEHOLDER
195 + ((Sequence) lf.element()).getName();
199 setMarkPlaceholders(has_placeholders);
220 public void drawNode(Graphics g, SequenceNode node, float chunk,
221 float scale, int width, int offx, int offy)
228 if ((node.left() == null) && (node.right() == null))
231 float height = node.height;
232 float dist = node.dist;
234 int xstart = (int) ((height - dist) * scale) + offx;
235 int xend = (int) (height * scale) + offx;
237 int ypos = (int) (node.ycount * chunk) + offy;
239 if (node.element() instanceof SequenceI)
241 SequenceI seq = (SequenceI) node.element();
243 if (av.getSequenceColour(seq) == Color.white)
245 g.setColor(Color.black);
249 g.setColor(av.getSequenceColour(seq).darker());
254 g.setColor(Color.black);
257 // Draw horizontal line
258 g.drawLine(xstart, ypos, xend, ypos);
260 String nodeLabel = "";
262 if (showDistances && (node.dist > 0))
264 nodeLabel = new Format("%-.2f").form(node.dist);
267 if (showBootstrap && node.bootstrap > -1)
271 nodeLabel = nodeLabel + " : ";
274 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
277 if (!nodeLabel.equals(""))
279 g.drawString(nodeLabel, xstart + 2, ypos - 2);
282 String name = (markPlaceholders && node.isPlaceholder()) ? (PLACEHOLDER + node
283 .getName()) : node.getName();
285 int charWidth = fm.stringWidth(name) + 3;
286 int charHeight = font.getSize();
288 Rectangle rect = new Rectangle(xend + 10, ypos - charHeight / 2,
289 charWidth, charHeight);
291 nameHash.put(node.element(), rect);
293 // Colour selected leaves differently
294 SequenceGroup selected = av.getSelectionGroup();
296 if ((selected != null)
297 && selected.getSequences(null).contains(
300 g.setColor(Color.gray);
302 g.fillRect(xend + 10, ypos - charHeight / 2, charWidth, charHeight);
303 g.setColor(Color.white);
306 g.drawString(name, xend + 10, ypos + fm.getDescent());
307 g.setColor(Color.black);
311 drawNode(g, (SequenceNode) node.left(), chunk, scale, width, offx,
313 drawNode(g, (SequenceNode) node.right(), chunk, scale, width, offx,
316 float height = node.height;
317 float dist = node.dist;
319 int xstart = (int) ((height - dist) * scale) + offx;
320 int xend = (int) (height * scale) + offx;
321 int ypos = (int) (node.ycount * chunk) + offy;
323 g.setColor(node.color.darker());
325 // Draw horizontal line
326 g.drawLine(xstart, ypos, xend, ypos);
327 if (node == highlightNode)
329 g.fillRect(xend - 3, ypos - 3, 6, 6);
333 g.fillRect(xend - 2, ypos - 2, 4, 4);
336 int ystart = (int) (((SequenceNode) node.left()).ycount * chunk)
338 int yend = (int) (((SequenceNode) node.right()).ycount * chunk)
341 Rectangle pos = new Rectangle(xend - 2, ypos - 2, 5, 5);
342 nodeHash.put(node, pos);
344 g.drawLine((int) (height * scale) + offx, ystart,
345 (int) (height * scale) + offx, yend);
347 String nodeLabel = "";
349 if (showDistances && (node.dist > 0))
351 nodeLabel = new Format("%-.2f").form(node.dist);
354 if (showBootstrap && node.bootstrap > -1)
358 nodeLabel = nodeLabel + " : ";
361 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
364 if (!nodeLabel.equals(""))
366 g.drawString(nodeLabel, xstart + 2, ypos - 2);
379 * @return DOCUMENT ME!
381 public Object findElement(int x, int y)
383 Enumeration keys = nameHash.keys();
385 while (keys.hasMoreElements())
387 Object ob = keys.nextElement();
388 Rectangle rect = (Rectangle) nameHash.get(ob);
390 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
391 && (y <= (rect.y + rect.height)))
397 keys = nodeHash.keys();
399 while (keys.hasMoreElements())
401 Object ob = keys.nextElement();
402 Rectangle rect = (Rectangle) nodeHash.get(ob);
404 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
405 && (y <= (rect.y + rect.height)))
420 public void pickNodes(Rectangle pickBox)
422 int width = getWidth();
423 int height = getHeight();
425 SequenceNode top = tree.getTopNode();
427 float wscale = (float) ((width * .8) - (offx * 2))
428 / tree.getMaxHeight();
432 top.count = ((SequenceNode) top.left()).count
433 + ((SequenceNode) top.right()).count;
436 float chunk = (float) (height - (offy)) / top.count;
438 pickNode(pickBox, top, chunk, wscale, width, offx, offy);
459 public void pickNode(Rectangle pickBox, SequenceNode node, float chunk,
460 float scale, int width, int offx, int offy)
467 if ((node.left() == null) && (node.right() == null))
469 float height = node.height;
470 float dist = node.dist;
472 int xstart = (int) ((height - dist) * scale) + offx;
473 int xend = (int) (height * scale) + offx;
475 int ypos = (int) (node.ycount * chunk) + offy;
477 if (pickBox.contains(new Point(xend, ypos)))
479 if (node.element() instanceof SequenceI)
481 SequenceI seq = (SequenceI) node.element();
482 SequenceGroup sg = av.getSelectionGroup();
486 sg.addOrRemove(seq, true);
493 pickNode(pickBox, (SequenceNode) node.left(), chunk, scale, width,
495 pickNode(pickBox, (SequenceNode) node.right(), chunk, scale, width,
508 public void setColor(SequenceNode node, Color c)
515 if ((node.left() == null) && (node.right() == null)) // TODO: internal node
519 if (node.element() instanceof SequenceI)
521 AlignmentPanel[] aps = getAssociatedPanels();
524 for (int a = 0; a < aps.length; a++)
526 final SequenceI seq = (SequenceI) node.element();
527 aps[a].av.setSequenceColour(seq, c);
535 setColor((SequenceNode) node.left(), c);
536 setColor((SequenceNode) node.right(), c);
545 Thread thread = new Thread(this);
549 // put printing in a thread to avoid painting problems
552 PrinterJob printJob = PrinterJob.getPrinterJob();
553 PageFormat pf = printJob.pageDialog(printJob.defaultPage());
555 printJob.setPrintable(this, pf);
557 if (printJob.printDialog())
562 } catch (Exception PrintException)
564 PrintException.printStackTrace();
579 * @return DOCUMENT ME!
581 * @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;
638 public void paintComponent(Graphics g)
640 super.paintComponent(g);
645 g.drawString(MessageManager.getString("label.calculating_tree")
646 + "....", 20, getHeight() / 2);
650 fm = g.getFontMetrics(font);
652 if (nameHash.size() == 0)
658 || (!fitToWindow && (scrollPane.getHeight() > ((fm
659 .getHeight() * nameHash.size()) + offy))))
661 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
662 setPreferredSize(null);
666 setPreferredSize(new Dimension(scrollPane.getWidth(),
667 fm.getHeight() * nameHash.size()));
668 draw(g, scrollPane.getWidth(), fm.getHeight() * nameHash.size());
671 scrollPane.revalidate();
681 public void setFont(Font font)
697 public void draw(Graphics g1, int width, int height)
699 Graphics2D g2 = (Graphics2D) g1;
700 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
701 RenderingHints.VALUE_ANTIALIAS_ON);
702 g2.setColor(Color.white);
703 g2.fillRect(0, 0, width, height);
706 if (longestName == null || tree == null)
708 g2.drawString("Calculating tree.", 20, 20);
710 offy = font.getSize() + 10;
712 fm = g2.getFontMetrics(font);
714 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
716 float wscale = (width - labelLength - (offx * 2))
717 / tree.getMaxHeight();
719 SequenceNode top = tree.getTopNode();
723 top.count = ((SequenceNode) top.left()).count
724 + ((SequenceNode) top.right()).count;
727 float chunk = (float) (height - (offy)) / top.count;
729 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
733 if (av.getCurrentTree() == tree)
735 g2.setColor(Color.red);
739 g2.setColor(Color.gray);
742 int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx))) + offx);
744 g2.drawLine(x, 0, x, getHeight());
754 public void mouseReleased(MouseEvent e)
764 public void mouseEntered(MouseEvent e)
774 public void mouseExited(MouseEvent e)
784 public void mouseClicked(MouseEvent evt)
786 if (highlightNode != null)
788 if (SwingUtilities.isRightMouseButton(evt))
790 Color col = JColorChooser.showDialog(this,
791 MessageManager.getString("label.select_subtree_colour"), highlightNode.color);
794 setColor(highlightNode, col);
797 else if (evt.getClickCount() > 1)
799 tree.swapNodes(highlightNode);
800 tree.reCount(tree.getTopNode());
801 tree.findHeight(tree.getTopNode());
805 Vector leaves = new Vector();
806 tree.findLeaves(highlightNode, leaves);
808 for (int i = 0; i < leaves.size(); i++)
810 SequenceI seq = (SequenceI) ((SequenceNode) leaves.elementAt(i))
812 treeSelectionChanged(seq);
817 PaintRefresher.Refresh(tp, av.getSequenceSetId());
822 public void mouseMoved(MouseEvent evt)
824 av.setCurrentTree(tree);
826 Object ob = findElement(evt.getX(), evt.getY());
828 if (ob instanceof SequenceNode)
830 highlightNode = (SequenceNode) ob;
831 this.setToolTipText("<html>"
832 + MessageManager.getString("label.highlightnode"));
838 if (highlightNode != null)
840 highlightNode = null;
841 setToolTipText(null);
847 public void mouseDragged(MouseEvent ect)
857 public void mousePressed(MouseEvent e)
859 av.setCurrentTree(tree);
864 Object ob = findElement(x, y);
866 if (ob instanceof SequenceI)
868 treeSelectionChanged((Sequence) ob);
869 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
874 else if (!(ob instanceof SequenceNode))
877 if (tree.getMaxHeight() != 0)
879 threshold = (float) (x - offx)
880 / (float) (getWidth() - labelLength - (2 * offx));
882 tree.getGroups().removeAllElements();
883 tree.groupNodes(tree.getTopNode(), threshold);
884 setColor(tree.getTopNode(), Color.black);
886 AlignmentPanel[] aps = getAssociatedPanels();
888 // TODO push calls below into a single AlignViewportI method?
889 // see also AlignViewController.deleteGroups
890 for (int a = 0; a < aps.length; a++)
892 aps[a].av.setSelectionGroup(null);
893 aps[a].av.getAlignment().deleteAllGroups();
894 aps[a].av.clearSequenceColours();
896 if (av.getCodingComplement() != null)
898 av.getCodingComplement().setSelectionGroup(null);
899 av.getCodingComplement().getAlignment().deleteAllGroups();
900 av.getCodingComplement().clearSequenceColours();
905 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
913 AlignmentPanel[] aps = getAssociatedPanels();
914 for (int i = 0; i < tree.getGroups().size(); i++)
916 Color col = new Color((int) (Math.random() * 255),
917 (int) (Math.random() * 255), (int) (Math.random() * 255));
918 setColor((SequenceNode) tree.getGroups().elementAt(i), col.brighter());
920 Vector l = tree.findLeaves(
921 (SequenceNode) tree.getGroups().elementAt(i), new Vector());
923 Vector sequences = new Vector();
925 for (int j = 0; j < l.size(); j++)
927 SequenceI s1 = (SequenceI) ((SequenceNode) l.elementAt(j))
930 if (!sequences.contains(s1))
932 sequences.addElement(s1);
936 ColourSchemeI cs = null;
937 SequenceGroup sg = new SequenceGroup(sequences, null, cs, true, true,
938 false, 0, av.getAlignment().getWidth() - 1);
940 if (av.getGlobalColourScheme() != null)
942 if (av.getGlobalColourScheme() instanceof UserColourScheme)
944 cs = new UserColourScheme(
945 ((UserColourScheme) av.getGlobalColourScheme())
951 cs = ColourSchemeProperty.getColour(sg, ColourSchemeProperty
952 .getColourName(av.getGlobalColourScheme()));
954 // cs is null if shading is an annotationColourGradient
957 cs.setThreshold(av.getGlobalColourScheme().getThreshold(),
958 av.isIgnoreGapsConsensus());
962 // sg.recalcConservation();
963 sg.setName("JTreeGroup:" + sg.hashCode());
966 for (int a = 0; a < aps.length; a++)
968 if (aps[a].av.getGlobalColourScheme() != null
969 && aps[a].av.getGlobalColourScheme().conservationApplied())
971 Conservation c = new Conservation("Group",
972 ResidueProperties.propHash, 3, sg.getSequences(null),
973 sg.getStartRes(), sg.getEndRes());
976 c.verdict(false, aps[a].av.getConsPercGaps());
977 sg.cs.setConservation(c);
980 aps[a].av.getAlignment().addGroup(new SequenceGroup(sg));
983 // TODO can we push all of the below into AlignViewportI?
984 av.getAlignment().addGroup(sg);
985 final AlignViewportI codingComplement = av.getCodingComplement();
986 if (codingComplement != null)
988 SequenceGroup mappedGroup = MappingUtils.mapSequenceGroup(sg, av,
990 if (mappedGroup.getSequences().size() > 0)
992 codingComplement.getAlignment().addGroup(mappedGroup);
993 for (SequenceI seq : mappedGroup.getSequences())
995 codingComplement.setSequenceColour(seq, col.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.getCodingComplement() != null)
1011 ((AlignViewport) av.getCodingComplement()).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[]