JAL-1767 refactorings to enable faithful restore of PCA from project
[jalview.git] / src / jalview / appletgui / 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.appletgui;
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.Image;
38 import java.awt.Panel;
39 import java.awt.event.KeyEvent;
40 import java.awt.event.KeyListener;
41 import java.awt.event.MouseEvent;
42 import java.awt.event.MouseListener;
43 import java.awt.event.MouseMotionListener;
44 import java.util.List;
45
46 public class RotatableCanvas extends Panel implements MouseListener,
47         MouseMotionListener, KeyListener, RotatableCanvasI
48 {
49   private static final int DIMS = 3;
50
51   String tooltip;
52
53   int toolx;
54
55   int tooly;
56
57   // RubberbandRectangle rubberband;
58
59   boolean drawAxes = true;
60
61   int mouseX = 0;
62
63   int mouseY = 0;
64
65   Image img;
66
67   Graphics ig;
68
69   Dimension prefsize;
70
71   Point centre;
72
73   float[] width = new float[DIMS];
74
75   float[] max = new float[DIMS];
76
77   float[] min = new float[DIMS];
78
79   float maxwidth;
80
81   float scale;
82
83   int npoint;
84
85   List<SequencePoint> points;
86
87   Point[] orig;
88
89   Point[] axisEndPoints;
90
91   int startx;
92
93   int starty;
94
95   int lastx;
96
97   int lasty;
98
99   int rectx1;
100
101   int recty1;
102
103   int rectx2;
104
105   int recty2;
106
107   float scalefactor = 1;
108
109   AlignmentViewport av;
110
111   boolean showLabels = false;
112
113   public RotatableCanvas(AlignmentViewport viewport)
114   {
115     this.av = viewport;
116     axisEndPoints = new Point[DIMS];
117   }
118
119   public void showLabels(boolean b)
120   {
121     showLabels = b;
122     repaint();
123   }
124
125   @Override
126   public void setPoints(List<SequencePoint> points, int npoint)
127   {
128     this.points = points;
129     this.npoint = npoint;
130     PaintRefresher.Register(this, av.getSequenceSetId());
131
132     prefsize = getPreferredSize();
133     orig = new Point[npoint];
134
135     for (int i = 0; i < npoint; i++)
136     {
137       SequencePoint sp = points.get(i);
138       orig[i] = sp.coord;
139     }
140
141     resetAxes();
142
143     findCentre();
144     findWidth();
145
146     scale = findScale();
147
148     // System.out.println("Scale factor = " + scale);
149
150     addMouseListener(this);
151     addKeyListener(this);
152     // if (getParent() != null) {
153     // getParent().addKeyListener(this);
154     // }
155     addMouseMotionListener(this);
156
157     // Add rubberband
158     // rubberband = new RubberbandRectangle(this);
159     // rubberband.setActive(true);
160     // rubberband.addListener(this);
161   }
162
163   /*
164    * public boolean handleSequenceSelectionEvent(SequenceSelectionEvent evt) {
165    * redrawneeded = true; repaint(); return true; }
166    * 
167    * public void removeNotify() { controller.removeListener(this);
168    * super.removeNotify(); }
169    */
170
171   /**
172    * Resets axes to the initial state: x-axis to the right, y-axis up, z-axis to
173    * back (so obscured in a 2-D display)
174    */
175   public void resetAxes()
176   {
177     axisEndPoints[0] = new Point(1f, 0f, 0f);
178     axisEndPoints[1] = new Point(0f, 1f, 0f);
179     axisEndPoints[2] = new Point(0f, 0f, 1f);
180   }
181
182   /**
183    * Computes and saves the maximum and minimum (x, y, z) positions of any
184    * sequence point, and also the min-max range (width) for each dimension, and
185    * the maximum width for all dimensions
186    */
187   public void findWidth()
188   {
189     max = new float[3];
190     min = new float[3];
191
192     max[0] = Float.MIN_VALUE;
193     max[1] = Float.MIN_VALUE;
194     max[2] = Float.MIN_VALUE;
195
196     min[0] = Float.MAX_VALUE;
197     min[1] = Float.MAX_VALUE;
198     min[2] = Float.MAX_VALUE;
199
200     for (SequencePoint sp : points)
201     {
202       max[0] = Math.max(max[0], sp.coord.x);
203       max[1] = Math.max(max[1], sp.coord.y);
204       max[2] = Math.max(max[2], sp.coord.z);
205       min[0] = Math.min(min[0], sp.coord.x);
206       min[1] = Math.min(min[1], sp.coord.y);
207       min[2] = Math.min(min[2], sp.coord.z);
208     }
209
210     width[0] = Math.abs(max[0] - min[0]);
211     width[1] = Math.abs(max[1] - min[1]);
212     width[2] = Math.abs(max[2] - min[2]);
213
214     maxwidth = Math.max(width[0], Math.max(width[1], width[2]));
215   }
216
217   public float findScale()
218   {
219     int dim, w, height;
220     if (getSize().width != 0)
221     {
222       w = getSize().width;
223       height = getSize().height;
224     }
225     else
226     {
227       w = prefsize.width;
228       height = prefsize.height;
229     }
230
231     if (w < height)
232     {
233       dim = w;
234     }
235     else
236     {
237       dim = height;
238     }
239
240     return dim * scalefactor / (2 * maxwidth);
241   }
242
243   /**
244    * Computes and saves the position of the centre of the view
245    */
246   public void findCentre()
247   {
248     findWidth();
249
250     float x = (max[0] + min[0]) / 2;
251     float y = (max[1] + min[1]) / 2;
252     float z = (max[2] + min[2]) / 2;
253
254     centre = new Point(x, y, z);
255   }
256
257   @Override
258   public Dimension getPreferredSize()
259   {
260     if (prefsize != null)
261     {
262       return prefsize;
263     }
264     else
265     {
266       return new Dimension(400, 400);
267     }
268   }
269
270   @Override
271   public Dimension getMinimumSize()
272   {
273     return getPreferredSize();
274   }
275
276   @Override
277   public void update(Graphics g)
278   {
279     paint(g);
280   }
281
282   @Override
283   public void paint(Graphics g)
284   {
285     if (points == null)
286     {
287       g.setFont(new Font("Verdana", Font.PLAIN, 18));
288       g.drawString(
289               MessageManager.getString("label.calculating_pca") + "....",
290               20, getSize().height / 2);
291     }
292     else
293     {
294
295       // Only create the image at the beginning -
296       if ((img == null) || (prefsize.width != getSize().width)
297               || (prefsize.height != getSize().height))
298       {
299         prefsize.width = getSize().width;
300         prefsize.height = getSize().height;
301
302         scale = findScale();
303
304         // System.out.println("New scale = " + scale);
305         img = createImage(getSize().width, getSize().height);
306         ig = img.getGraphics();
307
308       }
309
310       drawBackground(ig, Color.black);
311       drawScene(ig);
312       if (drawAxes)
313       {
314         drawAxes(ig);
315       }
316
317       if (tooltip != null)
318       {
319         ig.setColor(Color.red);
320         ig.drawString(tooltip, toolx, tooly);
321       }
322
323       g.drawImage(img, 0, 0, this);
324     }
325   }
326
327   public void drawAxes(Graphics g)
328   {
329
330     g.setColor(Color.yellow);
331     for (int i = 0; i < 3; i++)
332     {
333       g.drawLine(getSize().width / 2, getSize().height / 2,
334               (int) (axisEndPoints[i].x * scale * max[0] + getSize().width / 2),
335               (int) (axisEndPoints[i].y * scale * max[1] + getSize().height / 2));
336     }
337   }
338
339   public void drawBackground(Graphics g, Color col)
340   {
341     g.setColor(col);
342     g.fillRect(0, 0, prefsize.width, prefsize.height);
343   }
344
345   public void drawScene(Graphics g)
346   {
347     for (int i = 0; i < npoint; i++)
348     {
349       SequencePoint sp = points.get(i);
350       SequenceI sequence = sp.getSequence();
351       Color sequenceColour = av.getSequenceColour(sequence);
352       g.setColor(
353               sequenceColour == Color.black ? Color.white : sequenceColour);
354       if (av.getSelectionGroup() != null)
355       {
356         if (av.getSelectionGroup().getSequences(null)
357                 .contains(sequence))
358         {
359           g.setColor(Color.gray);
360         }
361       }
362
363       if (sp.coord.z < centre.z)
364       {
365         g.setColor(g.getColor().darker());
366       }
367
368       int halfwidth = getSize().width / 2;
369       int halfheight = getSize().height / 2;
370       int x = (int) ((sp.coord.x - centre.x) * scale) + halfwidth;
371       int y = (int) ((sp.coord.y - centre.y) * scale) + halfheight;
372       g.fillRect(x - 3, y - 3, 6, 6);
373
374       if (showLabels)
375       {
376         g.setColor(Color.red);
377         g.drawString(sequence.getName(), x - 3, y - 4);
378       }
379     }
380   }
381
382   @Override
383   public void keyTyped(KeyEvent evt)
384   {
385   }
386
387   @Override
388   public void keyReleased(KeyEvent evt)
389   {
390   }
391
392   @Override
393   public void keyPressed(KeyEvent evt)
394   {
395     if (evt.getKeyCode() == KeyEvent.VK_UP)
396     {
397       zoom(1.1f);
398     }
399     else if (evt.getKeyCode() == KeyEvent.VK_DOWN)
400     {
401       zoom(0.9f);
402     }
403     else if (evt.getKeyChar() == 's')
404     {
405       System.err.println("DEBUG: Rectangle selection"); // log.debug
406       if (rectx2 != -1 && recty2 != -1)
407       {
408         rectSelect(rectx1, recty1, rectx2, recty2);
409
410       }
411     }
412     repaint();
413   }
414
415   @Override
416   public void mouseClicked(MouseEvent evt)
417   {
418   }
419
420   @Override
421   public void mouseEntered(MouseEvent evt)
422   {
423   }
424
425   @Override
426   public void mouseExited(MouseEvent evt)
427   {
428   }
429
430   @Override
431   public void mouseReleased(MouseEvent evt)
432   {
433   }
434
435   @Override
436   public void mousePressed(MouseEvent evt)
437   {
438     int x = evt.getX();
439     int y = evt.getY();
440
441     mouseX = x;
442     mouseY = y;
443
444     startx = x;
445     starty = y;
446
447     rectx1 = x;
448     recty1 = y;
449
450     rectx2 = -1;
451     recty2 = -1;
452
453     SequenceI found = findSequenceAtPoint(x, y);
454
455     if (found != null)
456     {
457       // TODO: applet PCA is not associatable with multi-panels - only parent
458       // view
459       if (av.getSelectionGroup() != null)
460       {
461         av.getSelectionGroup().addOrRemove(found, true);
462         av.getSelectionGroup().setEndRes(av.getAlignment().getWidth() - 1);
463       }
464       else
465       {
466         av.setSelectionGroup(new SequenceGroup());
467         av.getSelectionGroup().addOrRemove(found, true);
468         av.getSelectionGroup().setEndRes(av.getAlignment().getWidth() - 1);
469
470       }
471       PaintRefresher.Refresh(this, av.getSequenceSetId());
472       av.sendSelection();
473     }
474     repaint();
475   }
476
477   @Override
478   public void mouseMoved(MouseEvent evt)
479   {
480     SequenceI found = findSequenceAtPoint(evt.getX(), evt.getY());
481     if (found == null)
482     {
483       tooltip = null;
484     }
485     else
486     {
487       tooltip = found.getName();
488       toolx = evt.getX();
489       tooly = evt.getY();
490     }
491     repaint();
492   }
493
494   @Override
495   public void mouseDragged(MouseEvent evt)
496   {
497     int xPos = evt.getX();
498     int yPos = evt.getY();
499
500     if (xPos == mouseX && yPos == mouseY)
501     {
502       return;
503     }
504
505     int xDelta = xPos - mouseX;
506     int yDelta = yPos - mouseY;
507
508     rotate(xDelta, yDelta);
509     repaint();
510   }
511
512   public void rectSelect(int x1, int y1, int x2, int y2)
513   {
514     // boolean changedSel = false;
515     for (int i = 0; i < npoint; i++)
516     {
517       SequencePoint sp = points.get(i);
518       int tmp1 = (int) ((sp.coord.x - centre.x) * scale
519               + getSize().width / 2.0);
520       int tmp2 = (int) ((sp.coord.y - centre.y) * scale
521               + getSize().height / 2.0);
522
523       SequenceI sequence = sp.getSequence();
524       if (tmp1 > x1 && tmp1 < x2 && tmp2 > y1 && tmp2 < y2)
525       {
526         if (av != null)
527         {
528           if (!av.getSelectionGroup().getSequences(null)
529                   .contains(sequence))
530           {
531             av.getSelectionGroup().addSequence(sequence, true);
532           }
533         }
534       }
535     }
536   }
537
538   /**
539    * Answers the first sequence found whose point on the display is within 2
540    * pixels of the given coordinates, or null if none is found
541    * 
542    * @param x
543    * @param y
544    * 
545    * @return
546    */
547   public SequenceI findSequenceAtPoint(int x, int y)
548   {
549     int halfwidth = getSize().width / 2;
550     int halfheight = getSize().height / 2;
551
552     int found = -1;
553
554     for (int i = 0; i < npoint; i++)
555     {
556
557       SequencePoint sp = points.get(i);
558       int px = (int) ((sp.coord.x - centre.x) * scale)
559               + halfwidth;
560       int py = (int) ((sp.coord.y - centre.y) * scale)
561               + halfheight;
562
563       if (Math.abs(px - x) < 3 && Math.abs(py - y) < 3)
564       {
565         found = i;
566         break;
567       }
568     }
569
570     if (found != -1)
571     {
572       return points.get(found).getSequence();
573     }
574     else
575     {
576       return null;
577     }
578   }
579
580   /**
581    * Resets the view to initial state (no rotation)
582    */
583   public void resetView()
584   {
585     img = null;
586     resetAxes();
587   }
588
589   @Override
590   public void zoom(float factor)
591   {
592     if (factor > 0f)
593     {
594       scalefactor *= factor;
595     }
596     scale = findScale();
597   }
598
599   @Override
600   public void rotate(float x, float y)
601   {
602     if (x == 0f && y == 0f)
603     {
604       return;
605     }
606   
607     /*
608      * get the identity transformation...
609      */
610     RotatableMatrix rotmat = new RotatableMatrix();
611   
612     /*
613      * rotate around the X axis for change in Y
614      * (mouse movement up/down); note we are equating a
615      * number of pixels with degrees of rotation here!
616      */
617     if (y != 0)
618     {
619       rotmat.rotate(y, Axis.X);
620     }
621   
622     /*
623      * rotate around the Y axis for change in X
624      * (mouse movement left/right)
625      */
626     if (x != 0)
627     {
628       rotmat.rotate(x, Axis.Y);
629     }
630   
631     /*
632      * apply the composite transformation to sequence points
633      */
634     for (int i = 0; i < npoint; i++)
635     {
636       SequencePoint sp = points.get(i);
637       sp.translate(-centre.x, -centre.y, -centre.z);
638
639       // Now apply the rotation matrix
640       sp.coord = rotmat.vectorMultiply(sp.coord);
641
642       // Now translate back again
643       sp.translate(centre.x, centre.y, centre.z);
644     }
645   
646     /*
647      * rotate the x/y/z axis positions
648      */
649     for (int i = 0; i < DIMS; i++)
650     {
651       axisEndPoints[i] = rotmat.vectorMultiply(axisEndPoints[i]);
652     }
653   }
654
655 }