Merge branch 'develop' into Jalview-BH/JAL-3026-JAL-3063-JAXB
[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.Point;
39 import java.awt.RenderingHints;
40 import java.awt.event.ActionEvent;
41 import java.awt.event.ActionListener;
42 import java.awt.event.MouseEvent;
43 import java.awt.event.MouseListener;
44 import java.awt.event.MouseMotionListener;
45 import java.beans.PropertyChangeEvent;
46 import java.util.Iterator;
47 import java.util.List;
48
49 import javax.swing.JMenuItem;
50 import javax.swing.JPanel;
51 import javax.swing.JPopupMenu;
52 import javax.swing.SwingUtilities;
53 import javax.swing.ToolTipManager;
54
55 /**
56  * The panel containing the sequence ruler (when not in wrapped mode), and
57  * supports a range of mouse operations to select, hide or reveal columns.
58  */
59 public class ScalePanel extends JPanel
60         implements MouseMotionListener, MouseListener, ViewportListenerI
61 {
62   protected int offy = 4;
63
64   public int width;
65
66   protected AlignViewport av;
67
68   AlignmentPanel ap;
69
70   boolean stretchingGroup = false;
71
72   /*
73    * min, max hold the extent of a mouse drag action
74    */
75   int min;
76
77   int max;
78
79   boolean mouseDragging = false;
80
81   /*
82    * holds a hidden column range when the mouse is over an adjacent column
83    */
84   int[] reveal;
85
86   /**
87    * Constructor
88    * 
89    * @param av
90    * @param ap
91    */
92   public ScalePanel(AlignViewport av, AlignmentPanel ap)
93   {
94     this.av = av;
95     this.ap = ap;
96
97     addMouseListener(this);
98     addMouseMotionListener(this);
99
100     av.getRanges().addPropertyChangeListener(this);
101   }
102
103   /**
104    * DOCUMENT ME!
105    * 
106    * @param evt
107    *          DOCUMENT ME!
108    */
109   @Override
110   public void mousePressed(MouseEvent evt)
111   {
112     int x = (evt.getX() / av.getCharWidth()) + av.getRanges().getStartRes();
113     final int res;
114
115     if (av.hasHiddenColumns())
116     {
117       x = av.getAlignment().getHiddenColumns().visibleToAbsoluteColumn(x);
118     }
119
120     if (x >= av.getAlignment().getWidth())
121     {
122       res = av.getAlignment().getWidth() - 1;
123     }
124     else
125     {
126       res = x;
127     }
128
129     min = res;
130     max = res;
131
132     if (evt.isPopupTrigger()) // Mac: mousePressed
133     {
134       rightMouseButtonPressed(evt, res);
135     }
136     else if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
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     else
146     {
147       leftMouseButtonPressed(evt, res);
148     }
149   }
150
151   /**
152    * Handles right mouse button press. If pressed in a selected column, opens
153    * context menu for 'Hide Columns'. If pressed on a hidden columns marker,
154    * opens context menu for 'Reveal / Reveal All'. Else does nothing.
155    * 
156    * @param evt
157    * @param res
158    */
159   protected void rightMouseButtonPressed(MouseEvent evt, final int res)
160   {
161     JPopupMenu pop = new JPopupMenu();
162     if (reveal != null)
163     {
164       JMenuItem item = new JMenuItem(
165               MessageManager.getString("label.reveal"));
166       item.addActionListener(new ActionListener()
167       {
168         @Override
169         public void actionPerformed(ActionEvent e)
170         {
171           av.showColumn(reveal[0]);
172           reveal = null;
173           ap.paintAlignment(true, true);
174           av.sendSelection();
175         }
176       });
177       pop.add(item);
178
179       if (av.getAlignment().getHiddenColumns().hasMultiHiddenColumnRegions())
180       {
181         item = new JMenuItem(MessageManager.getString("action.reveal_all"));
182         item.addActionListener(new ActionListener()
183         {
184           @Override
185           public void actionPerformed(ActionEvent e)
186           {
187             av.showAllHiddenColumns();
188             reveal = null;
189             ap.paintAlignment(true, true);
190             av.sendSelection();
191           }
192         });
193         pop.add(item);
194       }
195       pop.show(this, evt.getX(), evt.getY());
196     }
197     else if (av.getColumnSelection().contains(res))
198     {
199       JMenuItem item = new JMenuItem(
200               MessageManager.getString("label.hide_columns"));
201       item.addActionListener(new ActionListener()
202       {
203         @Override
204         public void actionPerformed(ActionEvent e)
205         {
206           av.hideColumns(res, res);
207           if (av.getSelectionGroup() != null && av.getSelectionGroup()
208                   .getSize() == av.getAlignment().getHeight())
209           {
210             av.setSelectionGroup(null);
211           }
212
213           ap.paintAlignment(true, true);
214           av.sendSelection();
215         }
216       });
217       pop.add(item);
218       pop.show(this, evt.getX(), evt.getY());
219     }
220   }
221
222   /**
223    * Handles left mouse button press
224    * 
225    * @param evt
226    * @param res
227    */
228   protected void leftMouseButtonPressed(MouseEvent evt, final int res)
229   {
230     /*
231      * Ctrl-click/Cmd-click adds to the selection
232      * Shift-click extends the selection
233      */
234     // TODO Problem: right-click on Windows not reported until mouseReleased?!?
235     if (!Platform.isControlDown(evt) && !evt.isShiftDown())
236     {
237       av.getColumnSelection().clear();
238     }
239
240     av.getColumnSelection().addElement(res);
241     SequenceGroup sg = new SequenceGroup();
242     // try to be as quick as possible
243     SequenceI[] iVec = av.getAlignment().getSequencesArray();
244     for (int i = 0; i < iVec.length; i++)
245     {
246       sg.addSequence(iVec[i], false);
247       iVec[i] = null;
248     }
249     iVec = null;
250     sg.setStartRes(res);
251     sg.setEndRes(res);
252
253     if (evt.isShiftDown())
254     {
255       int min = Math.min(av.getColumnSelection().getMin(), res);
256       int max = Math.max(av.getColumnSelection().getMax(), res);
257       for (int i = min; i < max; i++)
258       {
259         av.getColumnSelection().addElement(i);
260       }
261       sg.setStartRes(min);
262       sg.setEndRes(max);
263     }
264     av.setSelectionGroup(sg);
265     ap.paintAlignment(false, false);
266     av.sendSelection();
267   }
268
269   /**
270    * Action on mouseUp is to set the limit of the current selection group (if
271    * there is one) and broadcast the selection
272    * 
273    * @param evt
274    */
275   @Override
276   public void mouseReleased(MouseEvent evt)
277   {
278     mouseDragging = false;
279     ap.getSeqPanel().stopScrolling();
280
281     // todo res calculation should be a method on AlignViewport
282     int xCords = Math.max(0, evt.getX()); // prevent negative X coordinates
283
284     int res = (xCords / av.getCharWidth())
285             + av.getRanges().getStartRes();
286
287     if (av.hasHiddenColumns())
288     {
289       res = av.getAlignment().getHiddenColumns()
290               .visibleToAbsoluteColumn(res);
291     }
292     res = Math.min(res, av.getAlignment().getWidth() - 1);
293
294     if (!stretchingGroup)
295     {
296       if (evt.isPopupTrigger()) // Windows: mouseReleased
297       {
298         rightMouseButtonPressed(evt, res);
299       }
300       else
301       {
302         ap.paintAlignment(false, false);
303       }
304       return;
305     }
306
307     SequenceGroup sg = av.getSelectionGroup();
308
309     if (sg != null)
310     {
311       if (res > sg.getStartRes())
312       {
313         sg.setEndRes(res);
314       }
315       else if (res < sg.getStartRes())
316       {
317         sg.setStartRes(res);
318       }
319     }
320     stretchingGroup = false;
321     ap.paintAlignment(false, false);
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)
328    * 
329    * @param evt
330    */
331   @Override
332   public void mouseDragged(MouseEvent evt)
333   {
334     mouseDragging = true;
335     ColumnSelection cs = av.getColumnSelection();
336     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
337
338     int res = (evt.getX() / av.getCharWidth())
339             + av.getRanges().getStartRes();
340     res = Math.max(0, res);
341     res = hidden.visibleToAbsoluteColumn(res);
342     res = Math.min(res, av.getAlignment().getWidth() - 1);
343     min = Math.min(res, min);
344     max = Math.max(res, max);
345
346     SequenceGroup sg = av.getSelectionGroup();
347     if (sg != null)
348     {
349       stretchingGroup = true;
350       cs.stretchGroup(res, sg, min, max);
351       ap.paintAlignment(false, false);
352     }
353   }
354
355   @Override
356   public void mouseEntered(MouseEvent evt)
357   {
358     if (mouseDragging)
359     {
360       mouseDragging = false;
361       ap.getSeqPanel().stopScrolling();
362     }
363   }
364
365   /**
366    * Action on leaving the panel bounds with mouse drag in progress is to start
367    * scrolling the alignment in the direction of the mouse. To restrict
368    * scrolling to left-right (not up-down), the y-value of the mouse position is
369    * replaced with zero.
370    */
371   @Override
372   public void mouseExited(MouseEvent evt)
373   {
374     if (mouseDragging)
375     {
376       ap.getSeqPanel().startScrolling(new Point(evt.getX(), 0));
377     }
378   }
379
380   @Override
381   public void mouseClicked(MouseEvent evt)
382   {
383   }
384
385   /**
386    * Creates a tooltip when the mouse is over a hidden columns marker
387    */
388   @Override
389   public void mouseMoved(MouseEvent evt)
390   {
391     this.setToolTipText(null);
392     reveal = null;
393     if (!av.hasHiddenColumns())
394     {
395       return;
396     }
397
398     int res = (evt.getX() / av.getCharWidth())
399             + av.getRanges().getStartRes();
400
401     reveal = av.getAlignment().getHiddenColumns()
402             .getRegionWithEdgeAtRes(res);
403
404     res = av.getAlignment().getHiddenColumns().visibleToAbsoluteColumn(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);  // BH 2019
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 }