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