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 chooseSubtreeColour();
765 e.consume(); // prevent mouseClicked happening
770 * Empty method to satisfy the MouseListener interface
775 public void mouseEntered(MouseEvent e)
780 * Empty method to satisfy the MouseListener interface
785 public void mouseExited(MouseEvent e)
790 * Handles a mouse click on a tree node (clicks elsewhere are handled in
791 * mousePressed). Click selects the sub-tree, double-click swaps leaf nodes
792 * order, right-click opens a dialogue to choose colour for the sub-tree.
797 public void mouseClicked(MouseEvent evt)
799 if (highlightNode == null)
804 if (evt.getClickCount() > 1)
806 tree.swapNodes(highlightNode);
807 tree.reCount(tree.getTopNode());
808 tree.findHeight(tree.getTopNode());
812 Vector<SequenceNode> leaves = tree.findLeaves(highlightNode);
814 for (int i = 0; i < leaves.size(); i++)
816 SequenceI seq = (SequenceI) leaves.elementAt(i).element();
817 treeSelectionChanged(seq);
822 PaintRefresher.Refresh(tp, av.getSequenceSetId());
827 * Offer the user the option to choose a colour for the highlighted node and
828 * its children; this colour is also applied to the corresponding sequence ids
831 void chooseSubtreeColour()
833 String ttl = MessageManager.getString("label.select_subtree_colour");
834 ColourChooserListener listener = new ColourChooserListener() {
836 public void colourSelected(Color c)
838 setColor(highlightNode, c);
839 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
843 JalviewColourChooser.showColourChooser(this, ttl, highlightNode.color, listener);
847 public void mouseMoved(MouseEvent evt)
849 av.setCurrentTree(tree);
851 Object ob = findElement(evt.getX(), evt.getY());
853 if (ob instanceof SequenceNode)
855 highlightNode = (SequenceNode) ob;
857 "<html>" + MessageManager.getString("label.highlightnode"));
863 if (highlightNode != null)
865 highlightNode = null;
866 setToolTipText(null);
873 public void mouseDragged(MouseEvent ect)
878 * Handles a mouse press on a sequence name or the tree background canvas
879 * (click on a node is handled in mouseClicked). The action is to create
880 * groups by partitioning the tree at the mouse position. Colours for the
881 * groups (and sequence names) are generated randomly.
886 public void mousePressed(MouseEvent e)
888 av.setCurrentTree(tree);
891 * isPopupTrigger is set for mousePressed (Mac)
892 * or mouseReleased (Windows)
894 if (e.isPopupTrigger())
896 if (highlightNode != null)
898 chooseSubtreeColour();
904 * defer right-click handling on Windows to
905 * mouseClicked; note isRightMouseButton
906 * also matches Cmd-click on Mac which should do
909 if (SwingUtilities.isRightMouseButton(e))
917 Object ob = findElement(x, y);
919 if (ob instanceof SequenceI)
921 treeSelectionChanged((Sequence) ob);
922 PaintRefresher.Refresh(tp, getAssociatedPanel().av.getSequenceSetId());
927 else if (!(ob instanceof SequenceNode))
930 if (tree.getMaxHeight() != 0)
932 threshold = (float) (x - offx)
933 / (float) (getWidth() - labelLength - (2 * offx));
935 List<SequenceNode> groups = tree.groupNodes(threshold);
936 setColor(tree.getTopNode(), Color.black);
938 AlignmentPanel[] aps = getAssociatedPanels();
940 // TODO push calls below into a single AlignViewportI method?
941 // see also AlignViewController.deleteGroups
942 for (int a = 0; a < aps.length; a++)
944 aps[a].av.setSelectionGroup(null);
945 aps[a].av.getAlignment().deleteAllGroups();
946 aps[a].av.clearSequenceColours();
947 if (aps[a].av.getCodingComplement() != null)
949 aps[a].av.getCodingComplement().setSelectionGroup(null);
950 aps[a].av.getCodingComplement().getAlignment()
952 aps[a].av.getCodingComplement().clearSequenceColours();
954 aps[a].av.setUpdateStructures(true);
956 colourGroups(groups);
959 * clear partition (don't show vertical line) if
960 * it is to the right of all nodes
962 if (groups.isEmpty())
968 PaintRefresher.Refresh(tp, getAssociatedPanel().av.getSequenceSetId());
974 void colourGroups(List<SequenceNode> groups)
976 AlignmentPanel[] aps = getAssociatedPanels();
977 for (int i = 0; i < groups.size(); i++)
979 Color col = new Color((int) (Math.random() * 255),
980 (int) (Math.random() * 255), (int) (Math.random() * 255));
981 setColor(groups.get(i), col.brighter());
983 Vector<SequenceNode> l = tree.findLeaves(groups.get(i));
985 Vector<SequenceI> sequences = new Vector<>();
987 for (int j = 0; j < l.size(); j++)
989 SequenceI s1 = (SequenceI) l.elementAt(j).element();
991 if (!sequences.contains(s1))
993 sequences.addElement(s1);
997 ColourSchemeI cs = null;
998 SequenceGroup _sg = new SequenceGroup(sequences, null, cs, true, true,
999 false, 0, av.getAlignment().getWidth() - 1);
1001 _sg.setName("JTreeGroup:" + _sg.hashCode());
1002 _sg.setIdColour(col);
1004 for (int a = 0; a < aps.length; a++)
1006 SequenceGroup sg = new SequenceGroup(_sg);
1007 AlignViewport viewport = aps[a].av;
1009 // Propagate group colours in each view
1010 if (viewport.getGlobalColourScheme() != null)
1012 cs = viewport.getGlobalColourScheme().getInstance(viewport, sg);
1013 sg.setColourScheme(cs);
1014 sg.getGroupColourScheme().setThreshold(
1015 viewport.getResidueShading().getThreshold(),
1016 viewport.isIgnoreGapsConsensus());
1018 if (viewport.getResidueShading().conservationApplied())
1020 Conservation c = new Conservation("Group",
1021 sg.getSequences(null), sg.getStartRes(),
1024 c.verdict(false, viewport.getConsPercGaps());
1025 sg.cs.setConservation(c);
1028 // indicate that associated structure views will need an update
1029 viewport.setUpdateStructures(true);
1030 // propagate structure view update and sequence group to complement view
1031 viewport.addSequenceGroup(sg);
1035 // notify the panel(s) to redo any group specific stuff
1036 // also updates structure views if necessary
1037 for (int a = 0; a < aps.length; a++)
1039 aps[a].updateAnnotation();
1040 final AlignViewportI codingComplement = aps[a].av
1041 .getCodingComplement();
1042 if (codingComplement != null)
1044 ((AlignViewport) codingComplement).getAlignPanel()
1045 .updateAnnotation();
1056 public void setShowDistances(boolean state)
1058 this.showDistances = state;
1068 public void setShowBootstrap(boolean state)
1070 this.showBootstrap = state;
1080 public void setMarkPlaceholders(boolean state)
1082 this.markPlaceholders = state;
1086 AlignmentPanel[] getAssociatedPanels()
1088 if (applyToAllViews)
1090 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1094 return new AlignmentPanel[] { getAssociatedPanel() };
1098 public AlignmentPanel getAssociatedPanel()
1103 public void setAssociatedPanel(AlignmentPanel ap)
1108 public AlignViewport getViewport()
1113 public void setViewport(AlignViewport av)
1118 public float getThreshold()
1123 public void setThreshold(float threshold)
1125 this.threshold = threshold;
1128 public boolean isApplyToAllViews()
1130 return this.applyToAllViews;
1133 public void setApplyToAllViews(boolean applyToAllViews)
1135 this.applyToAllViews = applyToAllViews;