JAL-2480 efficient test for features present on sequence
[jalview.git] / src / jalview / renderer / seqfeatures / FeatureRenderer.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.renderer.seqfeatures;
22
23 import jalview.api.AlignViewportI;
24 import jalview.datamodel.SequenceFeature;
25 import jalview.datamodel.SequenceI;
26 import jalview.util.Comparison;
27 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
28
29 import java.awt.AlphaComposite;
30 import java.awt.Color;
31 import java.awt.FontMetrics;
32 import java.awt.Graphics;
33 import java.awt.Graphics2D;
34 import java.util.List;
35
36 public class FeatureRenderer extends FeatureRendererModel
37 {
38   private static final AlphaComposite NO_TRANSPARENCY = AlphaComposite
39           .getInstance(AlphaComposite.SRC_OVER, 1.0f);
40
41   /**
42    * Constructor given a viewport
43    * 
44    * @param viewport
45    */
46   public FeatureRenderer(AlignViewportI viewport)
47   {
48     this.av = viewport;
49   }
50
51   /**
52    * Renders the sequence using the given feature colour between the given start
53    * and end columns. Returns true if at least one column is drawn, else false
54    * (the feature range does not overlap the start and end positions).
55    * 
56    * @param g
57    * @param seq
58    * @param featureStart
59    * @param featureEnd
60    * @param featureColour
61    * @param start
62    * @param end
63    * @param y1
64    * @param colourOnly
65    * @return
66    */
67   boolean renderFeature(Graphics g, SequenceI seq, int featureStart,
68           int featureEnd, Color featureColour, int start, int end, int y1,
69           boolean colourOnly)
70   {
71     int charHeight = av.getCharHeight();
72     int charWidth = av.getCharWidth();
73     boolean validCharWidth = av.isValidCharWidth();
74
75     if (featureStart > end || featureEnd < start)
76     {
77       return false;
78     }
79
80     if (featureStart < start)
81     {
82       featureStart = start;
83     }
84     if (featureEnd >= end)
85     {
86       featureEnd = end;
87     }
88     int pady = (y1 + charHeight) - charHeight / 5;
89
90     FontMetrics fm = g.getFontMetrics();
91     for (int i = featureStart; i <= featureEnd; i++)
92     {
93       char s = seq.getCharAt(i);
94
95       if (Comparison.isGap(s))
96       {
97         continue;
98       }
99
100       g.setColor(featureColour);
101
102       g.fillRect((i - start) * charWidth, y1, charWidth,
103               charHeight);
104
105       if (colourOnly || !validCharWidth)
106       {
107         continue;
108       }
109
110       g.setColor(Color.white);
111       int charOffset = (charWidth - fm.charWidth(s)) / 2;
112       g.drawString(String.valueOf(s), charOffset
113               + (charWidth * (i - start)), pady);
114     }
115     return true;
116   }
117
118   /**
119    * Renders the sequence using the given SCORE feature colour between the given
120    * start and end columns. Returns true if at least one column is drawn, else
121    * false (the feature range does not overlap the start and end positions).
122    * 
123    * @param g
124    * @param seq
125    * @param fstart
126    * @param fend
127    * @param featureColour
128    * @param start
129    * @param end
130    * @param y1
131    * @param bs
132    * @param colourOnly
133    * @return
134    */
135   boolean renderScoreFeature(Graphics g, SequenceI seq, int fstart,
136           int fend, Color featureColour, int start, int end, int y1,
137           byte[] bs, boolean colourOnly)
138   {
139     if (fstart > end || fend < start)
140     {
141       return false;
142     }
143
144     if (fstart < start)
145     { // fix for if the feature we have starts before the sequence start,
146       fstart = start; // but the feature end is still valid!!
147     }
148
149     if (fend >= end)
150     {
151       fend = end;
152     }
153     int charHeight = av.getCharHeight();
154     int pady = (y1 + charHeight) - charHeight / 5;
155     int ystrt = 0, yend = charHeight;
156     if (bs[0] != 0)
157     {
158       // signed - zero is always middle of residue line.
159       if (bs[1] < 128)
160       {
161         yend = charHeight * (128 - bs[1]) / 512;
162         ystrt = charHeight - yend / 2;
163       }
164       else
165       {
166         ystrt = charHeight / 2;
167         yend = charHeight * (bs[1] - 128) / 512;
168       }
169     }
170     else
171     {
172       yend = charHeight * bs[1] / 255;
173       ystrt = charHeight - yend;
174
175     }
176
177     FontMetrics fm = g.getFontMetrics();
178     int charWidth = av.getCharWidth();
179
180     for (int i = fstart; i <= fend; i++)
181     {
182       char s = seq.getCharAt(i);
183
184       if (Comparison.isGap(s))
185       {
186         continue;
187       }
188
189       g.setColor(featureColour);
190       int x = (i - start) * charWidth;
191       g.drawRect(x, y1, charWidth, charHeight);
192       g.fillRect(x, y1 + ystrt, charWidth, yend);
193
194       if (colourOnly || !av.isValidCharWidth())
195       {
196         continue;
197       }
198
199       g.setColor(Color.black);
200       int charOffset = (charWidth - fm.charWidth(s)) / 2;
201       g.drawString(String.valueOf(s), charOffset
202               + (charWidth * (i - start)), pady);
203     }
204     return true;
205   }
206
207   /**
208    * {@inheritDoc}
209    */
210   @Override
211   public Color findFeatureColour(SequenceI seq, int column, Graphics g)
212   {
213     if (!av.isShowSequenceFeatures())
214     {
215       return null;
216     }
217
218     if (Comparison.isGap(seq.getCharAt(column)))
219     {
220       return Color.white;
221     }
222
223     Color renderedColour = null;
224     if (transparency == 1.0f)
225     {
226       /*
227        * simple case - just find the topmost rendered visible feature colour
228        */
229       renderedColour = findFeatureColour(seq, seq.findPosition(column));
230     }
231     else
232     {
233       /*
234        * transparency case - draw all visible features in render order to
235        * build up a composite colour on the graphics context
236        */
237       renderedColour = drawSequence(g, seq, column, column, 0, true);
238     }
239     return renderedColour;
240   }
241
242   /**
243    * Draws the sequence features on the graphics context, or just determines the
244    * colour that would be drawn (if flag colourOnly is true). Returns the last
245    * colour drawn (which may not be the effective colour if transparency
246    * applies), or null if no feature is drawn in the range given.
247    * 
248    * @param g
249    *          the graphics context to draw on (may be null if colourOnly==true)
250    * @param seq
251    * @param start
252    *          start column
253    * @param end
254    *          end column
255    * @param y1
256    *          vertical offset at which to draw on the graphics
257    * @param colourOnly
258    *          if true, only do enough to determine the colour for the position,
259    *          do not draw the character
260    * @return
261    */
262   public synchronized Color drawSequence(final Graphics g,
263           final SequenceI seq, int start, int end, int y1,
264           boolean colourOnly)
265   {
266     if (!seq.getFeatures().hasFeatures())
267     {
268       return null;
269     }
270
271     updateFeatures();
272
273     if (transparency != 1f && g != null)
274     {
275       Graphics2D g2 = (Graphics2D) g;
276       g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
277               transparency));
278     }
279
280     int startPos = seq.findPosition(start);
281     int endPos = seq.findPosition(end);// todo a performant overload of this!
282
283     Color drawnColour = null;
284
285     /*
286      * iterate over features in ordering of their rendering (last is on top)
287      */
288     for (int renderIndex = 0; renderIndex < renderOrder.length; renderIndex++)
289     {
290       String type = renderOrder[renderIndex];
291       if (!showFeatureOfType(type))
292       {
293         continue;
294       }
295
296       List<SequenceFeature> overlaps = seq.findFeatures(startPos, endPos,
297               type);
298       for (SequenceFeature sequenceFeature : overlaps)
299       {
300         /*
301          * a feature type may be flagged as shown but the group 
302          * an instance of it belongs to may be hidden
303          */
304         if (featureGroupNotShown(sequenceFeature))
305         {
306           continue;
307         }
308
309         Color featureColour = getColour(sequenceFeature);
310         boolean isContactFeature = sequenceFeature.isContactFeature();
311
312         if (isContactFeature)
313         {
314           boolean drawn = renderFeature(g, seq,
315                   seq.findIndex(sequenceFeature.begin) - 1,
316                   seq.findIndex(sequenceFeature.begin) - 1, featureColour,
317                   start, end, y1, colourOnly);
318           drawn |= renderFeature(g, seq,
319                   seq.findIndex(sequenceFeature.end) - 1,
320                   seq.findIndex(sequenceFeature.end) - 1, featureColour,
321                   start, end, y1, colourOnly);
322           if (drawn)
323           {
324             drawnColour = featureColour;
325           }
326         }
327         else if (showFeature(sequenceFeature))
328         {
329           /*
330            * showing feature score by height of colour
331            * is not implemented as a selectable option 
332            *
333           if (av.isShowSequenceFeaturesHeight()
334                   && !Float.isNaN(sequenceFeature.score))
335           {
336             boolean drawn = renderScoreFeature(g, seq,
337                     seq.findIndex(sequenceFeature.begin) - 1,
338                     seq.findIndex(sequenceFeature.end) - 1, featureColour,
339                     start, end, y1, normaliseScore(sequenceFeature),
340                     colourOnly);
341             if (drawn)
342             {
343               drawnColour = featureColour;
344             }
345           }
346           else
347           {
348           */
349             boolean drawn = renderFeature(g, seq,
350                     seq.findIndex(sequenceFeature.begin) - 1,
351                     seq.findIndex(sequenceFeature.end) - 1, featureColour,
352                     start, end, y1, colourOnly);
353             if (drawn)
354             {
355               drawnColour = featureColour;
356             }
357           /*}*/
358         }
359       }
360     }
361
362     if (transparency != 1.0f && g != null)
363     {
364       /*
365        * reset transparency
366        */
367       Graphics2D g2 = (Graphics2D) g;
368       g2.setComposite(NO_TRANSPARENCY);
369     }
370
371     return drawnColour;
372   }
373
374   /**
375    * Called when alignment in associated view has new/modified features to
376    * discover and display.
377    * 
378    */
379   @Override
380   public void featuresAdded()
381   {
382     findAllFeatures();
383   }
384
385   /**
386    * Returns the sequence feature colour rendered at the given sequence
387    * position, or null if none found. The feature of highest render order (i.e.
388    * on top) is found, subject to both feature type and feature group being
389    * visible, and its colour returned.
390    * 
391    * @param seq
392    * @param pos
393    * @return
394    */
395   Color findFeatureColour(SequenceI seq, int pos)
396   {
397     /*
398      * check for new feature added while processing
399      */
400     updateFeatures();
401
402     /*
403      * inspect features in reverse renderOrder (the last in the array is 
404      * displayed on top) until we find one that is rendered at the position
405      */
406     for (int renderIndex = renderOrder.length - 1; renderIndex >= 0; renderIndex--)
407     {
408       String type = renderOrder[renderIndex];
409       if (!showFeatureOfType(type))
410       {
411         continue;
412       }
413
414       List<SequenceFeature> overlaps = seq.findFeatures(pos, pos, type);
415       for (SequenceFeature sequenceFeature : overlaps)
416       {
417         if (!featureGroupNotShown(sequenceFeature))
418         {
419           return getColour(sequenceFeature);
420         }
421       }
422     }
423   
424     /*
425      * no displayed feature found at position
426      */
427     return null;
428   }
429 }