JAL-3446 JAL-3401 from JAL-3253 HoldRepaint and SeqCanvas sizing issues.
[jalview.git] / src / jalview / gui / IdCanvas.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.SequenceI;
24 import jalview.viewmodel.ViewportListenerI;
25 import jalview.viewmodel.ViewportRanges;
26
27 import java.awt.BorderLayout;
28 import java.awt.Color;
29 import java.awt.Font;
30 import java.awt.FontMetrics;
31 import java.awt.Graphics;
32 import java.awt.Graphics2D;
33 import java.awt.RenderingHints;
34 import java.awt.image.BufferedImage;
35 import java.beans.PropertyChangeEvent;
36 import java.util.List;
37
38 import javax.swing.JPanel;
39
40 /**
41  * DOCUMENT ME!
42  * 
43  * @author $author$
44  * @version $Revision$
45  */
46 public class IdCanvas extends JPanel implements ViewportListenerI
47 {
48   protected AlignViewport av;
49
50   protected boolean showScores = true;
51
52   protected int maxIdLength = -1;
53
54   protected String maxIdStr = null;
55
56   BufferedImage image;
57
58 //  Graphics2D gg;
59
60   int imgHeight = 0;
61
62   private boolean fastPaint = false;
63
64   List<SequenceI> searchResults;
65
66   AnnotationPanel ap;
67
68   private Font idfont;
69
70   /**
71    * Creates a new IdCanvas object.
72    * 
73    * @param av
74    *          DOCUMENT ME!
75    */
76   public IdCanvas(AlignViewport av)
77   {
78     setLayout(new BorderLayout());
79     this.av = av;
80     PaintRefresher.Register(this, av.getSequenceSetId());
81     av.getRanges().addPropertyChangeListener(this);
82     }
83
84   /**
85    * DOCUMENT ME!
86    * 
87    * @param g
88    *          DOCUMENT ME!
89    * @param hiddenRows
90    *          true - check and display hidden row marker if need be
91    * @param s
92    *          DOCUMENT ME!
93    * @param i
94    *          DOCUMENT ME!
95    * @param starty
96    *          DOCUMENT ME!
97    * @param ypos
98    *          DOCUMENT ME!
99    */
100   public void drawIdString(Graphics2D g, boolean hiddenRows, SequenceI s,
101           int i, int starty, int ypos)
102   {
103     int xPos = 0;
104     int panelWidth = getWidth();
105     int charHeight = av.getCharHeight();
106
107     if ((searchResults != null) && searchResults.contains(s))
108     {
109       g.setColor(Color.black);
110       g.fillRect(0, ((i - starty) * charHeight) + ypos, getWidth(),
111               charHeight);
112       g.setColor(Color.white);
113     }
114     else if ((av.getSelectionGroup() != null)
115             && av.getSelectionGroup().getSequences(null).contains(s))
116     {
117       g.setColor(Color.lightGray);
118       g.fillRect(0, ((i - starty) * charHeight) + ypos, getWidth(),
119               charHeight);
120       g.setColor(Color.white);
121     }
122     else
123     {
124       g.setColor(av.getSequenceColour(s));
125       g.fillRect(0, ((i - starty) * charHeight) + ypos, getWidth(),
126               charHeight);
127       g.setColor(Color.black);
128     }
129
130     if (av.isRightAlignIds())
131     {
132       FontMetrics fm = g.getFontMetrics();
133       xPos = panelWidth
134               - fm.stringWidth(s.getDisplayId(av.getShowJVSuffix())) - 4;
135     }
136
137     g.drawString(s.getDisplayId(av.getShowJVSuffix()), xPos,
138             (((i - starty + 1) * charHeight) + ypos) - (charHeight / 5));
139
140     // JAL-3253-applet was just hiddenRows here. ccfc48e (gmungoc) added getShowHiddenMarkers test
141     if (hiddenRows && av.getShowHiddenMarkers())
142     {
143       drawMarker(g, av, i, starty, ypos);
144     }
145
146   }
147
148   /**
149    * DOCUMENT ME!
150    * 
151    * @param vertical
152    *          DOCUMENT ME!
153    */
154   public void fastPaint(int vertical)
155   {
156
157     /*
158      * for now, not attempting fast paint of wrapped ids...
159      */
160     if (image == null || av.getWrapAlignment())
161     {
162       repaint();
163
164       return;
165     }
166
167     ViewportRanges ranges = av.getRanges();
168
169     Graphics2D gg = image.createGraphics();
170     gg.copyArea(0, 0, getWidth(), imgHeight, 0,
171             -vertical * av.getCharHeight());
172
173     int ss = ranges.getStartSeq();
174     int es = ranges.getEndSeq();
175     int transY = 0;
176
177     if (vertical > 0) // scroll down
178     {
179       ss = es - vertical;
180
181       if (ss < ranges.getStartSeq())
182       { // ie scrolling too fast, more than a page at a time
183         ss = ranges.getStartSeq();
184       }
185       else
186       {
187         transY = imgHeight - ((vertical + 1) * av.getCharHeight());
188       }
189     }
190     else if (vertical < 0) // scroll up
191     {
192       es = ss - vertical;
193
194       if (es > ranges.getEndSeq())
195       {
196         es = ranges.getEndSeq();
197       }
198     }
199
200     gg.translate(0, transY);
201
202     drawIds(gg, av, ss, es, searchResults);
203
204     gg.translate(0, -transY);
205
206     gg.dispose();
207     
208     fastPaint = true;
209
210     // Call repaint on alignment panel so that repaints from other alignment
211     // panel components can be aggregated. Otherwise performance of the overview
212     // window and others may be adversely affected.
213     av.getAlignPanel().repaint();
214   }
215
216   /**
217    * DOCUMENT ME!
218    * 
219    * @param g
220    *          DOCUMENT ME!
221    */
222   @Override
223   public void paintComponent(Graphics g)
224   {
225     if (av.getAlignPanel().getHoldRepaint())
226     {
227       return;
228     }
229
230     g.setColor(Color.white);
231     g.fillRect(0, 0, getWidth(), getHeight());
232     
233     if (fastPaint)
234     {
235       fastPaint = false;
236       g.drawImage(image, 0, 0, this);
237     
238       return;
239     }
240     
241     int oldHeight = imgHeight;
242     
243     imgHeight = getHeight();
244     imgHeight -= (imgHeight % av.getCharHeight());
245     
246     if (imgHeight < 1)
247     {
248       return;
249     }
250     
251     if (oldHeight != imgHeight || image.getWidth(this) != getWidth())
252     {
253       image = new BufferedImage(getWidth(), imgHeight,
254                 BufferedImage.TYPE_INT_RGB);
255     }
256     
257     Graphics2D gg = image.createGraphics();
258     
259     // Fill in the background
260     gg.setColor(Color.white);
261     gg.fillRect(0, 0, getWidth(), imgHeight);
262     
263     drawIds(gg, av, av.getRanges().getStartSeq(), av.getRanges().getEndSeq(), searchResults);
264
265     gg.dispose();
266     
267     g.drawImage(image, 0, 0, this);
268   }
269
270   /**
271    * Draws sequence ids from sequence index startSeq to endSeq (inclusive), with
272    * the font and other display settings configured on the viewport. Ids of
273    * sequences included in the selection are coloured grey, otherwise the
274    * current id colour for the sequence id is used.
275    * 
276    * @param g
277    * @param alignViewport
278    * @param startSeq
279    * @param endSeq
280    * @param selection
281    */
282   void drawIds(Graphics2D g, AlignViewport alignViewport, final int startSeq,
283           final int endSeq, List<SequenceI> selection)
284   {
285     Font font = alignViewport.getFont();
286     if (alignViewport.isSeqNameItalics())
287     {
288       setIdfont(new Font(font.getName(), Font.ITALIC,
289               font.getSize()));
290     }
291     else
292     {
293       setIdfont(font);
294     }
295
296     g.setFont(getIdfont());
297     FontMetrics fm = g.getFontMetrics();
298
299     if (alignViewport.antiAlias)
300     {
301       g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
302               RenderingHints.VALUE_ANTIALIAS_ON);
303     }
304
305     Color currentColor = Color.white;
306     Color currentTextColor = Color.black;
307
308     boolean hasHiddenRows = alignViewport.hasHiddenRows();
309
310     if (alignViewport.getWrapAlignment())
311     {
312       drawIdsWrapped(g, alignViewport, startSeq, getHeight());
313       return;
314     }
315
316     // Now draw the id strings
317     int panelWidth = getWidth();
318     int xPos = 0;
319
320     // Now draw the id strings
321     for (int i = startSeq; i <= endSeq; i++)
322     {
323       SequenceI sequence = alignViewport.getAlignment().getSequenceAt(i);
324
325       if (sequence == null)
326       {
327         continue;
328       }
329
330       if (hasHiddenRows || alignViewport.isDisplayReferenceSeq())
331       {
332         g.setFont(getHiddenFont(sequence, alignViewport));
333       }
334
335       // Selected sequence colours
336       if (selection != null && selection.contains(sequence))
337       {
338         currentColor = Color.black;
339         currentTextColor = Color.white;
340       }
341       else if ((alignViewport.getSelectionGroup() != null) && alignViewport
342               .getSelectionGroup().getSequences(null).contains(sequence))
343       {
344         currentColor = Color.lightGray;
345         currentTextColor = Color.black;
346       }
347       else
348       {
349         currentColor = alignViewport.getSequenceColour(sequence);
350         currentTextColor = Color.black;
351       }
352
353       g.setColor(currentColor);
354
355       int charHeight = alignViewport.getCharHeight();
356       g.fillRect(0, (i - startSeq) * charHeight,
357               getWidth(), charHeight);
358
359       g.setColor(currentTextColor);
360
361       String string = sequence
362               .getDisplayId(alignViewport.getShowJVSuffix());
363
364       if (alignViewport.isRightAlignIds())
365       {
366         xPos = panelWidth - fm.stringWidth(string) - 4;
367       }
368
369       g.drawString(string, xPos, (((i - startSeq) * charHeight) + charHeight)
370               - (charHeight / 5));
371
372       if (hasHiddenRows && av.getShowHiddenMarkers())
373       {
374         drawMarker(g, alignViewport, i, startSeq, 0);
375       }
376     }
377   }
378
379   /**
380    * Draws sequence ids, and annotation labels if annotations are shown, in
381    * wrapped mode
382    * 
383    * @param g
384    * @param alignViewport
385    * @param startSeq
386    */
387   void drawIdsWrapped(Graphics2D g, AlignViewport alignViewport,
388           int startSeq, int pageHeight)
389   {
390     int alignmentWidth = alignViewport.getAlignment().getWidth();
391     final int alheight = alignViewport.getAlignment().getHeight();
392
393     
394 //    int annotationHeight = 0;
395
396     /* (former)
397      * assumption: SeqCanvas.calculateWrappedGeometry has been called
398      * 
399      * was based on the fact that SeqCanvas was added as a child prior to IdCanvas, 
400      * and children are processed in order of addition.
401      * 
402      * It's probably fine. But...
403      * 
404      */
405     SeqCanvas seqCanvas = alignViewport.getAlignPanel()
406             .getSeqPanel().seqCanvas;
407     // ...better: let's call it now
408     seqCanvas.calculateWrappedGeometry();
409
410     final int charHeight = alignViewport.getCharHeight();
411
412     AnnotationLabels labels = null;
413     if (alignViewport.isShowAnnotation())
414     {
415         // BH when was ap == null?
416       if (ap == null)
417       {
418         ap = new AnnotationPanel(alignViewport);
419       }
420 //      annotationHeight = ap.adjustPanelHeight();
421       labels = new AnnotationLabels(alignViewport);
422     }
423
424 //    int hgap = charHeight;
425 //    if (alignViewport.getScaleAboveWrapped())
426 //    {
427 //      hgap += charHeight;
428 //    }
429 //
430 //    /*
431 //     * height of alignment + gap + annotations (if shown)
432 //     */
433 //    int cHeight = alheight * charHeight + hgap
434 //            + annotationHeight;
435 //
436     ViewportRanges ranges = alignViewport.getRanges();
437
438     int rowSize = ranges.getViewportWidth();
439
440     /*
441      * draw repeating sequence ids until out of sequence data or
442      * out of visible space, whichever comes first
443      */
444     boolean hasHiddenRows = alignViewport.hasHiddenRows();
445     int ypos = seqCanvas.wrappedSpaceAboveAlignment;
446     int rowStartRes = ranges.getStartRes();
447     while ((ypos <= pageHeight) && (rowStartRes < alignmentWidth))
448     {
449       for (int i = startSeq; i < alheight; i++)
450       {
451         SequenceI s = alignViewport.getAlignment().getSequenceAt(i);
452         if (hasHiddenRows || alignViewport.isDisplayReferenceSeq())
453         {
454           g.setFont(getHiddenFont(s, alignViewport));
455         }
456         else
457         {
458           g.setFont(getIdfont());
459         }
460         drawIdString(g, hasHiddenRows, s, i, 0, ypos);
461       }
462
463       if (labels != null && alignViewport.isShowAnnotation())
464       {
465         g.translate(0, ypos + (alheight * charHeight));
466         labels.drawComponent(g, getWidth());
467         g.translate(0, -ypos - (alheight * charHeight));
468       }
469
470       ypos += seqCanvas.wrappedRepeatHeightPx;
471       rowStartRes += rowSize;
472     }
473   }
474
475   /**
476    * Draws a marker (a blue right-pointing triangle) between sequences to
477    * indicate hidden sequences.
478    * 
479    * @param g
480    * @param alignViewport
481    * @param seqIndex
482    * @param starty
483    * @param yoffset
484    */
485   void drawMarker(Graphics2D g, AlignViewport alignViewport, int seqIndex, int starty, int yoffset)
486   {
487     SequenceI[] hseqs = alignViewport.getAlignment()
488             .getHiddenSequences().hiddenSequences;
489     // Use this method here instead of calling hiddenSeq adjust
490     // 3 times.
491     int hSize = hseqs.length;
492
493     int hiddenIndex = seqIndex;
494     int lastIndex = seqIndex - 1;
495     int nextIndex = seqIndex + 1;
496
497     for (int j = 0; j < hSize; j++)
498     {
499       if (hseqs[j] != null)
500       {
501         if (j - 1 < hiddenIndex)
502         {
503           hiddenIndex++;
504         }
505         if (j - 1 < lastIndex)
506         {
507           lastIndex++;
508         }
509         if (j - 1 < nextIndex)
510         {
511           nextIndex++;
512         }
513       }
514     }
515
516     /*
517      * are we below or above the hidden sequences?
518      */
519     boolean below = (hiddenIndex > lastIndex + 1);
520     boolean above = (nextIndex > hiddenIndex + 1);
521
522     g.setColor(Color.blue);
523     int charHeight = av.getCharHeight();
524
525     /*
526      * vertices of the triangle, below or above hidden seqs
527      */
528     int[] xPoints = new int[]
529     { getWidth() - charHeight,
530         getWidth() - charHeight, getWidth() };
531     int yShift = seqIndex - starty;
532
533     if (below)
534     {
535       int[] yPoints = new int[] { yShift * charHeight + yoffset,
536           yShift * charHeight + yoffset + charHeight / 4,
537           yShift * charHeight + yoffset };
538       g.fillPolygon(xPoints, yPoints, 3);
539     }
540     if (above)
541     {
542       yShift++;
543       int[] yPoints = new int[] { yShift * charHeight + yoffset,
544           yShift * charHeight + yoffset - charHeight / 4,
545           yShift * charHeight + yoffset };
546       g.fillPolygon(xPoints, yPoints, 3);
547     }
548   }
549
550   /**
551    * Answers the standard sequence id font, or a bold font if the sequence is
552    * set as reference or a hidden group representative
553    * 
554    * @param seq
555    * @param alignViewport
556    * @return
557    */
558   private Font getHiddenFont(SequenceI seq, AlignViewport alignViewport)
559   {
560     if (av.isReferenceSeq(seq) || av.isHiddenRepSequence(seq))
561     {
562       return new Font(av.getFont().getName(), Font.BOLD,
563               av.getFont().getSize());
564     }
565     return getIdfont();
566   }
567
568   /**
569    * DOCUMENT ME!
570    * 
571    * @param list
572    *          DOCUMENT ME!
573    */
574   public void setHighlighted(List<SequenceI> list)
575   {
576     searchResults = list;
577     repaint();
578   }
579
580   public Font getIdfont()
581   {
582     return idfont;
583   }
584
585   public void setIdfont(Font idfont)
586   {
587     this.idfont = idfont;
588   }
589
590   /**
591    * Respond to viewport range changes (e.g. alignment panel was scrolled). Both
592    * scrolling and resizing change viewport ranges. Scrolling changes both start
593    * and end points, but resize only changes end values. Here we only want to
594    * fastpaint on a scroll, with resize using a normal paint, so scroll events
595    * are identified as changes to the horizontal or vertical start value.
596    * <p>
597    * In unwrapped mode, only responds to a vertical scroll, as horizontal scroll
598    * leaves sequence ids unchanged. In wrapped mode, only vertical scroll is
599    * provided, but it generates a change of "startres" which does require an
600    * update here.
601    */
602   @Override
603   public void propertyChange(PropertyChangeEvent evt)
604   {
605     String propertyName = evt.getPropertyName();
606     switch (propertyName)
607     {
608     case ViewportRanges.STARTSEQ:
609       fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
610       break;
611     case ViewportRanges.STARTRES:
612       if (av.getWrapAlignment())
613       {
614         fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
615       }
616       break;
617     case ViewportRanges.STARTRESANDSEQ:
618       fastPaint(((int[]) evt.getNewValue())[1]
619               - ((int[]) evt.getOldValue())[1]);
620       break;
621     case ViewportRanges.MOVE_VIEWPORT:
622       repaint();
623       break;
624     default:
625     }
626   }
627
628   /**
629    * Clears the flag that allows a 'fast paint' on the next repaint, so
630    * requiring a full repaint
631    */
632   public void setNoFastPaint()
633   {
634     fastPaint = false;
635   }
636 }