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