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