JAL-3218 allow both Hide and Reveal in scale panel popup menu
[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.renderer.ScaleRenderer;
27 import jalview.renderer.ScaleRenderer.ScaleMark;
28 import jalview.util.MessageManager;
29 import jalview.util.Platform;
30 import jalview.viewmodel.ViewportListenerI;
31 import jalview.viewmodel.ViewportRanges;
32
33 import java.awt.Color;
34 import java.awt.FontMetrics;
35 import java.awt.Graphics;
36 import java.awt.Graphics2D;
37 import java.awt.Point;
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().visibleToAbsoluteColumn(x);
117     }
118     res = Math.min(x, av.getAlignment().getWidth() - 1);
119
120     min = res;
121     max = res;
122
123     if (evt.isPopupTrigger()) // Mac: mousePressed
124     {
125       rightMouseButtonPressed(evt, res);
126     }
127     else if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
128     {
129       /*
130        * defer right-mouse click handling to mouse up on Windows
131        * (where isPopupTrigger() will answer true)
132        * but accept Cmd-click on Mac which passes isRightMouseButton
133        */
134       return;
135     }
136     else
137     {
138       leftMouseButtonPressed(evt, res);
139     }
140   }
141
142   /**
143    * Handles right mouse button press. If pressed in a selected column, opens
144    * context menu for 'Hide Columns'. If pressed on a hidden columns marker,
145    * opens context menu for 'Reveal / Reveal All'. Else does nothing.
146    * 
147    * @param evt
148    * @param res
149    */
150   protected void rightMouseButtonPressed(MouseEvent evt, final int res)
151   {
152     JPopupMenu pop = buildPopupMenu(res);
153     if (pop.getSubElements().length > 0)
154     {
155       pop.show(this, evt.getX(), evt.getY());
156     }
157   }
158
159   /**
160    * Builds a popup menu with 'Hide' or 'Reveal' options, or both, or neither
161    * 
162    * @param res
163    *          column number (0..)
164    * @return
165    */
166   protected JPopupMenu buildPopupMenu(final int res)
167   {
168     JPopupMenu pop = new JPopupMenu();
169
170     /*
171      * logic here depends on 'reveal', set in mouseMoved;
172      * grab the hidden range in case mouseMoved nulls it later
173      */
174     final int[] hiddenRange = reveal;
175     if (hiddenRange != null)
176     {
177       JMenuItem item = new JMenuItem(
178               MessageManager.getString("label.reveal"));
179       item.addActionListener(new ActionListener()
180       {
181         @Override
182         public void actionPerformed(ActionEvent e)
183         {
184           av.showColumn(hiddenRange[0]);
185           reveal = null;
186           ap.updateLayout();
187           ap.paintAlignment(true, true);
188           av.sendSelection();
189         }
190       });
191       pop.add(item);
192
193       if (av.getAlignment().getHiddenColumns().hasMultiHiddenColumnRegions())
194       {
195         item = new JMenuItem(MessageManager.getString("action.reveal_all"));
196         item.addActionListener(new ActionListener()
197         {
198           @Override
199           public void actionPerformed(ActionEvent e)
200           {
201             av.showAllHiddenColumns();
202             reveal = null;
203             ap.updateLayout();
204             ap.paintAlignment(true, true);
205             av.sendSelection();
206           }
207         });
208         pop.add(item);
209       }
210     }
211
212     if (av.getColumnSelection().contains(res))
213     {
214       JMenuItem item = new JMenuItem(
215               MessageManager.getString("label.hide_columns"));
216       item.addActionListener(new ActionListener()
217       {
218         @Override
219         public void actionPerformed(ActionEvent e)
220         {
221           av.hideColumns(res, res);
222           if (av.getSelectionGroup() != null && av.getSelectionGroup()
223                   .getSize() == av.getAlignment().getHeight())
224           {
225             av.setSelectionGroup(null);
226           }
227
228           ap.updateLayout();
229           ap.paintAlignment(true, true);
230           av.sendSelection();
231         }
232       });
233       pop.add(item);
234     }
235     return pop;
236   }
237
238   /**
239    * Handles left mouse button press
240    * 
241    * @param evt
242    * @param res
243    */
244   protected void leftMouseButtonPressed(MouseEvent evt, final int res)
245   {
246     /*
247      * Ctrl-click/Cmd-click adds to the selection
248      * Shift-click extends the selection
249      */
250     // TODO Problem: right-click on Windows not reported until mouseReleased?!?
251     if (!Platform.isControlDown(evt) && !evt.isShiftDown())
252     {
253       av.getColumnSelection().clear();
254     }
255
256     av.getColumnSelection().addElement(res);
257     SequenceGroup sg = new SequenceGroup(av.getAlignment().getSequences());
258     sg.setStartRes(res);
259     sg.setEndRes(res);
260
261     if (evt.isShiftDown())
262     {
263       int min = Math.min(av.getColumnSelection().getMin(), res);
264       int max = Math.max(av.getColumnSelection().getMax(), res);
265       for (int i = min; i < max; i++)
266       {
267         av.getColumnSelection().addElement(i);
268       }
269       sg.setStartRes(min);
270       sg.setEndRes(max);
271     }
272     av.setSelectionGroup(sg);
273     ap.paintAlignment(false, false);
274     av.sendSelection();
275   }
276
277   /**
278    * Action on mouseUp is to set the limit of the current selection group (if
279    * there is one) and broadcast the selection
280    * 
281    * @param evt
282    */
283   @Override
284   public void mouseReleased(MouseEvent evt)
285   {
286     boolean wasDragging = mouseDragging;
287     mouseDragging = false;
288     ap.getSeqPanel().stopScrolling();
289
290     int xCords = Math.max(0, evt.getX()); // prevent negative X coordinates
291     ViewportRanges ranges = av.getRanges();
292     int res = (xCords / av.getCharWidth())
293             + ranges.getStartRes();
294     res = Math.min(res, ranges.getEndRes());
295     if (av.hasHiddenColumns())
296     {
297       res = av.getAlignment().getHiddenColumns()
298               .visibleToAbsoluteColumn(res);
299     }
300     res = Math.max(0, res);
301
302     if (!stretchingGroup)
303     {
304       if (evt.isPopupTrigger()) // Windows: mouseReleased
305       {
306         rightMouseButtonPressed(evt, res);
307       }
308       else
309       {
310         ap.paintAlignment(false, false);
311       }
312       return;
313     }
314
315     SequenceGroup sg = av.getSelectionGroup();
316
317     if (sg != null)
318     {
319       if (res > sg.getStartRes())
320       {
321         sg.setEndRes(res);
322       }
323       else if (res < sg.getStartRes())
324       {
325         sg.setStartRes(res);
326       }
327       if (wasDragging)
328       {
329         min = Math.min(res, min);
330         max = Math.max(res, max);
331         av.getColumnSelection().stretchGroup(res, sg, min, max);
332       }
333     }
334     stretchingGroup = false;
335     ap.paintAlignment(false, false);
336     av.isSelectionGroupChanged(true);
337     av.isColSelChanged(true);
338     av.sendSelection();
339   }
340
341   /**
342    * Action on dragging the mouse in the scale panel is to expand or shrink the
343    * selection group range (including any hidden columns that it spans). Note
344    * that the selection is only broadcast at the start of the drag (on
345    * mousePressed) and at the end (on mouseReleased), to avoid overload
346    * redrawing of other views.
347    * 
348    * @param evt
349    */
350   @Override
351   public void mouseDragged(MouseEvent evt)
352   {
353     mouseDragging = true;
354     ColumnSelection cs = av.getColumnSelection();
355     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
356
357     int res = (evt.getX() / av.getCharWidth())
358             + av.getRanges().getStartRes();
359     res = Math.max(0, res);
360     res = hidden.visibleToAbsoluteColumn(res);
361     res = Math.min(res, av.getAlignment().getWidth() - 1);
362     min = Math.min(res, min);
363     max = Math.max(res, max);
364
365     SequenceGroup sg = av.getSelectionGroup();
366     if (sg != null)
367     {
368       stretchingGroup = true;
369       cs.stretchGroup(res, sg, min, max);
370       ap.paintAlignment(false, false);
371     }
372   }
373
374   @Override
375   public void mouseEntered(MouseEvent evt)
376   {
377     if (mouseDragging)
378     {
379       ap.getSeqPanel().stopScrolling();
380     }
381   }
382
383   /**
384    * Action on leaving the panel bounds with mouse drag in progress is to start
385    * scrolling the alignment in the direction of the mouse. To restrict
386    * scrolling to left-right (not up-down), the y-value of the mouse position is
387    * replaced with zero.
388    */
389   @Override
390   public void mouseExited(MouseEvent evt)
391   {
392     if (mouseDragging)
393     {
394       ap.getSeqPanel().startScrolling(new Point(evt.getX(), 0));
395     }
396   }
397
398   @Override
399   public void mouseClicked(MouseEvent evt)
400   {
401   }
402
403   /**
404    * Creates a tooltip when the mouse is over a hidden columns marker
405    */
406   @Override
407   public void mouseMoved(MouseEvent evt)
408   {
409     this.setToolTipText(null);
410     reveal = null;
411     if (!av.hasHiddenColumns())
412     {
413       return;
414     }
415
416     int res = (evt.getX() / av.getCharWidth())
417             + av.getRanges().getStartRes();
418
419     reveal = av.getAlignment().getHiddenColumns()
420             .getRegionWithEdgeAtRes(res);
421
422     res = av.getAlignment().getHiddenColumns().visibleToAbsoluteColumn(res);
423
424     ToolTipManager.sharedInstance().registerComponent(this);
425     this.setToolTipText(
426             MessageManager.getString("label.reveal_hidden_columns"));
427     repaint();
428   }
429
430   /**
431    * DOCUMENT ME!
432    * 
433    * @param g
434    *          DOCUMENT ME!
435    */
436   @Override
437   public void paintComponent(Graphics g)
438   {
439     super.paintComponent(g);
440
441     /*
442      * shouldn't get called in wrapped mode as the scale above is
443      * drawn instead by SeqCanvas.drawNorthScale
444      */
445     if (!av.getWrapAlignment())
446     {
447       drawScale(g, av.getRanges().getStartRes(), av.getRanges().getEndRes(),
448               getWidth(), getHeight());
449     }
450   }
451
452   // scalewidth will normally be screenwidth,
453   public void drawScale(Graphics g, int startx, int endx, int width,
454           int height)
455   {
456     Graphics2D gg = (Graphics2D) g;
457     gg.setFont(av.getFont());
458
459     if (av.antiAlias)
460     {
461       gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
462               RenderingHints.VALUE_ANTIALIAS_ON);
463     }
464
465     // Fill in the background
466     gg.setColor(Color.white);
467     gg.fillRect(0, 0, width, height);
468     gg.setColor(Color.black);
469
470     // Fill the selected columns
471     ColumnSelection cs = av.getColumnSelection();
472     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
473     int avCharWidth = av.getCharWidth();
474     int avCharHeight = av.getCharHeight();
475
476     if (cs != null)
477     {
478       gg.setColor(new Color(220, 0, 0));
479
480       for (int sel : cs.getSelected())
481       {
482         // TODO: JAL-2001 - provide a fast method to list visible selected in a
483         // given range
484
485         if (av.hasHiddenColumns())
486         {
487           if (hidden.isVisible(sel))
488           {
489             sel = hidden.absoluteToVisibleColumn(sel);
490           }
491           else
492           {
493             continue;
494           }
495         }
496
497         if ((sel >= startx) && (sel <= endx))
498         {
499           gg.fillRect((sel - startx) * avCharWidth, 0, avCharWidth,
500                   getHeight());
501         }
502       }
503     }
504
505     int widthx = 1 + endx - startx;
506
507     FontMetrics fm = gg.getFontMetrics(av.getFont());
508     int y = avCharHeight;
509     int yOf = fm.getDescent();
510     y -= yOf;
511     if (av.hasHiddenColumns())
512     {
513       // draw any hidden column markers
514       gg.setColor(Color.blue);
515       int res;
516
517       if (av.getShowHiddenMarkers())
518       {
519         Iterator<Integer> it = hidden.getStartRegionIterator(startx,
520                 startx + widthx + 1);
521         while (it.hasNext())
522         {
523           res = it.next() - startx;
524
525           gg.fillPolygon(
526                   new int[]
527           { -1 + res * avCharWidth - avCharHeight / 4,
528               -1 + res * avCharWidth + avCharHeight / 4,
529               -1 + res * avCharWidth }, 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 overview
584     // window and others may be adversely affected.
585       av.getAlignPanel().repaint();
586     }
587   }
588
589 }