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 java.awt.Color;
24 import java.awt.Dimension;
26 import java.awt.FontMetrics;
27 import java.awt.Graphics;
28 import java.awt.Graphics2D;
29 import java.awt.Point;
30 import java.awt.Rectangle;
31 import java.awt.RenderingHints;
32 import java.awt.event.MouseEvent;
33 import java.awt.event.MouseListener;
34 import java.awt.event.MouseMotionListener;
35 import java.awt.print.PageFormat;
36 import java.awt.print.Printable;
37 import java.awt.print.PrinterException;
38 import java.awt.print.PrinterJob;
39 import java.util.Hashtable;
40 import java.util.List;
42 import java.util.Map.Entry;
43 import java.util.Vector;
45 import javax.swing.JPanel;
46 import javax.swing.JScrollPane;
47 import javax.swing.SwingUtilities;
48 import javax.swing.ToolTipManager;
50 import jalview.analysis.Conservation;
51 import jalview.analysis.TreeModel;
52 import jalview.api.AlignViewportI;
53 import jalview.datamodel.Sequence;
54 import jalview.datamodel.SequenceGroup;
55 import jalview.datamodel.SequenceI;
56 import jalview.datamodel.SequenceNode;
57 import jalview.gui.JalviewColourChooser.ColourChooserListener;
58 import jalview.schemes.ColourSchemeI;
59 import jalview.structure.SelectionSource;
60 import jalview.util.Format;
61 import jalview.util.MessageManager;
69 public class TreeCanvas extends JPanel implements MouseListener, Runnable,
70 Printable, MouseMotionListener, SelectionSource
73 public static final String PLACEHOLDER = " * ";
77 JScrollPane scrollPane;
81 private AlignViewport av;
83 private AlignmentPanel ap;
89 boolean fitToWindow = true;
91 boolean showDistances = false;
93 boolean showBootstrap = false;
95 boolean markPlaceholders = false;
101 private float threshold;
105 int labelLength = -1;
107 Map<Object, Rectangle> nameHash = new Hashtable<>();
109 Map<SequenceNode, Rectangle> nodeHash = new Hashtable<>();
111 SequenceNode highlightNode;
113 boolean applyToAllViews = false;
116 * Creates a new TreeCanvas object.
127 public TreeCanvas(TreePanel tp, AlignmentPanel ap, JScrollPane scroller)
131 this.setAssociatedPanel(ap);
133 scrollPane = scroller;
134 addMouseListener(this);
135 addMouseMotionListener(this);
136 ToolTipManager.sharedInstance().registerComponent(this);
145 public void treeSelectionChanged(SequenceI sequence)
147 AlignmentPanel[] aps = getAssociatedPanels();
149 for (int a = 0; a < aps.length; a++)
151 SequenceGroup selected = aps[a].av.getSelectionGroup();
153 if (selected == null)
155 selected = new SequenceGroup();
156 aps[a].av.setSelectionGroup(selected);
159 selected.setEndRes(aps[a].av.getAlignment().getWidth() - 1);
160 selected.addOrRemove(sequence, true);
170 public void setTree(TreeModel tree)
173 tree.findHeight(tree.getTopNode());
175 // Now have to calculate longest name based on the leaves
176 Vector<SequenceNode> leaves = tree.findLeaves(tree.getTopNode());
177 boolean has_placeholders = false;
180 for (int i = 0; i < leaves.size(); i++)
182 SequenceNode lf = leaves.elementAt(i);
184 if (lf.isPlaceholder())
186 has_placeholders = true;
189 if (longestName.length() < ((Sequence) lf.element()).getName()
192 longestName = TreeCanvas.PLACEHOLDER
193 + ((Sequence) lf.element()).getName();
197 setMarkPlaceholders(has_placeholders);
218 public void drawNode(Graphics g, SequenceNode node, float chunk,
219 double wscale, int width, int offx, int offy)
226 if ((node.left() == null) && (node.right() == null))
229 double height = node.height;
230 double dist = node.dist;
232 int xstart = (int) ((height - dist) * wscale) + offx;
233 int xend = (int) (height * wscale) + offx;
235 int ypos = (int) (node.ycount * chunk) + offy;
237 if (node.element() instanceof SequenceI)
239 SequenceI seq = (SequenceI) node.element();
241 if (av.getSequenceColour(seq) == Color.white)
243 g.setColor(Color.black);
247 g.setColor(av.getSequenceColour(seq).darker());
252 g.setColor(Color.black);
255 // Draw horizontal line
256 g.drawLine(xstart, ypos, xend, ypos);
258 String nodeLabel = "";
260 if (showDistances && (node.dist > 0))
262 nodeLabel = new Format("%-.2f").form(node.dist);
265 if (showBootstrap && node.bootstrap > -1)
269 nodeLabel = nodeLabel + " : ";
272 nodeLabel = nodeLabel + String.valueOf(node.bootstrap);
275 if (!nodeLabel.equals(""))
277 g.drawString(nodeLabel, xstart + 2, ypos - 2);
280 String name = (markPlaceholders && node.isPlaceholder())
281 ? (PLACEHOLDER + 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(node.element()))
298 g.setColor(Color.gray);
300 g.fillRect(xend + 10, ypos - charHeight / 2, charWidth, charHeight);
301 g.setColor(Color.white);
304 g.drawString(name, xend + 10, ypos + fm.getDescent());
305 g.setColor(Color.black);
309 drawNode(g, (SequenceNode) node.left(), chunk, wscale, width, offx,
311 drawNode(g, (SequenceNode) node.right(), chunk, wscale, width, offx,
314 double height = node.height;
315 double dist = node.dist;
317 int xstart = (int) ((height - dist) * wscale) + offx;
318 int xend = (int) (height * wscale) + offx;
319 int ypos = (int) (node.ycount * chunk) + offy;
321 g.setColor(node.color.darker());
323 // Draw horizontal line
324 g.drawLine(xstart, ypos, xend, ypos);
325 if (node == highlightNode)
327 g.fillRect(xend - 3, ypos - 3, 6, 6);
331 g.fillRect(xend - 2, ypos - 2, 4, 4);
334 int ystart = (node.left() == null ? 0
335 : (int) (((SequenceNode) node.left()).ycount * chunk)) + offy;
336 int yend = (node.right() == null ? 0
337 : (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 * wscale) + offx, ystart,
344 (int) (height * wscale) + 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 for (Entry<Object, Rectangle> entry : nameHash.entrySet())
384 Rectangle rect = entry.getValue();
386 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
387 && (y <= (rect.y + rect.height)))
389 return entry.getKey();
393 for (Entry<SequenceNode, Rectangle> entry : nodeHash.entrySet())
395 Rectangle rect = entry.getValue();
397 if ((x >= rect.x) && (x <= (rect.x + rect.width)) && (y >= rect.y)
398 && (y <= (rect.y + rect.height)))
400 return entry.getKey();
413 public void pickNodes(Rectangle pickBox)
415 int width = getWidth();
416 int height = getHeight();
418 SequenceNode top = tree.getTopNode();
420 double wscale = ((width * .8) - (offx * 2)) / tree.getMaxHeight();
424 top.count = ((SequenceNode) top.left()).count
425 + ((SequenceNode) top.right()).count;
428 float chunk = (float) (height - (offy)) / top.count;
430 pickNode(pickBox, top, chunk, wscale, width, offx, offy);
451 public void pickNode(Rectangle pickBox, SequenceNode node, float chunk,
452 double wscale, int width, int offx, int offy)
459 if ((node.left() == null) && (node.right() == null))
461 double height = node.height;
462 // double dist = node.dist;
463 // int xstart = (int) ((height - dist) * wscale) + offx;
464 int xend = (int) (height * wscale) + offx;
466 int ypos = (int) (node.ycount * chunk) + offy;
468 if (pickBox.contains(new Point(xend, ypos)))
470 if (node.element() instanceof SequenceI)
472 SequenceI seq = (SequenceI) node.element();
473 SequenceGroup sg = av.getSelectionGroup();
477 sg.addOrRemove(seq, true);
484 pickNode(pickBox, (SequenceNode) node.left(), chunk, wscale, width,
486 pickNode(pickBox, (SequenceNode) node.right(), chunk, wscale, width,
499 public void setColor(SequenceNode node, Color c)
507 if (node.element() instanceof SequenceI)
509 final SequenceI seq = (SequenceI) node.element();
510 AlignmentPanel[] aps = getAssociatedPanels();
513 for (int a = 0; a < aps.length; a++)
515 aps[a].av.setSequenceColour(seq, c);
519 setColor((SequenceNode) node.left(), c);
520 setColor((SequenceNode) node.right(), c);
528 Thread thread = new Thread(this);
532 // put printing in a thread to avoid painting problems
536 PrinterJob printJob = PrinterJob.getPrinterJob();
537 PageFormat defaultPage = printJob.defaultPage();
538 PageFormat pf = printJob.pageDialog(defaultPage);
540 if (defaultPage == pf)
548 printJob.setPrintable(this, pf);
550 if (printJob.printDialog())
555 } catch (Exception PrintException)
557 PrintException.printStackTrace();
572 * @return DOCUMENT ME!
574 * @throws PrinterException
578 public int print(Graphics pg, PageFormat pf, int pi)
579 throws PrinterException
582 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
584 int pwidth = (int) pf.getImageableWidth();
585 int pheight = (int) pf.getImageableHeight();
587 int noPages = getHeight() / pheight;
591 return Printable.NO_SUCH_PAGE;
594 if (pwidth > getWidth())
601 if (pheight > getHeight())
603 pheight = getHeight();
610 FontMetrics fm = pg.getFontMetrics(font);
611 int height = fm.getHeight() * nameHash.size();
612 pg.translate(0, -pi * pheight);
613 pg.setClip(0, pi * pheight, pwidth, (pi * pheight) + pheight);
615 // translate number of pages,
616 // height is screen size as this is the
617 // non overlapping text size
621 draw(pg, pwidth, pheight);
623 return Printable.PAGE_EXISTS;
633 public void paintComponent(Graphics g)
635 super.paintComponent(g);
641 MessageManager.getString("label.calculating_tree") + "....",
642 20, getHeight() / 2);
646 fm = g.getFontMetrics(font);
648 int nameCount = nameHash.size();
654 if (fitToWindow || (!fitToWindow && (scrollPane
655 .getHeight() > ((fm.getHeight() * nameCount) + offy))))
657 draw(g, scrollPane.getWidth(), scrollPane.getHeight());
658 setPreferredSize(null);
662 setPreferredSize(new Dimension(scrollPane.getWidth(),
663 fm.getHeight() * nameCount));
664 draw(g, scrollPane.getWidth(), fm.getHeight() * nameCount);
667 scrollPane.revalidate();
678 public void setFont(Font font)
694 public void draw(Graphics g1, int width, int height)
696 Graphics2D g2 = (Graphics2D) g1;
697 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
698 RenderingHints.VALUE_ANTIALIAS_ON);
699 g2.setColor(Color.white);
700 g2.fillRect(0, 0, width, height);
703 if (longestName == null || tree == null)
705 g2.drawString("Calculating tree.", 20, 20);
707 offy = font.getSize() + 10;
709 fm = g2.getFontMetrics(font);
711 labelLength = fm.stringWidth(longestName) + 20; // 20 allows for scrollbar
713 double wscale = (width - labelLength - (offx * 2))
714 / tree.getMaxHeight();
716 SequenceNode top = tree.getTopNode();
720 top.count = ((SequenceNode) top.left()).count
721 + ((SequenceNode) top.right()).count;
724 float chunk = (float) (height - (offy)) / top.count;
726 drawNode(g2, tree.getTopNode(), chunk, wscale, width, offx, offy);
730 if (av.getCurrentTree() == tree)
732 g2.setColor(Color.red);
736 g2.setColor(Color.gray);
739 int x = (int) ((threshold * (getWidth() - labelLength - (2 * offx)))
742 g2.drawLine(x, 0, x, getHeight());
747 * Empty method to satisfy the MouseListener interface
752 public void mouseReleased(MouseEvent e)
755 * isPopupTrigger is set on mouseReleased on Windows
757 if (e.isPopupTrigger())
759 if (highlightNode != null) {
760 chooseSubtreeColour();
762 e.consume(); // prevent mouseClicked happening
767 * Empty method to satisfy the MouseListener interface
772 public void mouseEntered(MouseEvent e)
777 * Empty method to satisfy the MouseListener interface
782 public void mouseExited(MouseEvent e)
787 * Handles a mouse click on a tree node (clicks elsewhere are handled in
788 * mousePressed). Click selects the sub-tree, double-click swaps leaf nodes
789 * order, right-click opens a dialogue to choose colour for the sub-tree.
794 public void mouseClicked(MouseEvent evt)
796 if (highlightNode == null)
801 if (evt.getClickCount() > 1)
803 tree.swapNodes(highlightNode);
804 tree.reCount(tree.getTopNode());
805 tree.findHeight(tree.getTopNode());
809 Vector<SequenceNode> leaves = tree.findLeaves(highlightNode);
811 for (int i = 0; i < leaves.size(); i++)
813 SequenceI seq = (SequenceI) leaves.elementAt(i).element();
814 treeSelectionChanged(seq);
819 PaintRefresher.Refresh(tp, av.getSequenceSetId());
824 * Offer the user the option to choose a colour for the highlighted node and
825 * its children; this colour is also applied to the corresponding sequence ids
828 void chooseSubtreeColour()
830 String ttl = MessageManager.getString("label.select_subtree_colour");
831 ColourChooserListener listener = new ColourChooserListener() {
833 public void colourSelected(Color c)
835 setColor(highlightNode, c);
836 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
840 JalviewColourChooser.showColourChooser(this, ttl, highlightNode.color, listener);
844 public void mouseMoved(MouseEvent evt)
846 av.setCurrentTree(tree);
848 Object ob = findElement(evt.getX(), evt.getY());
850 if (ob instanceof SequenceNode)
852 highlightNode = (SequenceNode) ob;
854 "<html>" + MessageManager.getString("label.highlightnode"));
860 if (highlightNode != null)
862 highlightNode = null;
863 setToolTipText(null);
870 public void mouseDragged(MouseEvent ect)
875 * Handles a mouse press on a sequence name or the tree background canvas
876 * (click on a node is handled in mouseClicked). The action is to create
877 * groups by partitioning the tree at the mouse position. Colours for the
878 * groups (and sequence names) are generated randomly.
883 public void mousePressed(MouseEvent e)
885 av.setCurrentTree(tree);
888 * isPopupTrigger is set for mousePressed (Mac)
889 * or mouseReleased (Windows)
891 if (e.isPopupTrigger())
893 if (highlightNode != null)
895 chooseSubtreeColour();
901 * defer right-click handling on Windows to
902 * mouseClicked; note isRightMouseButton
903 * also matches Cmd-click on Mac which should do
906 if (SwingUtilities.isRightMouseButton(e))
914 Object ob = findElement(x, y);
916 if (ob instanceof SequenceI)
918 treeSelectionChanged((Sequence) ob);
919 PaintRefresher.Refresh(tp, getAssociatedPanel().av.getSequenceSetId());
924 else if (!(ob instanceof SequenceNode))
927 if (tree.getMaxHeight() != 0)
929 threshold = (float) (x - offx)
930 / (float) (getWidth() - labelLength - (2 * offx));
932 List<SequenceNode> groups = tree.groupNodes(threshold);
933 setColor(tree.getTopNode(), Color.black);
935 AlignmentPanel[] aps = getAssociatedPanels();
937 // TODO push calls below into a single AlignViewportI method?
938 // see also AlignViewController.deleteGroups
939 for (int a = 0; a < aps.length; a++)
941 aps[a].av.setSelectionGroup(null);
942 aps[a].av.getAlignment().deleteAllGroups();
943 aps[a].av.clearSequenceColours();
944 if (aps[a].av.getCodingComplement() != null)
946 aps[a].av.getCodingComplement().setSelectionGroup(null);
947 aps[a].av.getCodingComplement().getAlignment()
949 aps[a].av.getCodingComplement().clearSequenceColours();
951 aps[a].av.setUpdateStructures(true);
953 colourGroups(groups);
956 * clear partition (don't show vertical line) if
957 * it is to the right of all nodes
959 if (groups.isEmpty())
965 PaintRefresher.Refresh(tp, getAssociatedPanel().av.getSequenceSetId());
971 void colourGroups(List<SequenceNode> groups)
973 AlignmentPanel[] aps = getAssociatedPanels();
974 for (int i = 0; i < groups.size(); i++)
976 Color col = new Color((int) (Math.random() * 255),
977 (int) (Math.random() * 255), (int) (Math.random() * 255));
978 setColor(groups.get(i), col.brighter());
980 Vector<SequenceNode> l = tree.findLeaves(groups.get(i));
982 Vector<SequenceI> sequences = new Vector<>();
984 for (int j = 0; j < l.size(); j++)
986 SequenceI s1 = (SequenceI) l.elementAt(j).element();
988 if (!sequences.contains(s1))
990 sequences.addElement(s1);
994 ColourSchemeI cs = null;
995 SequenceGroup _sg = new SequenceGroup(sequences, null, cs, true, true,
996 false, 0, av.getAlignment().getWidth() - 1);
998 _sg.setName("JTreeGroup:" + _sg.hashCode());
999 _sg.setIdColour(col);
1001 for (int a = 0; a < aps.length; a++)
1003 SequenceGroup sg = new SequenceGroup(_sg);
1004 AlignViewport viewport = aps[a].av;
1006 // Propagate group colours in each view
1007 if (viewport.getGlobalColourScheme() != null)
1009 cs = viewport.getGlobalColourScheme().getInstance(viewport, sg);
1010 sg.setColourScheme(cs);
1011 sg.getGroupColourScheme().setThreshold(
1012 viewport.getResidueShading().getThreshold(),
1013 viewport.isIgnoreGapsConsensus());
1015 if (viewport.getResidueShading().conservationApplied())
1017 Conservation c = new Conservation("Group",
1018 sg.getSequences(null), sg.getStartRes(),
1021 c.verdict(false, viewport.getConsPercGaps());
1022 sg.cs.setConservation(c);
1025 // indicate that associated structure views will need an update
1026 viewport.setUpdateStructures(true);
1027 // propagate structure view update and sequence group to complement view
1028 viewport.addSequenceGroup(sg);
1032 // notify the panel(s) to redo any group specific stuff
1033 // also updates structure views if necessary
1034 for (int a = 0; a < aps.length; a++)
1036 aps[a].updateAnnotation();
1037 final AlignViewportI codingComplement = aps[a].av
1038 .getCodingComplement();
1039 if (codingComplement != null)
1041 ((AlignViewport) codingComplement).getAlignPanel()
1042 .updateAnnotation();
1053 public void setShowDistances(boolean state)
1055 this.showDistances = state;
1065 public void setShowBootstrap(boolean state)
1067 this.showBootstrap = state;
1077 public void setMarkPlaceholders(boolean state)
1079 this.markPlaceholders = state;
1083 AlignmentPanel[] getAssociatedPanels()
1085 if (applyToAllViews)
1087 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1091 return new AlignmentPanel[] { getAssociatedPanel() };
1095 public AlignmentPanel getAssociatedPanel()
1100 public void setAssociatedPanel(AlignmentPanel ap)
1105 public AlignViewport getViewport()
1110 public void setViewport(AlignViewport av)
1115 public float getThreshold()
1120 public void setThreshold(float threshold)
1122 this.threshold = threshold;
1125 public boolean isApplyToAllViews()
1127 return this.applyToAllViews;
1130 public void setApplyToAllViews(boolean applyToAllViews)
1132 this.applyToAllViews = applyToAllViews;