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