f826a88cb2784bd75f6ade974f39ef35e35be943
[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    * This is used by Structure Viewers and the Overview Window to get the
214    * feature colour of the rendered sequence
215    * 
216    * @param seq
217    * @param column
218    * @return
219    */
220   @Override
221   public Color findFeatureColour(SequenceI seq, int column, Graphics g)
222   {
223     if (!av.isShowSequenceFeatures())
224     {
225       return null;
226     }
227
228     SequenceFeature[] sequenceFeatures = seq.getSequenceFeatures();
229     if (seq != lastSeq)
230     {
231       lastSeq = seq;
232       lastSequenceFeatures = sequenceFeatures;
233       if (lastSequenceFeatures != null)
234       {
235         sfSize = lastSequenceFeatures.length;
236       }
237     }
238     else
239     {
240       if (lastSequenceFeatures != sequenceFeatures)
241       {
242         lastSequenceFeatures = sequenceFeatures;
243         if (lastSequenceFeatures != null)
244         {
245           sfSize = lastSequenceFeatures.length;
246         }
247       }
248     }
249
250     if (lastSequenceFeatures == null || sfSize == 0)
251     {
252       return null;
253     }
254
255     if (Comparison.isGap(lastSeq.getCharAt(column)))
256     {
257       return Color.white;
258     }
259
260     Color renderedColour = null;
261     if (transparency == 1.0f)
262     {
263       renderedColour = findFeatureColour(seq, seq.findPosition(column));
264     }
265     else
266     {
267       renderedColour = drawSequence(g, lastSeq, column, column, 0, true);
268     }
269     return renderedColour;
270   }
271
272   /**
273    * Draws the sequence features on the graphics context, or just determines the
274    * colour that would be drawn (if flag offscreenrender is true).
275    * 
276    * @param g
277    *          the graphics context to draw on (may be null if colourOnly==true)
278    * @param seq
279    * @param start
280    *          start column (or sequence position in offscreenrender mode)
281    * @param end
282    *          end column (not used in offscreenrender mode)
283    * @param y1
284    *          vertical offset at which to draw on the graphics
285    * @param colourOnly
286    *          if true, only do enough to determine the colour for the position,
287    *          do not draw the character
288    * @return
289    */
290   public synchronized Color drawSequence(final Graphics g,
291           final SequenceI seq, int start, int end, int y1,
292           boolean colourOnly)
293   {
294     SequenceFeature[] sequenceFeatures = seq.getSequenceFeatures();
295     if (sequenceFeatures == null || sequenceFeatures.length == 0)
296     {
297       return null;
298     }
299
300     updateFeatures();
301
302     if (lastSeq == null || seq != lastSeq
303             || sequenceFeatures != lastSequenceFeatures)
304     {
305       lastSeq = seq;
306       lastSequenceFeatures = sequenceFeatures;
307     }
308
309     if (transparency != 1f && g != null)
310     {
311       Graphics2D g2 = (Graphics2D) g;
312       g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
313               transparency));
314     }
315
316     int startPos = lastSeq.findPosition(start);
317     int endPos = lastSeq.findPosition(end);
318
319     sfSize = lastSequenceFeatures.length;
320     Color drawnColour = null;
321
322     /*
323      * iterate over features in ordering of their rendering (last is on top)
324      */
325     for (int renderIndex = 0; renderIndex < renderOrder.length; renderIndex++)
326     {
327       String type = renderOrder[renderIndex];
328       if (!showFeatureOfType(type))
329       {
330         continue;
331       }
332
333       // loop through all features in sequence to find
334       // current feature to render
335       for (int sfindex = 0; sfindex < sfSize; sfindex++)
336       {
337         final SequenceFeature sequenceFeature = lastSequenceFeatures[sfindex];
338         if (!sequenceFeature.type.equals(type))
339         {
340           continue;
341         }
342
343         /*
344          * a feature type may be flagged as shown but the group 
345          * an instance of it belongs to may be hidden
346          */
347         if (featureGroupNotShown(sequenceFeature))
348         {
349           continue;
350         }
351
352         /*
353          * check feature overlaps the target range
354          * TODO: efficient retrieval of features overlapping a range
355          */
356         if (sequenceFeature.getBegin() > endPos
357                 || sequenceFeature.getEnd() < startPos)
358         {
359           continue;
360         }
361
362         Color featureColour = getColour(sequenceFeature);
363         boolean isContactFeature = sequenceFeature.isContactFeature();
364
365         if (isContactFeature)
366         {
367           boolean drawn = renderFeature(g, seq,
368                   seq.findIndex(sequenceFeature.begin) - 1,
369                   seq.findIndex(sequenceFeature.begin) - 1, featureColour,
370                   start, end, y1, colourOnly);
371           drawn |= renderFeature(g, seq,
372                   seq.findIndex(sequenceFeature.end) - 1,
373                   seq.findIndex(sequenceFeature.end) - 1, featureColour,
374                   start, end, y1, colourOnly);
375           if (drawn)
376           {
377             drawnColour = featureColour;
378           }
379         }
380         else if (showFeature(sequenceFeature))
381         {
382           if (av.isShowSequenceFeaturesHeight()
383                   && !Float.isNaN(sequenceFeature.score))
384           {
385             boolean drawn = renderScoreFeature(g, seq,
386                     seq.findIndex(sequenceFeature.begin) - 1,
387                     seq.findIndex(sequenceFeature.end) - 1, featureColour,
388                     start, end, y1, normaliseScore(sequenceFeature),
389                     colourOnly);
390             if (drawn)
391             {
392               drawnColour = featureColour;
393             }
394           }
395           else
396           {
397             boolean drawn = renderFeature(g, seq,
398                     seq.findIndex(sequenceFeature.begin) - 1,
399                     seq.findIndex(sequenceFeature.end) - 1, featureColour,
400                     start, end, y1, colourOnly);
401             if (drawn)
402             {
403               drawnColour = featureColour;
404             }
405           }
406         }
407       }
408     }
409
410     if (transparency != 1.0f && g != null)
411     {
412       /*
413        * reset transparency
414        */
415       Graphics2D g2 = (Graphics2D) g;
416       g2.setComposite(NO_TRANSPARENCY);
417     }
418
419     return drawnColour;
420   }
421
422   /**
423    * Answers true if the feature belongs to a feature group which is not
424    * currently displayed, else false
425    * 
426    * @param sequenceFeature
427    * @return
428    */
429   protected boolean featureGroupNotShown(
430           final SequenceFeature sequenceFeature)
431   {
432     return featureGroups != null
433             && sequenceFeature.featureGroup != null
434             && sequenceFeature.featureGroup.length() != 0
435             && featureGroups.containsKey(sequenceFeature.featureGroup)
436             && !featureGroups.get(sequenceFeature.featureGroup)
437                     .booleanValue();
438   }
439
440   /**
441    * Called when alignment in associated view has new/modified features to
442    * discover and display.
443    * 
444    */
445   @Override
446   public void featuresAdded()
447   {
448     lastSeq = null;
449     findAllFeatures();
450   }
451
452   /**
453    * Returns the sequence feature colour rendered at the given sequence
454    * position, or null if none found. The feature of highest render order (i.e.
455    * on top) is found, subject to both feature type and feature group being
456    * visible, and its colour returned.
457    * 
458    * @param seq
459    * @param pos
460    * @return
461    */
462   Color findFeatureColour(SequenceI seq, int pos)
463   {
464     SequenceFeature[] sequenceFeatures = seq.getSequenceFeatures();
465     if (sequenceFeatures == null || sequenceFeatures.length == 0)
466     {
467       return null;
468     }
469   
470     // updateFeatures();
471
472     /*
473      * inspect features in reverse renderOrder (the last in the array is 
474      * displayed on top) until we find one that is rendered at the position
475      */
476     for (int renderIndex = renderOrder.length - 1; renderIndex >= 0; renderIndex--)
477     {
478       String type = renderOrder[renderIndex];
479       if (!showFeatureOfType(type))
480       {
481         continue;
482       }
483
484       for (int sfindex = 0; sfindex < sequenceFeatures.length; sfindex++)
485       {
486         SequenceFeature sequenceFeature = sequenceFeatures[sfindex];
487         if (!sequenceFeature.type.equals(type))
488         {
489           continue;
490         }
491
492         if (featureGroupNotShown(sequenceFeature))
493         {
494           continue;
495         }
496
497         boolean featureIsAtPosition = sequenceFeature.begin <= pos
498                 && sequenceFeature.end >= pos;
499         if (sequenceFeature.isContactFeature())
500         {
501           featureIsAtPosition = sequenceFeature.begin == pos
502                   || sequenceFeature.end == pos;
503         }
504         if (featureIsAtPosition)
505         {
506           return getColour(sequenceFeature);
507         }
508       }
509     }
510   
511     /*
512      * no displayed feature found at position
513      */
514     return null;
515   }
516 }