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