JAL-2490 findFeaturesAtRes with performant feature lookup
[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     SequenceFeature[] sequenceFeatures = seq.getSequenceFeatures();
219
220     if (sequenceFeatures == null || sequenceFeatures.length == 0)
221     {
222       return null;
223     }
224
225     if (Comparison.isGap(seq.getCharAt(column)))
226     {
227       return Color.white;
228     }
229
230     Color renderedColour = null;
231     if (transparency == 1.0f)
232     {
233       /*
234        * simple case - just find the topmost rendered visible feature colour
235        */
236       renderedColour = findFeatureColour(seq, seq.findPosition(column));
237     }
238     else
239     {
240       /*
241        * transparency case - draw all visible features in render order to
242        * build up a composite colour on the graphics context
243        */
244       renderedColour = drawSequence(g, seq, column, column, 0, true);
245     }
246     return renderedColour;
247   }
248
249   /**
250    * Draws the sequence features on the graphics context, or just determines the
251    * colour that would be drawn (if flag colourOnly is true). Returns the last
252    * colour drawn (which may not be the effective colour if transparency
253    * applies), or null if no feature is drawn in the range given.
254    * 
255    * @param g
256    *          the graphics context to draw on (may be null if colourOnly==true)
257    * @param seq
258    * @param start
259    *          start column
260    * @param end
261    *          end column
262    * @param y1
263    *          vertical offset at which to draw on the graphics
264    * @param colourOnly
265    *          if true, only do enough to determine the colour for the position,
266    *          do not draw the character
267    * @return
268    */
269   public synchronized Color drawSequence(final Graphics g,
270           final SequenceI seq, int start, int end, int y1,
271           boolean colourOnly)
272   {
273     SequenceFeature[] sequenceFeatures = seq.getSequenceFeatures();
274     if (sequenceFeatures == null || sequenceFeatures.length == 0)
275     {
276       return null;
277     }
278
279     updateFeatures();
280
281     if (transparency != 1f && g != null)
282     {
283       Graphics2D g2 = (Graphics2D) g;
284       g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
285               transparency));
286     }
287
288     int startPos = seq.findPosition(start);
289     int endPos = seq.findPosition(end);
290
291     Color drawnColour = null;
292
293     /*
294      * iterate over features in ordering of their rendering (last is on top)
295      */
296     for (int renderIndex = 0; renderIndex < renderOrder.length; renderIndex++)
297     {
298       String type = renderOrder[renderIndex];
299       if (!showFeatureOfType(type))
300       {
301         continue;
302       }
303
304       List<SequenceFeature> overlaps = seq.findFeatures(startPos, endPos,
305               type);
306       for (SequenceFeature sequenceFeature : overlaps)
307       {
308         /*
309          * a feature type may be flagged as shown but the group 
310          * an instance of it belongs to may be hidden
311          */
312         if (featureGroupNotShown(sequenceFeature))
313         {
314           continue;
315         }
316
317         Color featureColour = getColour(sequenceFeature);
318         boolean isContactFeature = sequenceFeature.isContactFeature();
319
320         if (isContactFeature)
321         {
322           boolean drawn = renderFeature(g, seq,
323                   seq.findIndex(sequenceFeature.begin) - 1,
324                   seq.findIndex(sequenceFeature.begin) - 1, featureColour,
325                   start, end, y1, colourOnly);
326           drawn |= renderFeature(g, seq,
327                   seq.findIndex(sequenceFeature.end) - 1,
328                   seq.findIndex(sequenceFeature.end) - 1, featureColour,
329                   start, end, y1, colourOnly);
330           if (drawn)
331           {
332             drawnColour = featureColour;
333           }
334         }
335         else if (showFeature(sequenceFeature))
336         {
337           /*
338            * showing feature score by height of colour
339            * is not implemented as a selectable option 
340            *
341           if (av.isShowSequenceFeaturesHeight()
342                   && !Float.isNaN(sequenceFeature.score))
343           {
344             boolean drawn = renderScoreFeature(g, seq,
345                     seq.findIndex(sequenceFeature.begin) - 1,
346                     seq.findIndex(sequenceFeature.end) - 1, featureColour,
347                     start, end, y1, normaliseScore(sequenceFeature),
348                     colourOnly);
349             if (drawn)
350             {
351               drawnColour = featureColour;
352             }
353           }
354           else
355           {
356           */
357             boolean drawn = renderFeature(g, seq,
358                     seq.findIndex(sequenceFeature.begin) - 1,
359                     seq.findIndex(sequenceFeature.end) - 1, featureColour,
360                     start, end, y1, colourOnly);
361             if (drawn)
362             {
363               drawnColour = featureColour;
364             }
365           /*}*/
366         }
367       }
368     }
369
370     if (transparency != 1.0f && g != null)
371     {
372       /*
373        * reset transparency
374        */
375       Graphics2D g2 = (Graphics2D) g;
376       g2.setComposite(NO_TRANSPARENCY);
377     }
378
379     return drawnColour;
380   }
381
382   /**
383    * Called when alignment in associated view has new/modified features to
384    * discover and display.
385    * 
386    */
387   @Override
388   public void featuresAdded()
389   {
390     findAllFeatures();
391   }
392
393   /**
394    * Returns the sequence feature colour rendered at the given sequence
395    * position, or null if none found. The feature of highest render order (i.e.
396    * on top) is found, subject to both feature type and feature group being
397    * visible, and its colour returned.
398    * 
399    * @param seq
400    * @param pos
401    * @return
402    */
403   Color findFeatureColour(SequenceI seq, int pos)
404   {
405     /*
406      * check for new feature added while processing
407      */
408     updateFeatures();
409
410     /*
411      * inspect features in reverse renderOrder (the last in the array is 
412      * displayed on top) until we find one that is rendered at the position
413      */
414     for (int renderIndex = renderOrder.length - 1; renderIndex >= 0; renderIndex--)
415     {
416       String type = renderOrder[renderIndex];
417       if (!showFeatureOfType(type))
418       {
419         continue;
420       }
421
422       List<SequenceFeature> overlaps = seq.findFeatures(pos, pos, type);
423       for (SequenceFeature sequenceFeature : overlaps)
424       {
425         if (!featureGroupNotShown(sequenceFeature))
426         {
427           return getColour(sequenceFeature);
428         }
429       }
430     }
431   
432     /*
433      * no displayed feature found at position
434      */
435     return null;
436   }
437 }