/* * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$) * Copyright (C) $$Year-Rel$$ The Jalview Authors * * This file is part of Jalview. * * Jalview is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * Jalview is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Jalview. If not, see . * The Jalview Authors are detailed in the 'AUTHORS' file. */ package jalview.gui; import jalview.api.RotatableCanvasI; import jalview.datamodel.Point; import jalview.datamodel.SequenceGroup; import jalview.datamodel.SequenceI; import jalview.datamodel.SequencePoint; import jalview.math.RotatableMatrix; import jalview.math.RotatableMatrix.Axis; import jalview.util.ColorUtils; import jalview.util.MessageManager; import jalview.viewmodel.AlignmentViewport; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.util.Vector; import javax.swing.JPanel; import javax.swing.ToolTipManager; /** * Models a Panel on which a set of points, and optionally x/y/z axes, can be * drawn, and rotated or zoomed with the mouse */ public class RotatableCanvas extends JPanel implements MouseListener, MouseMotionListener, KeyListener, RotatableCanvasI { private static final int DIMS = 3; // RubberbandRectangle rubberband; boolean drawAxes = true; int mouseX = 0; int mouseY = 0; Image img; Graphics ig; Dimension prefsize; Point centre; float[] width = new float[DIMS]; float[] max = new float[DIMS]; float[] min = new float[DIMS]; float maxwidth; float scale; int npoint; Vector points; Point[] orig; Point[] axisEndPoints; int startx; int starty; int lastx; int lasty; int rectx1; int recty1; int rectx2; int recty2; float scalefactor = 1; AlignmentViewport av; AlignmentPanel ap; boolean showLabels = false; Color bgColour = Color.black; boolean applyToAllViews = false; boolean first = true; /** * Constructor * * @param panel */ public RotatableCanvas(AlignmentPanel panel) { this.av = panel.av; this.ap = panel; axisEndPoints = new Point[DIMS]; addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { double wheelRotation = e.getPreciseWheelRotation(); if (wheelRotation > 0) { /* * zoom in */ scale = (float) (scale * 1.1); repaint(); } else if (wheelRotation < 0) { /* * zoom out */ scale = (float) (scale * 0.9); repaint(); } } }); } /** * Refreshes the display with labels shown (or not) * * @param show */ public void showLabels(boolean show) { showLabels = show; repaint(); } @Override public void setPoints(Vector points, int npoint) { this.points = points; this.npoint = npoint; if (first) { ToolTipManager.sharedInstance().registerComponent(this); ToolTipManager.sharedInstance().setInitialDelay(0); ToolTipManager.sharedInstance().setDismissDelay(10000); } prefsize = getPreferredSize(); orig = new Point[npoint]; for (int i = 0; i < npoint; i++) { SequencePoint sp = points.elementAt(i); orig[i] = sp.coord; } resetAxes(); findCentre(); findWidth(); scale = findScale(); if (first) { addMouseListener(this); addMouseMotionListener(this); } first = false; } /** * Resets axes to the initial state: x-axis to the right, y-axis up, z-axis to * back (so obscured in a 2-D display) */ protected void resetAxes() { axisEndPoints[0] = new Point(1f, 0f, 0f); axisEndPoints[1] = new Point(0f, 1f, 0f); axisEndPoints[2] = new Point(0f, 0f, 1f); } /** * Computes and saves the maximum and minimum (x, y, z) positions of any * sequence point, and also the min-max range (width) for each dimension, and * the maximum width for all dimensions */ protected void findWidth() { max = new float[DIMS]; min = new float[DIMS]; max[0] = Float.MIN_VALUE; max[1] = Float.MIN_VALUE; max[2] = Float.MIN_VALUE; min[0] = Float.MAX_VALUE; min[1] = Float.MAX_VALUE; min[2] = Float.MAX_VALUE; for (SequencePoint sp : points) { max[0] = Math.max(max[0], sp.coord.x); max[1] = Math.max(max[1], sp.coord.y); max[2] = Math.max(max[2], sp.coord.z); min[0] = Math.min(min[0], sp.coord.x); min[1] = Math.min(min[1], sp.coord.y); min[2] = Math.min(min[2], sp.coord.z); } width[0] = Math.abs(max[0] - min[0]); width[1] = Math.abs(max[1] - min[1]); width[2] = Math.abs(max[2] - min[2]); maxwidth = Math.max(width[0], Math.max(width[1], width[2])); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ protected float findScale() { int dim; int w; int height; if (getWidth() != 0) { w = getWidth(); height = getHeight(); } else { w = prefsize.width; height = prefsize.height; } if (w < height) { dim = w; } else { dim = height; } return (dim * scalefactor) / (2 * maxwidth); } /** * Computes and saves the position of the centre of the view */ protected void findCentre() { findWidth(); float x = (max[0] + min[0]) / 2; float y = (max[1] + min[1]) / 2; float z = (max[2] + min[2]) / 2; centre = new Point(x, y, z); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public Dimension getPreferredSize() { if (prefsize != null) { return prefsize; } else { return new Dimension(400, 400); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public Dimension getMinimumSize() { return getPreferredSize(); } /** * DOCUMENT ME! * * @param g * DOCUMENT ME! */ @Override public void paintComponent(Graphics g1) { Graphics2D g = (Graphics2D) g1; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (points == null) { g.setFont(new Font("Verdana", Font.PLAIN, 18)); g.drawString( MessageManager.getString("label.calculating_pca") + "....", 20, getHeight() / 2); } else { // Only create the image at the beginning - if ((img == null) || (prefsize.width != getWidth()) || (prefsize.height != getHeight())) { prefsize.width = getWidth(); prefsize.height = getHeight(); scale = findScale(); // System.out.println("New scale = " + scale); img = createImage(getWidth(), getHeight()); ig = img.getGraphics(); } drawBackground(ig, bgColour); drawScene(ig); if (drawAxes) { drawAxes(ig); } g.drawImage(img, 0, 0, this); } } /** * Resets the view to initial state (no rotation) */ public void resetView() { img = null; resetAxes(); } /** * Draws lines for the x, y, z axes * * @param g */ public void drawAxes(Graphics g) { g.setColor(Color.yellow); for (int i = 0; i < DIMS; i++) { g.drawLine(getWidth() / 2, getHeight() / 2, (int) ((axisEndPoints[i].x * scale * max[0]) + (getWidth() / 2)), (int) ((axisEndPoints[i].y * scale * max[1]) + (getHeight() / 2))); } } /** * Fills the background with the specified colour * * @param g * @param col */ public void drawBackground(Graphics g, Color col) { g.setColor(col); g.fillRect(0, 0, prefsize.width, prefsize.height); } /** * Draws points (6x6 squares) for the sequences of the PCA, and labels * (sequence names) if configured to do so. The sequence points colours are * taken from the sequence ids in the alignment (converting black to white). * Sequences 'at the back' (z-coordinate is negative) are shaded slightly * darker to help give a 3-D sensation. * * @param g */ public void drawScene(Graphics g1) { Graphics2D g = (Graphics2D) g1; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); for (int i = 0; i < npoint; i++) { /* * sequence point colour as sequence id, but * gray if sequence is currently selected */ SequencePoint sp = points.elementAt(i); Color sequenceColour = getSequencePointColour(sp); g.setColor(sequenceColour); int halfwidth = getWidth() / 2; int halfheight = getHeight() / 2; int x = (int) ((sp.coord.x - centre.x) * scale) + halfwidth; int y = (int) ((sp.coord.y - centre.y) * scale) + halfheight; g.fillRect(x - 3, y - 3, 6, 6); if (showLabels) { g.setColor(Color.red); g.drawString(sp.getSequence().getName(), x - 3, y - 4); } } // //Now the rectangle // if (rectx2 != -1 && recty2 != -1) { // g.setColor(Color.white); // // g.drawRect(rectx1,recty1,rectx2-rectx1,recty2-recty1); // } } /** * Determines the colour to use when drawing a sequence point. The colour is * taken from the sequence id, with black converted to white, and then * graduated from darker (at the back) to brighter (at the front) based on the * z-axis coordinate of the point. * * @param sp * @return */ protected Color getSequencePointColour(SequencePoint sp) { SequenceI sequence = sp.getSequence(); Color sequenceColour = av.getSequenceColour(sequence); if (sequenceColour == Color.black) { sequenceColour = Color.white; } if (av.getSelectionGroup() != null) { if (av.getSelectionGroup().getSequences(null).contains(sequence)) { sequenceColour = Color.gray; } } /* * graduate from front (brighter) to back (darker) */ sequenceColour = ColorUtils.getGraduatedColour(sp.coord.z, min[2], max[2], sequenceColour); return sequenceColour; } @Override public void keyTyped(KeyEvent evt) { } @Override public void keyReleased(KeyEvent evt) { } /** * Responds to up or down arrow key by zooming in or out, respectively * * @param evt */ @Override public void keyPressed(KeyEvent evt) { if (evt.getKeyCode() == KeyEvent.VK_UP) { scalefactor = (float) (scalefactor * 1.1); scale = findScale(); } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) { scalefactor = (float) (scalefactor * 0.9); scale = findScale(); } else if (evt.getKeyChar() == 's') { // Cache.log.warn("DEBUG: Rectangle selection"); // todo not yet enabled as rectx2, recty2 are always -1 // need to set them in mouseDragged if ((rectx2 != -1) && (recty2 != -1)) { rectSelect(rectx1, recty1, rectx2, recty2); } } repaint(); } @Override public void mouseClicked(MouseEvent evt) { } @Override public void mouseEntered(MouseEvent evt) { } @Override public void mouseExited(MouseEvent evt) { } @Override public void mouseReleased(MouseEvent evt) { } /** * If the mouse press is at (within 2 pixels of) a sequence point, toggles * (adds or removes) the corresponding sequence as a member of the viewport * selection group. This supports configuring a group in the alignment by * clicking on points in the PCA display. */ @Override public void mousePressed(MouseEvent evt) { int x = evt.getX(); int y = evt.getY(); mouseX = x; mouseY = y; startx = x; starty = y; rectx1 = x; recty1 = y; rectx2 = -1; recty2 = -1; SequenceI found = findSequenceAtPoint(x, y); if (found != null) { AlignmentPanel[] aps = getAssociatedPanels(); for (int a = 0; a < aps.length; a++) { if (aps[a].av.getSelectionGroup() != null) { aps[a].av.getSelectionGroup().addOrRemove(found, true); } else { aps[a].av.setSelectionGroup(new SequenceGroup()); aps[a].av.getSelectionGroup().addOrRemove(found, true); aps[a].av.getSelectionGroup() .setEndRes(aps[a].av.getAlignment().getWidth() - 1); } } PaintRefresher.Refresh(this, av.getSequenceSetId()); // canonical selection is sent to other listeners av.sendSelection(); } repaint(); } /** * Sets the tooltip to the name of the sequence within 2 pixels of the mouse * position, or clears the tooltip if none found */ @Override public void mouseMoved(MouseEvent evt) { SequenceI found = findSequenceAtPoint(evt.getX(), evt.getY()); this.setToolTipText(found == null ? null : found.getName()); } /** * Action handler for a mouse drag. Rotates the display around the X axis (for * up/down mouse movement) and/or the Y axis (for left/right mouse movement). * * @param evt */ @Override public void mouseDragged(MouseEvent evt) { int xPos = evt.getX(); int yPos = evt.getY(); if (xPos == mouseX && yPos == mouseY) { return; } // Check if this is a rectangle drawing drag if ((evt.getModifiers() & InputEvent.BUTTON2_MASK) != 0) { // rectx2 = evt.getX(); // recty2 = evt.getY(); } else { /* * get the identity transformation... */ RotatableMatrix rotmat = new RotatableMatrix(); /* * rotate around the X axis for change in Y * (mouse movement up/down); note we are equating a * number of pixels with degrees of rotation here! */ if (yPos != mouseY) { rotmat.rotate(yPos - mouseY, Axis.X); } /* * rotate around the Y axis for change in X * (mouse movement left/right) */ if (xPos != mouseX) { rotmat.rotate(xPos - mouseX, Axis.Y); } /* * apply the composite transformation to sequence points */ for (int i = 0; i < npoint; i++) { SequencePoint sp = points.elementAt(i); sp.translateBack(centre); // Now apply the rotation matrix sp.coord = rotmat.vectorMultiply(sp.coord); // Now translate back again sp.translate(centre); } /* * rotate the x/y/z axis positions */ for (int i = 0; i < DIMS; i++) { axisEndPoints[i] = rotmat.vectorMultiply(axisEndPoints[i]); } mouseX = xPos; mouseY = yPos; paint(this.getGraphics()); } } /** * Adds any sequences whose displayed points are within the given rectangle to * the viewport's current selection. Intended for key 's' after dragging to * select a region of the PCA. * * @param x1 * @param y1 * @param x2 * @param y2 */ protected void rectSelect(int x1, int y1, int x2, int y2) { for (int i = 0; i < npoint; i++) { SequencePoint sp = points.elementAt(i); int tmp1 = (int) (((sp.coord.x - centre.x) * scale) + (getWidth() / 2.0)); int tmp2 = (int) (((sp.coord.y - centre.y) * scale) + (getHeight() / 2.0)); if ((tmp1 > x1) && (tmp1 < x2) && (tmp2 > y1) && (tmp2 < y2)) { if (av != null) { SequenceI sequence = sp.getSequence(); if (!av.getSelectionGroup().getSequences(null) .contains(sequence)) { av.getSelectionGroup().addSequence(sequence, true); } } } } } /** * Answers the first sequence found whose point on the display is within 2 * pixels of the given coordinates, or null if none is found * * @param x * @param y * * @return */ protected SequenceI findSequenceAtPoint(int x, int y) { int halfwidth = getWidth() / 2; int halfheight = getHeight() / 2; int found = -1; for (int i = 0; i < npoint; i++) { SequencePoint sp = points.elementAt(i); int px = (int) ((sp.coord.x - centre.x) * scale) + halfwidth; int py = (int) ((sp.coord.y - centre.y) * scale) + halfheight; if ((Math.abs(px - x) < 3) && (Math.abs(py - y) < 3)) { found = i; break; } } if (found != -1) { return points.elementAt(found).getSequence(); } else { return null; } } /** * Answers the panel the PCA is associated with (all panels for this alignment * if 'associate with all panels' is selected). * * @return */ AlignmentPanel[] getAssociatedPanels() { if (applyToAllViews) { return PaintRefresher.getAssociatedPanels(av.getSequenceSetId()); } else { return new AlignmentPanel[] { ap }; } } }