JAL-3108 fix concurrency bug in Reveal action handler
[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().visibleToAbsoluteColumn(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
162     /*
163      * grab the hidden range in case mouseMoved nulls it
164      */
165     final int[] hiddenRange = reveal;
166     if (hiddenRange != null)
167     {
168       JMenuItem item = new JMenuItem(
169               MessageManager.getString("label.reveal"));
170       item.addActionListener(new ActionListener()
171       {
172         @Override
173         public void actionPerformed(ActionEvent e)
174         {
175           av.showColumn(hiddenRange[0]);
176           reveal = null;
177           ap.paintAlignment(true, true);
178           av.sendSelection();
179         }
180       });
181       pop.add(item);
182
183       if (av.getAlignment().getHiddenColumns().hasMultiHiddenColumnRegions())
184       {
185         item = new JMenuItem(MessageManager.getString("action.reveal_all"));
186         item.addActionListener(new ActionListener()
187         {
188           @Override
189           public void actionPerformed(ActionEvent e)
190           {
191             av.showAllHiddenColumns();
192             reveal = null;
193             ap.paintAlignment(true, true);
194             av.sendSelection();
195           }
196         });
197         pop.add(item);
198       }
199       pop.show(this, evt.getX(), evt.getY());
200     }
201     else if (av.getColumnSelection().contains(res))
202     {
203       JMenuItem item = new JMenuItem(
204               MessageManager.getString("label.hide_columns"));
205       item.addActionListener(new ActionListener()
206       {
207         @Override
208         public void actionPerformed(ActionEvent e)
209         {
210           av.hideColumns(res, res);
211           if (av.getSelectionGroup() != null && av.getSelectionGroup()
212                   .getSize() == av.getAlignment().getHeight())
213           {
214             av.setSelectionGroup(null);
215           }
216
217           ap.paintAlignment(true, true);
218           av.sendSelection();
219         }
220       });
221       pop.add(item);
222       pop.show(this, evt.getX(), evt.getY());
223     }
224   }
225
226   /**
227    * Handles left mouse button press
228    * 
229    * @param evt
230    * @param res
231    */
232   protected void leftMouseButtonPressed(MouseEvent evt, final int res)
233   {
234     /*
235      * Ctrl-click/Cmd-click adds to the selection
236      * Shift-click extends the selection
237      */
238     // TODO Problem: right-click on Windows not reported until mouseReleased?!?
239     if (!Platform.isControlDown(evt) && !evt.isShiftDown())
240     {
241       av.getColumnSelection().clear();
242     }
243
244     av.getColumnSelection().addElement(res);
245     SequenceGroup sg = new SequenceGroup();
246     // try to be as quick as possible
247     SequenceI[] iVec = av.getAlignment().getSequencesArray();
248     for (int i = 0; i < iVec.length; i++)
249     {
250       sg.addSequence(iVec[i], false);
251       iVec[i] = null;
252     }
253     iVec = null;
254     sg.setStartRes(res);
255     sg.setEndRes(res);
256
257     if (evt.isShiftDown())
258     {
259       int min = Math.min(av.getColumnSelection().getMin(), res);
260       int max = Math.max(av.getColumnSelection().getMax(), res);
261       for (int i = min; i < max; i++)
262       {
263         av.getColumnSelection().addElement(i);
264       }
265       sg.setStartRes(min);
266       sg.setEndRes(max);
267     }
268     av.setSelectionGroup(sg);
269     ap.paintAlignment(false, false);
270     av.sendSelection();
271   }
272
273   /**
274    * DOCUMENT ME!
275    * 
276    * @param evt
277    *          DOCUMENT ME!
278    */
279   @Override
280   public void mouseReleased(MouseEvent evt)
281   {
282     mouseDragging = false;
283
284     int res = (evt.getX() / av.getCharWidth())
285             + av.getRanges().getStartRes();
286
287     if (av.hasHiddenColumns())
288     {
289       res = av.getAlignment().getHiddenColumns()
290               .visibleToAbsoluteColumn(res);
291     }
292
293     if (res >= av.getAlignment().getWidth())
294     {
295       res = av.getAlignment().getWidth() - 1;
296     }
297
298     if (!stretchingGroup)
299     {
300       if (evt.isPopupTrigger()) // Windows: mouseReleased
301       {
302         rightMouseButtonPressed(evt, res);
303       }
304       else
305       {
306         ap.paintAlignment(false, false);
307       }
308       return;
309     }
310
311     SequenceGroup sg = av.getSelectionGroup();
312
313     if (sg != null)
314     {
315       if (res > sg.getStartRes())
316       {
317         sg.setEndRes(res);
318       }
319       else if (res < sg.getStartRes())
320       {
321         sg.setStartRes(res);
322       }
323     }
324     stretchingGroup = false;
325     ap.paintAlignment(false, false);
326     av.sendSelection();
327   }
328
329   /**
330    * Action on dragging the mouse in the scale panel is to expand or shrink the
331    * selection group range (including any hidden columns that it spans)
332    * 
333    * @param evt
334    */
335   @Override
336   public void mouseDragged(MouseEvent evt)
337   {
338     mouseDragging = true;
339     ColumnSelection cs = av.getColumnSelection();
340     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
341
342     int res = (evt.getX() / av.getCharWidth())
343             + av.getRanges().getStartRes();
344     res = Math.max(0, res);
345     res = hidden.visibleToAbsoluteColumn(res);
346     res = Math.min(res, av.getAlignment().getWidth() - 1);
347     min = Math.min(res, min);
348     max = Math.max(res, max);
349
350     SequenceGroup sg = av.getSelectionGroup();
351     if (sg != null)
352     {
353       stretchingGroup = true;
354       cs.stretchGroup(res, sg, min, max);
355       ap.paintAlignment(false, false);
356     }
357   }
358
359   @Override
360   public void mouseEntered(MouseEvent evt)
361   {
362     if (mouseDragging)
363     {
364       ap.getSeqPanel().scrollCanvas(null);
365     }
366   }
367
368   @Override
369   public void mouseExited(MouseEvent evt)
370   {
371     if (mouseDragging)
372     {
373       ap.getSeqPanel().scrollCanvas(evt);
374     }
375   }
376
377   @Override
378   public void mouseClicked(MouseEvent evt)
379   {
380   }
381
382   /**
383    * Creates a tooltip when the mouse is over a hidden columns marker
384    */
385   @Override
386   public void mouseMoved(MouseEvent evt)
387   {
388     this.setToolTipText(null);
389     reveal = null;
390     if (!av.hasHiddenColumns())
391     {
392       return;
393     }
394
395     int res = (evt.getX() / av.getCharWidth())
396             + av.getRanges().getStartRes();
397
398     reveal = av.getAlignment().getHiddenColumns()
399             .getRegionWithEdgeAtRes(res);
400
401     res = av.getAlignment().getHiddenColumns().visibleToAbsoluteColumn(res);
402
403     ToolTipManager.sharedInstance().registerComponent(this);
404     this.setToolTipText(
405             MessageManager.getString("label.reveal_hidden_columns"));
406     repaint();
407   }
408
409   /**
410    * DOCUMENT ME!
411    * 
412    * @param g
413    *          DOCUMENT ME!
414    */
415   @Override
416   public void paintComponent(Graphics g)
417   {
418     super.paintComponent(g);
419
420     /*
421      * shouldn't get called in wrapped mode as the scale above is
422      * drawn instead by SeqCanvas.drawNorthScale
423      */
424     if (!av.getWrapAlignment())
425     {
426       drawScale(g, av.getRanges().getStartRes(), av.getRanges().getEndRes(),
427               getWidth(), getHeight());
428     }
429   }
430
431   // scalewidth will normally be screenwidth,
432   public void drawScale(Graphics g, int startx, int endx, int width,
433           int height)
434   {
435     Graphics2D gg = (Graphics2D) g;
436     gg.setFont(av.getFont());
437
438     if (av.antiAlias)
439     {
440       gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
441               RenderingHints.VALUE_ANTIALIAS_ON);
442     }
443
444     // Fill in the background
445     gg.setColor(Color.white);
446     gg.fillRect(0, 0, width, height);
447     gg.setColor(Color.black);
448
449     // Fill the selected columns
450     ColumnSelection cs = av.getColumnSelection();
451     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
452     int avCharWidth = av.getCharWidth();
453     int avCharHeight = av.getCharHeight();
454
455     if (cs != null)
456     {
457       gg.setColor(new Color(220, 0, 0));
458
459       for (int sel : cs.getSelected())
460       {
461         // TODO: JAL-2001 - provide a fast method to list visible selected in a
462         // given range
463
464         if (av.hasHiddenColumns())
465         {
466           if (hidden.isVisible(sel))
467           {
468             sel = hidden.absoluteToVisibleColumn(sel);
469           }
470           else
471           {
472             continue;
473           }
474         }
475
476         if ((sel >= startx) && (sel <= endx))
477         {
478           gg.fillRect((sel - startx) * avCharWidth, 0, avCharWidth,
479                   getHeight());
480         }
481       }
482     }
483
484     int widthx = 1 + endx - startx;
485
486     FontMetrics fm = gg.getFontMetrics(av.getFont());
487     int y = avCharHeight;
488     int yOf = fm.getDescent();
489     y -= yOf;
490     if (av.hasHiddenColumns())
491     {
492       // draw any hidden column markers
493       gg.setColor(Color.blue);
494       int res;
495
496       if (av.getShowHiddenMarkers())
497       {
498         Iterator<Integer> it = hidden.getStartRegionIterator(startx,
499                 startx + widthx + 1);
500         while (it.hasNext())
501         {
502           res = it.next() - startx;
503
504           gg.fillPolygon(
505                   new int[]
506           { -1 + res * avCharWidth - avCharHeight / 4,
507               -1 + res * avCharWidth + avCharHeight / 4,
508               -1 + res * avCharWidth }, new int[]
509           { y, y, y + 2 * yOf }, 3);
510         }
511       }
512     }
513     // Draw the scale numbers
514     gg.setColor(Color.black);
515
516     int maxX = 0;
517     List<ScaleMark> marks = new ScaleRenderer().calculateMarks(av, startx,
518             endx);
519
520     for (ScaleMark mark : marks)
521     {
522       boolean major = mark.major;
523       int mpos = mark.column; // (i - startx - 1)
524       String mstring = mark.text;
525       if (mstring != null)
526       {
527         if (mpos * avCharWidth > maxX)
528         {
529           gg.drawString(mstring, mpos * avCharWidth, y);
530           maxX = (mpos + 2) * avCharWidth + fm.stringWidth(mstring);
531         }
532       }
533       if (major)
534       {
535         gg.drawLine((mpos * avCharWidth) + (avCharWidth / 2), y + 2,
536                 (mpos * avCharWidth) + (avCharWidth / 2), y + (yOf * 2));
537       }
538       else
539       {
540         gg.drawLine((mpos * avCharWidth) + (avCharWidth / 2), y + yOf,
541                 (mpos * avCharWidth) + (avCharWidth / 2), y + (yOf * 2));
542       }
543     }
544   }
545
546   @Override
547   public void propertyChange(PropertyChangeEvent evt)
548   {
549     // Respond to viewport change events (e.g. alignment panel was scrolled)
550     // Both scrolling and resizing change viewport ranges: scrolling changes
551     // both start and end points, but resize only changes end values.
552     // Here we only want to fastpaint on a scroll, with resize using a normal
553     // paint, so scroll events are identified as changes to the horizontal or
554     // vertical start value.
555     if (evt.getPropertyName().equals(ViewportRanges.STARTRES)
556             || evt.getPropertyName().equals(ViewportRanges.STARTRESANDSEQ)
557             || evt.getPropertyName().equals(ViewportRanges.MOVE_VIEWPORT))
558     {
559       // scroll event, repaint panel
560         
561         // Call repaint on alignment panel so that repaints from other alignment
562     // panel components can be aggregated. Otherwise performance of the overview
563     // window and others may be adversely affected.
564       av.getAlignPanel().repaint();
565     }
566   }
567
568 }