JAL-3097 adjust viewport width on hiding columns
[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.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.SwingUtilities;
52 import javax.swing.ToolTipManager;
53
54 /**
55  * The panel containing the sequence ruler (when not in wrapped mode), and
56  * supports a range of mouse operations to select, hide or reveal columns.
57  */
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
119     if (x >= av.getAlignment().getWidth())
120     {
121       res = av.getAlignment().getWidth() - 1;
122     }
123     else
124     {
125       res = x;
126     }
127
128     min = res;
129     max = res;
130
131     if (evt.isPopupTrigger()) // Mac: mousePressed
132     {
133       rightMouseButtonPressed(evt, res);
134     }
135     else if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
136     {
137       /*
138        * defer right-mouse click handling to mouse up on Windows
139        * (where isPopupTrigger() will answer true)
140        * but accept Cmd-click on Mac which passes isRightMouseButton
141        */
142       return;
143     }
144     else
145     {
146       leftMouseButtonPressed(evt, res);
147     }
148   }
149
150   /**
151    * Handles right mouse button press. If pressed in a selected column, opens
152    * context menu for 'Hide Columns'. If pressed on a hidden columns marker,
153    * opens context menu for 'Reveal / Reveal All'. Else does nothing.
154    * 
155    * @param evt
156    * @param res
157    */
158   protected void rightMouseButtonPressed(MouseEvent evt, final int res)
159   {
160     JPopupMenu pop = new JPopupMenu();
161
162     /*
163      * grab the hidden range in case mouseMoved nulls it
164      */
165     final int[] hiddenRange = reveal;
166     if (hiddenRange != null)
167     {
168       JMenuItem item = new JMenuItem(
169               MessageManager.getString("label.reveal"));
170       item.addActionListener(new ActionListener()
171       {
172         @Override
173         public void actionPerformed(ActionEvent e)
174         {
175           av.showColumn(hiddenRange[0]);
176           reveal = null;
177           ap.updateLayout();
178           ap.paintAlignment(true, true);
179           av.sendSelection();
180         }
181       });
182       pop.add(item);
183
184       if (av.getAlignment().getHiddenColumns().hasMultiHiddenColumnRegions())
185       {
186         item = new JMenuItem(MessageManager.getString("action.reveal_all"));
187         item.addActionListener(new ActionListener()
188         {
189           @Override
190           public void actionPerformed(ActionEvent e)
191           {
192             av.showAllHiddenColumns();
193             reveal = null;
194             ap.updateLayout();
195             ap.paintAlignment(true, true);
196             av.sendSelection();
197           }
198         });
199         pop.add(item);
200       }
201       pop.show(this, evt.getX(), evt.getY());
202     }
203     else if (av.getColumnSelection().contains(res))
204     {
205       JMenuItem item = new JMenuItem(
206               MessageManager.getString("label.hide_columns"));
207       item.addActionListener(new ActionListener()
208       {
209         @Override
210         public void actionPerformed(ActionEvent e)
211         {
212           av.hideColumns(res, res);
213           if (av.getSelectionGroup() != null && av.getSelectionGroup()
214                   .getSize() == av.getAlignment().getHeight())
215           {
216             av.setSelectionGroup(null);
217           }
218
219           ap.updateLayout();
220           ap.paintAlignment(true, true);
221           av.sendSelection();
222         }
223       });
224       pop.add(item);
225       pop.show(this, evt.getX(), evt.getY());
226     }
227   }
228
229   /**
230    * Handles left mouse button press
231    * 
232    * @param evt
233    * @param res
234    */
235   protected void leftMouseButtonPressed(MouseEvent evt, final int res)
236   {
237     /*
238      * Ctrl-click/Cmd-click adds to the selection
239      * Shift-click extends the selection
240      */
241     // TODO Problem: right-click on Windows not reported until mouseReleased?!?
242     if (!Platform.isControlDown(evt) && !evt.isShiftDown())
243     {
244       av.getColumnSelection().clear();
245     }
246
247     av.getColumnSelection().addElement(res);
248     SequenceGroup sg = new SequenceGroup();
249     // try to be as quick as possible
250     SequenceI[] iVec = av.getAlignment().getSequencesArray();
251     for (int i = 0; i < iVec.length; i++)
252     {
253       sg.addSequence(iVec[i], false);
254       iVec[i] = null;
255     }
256     iVec = null;
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    * DOCUMENT ME!
278    * 
279    * @param evt
280    *          DOCUMENT ME!
281    */
282   @Override
283   public void mouseReleased(MouseEvent evt)
284   {
285     mouseDragging = false;
286
287     int res = (evt.getX() / av.getCharWidth())
288             + av.getRanges().getStartRes();
289
290     if (av.hasHiddenColumns())
291     {
292       res = av.getAlignment().getHiddenColumns()
293               .visibleToAbsoluteColumn(res);
294     }
295
296     if (res >= av.getAlignment().getWidth())
297     {
298       res = av.getAlignment().getWidth() - 1;
299     }
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     }
327     stretchingGroup = false;
328     ap.paintAlignment(false, false);
329     av.sendSelection();
330   }
331
332   /**
333    * Action on dragging the mouse in the scale panel is to expand or shrink the
334    * selection group range (including any hidden columns that it spans)
335    * 
336    * @param evt
337    */
338   @Override
339   public void mouseDragged(MouseEvent evt)
340   {
341     mouseDragging = true;
342     ColumnSelection cs = av.getColumnSelection();
343     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
344
345     int res = (evt.getX() / av.getCharWidth())
346             + av.getRanges().getStartRes();
347     res = Math.max(0, res);
348     res = hidden.visibleToAbsoluteColumn(res);
349     res = Math.min(res, av.getAlignment().getWidth() - 1);
350     min = Math.min(res, min);
351     max = Math.max(res, max);
352
353     SequenceGroup sg = av.getSelectionGroup();
354     if (sg != null)
355     {
356       stretchingGroup = true;
357       cs.stretchGroup(res, sg, min, max);
358       ap.paintAlignment(false, false);
359     }
360   }
361
362   @Override
363   public void mouseEntered(MouseEvent evt)
364   {
365     if (mouseDragging)
366     {
367       ap.getSeqPanel().scrollCanvas(null);
368     }
369   }
370
371   @Override
372   public void mouseExited(MouseEvent evt)
373   {
374     if (mouseDragging)
375     {
376       ap.getSeqPanel().scrollCanvas(evt);
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);
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 }