Merge branch 'develop' into feature/JAL-2759
[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.HiddenColumns;
25 import jalview.datamodel.SequenceGroup;
26 import jalview.datamodel.SequenceI;
27 import jalview.renderer.ScaleRenderer;
28 import jalview.renderer.ScaleRenderer.ScaleMark;
29 import jalview.util.MessageManager;
30 import jalview.util.Platform;
31 import jalview.viewmodel.ViewportListenerI;
32 import jalview.viewmodel.ViewportRanges;
33
34 import java.awt.Color;
35 import java.awt.FontMetrics;
36 import java.awt.Graphics;
37 import java.awt.Graphics2D;
38 import java.awt.RenderingHints;
39 import java.awt.event.ActionEvent;
40 import java.awt.event.ActionListener;
41 import java.awt.event.MouseEvent;
42 import java.awt.event.MouseListener;
43 import java.awt.event.MouseMotionListener;
44 import java.beans.PropertyChangeEvent;
45 import java.util.Iterator;
46 import java.util.List;
47
48 import javax.swing.JMenuItem;
49 import javax.swing.JPanel;
50 import javax.swing.JPopupMenu;
51 import javax.swing.SwingUtilities;
52 import javax.swing.ToolTipManager;
53
54 /**
55  * The panel containing the sequence ruler (when not in wrapped mode), and
56  * supports a range of mouse operations to select, hide or reveal columns.
57  */
58 public class ScalePanel extends JPanel
59         implements MouseMotionListener, MouseListener, ViewportListenerI
60 {
61   protected int offy = 4;
62
63   public int width;
64
65   protected AlignViewport av;
66
67   AlignmentPanel ap;
68
69   boolean stretchingGroup = false;
70
71   /*
72    * min, max hold the extent of a mouse drag action
73    */
74   int min;
75
76   int max;
77
78   boolean mouseDragging = false;
79
80   /*
81    * holds a hidden column range when the mouse is over an adjacent column
82    */
83   int[] reveal;
84
85   /**
86    * Constructor
87    * 
88    * @param av
89    * @param ap
90    */
91   public ScalePanel(AlignViewport av, AlignmentPanel ap)
92   {
93     this.av = av;
94     this.ap = ap;
95
96     addMouseListener(this);
97     addMouseMotionListener(this);
98
99     av.getRanges().addPropertyChangeListener(this);
100   }
101
102   /**
103    * DOCUMENT ME!
104    * 
105    * @param evt
106    *          DOCUMENT ME!
107    */
108   @Override
109   public void mousePressed(MouseEvent evt)
110   {
111     int x = (evt.getX() / av.getCharWidth()) + av.getRanges().getStartRes();
112     final int res;
113
114     if (av.hasHiddenColumns())
115     {
116       x = av.getAlignment().getHiddenColumns().adjustForHiddenColumns(x);
117     }
118
119     if (x >= av.getAlignment().getWidth())
120     {
121       res = av.getAlignment().getWidth() - 1;
122     }
123     else
124     {
125       res = x;
126     }
127
128     min = res;
129     max = res;
130
131     if (evt.isPopupTrigger()) // Mac: mousePressed
132     {
133       rightMouseButtonPressed(evt, res);
134     }
135     else if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
136     {
137       /*
138        * defer right-mouse click handling to mouse up on Windows
139        * (where isPopupTrigger() will answer true)
140        * but accept Cmd-click on Mac which passes isRightMouseButton
141        */
142       return;
143     }
144     else
145     {
146       leftMouseButtonPressed(evt, res);
147     }
148   }
149
150   /**
151    * Handles right mouse button press. If pressed in a selected column, opens
152    * context menu for 'Hide Columns'. If pressed on a hidden columns marker,
153    * opens context menu for 'Reveal / Reveal All'. Else does nothing.
154    * 
155    * @param evt
156    * @param res
157    */
158   protected void rightMouseButtonPressed(MouseEvent evt, final int res)
159   {
160     JPopupMenu pop = new JPopupMenu();
161     if (reveal != null)
162     {
163       JMenuItem item = new JMenuItem(
164               MessageManager.getString("label.reveal"));
165       item.addActionListener(new ActionListener()
166       {
167         @Override
168         public void actionPerformed(ActionEvent e)
169         {
170           av.showColumn(reveal[0]);
171           reveal = null;
172           ap.paintAlignment(true, true);
173           av.sendSelection();
174         }
175       });
176       pop.add(item);
177
178       if (av.getAlignment().getHiddenColumns().hasManyHiddenColumns())
179       {
180         item = new JMenuItem(MessageManager.getString("action.reveal_all"));
181         item.addActionListener(new ActionListener()
182         {
183           @Override
184           public void actionPerformed(ActionEvent e)
185           {
186             av.showAllHiddenColumns();
187             reveal = null;
188             ap.paintAlignment(true, true);
189             av.sendSelection();
190           }
191         });
192         pop.add(item);
193       }
194       pop.show(this, evt.getX(), evt.getY());
195     }
196     else if (av.getColumnSelection().contains(res))
197     {
198       JMenuItem item = new JMenuItem(
199               MessageManager.getString("label.hide_columns"));
200       item.addActionListener(new ActionListener()
201       {
202         @Override
203         public void actionPerformed(ActionEvent e)
204         {
205           av.hideColumns(res, res);
206           if (av.getSelectionGroup() != null && av.getSelectionGroup()
207                   .getSize() == av.getAlignment().getHeight())
208           {
209             av.setSelectionGroup(null);
210           }
211
212           ap.paintAlignment(true, true);
213           av.sendSelection();
214         }
215       });
216       pop.add(item);
217       pop.show(this, evt.getX(), evt.getY());
218     }
219   }
220
221   /**
222    * Handles left mouse button press
223    * 
224    * @param evt
225    * @param res
226    */
227   protected void leftMouseButtonPressed(MouseEvent evt, final int res)
228   {
229     /*
230      * Ctrl-click/Cmd-click adds to the selection
231      * Shift-click extends the selection
232      */
233     // TODO Problem: right-click on Windows not reported until mouseReleased?!?
234     if (!Platform.isControlDown(evt) && !evt.isShiftDown())
235     {
236       av.getColumnSelection().clear();
237     }
238
239     av.getColumnSelection().addElement(res);
240     SequenceGroup sg = new SequenceGroup();
241     // try to be as quick as possible
242     SequenceI[] iVec = av.getAlignment().getSequencesArray();
243     for (int i = 0; i < iVec.length; i++)
244     {
245       sg.addSequence(iVec[i], false);
246       iVec[i] = null;
247     }
248     iVec = null;
249     sg.setStartRes(res);
250     sg.setEndRes(res);
251
252     if (evt.isShiftDown())
253     {
254       int min = Math.min(av.getColumnSelection().getMin(), res);
255       int max = Math.max(av.getColumnSelection().getMax(), res);
256       for (int i = min; i < max; i++)
257       {
258         av.getColumnSelection().addElement(i);
259       }
260       sg.setStartRes(min);
261       sg.setEndRes(max);
262     }
263     av.setSelectionGroup(sg);
264     ap.paintAlignment(false, false);
265     av.sendSelection();
266   }
267
268   /**
269    * DOCUMENT ME!
270    * 
271    * @param evt
272    *          DOCUMENT ME!
273    */
274   @Override
275   public void mouseReleased(MouseEvent evt)
276   {
277     mouseDragging = false;
278
279     int res = (evt.getX() / av.getCharWidth())
280             + av.getRanges().getStartRes();
281
282     if (av.hasHiddenColumns())
283     {
284       res = av.getAlignment().getHiddenColumns()
285               .adjustForHiddenColumns(res);
286     }
287
288     if (res >= av.getAlignment().getWidth())
289     {
290       res = av.getAlignment().getWidth() - 1;
291     }
292
293     if (!stretchingGroup)
294     {
295       if (evt.isPopupTrigger()) // Windows: mouseReleased
296       {
297         rightMouseButtonPressed(evt, res);
298       }
299       else
300       {
301         ap.paintAlignment(false, false);
302       }
303       return;
304     }
305
306     SequenceGroup sg = av.getSelectionGroup();
307
308     if (sg != null)
309     {
310       if (res > sg.getStartRes())
311       {
312         sg.setEndRes(res);
313       }
314       else if (res < sg.getStartRes())
315       {
316         sg.setStartRes(res);
317       }
318     }
319     stretchingGroup = false;
320     ap.paintAlignment(false, false);
321     av.sendSelection();
322   }
323
324   /**
325    * Action on dragging the mouse in the scale panel is to expand or shrink the
326    * selection group range (including any hidden columns that it spans)
327    * 
328    * @param evt
329    */
330   @Override
331   public void mouseDragged(MouseEvent evt)
332   {
333     mouseDragging = true;
334     ColumnSelection cs = av.getColumnSelection();
335     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
336
337     int res = (evt.getX() / av.getCharWidth())
338             + av.getRanges().getStartRes();
339     res = Math.max(0, res);
340     res = hidden.adjustForHiddenColumns(res);
341     res = Math.min(res, av.getAlignment().getWidth() - 1);
342     min = Math.min(res, min);
343     max = Math.max(res, max);
344
345     SequenceGroup sg = av.getSelectionGroup();
346     if (sg != null)
347     {
348       stretchingGroup = true;
349       cs.stretchGroup(res, sg, min, max);
350       ap.paintAlignment(false, false);
351     }
352   }
353
354   @Override
355   public void mouseEntered(MouseEvent evt)
356   {
357     if (mouseDragging)
358     {
359       ap.getSeqPanel().scrollCanvas(null);
360     }
361   }
362
363   @Override
364   public void mouseExited(MouseEvent evt)
365   {
366     if (mouseDragging)
367     {
368       ap.getSeqPanel().scrollCanvas(evt);
369     }
370   }
371
372   @Override
373   public void mouseClicked(MouseEvent evt)
374   {
375   }
376
377   /**
378    * Creates a tooltip when the mouse is over a hidden columns marker
379    */
380   @Override
381   public void mouseMoved(MouseEvent evt)
382   {
383     this.setToolTipText(null);
384     reveal = null;
385     if (!av.hasHiddenColumns())
386     {
387       return;
388     }
389
390     int res = (evt.getX() / av.getCharWidth())
391             + av.getRanges().getStartRes();
392
393     reveal = av.getAlignment().getHiddenColumns()
394             .getRegionWithEdgeAtRes(res);
395
396     res = av.getAlignment().getHiddenColumns().adjustForHiddenColumns(res);
397
398     ToolTipManager.sharedInstance().registerComponent(this);
399     this.setToolTipText(
400             MessageManager.getString("label.reveal_hidden_columns"));
401     repaint();
402   }
403
404   /**
405    * DOCUMENT ME!
406    * 
407    * @param g
408    *          DOCUMENT ME!
409    */
410   @Override
411   public void paintComponent(Graphics g)
412   {
413     /*
414      * shouldn't get called in wrapped mode as the scale above is
415      * drawn instead by SeqCanvas.drawNorthScale
416      */
417     if (!av.getWrapAlignment())
418     {
419       drawScale(g, av.getRanges().getStartRes(), av.getRanges().getEndRes(),
420               getWidth(), getHeight());
421     }
422   }
423
424   // scalewidth will normally be screenwidth,
425   public void drawScale(Graphics g, int startx, int endx, int width,
426           int height)
427   {
428     Graphics2D gg = (Graphics2D) g;
429     gg.setFont(av.getFont());
430
431     if (av.antiAlias)
432     {
433       gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
434               RenderingHints.VALUE_ANTIALIAS_ON);
435     }
436
437     // Fill in the background
438     gg.setColor(Color.white);
439     gg.fillRect(0, 0, width, height);
440     gg.setColor(Color.black);
441
442     // Fill the selected columns
443     ColumnSelection cs = av.getColumnSelection();
444     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
445     int avCharWidth = av.getCharWidth();
446     int avCharHeight = av.getCharHeight();
447
448     if (cs != null)
449     {
450       gg.setColor(new Color(220, 0, 0));
451
452       for (int sel : cs.getSelected())
453       {
454         // TODO: JAL-2001 - provide a fast method to list visible selected in a
455         // given range
456
457         if (av.hasHiddenColumns())
458         {
459           if (hidden.isVisible(sel))
460           {
461             sel = hidden.findColumnPosition(sel);
462           }
463           else
464           {
465             continue;
466           }
467         }
468
469         if ((sel >= startx) && (sel <= endx))
470         {
471           gg.fillRect((sel - startx) * avCharWidth, 0, avCharWidth,
472                   getHeight());
473         }
474       }
475     }
476
477     int widthx = 1 + endx - startx;
478
479     FontMetrics fm = gg.getFontMetrics(av.getFont());
480     int y = avCharHeight;
481     int yOf = fm.getDescent();
482     y -= yOf;
483     if (av.hasHiddenColumns())
484     {
485       // draw any hidden column markers
486       gg.setColor(Color.blue);
487       int res;
488
489       if (av.getShowHiddenMarkers())
490       {
491         Iterator<Integer> it = hidden.getBoundedStartIterator(startx,
492                 startx + widthx + 1);
493         while (it.hasNext())
494         {
495           res = it.next() - startx;
496
497           gg.fillPolygon(
498                   new int[]
499           { -1 + res * avCharWidth - avCharHeight / 4,
500               -1 + res * avCharWidth + avCharHeight / 4,
501               -1 + res * avCharWidth }, new int[]
502           { y, y, y + 2 * yOf }, 3);
503         }
504       }
505     }
506     // Draw the scale numbers
507     gg.setColor(Color.black);
508
509     int maxX = 0;
510     List<ScaleMark> marks = new ScaleRenderer().calculateMarks(av, startx,
511             endx);
512
513     for (ScaleMark mark : marks)
514     {
515       boolean major = mark.major;
516       int mpos = mark.column; // (i - startx - 1)
517       String mstring = mark.text;
518       if (mstring != null)
519       {
520         if (mpos * avCharWidth > maxX)
521         {
522           gg.drawString(mstring, mpos * avCharWidth, y);
523           maxX = (mpos + 2) * avCharWidth + fm.stringWidth(mstring);
524         }
525       }
526       if (major)
527       {
528         gg.drawLine((mpos * avCharWidth) + (avCharWidth / 2), y + 2,
529                 (mpos * avCharWidth) + (avCharWidth / 2), y + (yOf * 2));
530       }
531       else
532       {
533         gg.drawLine((mpos * avCharWidth) + (avCharWidth / 2), y + yOf,
534                 (mpos * avCharWidth) + (avCharWidth / 2), y + (yOf * 2));
535       }
536     }
537   }
538
539   @Override
540   public void propertyChange(PropertyChangeEvent evt)
541   {
542     // Respond to viewport change events (e.g. alignment panel was scrolled)
543     // Both scrolling and resizing change viewport ranges: scrolling changes
544     // both start and end points, but resize only changes end values.
545     // Here we only want to fastpaint on a scroll, with resize using a normal
546     // paint, so scroll events are identified as changes to the horizontal or
547     // vertical start value.
548     if (evt.getPropertyName().equals(ViewportRanges.STARTRES)
549             || evt.getPropertyName().equals(ViewportRanges.STARTRESANDSEQ)
550             || evt.getPropertyName().equals(ViewportRanges.MOVE_VIEWPORT))
551     {
552       // scroll event, repaint panel
553       repaint();
554     }
555   }
556
557 }