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 chooseSubtreeColour();
760 e.consume(); // prevent mouseClicked happening
765 * Empty method to satisfy the MouseListener interface
770 public void mouseEntered(MouseEvent e)
775 * Empty method to satisfy the MouseListener interface
780 public void mouseExited(MouseEvent e)
785 * Handles a mouse click on a tree node (clicks elsewhere are handled in
786 * mousePressed). Click selects the sub-tree, double-click swaps leaf nodes
787 * order, right-click opens a dialogue to choose colour for the sub-tree.
792 public void mouseClicked(MouseEvent evt)
794 if (highlightNode == null)
799 if (evt.getClickCount() > 1)
801 tree.swapNodes(highlightNode);
802 tree.reCount(tree.getTopNode());
803 tree.findHeight(tree.getTopNode());
807 Vector<SequenceNode> leaves = tree.findLeaves(highlightNode);
809 for (int i = 0; i < leaves.size(); i++)
811 SequenceI seq = (SequenceI) leaves.elementAt(i).element();
812 treeSelectionChanged(seq);
817 PaintRefresher.Refresh(tp, av.getSequenceSetId());
822 * Offer the user the option to choose a colour for the highlighted node and
823 * its children; this colour is also applied to the corresponding sequence ids
826 void chooseSubtreeColour()
828 String ttl = MessageManager.getString("label.select_subtree_colour");
829 ColourChooserListener listener = new ColourChooserListener() {
831 public void colourSelected(Color c)
833 setColor(highlightNode, c);
834 PaintRefresher.Refresh(tp, ap.av.getSequenceSetId());
838 JalviewColourChooser.showColourChooser(this, ttl, highlightNode.color, listener);
842 public void mouseMoved(MouseEvent evt)
844 av.setCurrentTree(tree);
846 Object ob = findElement(evt.getX(), evt.getY());
848 if (ob instanceof SequenceNode)
850 highlightNode = (SequenceNode) ob;
852 "<html>" + MessageManager.getString("label.highlightnode"));
858 if (highlightNode != null)
860 highlightNode = null;
861 setToolTipText(null);
868 public void mouseDragged(MouseEvent ect)
873 * Handles a mouse press on a sequence name or the tree background canvas
874 * (click on a node is handled in mouseClicked). The action is to create
875 * groups by partitioning the tree at the mouse position. Colours for the
876 * groups (and sequence names) are generated randomly.
881 public void mousePressed(MouseEvent e)
883 av.setCurrentTree(tree);
886 * isPopupTrigger is set for mousePressed (Mac)
887 * or mouseReleased (Windows)
889 if (e.isPopupTrigger())
891 if (highlightNode != null)
893 chooseSubtreeColour();
899 * defer right-click handling on Windows to
900 * mouseClicked; note isRightMouseButton
901 * also matches Cmd-click on Mac which should do
904 if (SwingUtilities.isRightMouseButton(e))
912 Object ob = findElement(x, y);
914 if (ob instanceof SequenceI)
916 treeSelectionChanged((Sequence) ob);
917 PaintRefresher.Refresh(tp, getAssociatedPanel().av.getSequenceSetId());
922 else if (!(ob instanceof SequenceNode))
925 if (tree.getMaxHeight() != 0)
927 threshold = (float) (x - offx)
928 / (float) (getWidth() - labelLength - (2 * offx));
930 List<SequenceNode> groups = tree.groupNodes(threshold);
931 setColor(tree.getTopNode(), Color.black);
933 AlignmentPanel[] aps = getAssociatedPanels();
935 // TODO push calls below into a single AlignViewportI method?
936 // see also AlignViewController.deleteGroups
937 for (int a = 0; a < aps.length; a++)
939 aps[a].av.setSelectionGroup(null);
940 aps[a].av.getAlignment().deleteAllGroups();
941 aps[a].av.clearSequenceColours();
942 if (aps[a].av.getCodingComplement() != null)
944 aps[a].av.getCodingComplement().setSelectionGroup(null);
945 aps[a].av.getCodingComplement().getAlignment()
947 aps[a].av.getCodingComplement().clearSequenceColours();
949 aps[a].av.setUpdateStructures(true);
951 colourGroups(groups);
954 * clear partition (don't show vertical line) if
955 * it is to the right of all nodes
957 if (groups.isEmpty())
963 PaintRefresher.Refresh(tp, getAssociatedPanel().av.getSequenceSetId());
969 void colourGroups(List<SequenceNode> groups)
971 AlignmentPanel[] aps = getAssociatedPanels();
972 for (int i = 0; i < groups.size(); i++)
974 Color col = new Color((int) (Math.random() * 255),
975 (int) (Math.random() * 255), (int) (Math.random() * 255));
976 setColor(groups.get(i), col.brighter());
978 Vector<SequenceNode> l = tree.findLeaves(groups.get(i));
980 Vector<SequenceI> sequences = new Vector<>();
982 for (int j = 0; j < l.size(); j++)
984 SequenceI s1 = (SequenceI) l.elementAt(j).element();
986 if (!sequences.contains(s1))
988 sequences.addElement(s1);
992 ColourSchemeI cs = null;
993 SequenceGroup _sg = new SequenceGroup(sequences, null, cs, true, true,
994 false, 0, av.getAlignment().getWidth() - 1);
996 _sg.setName("JTreeGroup:" + _sg.hashCode());
997 _sg.setIdColour(col);
999 for (int a = 0; a < aps.length; a++)
1001 SequenceGroup sg = new SequenceGroup(_sg);
1002 AlignViewport viewport = aps[a].av;
1004 // Propagate group colours in each view
1005 if (viewport.getGlobalColourScheme() != null)
1007 cs = viewport.getGlobalColourScheme().getInstance(viewport, sg);
1008 sg.setColourScheme(cs);
1009 sg.getGroupColourScheme().setThreshold(
1010 viewport.getResidueShading().getThreshold(),
1011 viewport.isIgnoreGapsConsensus());
1013 if (viewport.getResidueShading().conservationApplied())
1015 Conservation c = new Conservation("Group",
1016 sg.getSequences(null), sg.getStartRes(),
1019 c.verdict(false, viewport.getConsPercGaps());
1020 sg.cs.setConservation(c);
1023 // indicate that associated structure views will need an update
1024 viewport.setUpdateStructures(true);
1025 // propagate structure view update and sequence group to complement view
1026 viewport.addSequenceGroup(sg);
1030 // notify the panel(s) to redo any group specific stuff
1031 // also updates structure views if necessary
1032 for (int a = 0; a < aps.length; a++)
1034 aps[a].updateAnnotation();
1035 final AlignViewportI codingComplement = aps[a].av
1036 .getCodingComplement();
1037 if (codingComplement != null)
1039 ((AlignViewport) codingComplement).getAlignPanel()
1040 .updateAnnotation();
1051 public void setShowDistances(boolean state)
1053 this.showDistances = state;
1063 public void setShowBootstrap(boolean state)
1065 this.showBootstrap = state;
1075 public void setMarkPlaceholders(boolean state)
1077 this.markPlaceholders = state;
1081 AlignmentPanel[] getAssociatedPanels()
1083 if (applyToAllViews)
1085 return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
1089 return new AlignmentPanel[] { getAssociatedPanel() };
1093 public AlignmentPanel getAssociatedPanel()
1098 public void setAssociatedPanel(AlignmentPanel ap)
1103 public AlignViewport getViewport()
1108 public void setViewport(AlignViewport av)
1113 public float getThreshold()
1118 public void setThreshold(float threshold)
1120 this.threshold = threshold;
1123 public boolean isApplyToAllViews()
1125 return this.applyToAllViews;
1128 public void setApplyToAllViews(boolean applyToAllViews)
1130 this.applyToAllViews = applyToAllViews;