JAL-1767 refactorings to enable faithful restore of PCA from project
[jalview.git] / src / jalview / gui / RotatableCanvas.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.gui;
22
23 import jalview.api.RotatableCanvasI;
24 import jalview.datamodel.Point;
25 import jalview.datamodel.SequenceGroup;
26 import jalview.datamodel.SequenceI;
27 import jalview.datamodel.SequencePoint;
28 import jalview.math.RotatableMatrix;
29 import jalview.math.RotatableMatrix.Axis;
30 import jalview.util.MessageManager;
31 import jalview.viewmodel.AlignmentViewport;
32
33 import java.awt.Color;
34 import java.awt.Dimension;
35 import java.awt.Font;
36 import java.awt.Graphics;
37 import java.awt.Graphics2D;
38 import java.awt.Image;
39 import java.awt.RenderingHints;
40 import java.awt.event.InputEvent;
41 import java.awt.event.KeyEvent;
42 import java.awt.event.KeyListener;
43 import java.awt.event.MouseEvent;
44 import java.awt.event.MouseListener;
45 import java.awt.event.MouseMotionListener;
46 import java.awt.event.MouseWheelEvent;
47 import java.awt.event.MouseWheelListener;
48 import java.util.Arrays;
49 import java.util.Iterator;
50 import java.util.List;
51
52 import javax.swing.JPanel;
53 import javax.swing.ToolTipManager;
54
55 /**
56  * Models a Panel on which a set of points, and optionally x/y/z axes, can be
57  * drawn, and rotated or zoomed with the mouse
58  */
59 public class RotatableCanvas extends JPanel implements MouseListener,
60         MouseMotionListener, KeyListener, RotatableCanvasI,
61         MouseWheelListener
62 {
63   private static final float ZOOM_OUT = 0.9f;
64
65   private static final float ZOOM_IN = 1.1f;
66
67   /*
68    * pixels distance within which tooltip shows sequence name
69    */
70   private static final int NEARBY = 3;
71
72   private static final List<String> AXES = Arrays.asList("x", "y", "z");
73
74   private static final Color AXIS_COLOUR = Color.yellow;
75
76   private static final int DIMS = 3;
77
78   boolean drawAxes = true;
79
80   int mouseX;
81
82   int mouseY;
83
84   Image img;
85
86   Graphics ig;
87
88   Dimension prefSize;
89
90   /*
91    * the min-max [x, y, z] values of sequence points when the points
92    * were set on the object, or when the view is reset; 
93    * x and y ranges are not recomputed as points are rotated, as this
94    * would make scaling (zoom) unstable, but z ranges are (for correct
95    * graduated colour brightness based on z-coordinate)
96    */
97   float[] seqMin;
98
99   float[] seqMax;
100
101   /*
102    * a scale factor used in drawing; when equal to 1, the points span
103    * half the available width or height (whichever is less); increase this
104    * factor to zoom in, decrease it to zoom out
105    */
106   float scaleFactor;
107
108   int npoint;
109
110   /*
111    * sequences and their (x, y, z) PCA dimension values
112    */
113   List<SequencePoint> sequencePoints;
114
115   /*
116    * x, y, z axis end points (PCA dimension values)
117    */
118   Point[] axisEndPoints;
119
120   // fields for 'select rectangle' (JAL-1124)
121   // int rectx1;
122   // int recty1;
123   // int rectx2;
124   // int recty2;
125
126   AlignmentViewport av;
127
128   AlignmentPanel ap;
129
130   boolean showLabels;
131
132   Color bgColour;
133
134   boolean applyToAllViews;
135
136   /**
137    * Constructor
138    * 
139    * @param panel
140    */
141   public RotatableCanvas(AlignmentPanel panel)
142   {
143     this.av = panel.av;
144     this.ap = panel;
145     axisEndPoints = new Point[DIMS];
146     showLabels = false;
147     applyToAllViews = false;
148     bgColour = Color.BLACK;
149     resetAxes();
150
151     ToolTipManager.sharedInstance().registerComponent(this);
152
153     addMouseListener(this);
154     addMouseMotionListener(this);
155     addMouseWheelListener(this);
156   }
157
158   /**
159    * Refreshes the display with labels shown (or not)
160    * 
161    * @param show
162    */
163   public void showLabels(boolean show)
164   {
165     showLabels = show;
166     repaint();
167   }
168
169   @Override
170   public void setPoints(List<SequencePoint> points, int np)
171   {
172     this.sequencePoints = points;
173     this.npoint = np;
174     prefSize = getPreferredSize();
175
176     findWidths();
177
178     scaleFactor = 1f;
179   }
180
181   /**
182    * Resets axes to the initial state: x-axis to the right, y-axis up, z-axis to
183    * back (so obscured in a 2-D display)
184    */
185   protected void resetAxes()
186   {
187     axisEndPoints[0] = new Point(1f, 0f, 0f);
188     axisEndPoints[1] = new Point(0f, 1f, 0f);
189     axisEndPoints[2] = new Point(0f, 0f, 1f);
190   }
191
192   /**
193    * Computes and saves the min-max ranges of x/y/z positions of the sequence
194    * points
195    */
196   protected void findWidths()
197   {
198     float[] max = new float[DIMS];
199     float[] min = new float[DIMS];
200     
201     max[0] = -Float.MAX_VALUE;
202     max[1] = -Float.MAX_VALUE;
203     max[2] = -Float.MAX_VALUE;
204     
205     min[0] = Float.MAX_VALUE;
206     min[1] = Float.MAX_VALUE;
207     min[2] = Float.MAX_VALUE;
208     
209     for (SequencePoint sp : sequencePoints)
210     {
211       max[0] = Math.max(max[0], sp.coord.x);
212       max[1] = Math.max(max[1], sp.coord.y);
213       max[2] = Math.max(max[2], sp.coord.z);
214       min[0] = Math.min(min[0], sp.coord.x);
215       min[1] = Math.min(min[1], sp.coord.y);
216       min[2] = Math.min(min[2], sp.coord.z);
217     }
218     
219     seqMin = min;
220     seqMax = max;
221   }
222
223   /**
224    * Answers the preferred size if it has been set, else 400 x 400
225    * 
226    * @return
227    */
228   @Override
229   public Dimension getPreferredSize()
230   {
231     if (prefSize != null)
232     {
233       return prefSize;
234     }
235     else
236     {
237       return new Dimension(400, 400);
238     }
239   }
240
241   /**
242    * Answers the preferred size
243    * 
244    * @return
245    * @see RotatableCanvas#getPreferredSize()
246    */
247   @Override
248   public Dimension getMinimumSize()
249   {
250     return getPreferredSize();
251   }
252
253   /**
254    * Repaints the panel
255    * 
256    * @param g
257    */
258   @Override
259   public void paintComponent(Graphics g1)
260   {
261
262     Graphics2D g = (Graphics2D) g1;
263
264     g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
265             RenderingHints.VALUE_ANTIALIAS_ON);
266     if (sequencePoints == null)
267     {
268       g.setFont(new Font("Verdana", Font.PLAIN, 18));
269       g.drawString(
270               MessageManager.getString("label.calculating_pca") + "....",
271               20, getHeight() / 2);
272     }
273     else
274     {
275       /*
276        * create the image at the beginning or after a resize
277        */
278       boolean resized = prefSize.width != getWidth()
279               || prefSize.height != getHeight();
280       if (img == null || resized)
281       {
282         prefSize.width = getWidth();
283         prefSize.height = getHeight();
284
285         img = createImage(getWidth(), getHeight());
286         ig = img.getGraphics();
287       }
288
289       drawBackground(ig, bgColour);
290       drawScene(ig);
291
292       if (drawAxes)
293       {
294         drawAxes(ig);
295       }
296
297       g.drawImage(img, 0, 0, this);
298     }
299   }
300
301   /**
302    * Resets the rotation and choice of axes to the initial state (without change
303    * of scale factor)
304    */
305   public void resetView()
306   {
307     img = null;
308     findWidths();
309     resetAxes();
310     repaint();
311   }
312
313   /**
314    * Draws lines for the x, y, z axes
315    * 
316    * @param g
317    */
318   public void drawAxes(Graphics g)
319   {
320     g.setColor(AXIS_COLOUR);
321
322     int midX = getWidth() / 2;
323     int midY = getHeight() / 2;
324     float maxWidth = Math.max(Math.abs(seqMax[0] - seqMin[0]),
325             Math.abs(seqMax[1] - seqMin[1]));
326     int pix = Math.min(getWidth(), getHeight());
327     float scaleBy = pix * scaleFactor / (2f * maxWidth);
328
329     for (int i = 0; i < DIMS; i++)
330     {
331       g.drawLine(midX, midY,
332               midX + (int) (axisEndPoints[i].x * scaleBy * seqMax[0]),
333               midY + (int) (axisEndPoints[i].y * scaleBy * seqMax[1]));
334     }
335   }
336
337   /**
338    * Fills the background with the specified colour
339    * 
340    * @param g
341    * @param col
342    */
343   public void drawBackground(Graphics g, Color col)
344   {
345     g.setColor(col);
346     g.fillRect(0, 0, prefSize.width, prefSize.height);
347   }
348
349   /**
350    * Draws points (6x6 squares) for the sequences of the PCA, and labels
351    * (sequence names) if configured to do so. The sequence points colours are
352    * taken from the sequence ids in the alignment (converting black to white).
353    * Sequences 'at the back' (z-coordinate is negative) are shaded slightly
354    * darker to help give a 3-D sensation.
355    * 
356    * @param g
357    */
358   public void drawScene(Graphics g1)
359   {
360     Graphics2D g = (Graphics2D) g1;
361
362     g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
363             RenderingHints.VALUE_ANTIALIAS_ON);
364     int pix = Math.min(getWidth(), getHeight());
365     float xWidth = Math.abs(seqMax[0] - seqMin[0]);
366     float yWidth = Math.abs(seqMax[1] - seqMin[1]);
367     float maxWidth = Math.max(xWidth, yWidth);
368     float scaleBy = pix * scaleFactor / (2f * maxWidth);
369
370     float[] centre = getCentre();
371
372     for (int i = 0; i < npoint; i++)
373     {
374       /*
375        * sequence point colour as sequence id, but
376        * gray if sequence is currently selected
377        */
378       SequencePoint sp = sequencePoints.get(i);
379       Color sequenceColour = getSequencePointColour(sp);
380       g.setColor(sequenceColour);
381
382       int halfwidth = getWidth() / 2;
383       int halfheight = getHeight() / 2;
384       int x = (int) ((sp.coord.x - centre[0]) * scaleBy) + halfwidth;
385       int y = (int) ((sp.coord.y - centre[1]) * scaleBy) + halfheight;
386       g.fillRect(x - 3, y - 3, 6, 6);
387
388       if (showLabels)
389       {
390         g.setColor(Color.red);
391         g.drawString(sp.getSequence().getName(), x - 3, y - 4);
392       }
393     }
394     if (showLabels)
395     {
396       g.setColor(AXIS_COLOUR);
397       int midX = getWidth() / 2;
398       int midY = getHeight() / 2;
399       Iterator<String> axes = AXES.iterator();
400       for (Point p : axisEndPoints)
401       {
402         int x = midX + (int) (p.x * scaleBy * seqMax[0]);
403         int y = midY + (int) (p.y * scaleBy * seqMax[1]);
404         g.drawString(axes.next(), x - 3, y - 4);
405       }
406     }
407     // //Now the rectangle
408     // if (rectx2 != -1 && recty2 != -1) {
409     // g.setColor(Color.white);
410     //
411     // g.drawRect(rectx1,recty1,rectx2-rectx1,recty2-recty1);
412     // }
413   }
414
415   /**
416    * Determines the colour to use when drawing a sequence point. The colour is
417    * taken from the sequence id, with black converted to white, and then
418    * graduated from darker (at the back) to brighter (at the front) based on the
419    * z-axis coordinate of the point.
420    * 
421    * @param sp
422    * @return
423    */
424   protected Color getSequencePointColour(SequencePoint sp)
425   {
426     SequenceI sequence = sp.getSequence();
427     Color sequenceColour = av.getSequenceColour(sequence);
428     if (sequenceColour == Color.black)
429     {
430       sequenceColour = Color.white;
431     }
432     if (av.getSelectionGroup() != null)
433     {
434       if (av.getSelectionGroup().getSequences(null).contains(sequence))
435       {
436         sequenceColour = Color.gray;
437       }
438     }
439     if (sp.coord.z < 0f)
440     {
441       sequenceColour = sequenceColour.darker();
442     }
443
444     return sequenceColour;
445   }
446
447   @Override
448   public void keyTyped(KeyEvent evt)
449   {
450   }
451
452   @Override
453   public void keyReleased(KeyEvent evt)
454   {
455   }
456
457   /**
458    * Responds to up or down arrow key by zooming in or out, respectively
459    * 
460    * @param evt
461    */
462   @Override
463   public void keyPressed(KeyEvent evt)
464   {
465     int keyCode = evt.getKeyCode();
466
467     if (keyCode == KeyEvent.VK_UP)
468     {
469       zoom(ZOOM_IN);
470     }
471     else if (keyCode == KeyEvent.VK_DOWN)
472     {
473       zoom(ZOOM_OUT);
474     }
475     else if (evt.getKeyChar() == 's')
476     {
477       // Cache.log.warn("DEBUG: Rectangle selection");
478       // todo not yet enabled as rectx2, recty2 are always -1
479       // need to set them in mouseDragged; JAL-1124
480       // if ((rectx2 != -1) && (recty2 != -1))
481       // {
482       // rectSelect(rectx1, recty1, rectx2, recty2);
483       // }
484     }
485
486     repaint();
487   }
488
489   @Override
490   public void zoom(float factor)
491   {
492     if (factor > 0f)
493     {
494       scaleFactor *= factor;
495     }
496   }
497
498   @Override
499   public void mouseClicked(MouseEvent evt)
500   {
501   }
502
503   @Override
504   public void mouseEntered(MouseEvent evt)
505   {
506   }
507
508   @Override
509   public void mouseExited(MouseEvent evt)
510   {
511   }
512
513   @Override
514   public void mouseReleased(MouseEvent evt)
515   {
516   }
517
518   /**
519    * If the mouse press is at (within 2 pixels of) a sequence point, toggles
520    * (adds or removes) the corresponding sequence as a member of the viewport
521    * selection group. This supports configuring a group in the alignment by
522    * clicking on points in the PCA display.
523    */
524   @Override
525   public void mousePressed(MouseEvent evt)
526   {
527     int x = evt.getX();
528     int y = evt.getY();
529
530     mouseX = x;
531     mouseY = y;
532
533     // rectx1 = x;
534     // recty1 = y;
535     // rectx2 = -1;
536     // recty2 = -1;
537
538     SequenceI found = findSequenceAtPoint(x, y);
539
540     if (found != null)
541     {
542       AlignmentPanel[] aps = getAssociatedPanels();
543
544       for (int a = 0; a < aps.length; a++)
545       {
546         if (aps[a].av.getSelectionGroup() != null)
547         {
548           aps[a].av.getSelectionGroup().addOrRemove(found, true);
549         }
550         else
551         {
552           aps[a].av.setSelectionGroup(new SequenceGroup());
553           aps[a].av.getSelectionGroup().addOrRemove(found, true);
554           aps[a].av.getSelectionGroup()
555                   .setEndRes(aps[a].av.getAlignment().getWidth() - 1);
556         }
557       }
558       PaintRefresher.Refresh(this, av.getSequenceSetId());
559       // canonical selection is sent to other listeners
560       av.sendSelection();
561     }
562
563     repaint();
564   }
565
566   /**
567    * Sets the tooltip to the name of the sequence within 2 pixels of the mouse
568    * position, or clears the tooltip if none found
569    */
570   @Override
571   public void mouseMoved(MouseEvent evt)
572   {
573     SequenceI found = findSequenceAtPoint(evt.getX(), evt.getY());
574
575     this.setToolTipText(found == null ? null : found.getName());
576   }
577
578   /**
579    * Action handler for a mouse drag. Rotates the display around the X axis (for
580    * up/down mouse movement) and/or the Y axis (for left/right mouse movement).
581    * 
582    * @param evt
583    */
584   @Override
585   public void mouseDragged(MouseEvent evt)
586   {
587     int xPos = evt.getX();
588     int yPos = evt.getY();
589
590     if (xPos == mouseX && yPos == mouseY)
591     {
592       return;
593     }
594
595     int xDelta = xPos - mouseX;
596     int yDelta = yPos - mouseY;
597
598     // Check if this is a rectangle drawing drag
599     if ((evt.getModifiers() & InputEvent.BUTTON2_MASK) != 0)
600     {
601       // rectx2 = evt.getX();
602       // recty2 = evt.getY();
603     }
604     else
605     {
606       rotate(xDelta, yDelta);
607
608       mouseX = xPos;
609       mouseY = yPos;
610
611       // findWidths();
612
613       repaint();
614     }
615   }
616
617   @Override
618   public void rotate(float x, float y)
619   {
620     if (x == 0f && y == 0f)
621     {
622       return;
623     }
624
625     /*
626      * get the identity transformation...
627      */
628     RotatableMatrix rotmat = new RotatableMatrix();
629
630     /*
631      * rotate around the X axis for change in Y
632      * (mouse movement up/down); note we are equating a
633      * number of pixels with degrees of rotation here!
634      */
635     if (y != 0)
636     {
637       rotmat.rotate(y, Axis.X);
638     }
639
640     /*
641      * rotate around the Y axis for change in X
642      * (mouse movement left/right)
643      */
644     if (x != 0)
645     {
646       rotmat.rotate(x, Axis.Y);
647     }
648
649     /*
650      * apply the composite transformation to sequence points;
651      * update z min-max range (affects colour graduation), but not
652      * x or y min-max (as this would affect axis scaling)
653      */
654     float[] centre = getCentre();
655     float zMin = Float.MAX_VALUE;
656     float zMax = -Float.MAX_VALUE;
657
658     for (int i = 0; i < npoint; i++)
659     {
660       SequencePoint sp = sequencePoints.get(i);
661       sp.translate(-centre[0], -centre[1], -centre[2]);
662
663       // Now apply the rotation matrix
664       sp.coord = rotmat.vectorMultiply(sp.coord);
665
666       // Now translate back again
667       sp.translate(centre[0], centre[1], centre[2]);
668       
669       zMin = Math.min(zMin, sp.coord.z);
670       zMax = Math.max(zMax, sp.coord.z);
671     }
672
673     seqMin[2] = zMin;
674     seqMax[2] = zMax;
675
676     /*
677      * rotate the x/y/z axis positions
678      */
679     for (int i = 0; i < DIMS; i++)
680     {
681       axisEndPoints[i] = rotmat.vectorMultiply(axisEndPoints[i]);
682     }
683   }
684
685   /**
686    * Answers the x/y/z coordinates that are midway between the maximum and
687    * minimum sequence point values
688    * 
689    * @return
690    */
691   private float[] getCentre()
692   {
693     float xCentre = (seqMin[0] + seqMax[0]) / 2f;
694     float yCentre = (seqMin[1] + seqMax[1]) / 2f;
695     float zCentre = (seqMin[2] + seqMax[2]) / 2f;
696
697     return new float[] { xCentre, yCentre, zCentre };
698   }
699
700   /**
701    * Adds any sequences whose displayed points are within the given rectangle to
702    * the viewport's current selection. Intended for key 's' after dragging to
703    * select a region of the PCA.
704    * 
705    * @param x1
706    * @param y1
707    * @param x2
708    * @param y2
709    */
710   protected void rectSelect(int x1, int y1, int x2, int y2)
711   {
712     float[] centre = getCentre();
713
714     for (int i = 0; i < npoint; i++)
715     {
716       SequencePoint sp = sequencePoints.get(i);
717       int tmp1 = (int) (((sp.coord.x - centre[0]) * scaleFactor)
718               + (getWidth() / 2.0));
719       int tmp2 = (int) (((sp.coord.y - centre[1]) * scaleFactor)
720               + (getHeight() / 2.0));
721
722       if ((tmp1 > x1) && (tmp1 < x2) && (tmp2 > y1) && (tmp2 < y2))
723       {
724         if (av != null)
725         {
726           SequenceI sequence = sp.getSequence();
727           if (!av.getSelectionGroup().getSequences(null)
728                   .contains(sequence))
729           {
730             av.getSelectionGroup().addSequence(sequence, true);
731           }
732         }
733       }
734     }
735   }
736
737   /**
738    * Answers the first sequence found whose point on the display is within 2
739    * pixels of the given coordinates, or null if none is found
740    * 
741    * @param x
742    * @param y
743    * 
744    * @return
745    */
746   protected SequenceI findSequenceAtPoint(int x, int y)
747   {
748     int halfwidth = getWidth() / 2;
749     int halfheight = getHeight() / 2;
750
751     int found = -1;
752     int pix = Math.min(getWidth(), getHeight());
753     float xWidth = Math.abs(seqMax[0] - seqMin[0]);
754     float yWidth = Math.abs(seqMax[1] - seqMin[1]);
755     float maxWidth = Math.max(xWidth, yWidth);
756     float scaleBy = pix * scaleFactor / (2f * maxWidth);
757
758     float[] centre = getCentre();
759
760     for (int i = 0; i < npoint; i++)
761     {
762       SequencePoint sp = sequencePoints.get(i);
763       int px = (int) ((sp.coord.x - centre[0]) * scaleBy)
764               + halfwidth;
765       int py = (int) ((sp.coord.y - centre[1]) * scaleBy)
766               + halfheight;
767
768       if ((Math.abs(px - x) < NEARBY) && (Math.abs(py - y) < NEARBY))
769       {
770         found = i;
771         break;
772       }
773     }
774
775     if (found != -1)
776     {
777       return sequencePoints.get(found).getSequence();
778     }
779     else
780     {
781       return null;
782     }
783   }
784
785   /**
786    * Answers the panel the PCA is associated with (all panels for this alignment
787    * if 'associate with all panels' is selected).
788    * 
789    * @return
790    */
791   AlignmentPanel[] getAssociatedPanels()
792   {
793     if (applyToAllViews)
794     {
795       return PaintRefresher.getAssociatedPanels(av.getSequenceSetId());
796     }
797     else
798     {
799       return new AlignmentPanel[] { ap };
800     }
801   }
802
803   public Color getBackgroundColour()
804   {
805     return bgColour;
806   }
807
808   /**
809    * Zooms in or out in response to mouse wheel movement
810    */
811   @Override
812   public void mouseWheelMoved(MouseWheelEvent e)
813   {
814     double wheelRotation = e.getPreciseWheelRotation();
815     if (wheelRotation > 0)
816     {
817       zoom(ZOOM_IN);
818       repaint();
819     }
820     else if (wheelRotation < 0)
821     {
822       zoom(ZOOM_OUT);
823       repaint();
824     }
825   }
826
827   /**
828    * Answers the sequence point minimum [x, y, z] values. Note these are derived
829    * when sequence points are set, but x and y values are not updated on
830    * rotation (because this would result in changes to scaling).
831    * 
832    * @return
833    */
834   public float[] getSeqMin()
835   {
836     return seqMin;
837   }
838
839   /**
840    * Answers the sequence point maximum [x, y, z] values. Note these are derived
841    * when sequence points are set, but x and y values are not updated on
842    * rotation (because this would result in changes to scaling).
843    * 
844    * @return
845    */
846   public float[] getSeqMax()
847   {
848     return seqMax;
849   }
850
851   /**
852    * Sets the minimum and maximum [x, y, z] positions for sequence points. For
853    * use when restoring a saved PCA from state data.
854    * 
855    * @param min
856    * @param max
857    */
858   public void setSeqMinMax(float[] min, float[] max)
859   {
860     seqMin = min;
861     seqMax = max;
862   }
863 }