JAL-192 JAL-2099 factored out calculation from rendering code #2
[jalview.git] / src / jalview / gui / ScalePanel.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.datamodel.ColumnSelection;
24 import jalview.datamodel.SequenceGroup;
25 import jalview.datamodel.SequenceI;
26 import jalview.util.MessageManager;
27
28 import java.awt.Color;
29 import java.awt.FontMetrics;
30 import java.awt.Graphics;
31 import java.awt.Graphics2D;
32 import java.awt.RenderingHints;
33 import java.awt.event.ActionEvent;
34 import java.awt.event.ActionListener;
35 import java.awt.event.MouseEvent;
36 import java.awt.event.MouseListener;
37 import java.awt.event.MouseMotionListener;
38 import java.util.ArrayList;
39 import java.util.List;
40
41 import javax.swing.JMenuItem;
42 import javax.swing.JPanel;
43 import javax.swing.JPopupMenu;
44 import javax.swing.ToolTipManager;
45
46 /**
47  * DOCUMENT ME!
48  * 
49  * @author $author$
50  * @version $Revision$
51  */
52 public class ScalePanel extends JPanel implements MouseMotionListener,
53         MouseListener
54 {
55   protected int offy = 4;
56
57   /** DOCUMENT ME!! */
58   public int width;
59
60   protected AlignViewport av;
61
62   AlignmentPanel ap;
63
64   boolean stretchingGroup = false;
65
66   int min; // used by mouseDragged to see if user
67
68   int max; // used by mouseDragged to see if user
69
70   boolean mouseDragging = false;
71
72   // wants to delete columns
73   public ScalePanel(AlignViewport av, AlignmentPanel ap)
74   {
75     this.av = av;
76     this.ap = ap;
77
78     addMouseListener(this);
79     addMouseMotionListener(this);
80   }
81
82   /**
83    * DOCUMENT ME!
84    * 
85    * @param evt
86    *          DOCUMENT ME!
87    */
88   @Override
89   public void mousePressed(MouseEvent evt)
90   {
91     int x = (evt.getX() / av.getCharWidth()) + av.getStartRes();
92     final int res;
93
94     if (av.hasHiddenColumns())
95     {
96       x = av.getColumnSelection().adjustForHiddenColumns(x);
97     }
98
99     if (x >= av.getAlignment().getWidth())
100     {
101       res = av.getAlignment().getWidth() - 1;
102     }
103     else
104     {
105       res = x;
106     }
107
108     min = res;
109     max = res;
110
111     if (evt.isPopupTrigger())
112     {
113       rightMouseButtonPressed(evt, res);
114     }
115     else
116     {
117       leftMouseButtonPressed(evt, res);
118     }
119   }
120
121   /**
122    * Handles right mouse button press. If pressed in a selected column, opens
123    * context menu for 'Hide Columns'. If pressed on a hidden columns marker,
124    * opens context menu for 'Reveal / Reveal All'. Else does nothing.
125    * 
126    * @param evt
127    * @param res
128    */
129   protected void rightMouseButtonPressed(MouseEvent evt, final int res)
130   {
131     JPopupMenu pop = new JPopupMenu();
132     if (reveal != null)
133     {
134       JMenuItem item = new JMenuItem(
135               MessageManager.getString("label.reveal"));
136       item.addActionListener(new ActionListener()
137       {
138         @Override
139         public void actionPerformed(ActionEvent e)
140         {
141           av.showColumn(reveal[0]);
142           reveal = null;
143           ap.paintAlignment(true);
144           if (ap.overviewPanel != null)
145           {
146             ap.overviewPanel.updateOverviewImage();
147           }
148           av.sendSelection();
149         }
150       });
151       pop.add(item);
152
153       if (av.getColumnSelection().hasHiddenColumns())
154       {
155         item = new JMenuItem(MessageManager.getString("action.reveal_all"));
156         item.addActionListener(new ActionListener()
157         {
158           @Override
159           public void actionPerformed(ActionEvent e)
160           {
161             av.showAllHiddenColumns();
162             reveal = null;
163             ap.paintAlignment(true);
164             if (ap.overviewPanel != null)
165             {
166               ap.overviewPanel.updateOverviewImage();
167             }
168             av.sendSelection();
169           }
170         });
171         pop.add(item);
172       }
173       pop.show(this, evt.getX(), evt.getY());
174     }
175     else if (av.getColumnSelection().contains(res))
176     {
177       JMenuItem item = new JMenuItem(
178               MessageManager.getString("label.hide_columns"));
179       item.addActionListener(new ActionListener()
180       {
181         @Override
182         public void actionPerformed(ActionEvent e)
183         {
184           av.hideColumns(res, res);
185           if (av.getSelectionGroup() != null
186                   && av.getSelectionGroup().getSize() == av.getAlignment()
187                           .getHeight())
188           {
189             av.setSelectionGroup(null);
190           }
191
192           ap.paintAlignment(true);
193           if (ap.overviewPanel != null)
194           {
195             ap.overviewPanel.updateOverviewImage();
196           }
197           av.sendSelection();
198         }
199       });
200       pop.add(item);
201       pop.show(this, evt.getX(), evt.getY());
202     }
203   }
204
205   /**
206    * Handles left mouse button press
207    * 
208    * @param evt
209    * @param res
210    */
211   protected void leftMouseButtonPressed(MouseEvent evt, final int res)
212   {
213     if (!evt.isControlDown() && !evt.isShiftDown())
214     {
215       av.getColumnSelection().clear();
216     }
217
218     av.getColumnSelection().addElement(res);
219     SequenceGroup sg = new SequenceGroup();
220     // try to be as quick as possible
221     SequenceI[] iVec = av.getAlignment().getSequencesArray();
222     for (int i = 0; i < iVec.length; i++)
223     {
224       sg.addSequence(iVec[i], false);
225       iVec[i] = null;
226     }
227     iVec = null;
228     sg.setStartRes(res);
229     sg.setEndRes(res);
230
231     if (evt.isShiftDown())
232     {
233       int min = Math.min(av.getColumnSelection().getMin(), res);
234       int max = Math.max(av.getColumnSelection().getMax(), res);
235       for (int i = min; i < max; i++)
236       {
237         av.getColumnSelection().addElement(i);
238       }
239       sg.setStartRes(min);
240       sg.setEndRes(max);
241     }
242     av.setSelectionGroup(sg);
243     ap.paintAlignment(false);
244     av.sendSelection();
245   }
246
247   /**
248    * DOCUMENT ME!
249    * 
250    * @param evt
251    *          DOCUMENT ME!
252    */
253   @Override
254   public void mouseReleased(MouseEvent evt)
255   {
256     mouseDragging = false;
257
258     int res = (evt.getX() / av.getCharWidth()) + av.getStartRes();
259
260     if (av.hasHiddenColumns())
261     {
262       res = av.getColumnSelection().adjustForHiddenColumns(res);
263     }
264
265     if (res >= av.getAlignment().getWidth())
266     {
267       res = av.getAlignment().getWidth() - 1;
268     }
269
270     if (!stretchingGroup)
271     {
272       ap.paintAlignment(false);
273
274       return;
275     }
276
277     SequenceGroup sg = av.getSelectionGroup();
278
279     if (sg != null)
280     {
281       if (res > sg.getStartRes())
282       {
283         sg.setEndRes(res);
284       }
285       else if (res < sg.getStartRes())
286       {
287         sg.setStartRes(res);
288       }
289     }
290     stretchingGroup = false;
291     ap.paintAlignment(false);
292     av.sendSelection();
293   }
294
295   /**
296    * DOCUMENT ME!
297    * 
298    * @param evt
299    *          DOCUMENT ME!
300    */
301   @Override
302   public void mouseDragged(MouseEvent evt)
303   {
304     mouseDragging = true;
305
306     int res = (evt.getX() / av.getCharWidth()) + av.getStartRes();
307     if (res < 0)
308     {
309       res = 0;
310     }
311
312     if (av.hasHiddenColumns())
313     {
314       res = av.getColumnSelection().adjustForHiddenColumns(res);
315     }
316
317     if (res >= av.getAlignment().getWidth())
318     {
319       res = av.getAlignment().getWidth() - 1;
320     }
321
322     if (res < min)
323     {
324       min = res;
325     }
326
327     if (res > max)
328     {
329       max = res;
330     }
331
332     SequenceGroup sg = av.getSelectionGroup();
333
334     if (sg != null)
335     {
336       stretchingGroup = true;
337
338       if (!av.getColumnSelection().contains(res))
339       {
340         av.getColumnSelection().addElement(res);
341       }
342
343       if (res > sg.getStartRes())
344       {
345         sg.setEndRes(res);
346       }
347       if (res < sg.getStartRes())
348       {
349         sg.setStartRes(res);
350       }
351
352       int col;
353       for (int i = min; i <= max; i++)
354       {
355         col = i; // av.getColumnSelection().adjustForHiddenColumns(i);
356
357         if ((col < sg.getStartRes()) || (col > sg.getEndRes()))
358         {
359           av.getColumnSelection().removeElement(col);
360         }
361         else
362         {
363           av.getColumnSelection().addElement(col);
364         }
365       }
366
367       ap.paintAlignment(false);
368     }
369   }
370
371   @Override
372   public void mouseEntered(MouseEvent evt)
373   {
374     if (mouseDragging)
375     {
376       ap.getSeqPanel().scrollCanvas(null);
377     }
378   }
379
380   @Override
381   public void mouseExited(MouseEvent evt)
382   {
383     if (mouseDragging)
384     {
385       ap.getSeqPanel().scrollCanvas(evt);
386     }
387   }
388
389   @Override
390   public void mouseClicked(MouseEvent evt)
391   {
392   }
393
394   @Override
395   public void mouseMoved(MouseEvent evt)
396   {
397     if (!av.hasHiddenColumns())
398     {
399       return;
400     }
401
402     int res = (evt.getX() / av.getCharWidth()) + av.getStartRes();
403
404     res = av.getColumnSelection().adjustForHiddenColumns(res);
405
406     reveal = null;
407     if (av.getColumnSelection().getHiddenColumns() != null)
408     {
409       for (int[] region : av.getColumnSelection().getHiddenColumns())
410       {
411         if (res + 1 == region[0] || res - 1 == region[1])
412         {
413           reveal = region;
414           ToolTipManager.sharedInstance().registerComponent(this);
415           this.setToolTipText(MessageManager
416                   .getString("label.reveal_hidden_columns"));
417           break;
418         }
419         else
420         {
421           this.setToolTipText(null);
422         }
423       }
424     }
425     repaint();
426   }
427
428   int[] reveal;
429
430   /**
431    * DOCUMENT ME!
432    * 
433    * @param g
434    *          DOCUMENT ME!
435    */
436   @Override
437   public void paintComponent(Graphics g)
438   {
439     drawScale(g, av.getStartRes(), av.getEndRes(), getWidth(), getHeight());
440   }
441
442   // scalewidth will normally be screenwidth,
443   public void drawScale(Graphics g, int startx, int endx, int width,
444           int height)
445   {
446     Graphics2D gg = (Graphics2D) g;
447     gg.setFont(av.getFont());
448
449     if (av.antiAlias)
450     {
451       gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
452               RenderingHints.VALUE_ANTIALIAS_ON);
453     }
454
455     // Fill in the background
456     gg.setColor(Color.white);
457     gg.fillRect(0, 0, width, height);
458     gg.setColor(Color.black);
459
460     // Fill the selected columns
461     ColumnSelection cs = av.getColumnSelection();
462     int avCharWidth = av.getCharWidth(), avCharHeight = av.getCharHeight();
463
464     int s;
465     if (cs != null)
466     {
467       gg.setColor(new Color(220, 0, 0));
468
469       for (int sel : cs.getSelected())
470       {
471         // TODO: JAL-2001 - provide a fast method to list visible selected in a
472         // given range
473
474         if (av.hasHiddenColumns())
475         {
476           if (cs.isVisible(sel))
477           {
478             sel = cs.findColumnPosition(sel);
479           }
480           else
481           {
482             continue;
483           }
484         }
485
486         if ((sel >= startx) && (sel <= endx))
487         {
488           gg.fillRect((sel - startx) * avCharWidth, 0, avCharWidth,
489                   getHeight());
490         }
491       }
492     }
493
494     int widthx = 1 + endx - startx;
495
496     FontMetrics fm = gg.getFontMetrics(av.getFont());
497     int y = avCharHeight, yOf = fm.getDescent();
498     y -= yOf;
499     if (av.hasHiddenColumns())
500     {
501       // draw any hidden column markers
502       gg.setColor(Color.blue);
503       int res;
504       if (av.getShowHiddenMarkers()
505               && av.getColumnSelection().getHiddenColumns() != null)
506       {
507         for (int i = 0; i < av.getColumnSelection().getHiddenColumns()
508                 .size(); i++)
509         {
510           res = av.getColumnSelection().findHiddenRegionPosition(i)
511                   - startx;
512
513           if (res < 0 || res > widthx)
514           {
515             continue;
516           }
517
518           gg.fillPolygon(new int[] {
519               -1 + res * avCharWidth - avCharHeight / 4,
520               -1 + res * avCharWidth + avCharHeight / 4,
521               -1 + res * avCharWidth }, new int[] { y, y, y + 2 * yOf }, 3);
522
523         }
524       }
525     }
526     // Draw the scale numbers
527     gg.setColor(Color.black);
528
529     List<Object[]> marks = calculateMarks(startx, endx);
530     int maxX = 0;
531     for (Object[] mark : marks)
532     {
533       boolean major = Boolean.valueOf((Boolean) mark[0]);
534       int mpos = ((Integer) mark[1]).intValue(); // (i - startx - 1)
535       String mstring = (String) mark[2];
536       if (mstring != null)
537       {
538         if (mpos * avCharWidth > maxX)
539         {
540           gg.drawString(mstring, mpos * avCharWidth, y);
541           maxX = (mpos + 2) * avCharWidth + fm.stringWidth(mstring);
542         }
543       }
544       if (major)
545       {
546         gg.drawLine((mpos * avCharWidth) + (avCharWidth / 2), y + 2,
547                 (mpos * avCharWidth) + (avCharWidth / 2), y + (yOf * 2));
548       }
549       else
550       {
551         gg.drawLine((mpos * avCharWidth) + (avCharWidth / 2), y + yOf,
552                 (mpos * avCharWidth) + (avCharWidth / 2), y + (yOf * 2));
553       }
554     }
555     if (av.hasHiddenColumns())
556     {
557       if (reveal != null && reveal[0] > startx && reveal[0] < endx)
558       {
559         gg.drawString(MessageManager.getString("label.reveal_columns"),
560                 reveal[0] * avCharWidth, 0);
561       }
562     }
563
564   }
565
566   /**
567    * calculate positions markers on the alignment ruler
568    * 
569    * @return List { Object { .. } } Boolean: true/false for major/minor mark,
570    *         Integer: marker position in alignment column coords, String: null
571    *         or a String to be rendered at the position.
572    */
573   public List<Object[]> calculateMarks(int startx, int endx)
574   {
575     new ArrayList<Object[]>();
576
577     int scalestartx = (startx / 10) * 10;
578
579     SequenceI refSeq = av.getAlignment().getSeqrep();
580     int refSp = 0, refEp = -1, refStart = 0, refEnd = -1, refStartI = 0, refEndI = -1;
581     if (refSeq != null)
582     {
583       // find bounds and set origin appopriately
584       // locate first visible position for this sequence
585       int[] refbounds = av.getColumnSelection()
586               .locateVisibleBoundsOfSequence(refSeq);
587
588       refSp = refbounds[0];
589       refEp = refbounds[1];
590       refStart = refbounds[2];
591       refEnd = refbounds[3];
592       refStartI = refbounds[4];
593       refEndI = refbounds[5];
594       scalestartx = refSp + ((scalestartx - refSp) / 10) * 10;
595     }
596
597
598     if (refSeq == null && scalestartx % 10 == 0)
599     {
600       scalestartx += 5;
601     }
602     List<Object[]> marks = new ArrayList<Object[]>();
603     String string;
604     int maxX = 0, refN, iadj;
605     // todo: add a 'reference origin column' to set column number relative to
606     for (int i = scalestartx; i < endx; i += 5)
607     {
608       Object[] amark = new Object[3];
609       if (((i - refSp) % 10) == 0)
610       {
611         if (refSeq == null)
612         {
613           iadj = av.getColumnSelection().adjustForHiddenColumns(i - 1) + 1;
614           string = String.valueOf(iadj);
615         }
616         else
617         {
618           iadj = av.getColumnSelection().adjustForHiddenColumns(i - 1);
619           refN = refSeq.findPosition(iadj);
620           // TODO show bounds if position is a gap
621           // - ie L--R -> "1L|2R" for
622           // marker
623           if (iadj < refStartI)
624           {
625             string = String.valueOf(iadj - refStartI);
626           }
627           else if (iadj > refEndI)
628           {
629             string = "+" + String.valueOf(iadj - refEndI);
630           }
631           else
632           {
633             string = String.valueOf(refN) + refSeq.getCharAt(iadj);
634           }
635         }
636         amark[0] = Boolean.TRUE;
637         amark[1] = Integer.valueOf(i - startx - 1);
638         amark[2] = string;
639
640       }
641       else
642       {
643         amark[0] = Boolean.FALSE;
644         amark[1] = Integer.valueOf(i - startx - 1);
645         amark[2] = null;
646       }
647       marks.add(amark);
648     }
649     return marks;
650   }
651 }