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