JAL-3673 make sure font metrics are updated if dealing with reference sequence font !
[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 java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Font;
26 import java.awt.FontMetrics;
27 import java.awt.Graphics;
28 import java.awt.Graphics2D;
29 import java.awt.RenderingHints;
30 import java.awt.image.BufferedImage;
31 import java.beans.PropertyChangeEvent;
32 import java.util.List;
33
34 import javax.swing.JPanel;
35
36 import jalview.datamodel.SequenceI;
37 import jalview.viewmodel.ViewportListenerI;
38 import jalview.viewmodel.ViewportRanges;
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   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     if (hiddenRows && av.getShowHiddenMarkers())
141     {
142       drawMarker(g, av, i, starty, ypos);
143     }
144
145   }
146
147   /**
148    * DOCUMENT ME!
149    * 
150    * @param vertical
151    *          DOCUMENT ME!
152    */
153   public void fastPaint(int vertical)
154   {
155     /*
156      * for now, not attempting fast paint of wrapped ids...
157      */
158     if (gg == null || av.getWrapAlignment())
159     {
160       repaint();
161
162       return;
163     }
164
165     ViewportRanges ranges = av.getRanges();
166
167     gg.copyArea(0, 0, getWidth(), imgHeight, 0,
168             -vertical * av.getCharHeight());
169
170     int ss = ranges.getStartSeq();
171     int es = ranges.getEndSeq();
172     int transY = 0;
173
174     if (vertical > 0) // scroll down
175     {
176       ss = es - vertical;
177
178       if (ss < ranges.getStartSeq())
179       { // ie scrolling too fast, more than a page at a time
180         ss = ranges.getStartSeq();
181       }
182       else
183       {
184         transY = imgHeight - ((vertical + 1) * av.getCharHeight());
185       }
186     }
187     else if (vertical < 0) // scroll up
188     {
189       es = ss - vertical;
190
191       if (es > ranges.getEndSeq())
192       {
193         es = ranges.getEndSeq();
194       }
195     }
196
197     gg.translate(0, transY);
198
199     drawIds(gg, av, ss, es, searchResults);
200
201     gg.translate(0, -transY);
202
203     fastPaint = true;
204
205     // Call repaint on alignment panel so that repaints from other alignment
206     // panel components can be aggregated. Otherwise performance of the overview
207     // window and others may be adversely affected.
208     av.getAlignPanel().repaint();
209   }
210
211   /**
212    * DOCUMENT ME!
213    * 
214    * @param g
215    *          DOCUMENT ME!
216    */
217   @Override
218   public void paintComponent(Graphics g)
219   {
220     super.paintComponent(g);
221
222     g.setColor(Color.white);
223     g.fillRect(0, 0, getWidth(), getHeight());
224     
225     if (fastPaint)
226     {
227       fastPaint = false;
228       g.drawImage(image, 0, 0, this);
229     
230       return;
231     }
232     
233     int oldHeight = imgHeight;
234     
235     imgHeight = getHeight();
236     imgHeight -= (imgHeight % av.getCharHeight());
237     
238     if (imgHeight < 1)
239     {
240       return;
241     }
242     
243     if (oldHeight != imgHeight || image.getWidth(this) != getWidth())
244     {
245         image = new BufferedImage(getWidth(), imgHeight,
246                 BufferedImage.TYPE_INT_RGB);
247     }
248     
249     gg = (Graphics2D) image.getGraphics();
250     
251     // Fill in the background
252     gg.setColor(Color.white);
253     gg.fillRect(0, 0, getWidth(), imgHeight);
254     
255     drawIds(gg, av, av.getRanges().getStartSeq(), av.getRanges().getEndSeq(), searchResults);
256     
257     g.drawImage(image, 0, 0, this);
258   }
259
260   /**
261    * Draws sequence ids from sequence index startSeq to endSeq (inclusive), with
262    * the font and other display settings configured on the viewport. Ids of
263    * sequences included in the selection are coloured grey, otherwise the
264    * current id colour for the sequence id is used.
265    * 
266    * @param g
267    * @param alignViewport
268    * @param startSeq
269    * @param endSeq
270    * @param selection
271    */
272   void drawIds(Graphics2D g, AlignViewport alignViewport, final int startSeq,
273           final int endSeq, List<SequenceI> selection)
274   {
275     Font font = alignViewport.getFont();
276     if (alignViewport.isSeqNameItalics())
277     {
278       setIdfont(new Font(font.getName(), Font.ITALIC,
279               font.getSize()));
280     }
281     else
282     {
283       setIdfont(font);
284     }
285
286     g.setFont(getIdfont());
287     FontMetrics fm = g.getFontMetrics();
288
289     if (alignViewport.antiAlias)
290     {
291       g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
292               RenderingHints.VALUE_ANTIALIAS_ON);
293     }
294
295     Color currentColor = Color.white;
296     Color currentTextColor = Color.black;
297
298     boolean hasHiddenRows = alignViewport.hasHiddenRows();
299
300     if (alignViewport.getWrapAlignment())
301     {
302       drawIdsWrapped(g, alignViewport, startSeq, getHeight());
303       return;
304     }
305
306     // Now draw the id strings
307     int panelWidth = getWidth();
308     int xPos = 0;
309
310     // Now draw the id strings
311     for (int i = startSeq; i <= endSeq; i++)
312     {
313       SequenceI sequence = alignViewport.getAlignment().getSequenceAt(i);
314
315       if (sequence == null)
316       {
317         continue;
318       }
319
320       if (hasHiddenRows || alignViewport.isDisplayReferenceSeq())
321       {
322         g.setFont(getHiddenFont(sequence, alignViewport));
323         fm = g.getFontMetrics();
324       }
325
326       // Selected sequence colours
327       if (selection != null && selection.contains(sequence))
328       {
329         currentColor = Color.black;
330         currentTextColor = Color.white;
331       }
332       else if ((alignViewport.getSelectionGroup() != null) && alignViewport
333               .getSelectionGroup().getSequences(null).contains(sequence))
334       {
335         currentColor = Color.lightGray;
336         currentTextColor = Color.black;
337       }
338       else
339       {
340         currentColor = alignViewport.getSequenceColour(sequence);
341         currentTextColor = Color.black;
342       }
343
344       g.setColor(currentColor);
345
346       int charHeight = alignViewport.getCharHeight();
347       g.fillRect(0, (i - startSeq) * charHeight,
348               getWidth(), charHeight);
349
350       g.setColor(currentTextColor);
351
352       String string = sequence
353               .getDisplayId(alignViewport.getShowJVSuffix());
354
355       if (alignViewport.isRightAlignIds())
356       {
357         xPos = panelWidth - fm.stringWidth(string) - 4;
358       }
359
360       g.drawString(string, xPos, (((i - startSeq) * charHeight) + charHeight)
361               - (charHeight / 5));
362
363       if (hasHiddenRows && av.getShowHiddenMarkers())
364       {
365         drawMarker(g, alignViewport, i, startSeq, 0);
366       }
367     }
368   }
369
370   /**
371    * Draws sequence ids, and annotation labels if annotations are shown, in
372    * wrapped mode
373    * 
374    * @param g
375    * @param alignViewport
376    * @param startSeq
377    */
378   void drawIdsWrapped(Graphics2D g, AlignViewport alignViewport,
379           int startSeq, int pageHeight)
380   {
381     int alignmentWidth = alignViewport.getAlignment().getWidth();
382     final int alheight = alignViewport.getAlignment().getHeight();
383
384     /*
385      * assumption: SeqCanvas.calculateWrappedGeometry has been called
386      */
387     SeqCanvas seqCanvas = alignViewport.getAlignPanel()
388             .getSeqPanel().seqCanvas;
389
390     final int charHeight = alignViewport.getCharHeight();
391
392     AnnotationLabels labels = null;
393     if (alignViewport.isShowAnnotation())
394     {
395       labels = new AnnotationLabels(alignViewport);
396     }
397
398     ViewportRanges ranges = alignViewport.getRanges();
399
400     int rowSize = ranges.getViewportWidth();
401
402     /*
403      * draw repeating sequence ids until out of sequence data or
404      * out of visible space, whichever comes first
405      */
406     boolean hasHiddenRows = alignViewport.hasHiddenRows();
407     int ypos = seqCanvas.wrappedSpaceAboveAlignment;
408     int rowStartRes = ranges.getStartRes();
409     while ((ypos <= pageHeight) && (rowStartRes < alignmentWidth))
410     {
411       for (int i = startSeq; i < alheight; i++)
412       {
413         SequenceI s = alignViewport.getAlignment().getSequenceAt(i);
414         if (hasHiddenRows || alignViewport.isDisplayReferenceSeq())
415         {
416           g.setFont(getHiddenFont(s, alignViewport));
417         }
418         else
419         {
420           g.setFont(getIdfont());
421         }
422         drawIdString(g, hasHiddenRows, s, i, 0, ypos);
423       }
424
425       if (labels != null && alignViewport.isShowAnnotation())
426       {
427         g.translate(0, ypos + (alheight * charHeight));
428         labels.drawComponent(g, getWidth());
429         g.translate(0, -ypos - (alheight * charHeight));
430       }
431
432       ypos += seqCanvas.wrappedRepeatHeightPx;
433       rowStartRes += rowSize;
434     }
435   }
436
437   /**
438    * Draws a marker (a blue right-pointing triangle) between sequences to
439    * indicate hidden sequences.
440    * 
441    * @param g
442    * @param alignViewport
443    * @param seqIndex
444    * @param starty
445    * @param yoffset
446    */
447   void drawMarker(Graphics2D g, AlignViewport alignViewport, int seqIndex, int starty, int yoffset)
448   {
449     SequenceI[] hseqs = alignViewport.getAlignment()
450             .getHiddenSequences().hiddenSequences;
451     // Use this method here instead of calling hiddenSeq adjust
452     // 3 times.
453     int hSize = hseqs.length;
454
455     int hiddenIndex = seqIndex;
456     int lastIndex = seqIndex - 1;
457     int nextIndex = seqIndex + 1;
458
459     for (int j = 0; j < hSize; j++)
460     {
461       if (hseqs[j] != null)
462       {
463         if (j - 1 < hiddenIndex)
464         {
465           hiddenIndex++;
466         }
467         if (j - 1 < lastIndex)
468         {
469           lastIndex++;
470         }
471         if (j - 1 < nextIndex)
472         {
473           nextIndex++;
474         }
475       }
476     }
477
478     /*
479      * are we below or above the hidden sequences?
480      */
481     boolean below = (hiddenIndex > lastIndex + 1);
482     boolean above = (nextIndex > hiddenIndex + 1);
483
484     g.setColor(Color.blue);
485     int charHeight = av.getCharHeight();
486
487     /*
488      * vertices of the triangle, below or above hidden seqs
489      */
490     int[] xPoints = new int[]
491     { getWidth() - charHeight,
492         getWidth() - charHeight, getWidth() };
493     int yShift = seqIndex - starty;
494
495     if (below)
496     {
497       int[] yPoints = new int[] { yShift * charHeight + yoffset,
498           yShift * charHeight + yoffset + charHeight / 4,
499           yShift * charHeight + yoffset };
500       g.fillPolygon(xPoints, yPoints, 3);
501     }
502     if (above)
503     {
504       yShift++;
505       int[] yPoints = new int[] { yShift * charHeight + yoffset,
506           yShift * charHeight + yoffset - charHeight / 4,
507           yShift * charHeight + yoffset };
508       g.fillPolygon(xPoints, yPoints, 3);
509     }
510   }
511
512   /**
513    * Answers the standard sequence id font, or a bold font if the sequence is
514    * set as reference or a hidden group representative
515    * 
516    * @param seq
517    * @param alignViewport
518    * @return
519    */
520   private Font getHiddenFont(SequenceI seq, AlignViewport alignViewport)
521   {
522     if (av.isReferenceSeq(seq) || av.isHiddenRepSequence(seq))
523     {
524       return new Font(av.getFont().getName(), Font.BOLD,
525               av.getFont().getSize());
526     }
527     return getIdfont();
528   }
529
530   /**
531    * DOCUMENT ME!
532    * 
533    * @param list
534    *          DOCUMENT ME!
535    */
536   public void setHighlighted(List<SequenceI> list)
537   {
538     searchResults = list;
539     repaint();
540   }
541
542   public Font getIdfont()
543   {
544     return idfont;
545   }
546
547   public void setIdfont(Font idfont)
548   {
549     this.idfont = idfont;
550   }
551
552   /**
553    * Respond to viewport range changes (e.g. alignment panel was scrolled). Both
554    * scrolling and resizing change viewport ranges. Scrolling changes both start
555    * and end points, but resize only changes end values. Here we only want to
556    * fastpaint on a scroll, with resize using a normal paint, so scroll events
557    * are identified as changes to the horizontal or vertical start value.
558    * <p>
559    * In unwrapped mode, only responds to a vertical scroll, as horizontal scroll
560    * leaves sequence ids unchanged. In wrapped mode, only vertical scroll is
561    * provided, but it generates a change of "startres" which does require an
562    * update here.
563    */
564   @Override
565   public void propertyChange(PropertyChangeEvent evt)
566   {
567     String propertyName = evt.getPropertyName();
568     if (propertyName.equals(ViewportRanges.STARTSEQ)
569             || (av.getWrapAlignment()
570                     && propertyName.equals(ViewportRanges.STARTRES)))
571     {
572       fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
573     }
574     else if (propertyName.equals(ViewportRanges.STARTRESANDSEQ))
575     {
576       fastPaint(((int[]) evt.getNewValue())[1]
577               - ((int[]) evt.getOldValue())[1]);
578     }
579     else if (propertyName.equals(ViewportRanges.MOVE_VIEWPORT))
580     {
581       repaint();
582     }
583   }
584 }