Merge branch 'patch/JAL-4260_fix_up_select_via_ruler_in_wrapped' into develop
[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().findAlignmentColumn(evt);
111
112     min = res;
113     max = res;
114
115     if (evt.isPopupTrigger()) // Mac: mousePressed
116     {
117       rightMouseButtonPressed(evt, res);
118       return;
119     }
120     if (Platform.isWinRightButton(evt))
121     {
122       /*
123        * defer right-mouse click handling to mouse up on Windows
124        * (where isPopupTrigger() will answer true)
125        * but accept Cmd-click on Mac which passes isRightMouseButton
126        */
127       return;
128     }
129     leftMouseButtonPressed(evt, res);
130   }
131
132   /**
133    * Handles right mouse button press. If pressed in a selected column, opens
134    * context menu for 'Hide Columns'. If pressed on a hidden columns marker,
135    * opens context menu for 'Reveal / Reveal All'. Else does nothing.
136    * 
137    * @param evt
138    * @param res
139    */
140   protected void rightMouseButtonPressed(MouseEvent evt, final int res)
141   {
142     JPopupMenu pop = buildPopupMenu(res);
143     if (pop.getSubElements().length > 0)
144     {
145       pop.show(this, evt.getX(), evt.getY());
146     }
147   }
148
149   /**
150    * Builds a popup menu with 'Hide' or 'Reveal' options, or both, or neither
151    * 
152    * @param res
153    *          column number (0..)
154    * @return
155    */
156   protected JPopupMenu buildPopupMenu(final int res)
157   {
158     JPopupMenu pop = new JPopupMenu();
159
160     /*
161      * logic here depends on 'reveal', set in mouseMoved;
162      * grab the hidden range in case mouseMoved nulls it later
163      */
164     final int[] hiddenRange = reveal;
165     if (hiddenRange != null)
166     {
167       JMenuItem item = new JMenuItem(
168               MessageManager.getString("label.reveal"));
169       item.addActionListener(new ActionListener()
170       {
171         @Override
172         public void actionPerformed(ActionEvent e)
173         {
174           av.showColumn(hiddenRange[0]);
175           reveal = null;
176           ap.updateLayout();
177           ap.paintAlignment(true, true);
178           av.sendSelection();
179         }
180       });
181       pop.add(item);
182
183       if (av.getAlignment().getHiddenColumns()
184               .hasMultiHiddenColumnRegions())
185       {
186         item = new JMenuItem(MessageManager.getString("action.reveal_all"));
187         item.addActionListener(new ActionListener()
188         {
189           @Override
190           public void actionPerformed(ActionEvent e)
191           {
192             av.showAllHiddenColumns();
193             reveal = null;
194             ap.updateLayout();
195             ap.paintAlignment(true, true);
196             av.sendSelection();
197           }
198         });
199         pop.add(item);
200       }
201     }
202
203     if (av.getColumnSelection().contains(res))
204     {
205       JMenuItem item = new JMenuItem(
206               MessageManager.getString("label.hide_columns"));
207       item.addActionListener(new ActionListener()
208       {
209         @Override
210         public void actionPerformed(ActionEvent e)
211         {
212           av.hideColumns(res, res);
213           if (av.getSelectionGroup() != null && av.getSelectionGroup()
214                   .getSize() == av.getAlignment().getHeight())
215           {
216             av.setSelectionGroup(null);
217           }
218
219           ap.updateLayout();
220           ap.paintAlignment(true, true);
221           av.sendSelection();
222         }
223       });
224       pop.add(item);
225     }
226     return pop;
227   }
228
229   /**
230    * Handles left mouse button press
231    * 
232    * @param evt
233    * @param res
234    */
235   protected void leftMouseButtonPressed(MouseEvent evt, final int res)
236   {
237     /*
238      * Ctrl-click/Cmd-click adds to the selection
239      * Shift-click extends the selection
240      */
241     // TODO Problem: right-click on Windows not reported until mouseReleased?!?
242     if (!Platform.isControlDown(evt) && !evt.isShiftDown())
243     {
244       av.getColumnSelection().clear();
245     }
246
247     av.getColumnSelection().addElement(res);
248     SequenceGroup sg = new SequenceGroup(av.getAlignment().getSequences());
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     PaintRefresher.Refresh(this,av.getSequenceSetId());
266     av.sendSelection();
267   }
268
269   /**
270    * Action on mouseUp is to set the limit of the current selection group (if
271    * there is one) and broadcast the selection
272    * 
273    * @param evt
274    */
275   @Override
276   public void mouseReleased(MouseEvent evt)
277   {
278     boolean wasDragging = mouseDragging;
279     mouseDragging = false;
280     ap.getSeqPanel().stopScrolling();
281
282     int res = ap.getSeqPanel().findAlignmentColumn(evt);
283     
284     if (!stretchingGroup)
285     {
286       if (evt.isPopupTrigger()) // Windows: mouseReleased
287       {
288         rightMouseButtonPressed(evt, res);
289       }
290       else
291       {
292         ap.paintAlignment(false, false);
293       }
294       return;
295     }
296
297     SequenceGroup sg = av.getSelectionGroup();
298
299     if (sg != null)
300     {
301       if (res > sg.getStartRes())
302       {
303         sg.setEndRes(res);
304       }
305       else if (res < sg.getStartRes())
306       {
307         sg.setStartRes(res);
308       }
309       if (wasDragging)
310       {
311         min = Math.min(res, min);
312         max = Math.max(res, max);
313         av.getColumnSelection().stretchGroup(res, sg, min, max);
314       }
315     }
316     stretchingGroup = false;
317     ap.paintAlignment(false, false);
318     av.isSelectionGroupChanged(true);
319     av.isColSelChanged(true);
320     PaintRefresher.Refresh(ap, av.getSequenceSetId());
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). Note
327    * that the selection is only broadcast at the start of the drag (on
328    * mousePressed) and at the end (on mouseReleased), to avoid overload
329    * redrawing of other views.
330    * 
331    * @param evt
332    */
333   @Override
334   public void mouseDragged(MouseEvent evt)
335   {
336     mouseDragging = true;  
337     int res = ap.getSeqPanel().findAlignmentColumn(evt);
338     
339     ColumnSelection cs = av.getColumnSelection();
340     
341     min = Math.min(res,min);
342     max = Math.max(res, max);
343
344     SequenceGroup sg = av.getSelectionGroup();
345     if (sg != null)
346     {
347       stretchingGroup = true;
348       cs.stretchGroup(res, sg, min, max);
349       ap.paintAlignment(false, false);
350       PaintRefresher.Refresh(ap, av.getSequenceSetId());
351     }
352   }
353
354   @Override
355   public void mouseEntered(MouseEvent evt)
356   {
357     if (mouseDragging)
358     {
359       mouseDragging = false;
360       ap.getSeqPanel().stopScrolling();
361     }
362   }
363
364   /**
365    * Action on leaving the panel bounds with mouse drag in progress is to start
366    * scrolling the alignment in the direction of the mouse. To restrict
367    * scrolling to left-right (not up-down), the y-value of the mouse position is
368    * replaced with zero.
369    */
370   @Override
371   public void mouseExited(MouseEvent evt)
372   {
373     if (mouseDragging)
374     {
375       ap.getSeqPanel().startScrolling(new Point(evt.getX(), 0));
376     }
377   }
378
379   @Override
380   public void mouseClicked(MouseEvent evt)
381   {
382   }
383
384   /**
385    * Creates a tooltip when the mouse is over a hidden columns marker
386    */
387   @Override
388   public void mouseMoved(MouseEvent evt)
389   {
390     this.setToolTipText(null);
391     reveal = null;
392     final int res = ap.getSeqPanel().findAlignmentColumn(evt);
393     
394     highlightAllStructPos(res);
395     if (!av.hasHiddenColumns()) {
396       return;
397     }
398     reveal = av.getAlignment().getHiddenColumns()
399             .getRegionWithEdgeAtRes(av.getAlignment().getHiddenColumns().absoluteToVisibleColumn(res));
400     if (reveal==null)
401     {
402       return;
403     }
404     ToolTipManager.sharedInstance().registerComponent(this);
405     this.setToolTipText(
406             MessageManager.getString("label.reveal_hidden_columns"));
407     repaint();
408   }
409
410   public void highlightAllStructPos(int col)
411   {
412     ap.getStructureSelectionManager().highlightPositionsOnMany(
413             ap.av.getAlignment().getSequencesArray(), new int[]
414             { col, col }, ap);
415
416   }
417
418   /**
419    * DOCUMENT ME!
420    * 
421    * @param g
422    *          DOCUMENT ME!
423    */
424   @Override
425   public void paintComponent(Graphics g)
426   {
427     // super.paintComponent(g); // BH 2019
428
429     /*
430      * shouldn't get called in wrapped mode as the scale above is
431      * drawn instead by SeqCanvas.drawNorthScale
432      */
433     if (!av.getWrapAlignment())
434     {
435       drawScale(g, av.getRanges().getStartRes(), av.getRanges().getEndRes(),
436               getWidth(), getHeight());
437     }
438   }
439
440   // scalewidth will normally be screenwidth,
441   public void drawScale(Graphics g, int startx, int endx, int width,
442           int height)
443   {
444     Graphics2D gg = (Graphics2D) g;
445     gg.setFont(av.getFont());
446
447     if (av.antiAlias)
448     {
449       gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
450               RenderingHints.VALUE_ANTIALIAS_ON);
451     }
452
453     // Fill in the background
454     gg.setColor(Color.white);
455     gg.fillRect(0, 0, width, height);
456     gg.setColor(Color.black);
457
458     // Fill the selected columns
459     ColumnSelection cs = av.getColumnSelection();
460     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
461     int avCharWidth = av.getCharWidth();
462     int avCharHeight = av.getCharHeight();
463
464     if (cs != null)
465     {
466       gg.setColor(new Color(220, 0, 0));
467
468       for (int sel : cs.getSelected())
469       {
470         // TODO: JAL-2001 - provide a fast method to list visible selected in a
471         // given range
472
473         if (av.hasHiddenColumns())
474         {
475           if (hidden.isVisible(sel))
476           {
477             sel = hidden.absoluteToVisibleColumn(sel);
478           }
479           else
480           {
481             continue;
482           }
483         }
484
485         if ((sel >= startx) && (sel <= endx))
486         {
487           gg.fillRect((sel - startx) * avCharWidth, 0, avCharWidth,
488                   getHeight());
489         }
490       }
491     }
492
493     int widthx = 1 + endx - startx;
494
495     FontMetrics fm = gg.getFontMetrics(av.getFont());
496     int y = avCharHeight;
497     int 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
505       if (av.getShowHiddenMarkers())
506       {
507         Iterator<Integer> it = hidden.getStartRegionIterator(startx,
508                 startx + widthx + 1);
509         while (it.hasNext())
510         {
511           res = it.next() - startx;
512
513           gg.fillPolygon(
514                   new int[]
515                   { -1 + res * avCharWidth - avCharHeight / 4,
516                       -1 + res * avCharWidth + avCharHeight / 4,
517                       -1 + res * avCharWidth },
518                   new int[]
519                   { y, y, y + 2 * yOf }, 3);
520         }
521       }
522     }
523     // Draw the scale numbers
524     gg.setColor(Color.black);
525
526     int maxX = 0;
527     List<ScaleMark> marks = new ScaleRenderer().calculateMarks(av, startx,
528             endx);
529
530     for (ScaleMark mark : marks)
531     {
532       boolean major = mark.major;
533       int mpos = mark.column; // (i - startx - 1)
534       String mstring = mark.text;
535       if (mstring != null)
536       {
537         if (mpos * avCharWidth > maxX)
538         {
539           gg.drawString(mstring, mpos * avCharWidth, y);
540           maxX = (mpos + 2) * avCharWidth + fm.stringWidth(mstring);
541         }
542       }
543       if (major)
544       {
545         gg.drawLine((mpos * avCharWidth) + (avCharWidth / 2), y + 2,
546                 (mpos * avCharWidth) + (avCharWidth / 2), y + (yOf * 2));
547       }
548       else
549       {
550         gg.drawLine((mpos * avCharWidth) + (avCharWidth / 2), y + yOf,
551                 (mpos * avCharWidth) + (avCharWidth / 2), y + (yOf * 2));
552       }
553     }
554   }
555
556   @Override
557   public void propertyChange(PropertyChangeEvent evt)
558   {
559     // Respond to viewport change events (e.g. alignment panel was scrolled)
560     // Both scrolling and resizing change viewport ranges: scrolling changes
561     // both start and end points, but resize only changes end values.
562     // Here we only want to fastpaint on a scroll, with resize using a normal
563     // paint, so scroll events are identified as changes to the horizontal or
564     // vertical start value.
565     if (evt.getPropertyName().equals(ViewportRanges.STARTRES)
566             || evt.getPropertyName().equals(ViewportRanges.STARTRESANDSEQ)
567             || evt.getPropertyName().equals(ViewportRanges.MOVE_VIEWPORT))
568     {
569       // scroll event, repaint panel
570
571       // Call repaint on alignment panel so that repaints from other alignment
572       // panel components can be aggregated. Otherwise performance of the
573       // overview
574       // window and others may be adversely affected.
575       av.getAlignPanel().repaint();
576     }
577   }
578
579 }