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