Merge branch 'bug/JAL-2750' 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 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     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().hasMultiHiddenColumnRegions())
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 xCords = Math.max(0, evt.getX()); // prevent negative X coordinates
280
281     int res = (xCords / av.getCharWidth())
282             + av.getRanges().getStartRes();
283
284     if (av.hasHiddenColumns())
285     {
286       res = av.getAlignment().getHiddenColumns()
287               .visibleToAbsoluteColumn(res);
288     }
289
290     if (res >= av.getAlignment().getWidth())
291     {
292       res = av.getAlignment().getWidth() - 1;
293     }
294
295     if (!stretchingGroup)
296     {
297       if (evt.isPopupTrigger()) // Windows: mouseReleased
298       {
299         rightMouseButtonPressed(evt, res);
300       }
301       else
302       {
303         ap.paintAlignment(false, false);
304       }
305       return;
306     }
307
308     SequenceGroup sg = av.getSelectionGroup();
309
310     if (sg != null)
311     {
312       if (res > sg.getStartRes())
313       {
314         sg.setEndRes(res);
315       }
316       else if (res < sg.getStartRes())
317       {
318         sg.setStartRes(res);
319       }
320     }
321     stretchingGroup = false;
322     ap.paintAlignment(false, false);
323     av.sendSelection();
324   }
325
326   /**
327    * Action on dragging the mouse in the scale panel is to expand or shrink the
328    * selection group range (including any hidden columns that it spans)
329    * 
330    * @param evt
331    */
332   @Override
333   public void mouseDragged(MouseEvent evt)
334   {
335     mouseDragging = true;
336     ColumnSelection cs = av.getColumnSelection();
337     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
338
339     int res = (evt.getX() / av.getCharWidth())
340             + av.getRanges().getStartRes();
341     res = Math.max(0, res);
342     res = hidden.visibleToAbsoluteColumn(res);
343     res = Math.min(res, av.getAlignment().getWidth() - 1);
344     min = Math.min(res, min);
345     max = Math.max(res, max);
346
347     SequenceGroup sg = av.getSelectionGroup();
348     if (sg != null)
349     {
350       stretchingGroup = true;
351       cs.stretchGroup(res, sg, min, max);
352       ap.paintAlignment(false, false);
353     }
354   }
355
356   @Override
357   public void mouseEntered(MouseEvent evt)
358   {
359     if (mouseDragging)
360     {
361       ap.getSeqPanel().scrollCanvas(null);
362     }
363   }
364
365   @Override
366   public void mouseExited(MouseEvent evt)
367   {
368     if (mouseDragging)
369     {
370       ap.getSeqPanel().scrollCanvas(evt);
371     }
372   }
373
374   @Override
375   public void mouseClicked(MouseEvent evt)
376   {
377   }
378
379   /**
380    * Creates a tooltip when the mouse is over a hidden columns marker
381    */
382   @Override
383   public void mouseMoved(MouseEvent evt)
384   {
385     this.setToolTipText(null);
386     reveal = null;
387     if (!av.hasHiddenColumns())
388     {
389       return;
390     }
391
392     int res = (evt.getX() / av.getCharWidth())
393             + av.getRanges().getStartRes();
394
395     reveal = av.getAlignment().getHiddenColumns()
396             .getRegionWithEdgeAtRes(res);
397
398     res = av.getAlignment().getHiddenColumns().visibleToAbsoluteColumn(res);
399
400     ToolTipManager.sharedInstance().registerComponent(this);
401     this.setToolTipText(
402             MessageManager.getString("label.reveal_hidden_columns"));
403     repaint();
404   }
405
406   /**
407    * DOCUMENT ME!
408    * 
409    * @param g
410    *          DOCUMENT ME!
411    */
412   @Override
413   public void paintComponent(Graphics g)
414   {
415     super.paintComponent(g);
416
417     /*
418      * shouldn't get called in wrapped mode as the scale above is
419      * drawn instead by SeqCanvas.drawNorthScale
420      */
421     if (!av.getWrapAlignment())
422     {
423       drawScale(g, av.getRanges().getStartRes(), av.getRanges().getEndRes(),
424               getWidth(), getHeight());
425     }
426   }
427
428   // scalewidth will normally be screenwidth,
429   public void drawScale(Graphics g, int startx, int endx, int width,
430           int height)
431   {
432     Graphics2D gg = (Graphics2D) g;
433     gg.setFont(av.getFont());
434
435     if (av.antiAlias)
436     {
437       gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
438               RenderingHints.VALUE_ANTIALIAS_ON);
439     }
440
441     // Fill in the background
442     gg.setColor(Color.white);
443     gg.fillRect(0, 0, width, height);
444     gg.setColor(Color.black);
445
446     // Fill the selected columns
447     ColumnSelection cs = av.getColumnSelection();
448     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
449     int avCharWidth = av.getCharWidth();
450     int avCharHeight = av.getCharHeight();
451
452     if (cs != null)
453     {
454       gg.setColor(new Color(220, 0, 0));
455
456       for (int sel : cs.getSelected())
457       {
458         // TODO: JAL-2001 - provide a fast method to list visible selected in a
459         // given range
460
461         if (av.hasHiddenColumns())
462         {
463           if (hidden.isVisible(sel))
464           {
465             sel = hidden.absoluteToVisibleColumn(sel);
466           }
467           else
468           {
469             continue;
470           }
471         }
472
473         if ((sel >= startx) && (sel <= endx))
474         {
475           gg.fillRect((sel - startx) * avCharWidth, 0, avCharWidth,
476                   getHeight());
477         }
478       }
479     }
480
481     int widthx = 1 + endx - startx;
482
483     FontMetrics fm = gg.getFontMetrics(av.getFont());
484     int y = avCharHeight;
485     int yOf = fm.getDescent();
486     y -= yOf;
487     if (av.hasHiddenColumns())
488     {
489       // draw any hidden column markers
490       gg.setColor(Color.blue);
491       int res;
492
493       if (av.getShowHiddenMarkers())
494       {
495         Iterator<Integer> it = hidden.getStartRegionIterator(startx,
496                 startx + widthx + 1);
497         while (it.hasNext())
498         {
499           res = it.next() - startx;
500
501           gg.fillPolygon(
502                   new int[]
503           { -1 + res * avCharWidth - avCharHeight / 4,
504               -1 + res * avCharWidth + avCharHeight / 4,
505               -1 + res * avCharWidth }, new int[]
506           { y, y, y + 2 * yOf }, 3);
507         }
508       }
509     }
510     // Draw the scale numbers
511     gg.setColor(Color.black);
512
513     int maxX = 0;
514     List<ScaleMark> marks = new ScaleRenderer().calculateMarks(av, startx,
515             endx);
516
517     for (ScaleMark mark : marks)
518     {
519       boolean major = mark.major;
520       int mpos = mark.column; // (i - startx - 1)
521       String mstring = mark.text;
522       if (mstring != null)
523       {
524         if (mpos * avCharWidth > maxX)
525         {
526           gg.drawString(mstring, mpos * avCharWidth, y);
527           maxX = (mpos + 2) * avCharWidth + fm.stringWidth(mstring);
528         }
529       }
530       if (major)
531       {
532         gg.drawLine((mpos * avCharWidth) + (avCharWidth / 2), y + 2,
533                 (mpos * avCharWidth) + (avCharWidth / 2), y + (yOf * 2));
534       }
535       else
536       {
537         gg.drawLine((mpos * avCharWidth) + (avCharWidth / 2), y + yOf,
538                 (mpos * avCharWidth) + (avCharWidth / 2), y + (yOf * 2));
539       }
540     }
541   }
542
543   @Override
544   public void propertyChange(PropertyChangeEvent evt)
545   {
546     // Respond to viewport change events (e.g. alignment panel was scrolled)
547     // Both scrolling and resizing change viewport ranges: scrolling changes
548     // both start and end points, but resize only changes end values.
549     // Here we only want to fastpaint on a scroll, with resize using a normal
550     // paint, so scroll events are identified as changes to the horizontal or
551     // vertical start value.
552     if (evt.getPropertyName().equals(ViewportRanges.STARTRES)
553             || evt.getPropertyName().equals(ViewportRanges.STARTRESANDSEQ)
554             || evt.getPropertyName().equals(ViewportRanges.MOVE_VIEWPORT))
555     {
556       // scroll event, repaint panel
557         
558         // Call repaint on alignment panel so that repaints from other alignment
559     // panel components can be aggregated. Otherwise performance of the overview
560     // window and others may be adversely affected.
561       av.getAlignPanel().repaint();
562     }
563   }
564
565 }