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