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