JAL-3253-applet JAL-3383
[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.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 @SuppressWarnings("serial")
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     res = Math.min(x, av.getAlignment().getWidth() - 1);
119
120     min = res;
121     max = res;
122
123     if (evt.isPopupTrigger()) // Mac: mousePressed
124     {
125       rightMouseButtonPressed(evt, res);
126       return;
127     }
128     if (Platform.isWinRightButton(evt))
129     {
130       /*
131        * defer right-mouse click handling to mouse up on Windows
132        * (where isPopupTrigger() will answer true)
133        * but accept Cmd-click on Mac which passes isRightMouseButton
134        */
135       return;
136     }
137     leftMouseButtonPressed(evt, res);
138   }
139
140   /**
141    * Handles right mouse button press. If pressed in a selected column, opens
142    * context menu for 'Hide Columns'. If pressed on a hidden columns marker,
143    * opens context menu for 'Reveal / Reveal All'. Else does nothing.
144    * 
145    * @param evt
146    * @param res
147    */
148   protected void rightMouseButtonPressed(MouseEvent evt, final int res)
149   {
150     JPopupMenu pop = buildPopupMenu(res);
151     if (pop.getSubElements().length > 0)
152     {
153       pop.show(this, evt.getX(), evt.getY());
154     }
155   }
156
157   /**
158    * Builds a popup menu with 'Hide' or 'Reveal' options, or both, or neither
159    * 
160    * @param res
161    *          column number (0..)
162    * @return
163    */
164   protected JPopupMenu buildPopupMenu(final int res)
165   {
166     JPopupMenu pop = new JPopupMenu();
167
168     /*
169      * logic here depends on 'reveal', set in mouseMoved;
170      * grab the hidden range in case mouseMoved nulls it later
171      */
172     final int[] hiddenRange = reveal;
173     if (hiddenRange != null)
174     {
175       JMenuItem item = new JMenuItem(
176               MessageManager.getString("label.reveal"));
177       item.addActionListener(new ActionListener()
178       {
179         @Override
180         public void actionPerformed(ActionEvent e)
181         {
182           av.showColumn(hiddenRange[0]);
183           reveal = null;
184           ap.updateLayout();
185           ap.paintAlignment(true, true);
186           av.sendSelection();
187         }
188       });
189       pop.add(item);
190
191       if (av.getAlignment().getHiddenColumns()
192               .hasMultiHiddenColumnRegions())
193       {
194         item = new JMenuItem(MessageManager.getString("action.reveal_all"));
195         item.addActionListener(new ActionListener()
196         {
197           @Override
198           public void actionPerformed(ActionEvent e)
199           {
200             av.showAllHiddenColumns();
201             reveal = null;
202             ap.updateLayout();
203             ap.paintAlignment(true, true);
204             av.sendSelection();
205           }
206         });
207         pop.add(item);
208       }
209     }
210
211     if (av.getColumnSelection().contains(res))
212     {
213       JMenuItem item = new JMenuItem(
214               MessageManager.getString("label.hide_columns"));
215       item.addActionListener(new ActionListener()
216       {
217         @Override
218         public void actionPerformed(ActionEvent e)
219         {
220           av.hideColumns(res, res);
221           if (av.getSelectionGroup() != null && av.getSelectionGroup()
222                   .getSize() == av.getAlignment().getHeight())
223           {
224             av.setSelectionGroup(null);
225           }
226
227           ap.updateLayout();
228           ap.paintAlignment(true, true);
229           av.sendSelection();
230         }
231       });
232       pop.add(item);
233     }
234     return pop;
235   }
236
237   /**
238    * Handles left mouse button press
239    * 
240    * @param evt
241    * @param res
242    */
243   protected void leftMouseButtonPressed(MouseEvent evt, final int res)
244   {
245     /*
246      * Ctrl-click/Cmd-click adds to the selection
247      * Shift-click extends the selection
248      */
249     // TODO Problem: right-click on Windows not reported until mouseReleased?!?
250     if (!Platform.isControlDown(evt) && !evt.isShiftDown())
251     {
252       av.getColumnSelection().clear();
253     }
254
255     av.getColumnSelection().addElement(res);
256     SequenceGroup sg = new SequenceGroup(av.getAlignment().getSequences());
257     sg.setStartRes(res);
258     sg.setEndRes(res);
259
260     if (evt.isShiftDown())
261     {
262       int min = Math.min(av.getColumnSelection().getMin(), res);
263       int max = Math.max(av.getColumnSelection().getMax(), res);
264       for (int i = min; i < max; i++)
265       {
266         av.getColumnSelection().addElement(i);
267       }
268       sg.setStartRes(min);
269       sg.setEndRes(max);
270     }
271     av.setSelectionGroup(sg);
272     ap.paintAlignment(false, false);
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     av.sendSelection();
338   }
339
340   /**
341    * Action on dragging the mouse in the scale panel is to expand or shrink the
342    * selection group range (including any hidden columns that it spans). Note
343    * that the selection is only broadcast at the start of the drag (on
344    * mousePressed) and at the end (on mouseReleased), to avoid overload
345    * redrawing of other views.
346    * 
347    * @param evt
348    */
349   @Override
350   public void mouseDragged(MouseEvent evt)
351   {
352     mouseDragging = true;
353     ColumnSelection cs = av.getColumnSelection();
354     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
355
356     int res = (evt.getX() / av.getCharWidth())
357             + av.getRanges().getStartRes();
358     res = Math.max(0, res);
359     res = hidden.visibleToAbsoluteColumn(res);
360     res = Math.min(res, av.getAlignment().getWidth() - 1);
361     min = Math.min(res, min);
362     max = Math.max(res, max);
363
364     SequenceGroup sg = av.getSelectionGroup();
365     if (sg != null)
366     {
367       stretchingGroup = true;
368       cs.stretchGroup(res, sg, min, max);
369       ap.paintAlignment(false, false);
370     }
371   }
372
373   @Override
374   public void mouseEntered(MouseEvent evt)
375   {
376     if (mouseDragging)
377     {
378       mouseDragging = false;
379       ap.getSeqPanel().stopScrolling();
380     }
381   }
382
383   /**
384    * Action on leaving the panel bounds with mouse drag in progress is to start
385    * scrolling the alignment in the direction of the mouse. To restrict
386    * scrolling to left-right (not up-down), the y-value of the mouse position is
387    * replaced with zero.
388    */
389   @Override
390   public void mouseExited(MouseEvent evt)
391   {
392     if (mouseDragging)
393     {
394       ap.getSeqPanel().startScrolling(new Point(evt.getX(), 0));
395     }
396   }
397
398   @Override
399   public void mouseClicked(MouseEvent evt)
400   {
401   }
402
403   /**
404    * Creates a tooltip when the mouse is over a hidden columns marker
405    */
406   @Override
407   public void mouseMoved(MouseEvent evt)
408   {
409     this.setToolTipText(null);
410     reveal = null;
411     if (!av.hasHiddenColumns())
412     {
413       return;
414     }
415
416     int res = (evt.getX() / av.getCharWidth())
417             + av.getRanges().getStartRes();
418
419     reveal = av.getAlignment().getHiddenColumns()
420             .getRegionWithEdgeAtRes(res);
421
422     res = av.getAlignment().getHiddenColumns().visibleToAbsoluteColumn(res);
423
424     ToolTipManager.sharedInstance().registerComponent(this);
425     this.setToolTipText(
426             MessageManager.getString("label.reveal_hidden_columns"));
427     repaint();
428   }
429
430   /**
431    * DOCUMENT ME!
432    * 
433    * @param g
434    *          DOCUMENT ME!
435    */
436   @Override
437   public void paintComponent(Graphics g)
438   {
439
440     // super.paintComponent(g); // BH 2019
441
442     /*
443      * shouldn't get called in wrapped mode as the scale above is
444      * drawn instead by SeqCanvas.drawNorthScale
445      */
446     if (!av.getWrapAlignment())
447     {
448       drawScale(g, av.getRanges().getStartRes(), av.getRanges().getEndRes(),
449               getWidth(), getHeight());
450     }
451   }
452
453   // scalewidth will normally be screenwidth,
454   public void drawScale(Graphics g, int startx, int endx, int width,
455           int height)
456   {
457     Graphics2D gg = (Graphics2D) g;
458     gg.setFont(av.getFont());
459
460     if (av.antiAlias)
461     {
462       gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
463               RenderingHints.VALUE_ANTIALIAS_ON);
464     }
465
466     // Fill in the background
467     gg.setColor(Color.white);
468     gg.fillRect(0, 0, width, height);
469     gg.setColor(Color.black);
470
471     // Fill the selected columns
472     ColumnSelection cs = av.getColumnSelection();
473     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
474     int avCharWidth = av.getCharWidth();
475     int avCharHeight = av.getCharHeight();
476
477     if (cs != null)
478     {
479       gg.setColor(new Color(220, 0, 0));
480
481       for (int sel : cs.getSelected())
482       {
483         // TODO: JAL-2001 - provide a fast method to list visible selected in a
484         // given range
485
486         if (av.hasHiddenColumns())
487         {
488           if (hidden.isVisible(sel))
489           {
490             sel = hidden.absoluteToVisibleColumn(sel);
491           }
492           else
493           {
494             continue;
495           }
496         }
497
498         if ((sel >= startx) && (sel <= endx))
499         {
500           gg.fillRect((sel - startx) * avCharWidth, 0, avCharWidth,
501                   getHeight());
502         }
503       }
504     }
505
506     int widthx = 1 + endx - startx;
507
508     FontMetrics fm = gg.getFontMetrics(av.getFont());
509     int y = avCharHeight;
510     int yOf = fm.getDescent();
511     y -= yOf;
512     if (av.hasHiddenColumns())
513     {
514       // draw any hidden column markers
515       gg.setColor(Color.blue);
516       int res;
517
518       if (av.getShowHiddenMarkers())
519       {
520         Iterator<Integer> it = hidden.getStartRegionIterator(startx,
521                 startx + widthx + 1);
522         while (it.hasNext())
523         {
524           res = it.next() - startx;
525
526           gg.fillPolygon(
527                   new int[]
528                   { -1 + res * avCharWidth - avCharHeight / 4,
529                       -1 + res * avCharWidth + avCharHeight / 4,
530                       -1 + res * avCharWidth },
531                   new int[]
532                   { y, y, y + 2 * yOf }, 3);
533         }
534       }
535     }
536     // Draw the scale numbers
537     gg.setColor(Color.black);
538
539     int maxX = 0;
540     List<ScaleMark> marks = new ScaleRenderer().calculateMarks(av, startx,
541             endx);
542
543     for (ScaleMark mark : marks)
544     {
545       boolean major = mark.major;
546       int mpos = mark.column; // (i - startx - 1)
547       String mstring = mark.text;
548       if (mstring != null)
549       {
550         if (mpos * avCharWidth > maxX)
551         {
552           gg.drawString(mstring, mpos * avCharWidth, y);
553           maxX = (mpos + 2) * avCharWidth + fm.stringWidth(mstring);
554         }
555       }
556       if (major)
557       {
558         gg.drawLine((mpos * avCharWidth) + (avCharWidth / 2), y + 2,
559                 (mpos * avCharWidth) + (avCharWidth / 2), y + (yOf * 2));
560       }
561       else
562       {
563         gg.drawLine((mpos * avCharWidth) + (avCharWidth / 2), y + yOf,
564                 (mpos * avCharWidth) + (avCharWidth / 2), y + (yOf * 2));
565       }
566     }
567   }
568
569   @Override
570   public void propertyChange(PropertyChangeEvent evt)
571   {
572     switch (evt.getPropertyName())
573     {
574     case ViewportRanges.STARTRES:
575     case ViewportRanges.STARTRESANDSEQ:
576     case ViewportRanges.MOVE_VIEWPORT:
577       // scroll event, repaint panel
578       // original comment:
579       // Call repaint on alignment panel so that repaints from other alignment
580       // panel components can be aggregated. Otherwise performance of the
581       // overview
582       // window and others may be adversely affected.
583
584       // TODO: check this?
585       // BH: This is actually quite strange. AlignmentPanel is taking care of
586       // all of this with fast paint, so why indirectly trigger a repaint from
587       // the ScalePanel? Where do we see this behavior necessary?
588       // I have set this to check for a trigger from some other ViewportRanges,
589       // but I don't actually think that is possible.
590
591       if (evt.getSource() != av.getRanges())
592       {
593         av.getAlignPanel().repaint();
594       }
595       break;
596     }
597   }
598
599   public boolean isMouseDragging()
600   {
601     return mouseDragging;
602   }
603
604 }