JAL-2446 optimised new method to find feature colour for overview
[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(type, startPos, endPos);
305       for (SequenceFeature sequenceFeature : overlaps)
306       {
307         /*
308          * a feature type may be flagged as shown but the group 
309          * an instance of it belongs to may be hidden
310          */
311         if (featureGroupNotShown(sequenceFeature))
312         {
313           continue;
314         }
315
316         Color featureColour = getColour(sequenceFeature);
317         boolean isContactFeature = sequenceFeature.isContactFeature();
318
319         if (isContactFeature)
320         {
321           boolean drawn = renderFeature(g, seq,
322                   seq.findIndex(sequenceFeature.begin) - 1,
323                   seq.findIndex(sequenceFeature.begin) - 1, featureColour,
324                   start, end, y1, colourOnly);
325           drawn |= renderFeature(g, seq,
326                   seq.findIndex(sequenceFeature.end) - 1,
327                   seq.findIndex(sequenceFeature.end) - 1, featureColour,
328                   start, end, y1, colourOnly);
329           if (drawn)
330           {
331             drawnColour = featureColour;
332           }
333         }
334         else if (showFeature(sequenceFeature))
335         {
336           /*
337            * showing feature score by height of colour
338            * is not implemented as a selectable option 
339            *
340           if (av.isShowSequenceFeaturesHeight()
341                   && !Float.isNaN(sequenceFeature.score))
342           {
343             boolean drawn = renderScoreFeature(g, seq,
344                     seq.findIndex(sequenceFeature.begin) - 1,
345                     seq.findIndex(sequenceFeature.end) - 1, featureColour,
346                     start, end, y1, normaliseScore(sequenceFeature),
347                     colourOnly);
348             if (drawn)
349             {
350               drawnColour = featureColour;
351             }
352           }
353           else
354           {
355           */
356             boolean drawn = renderFeature(g, seq,
357                     seq.findIndex(sequenceFeature.begin) - 1,
358                     seq.findIndex(sequenceFeature.end) - 1, featureColour,
359                     start, end, y1, colourOnly);
360             if (drawn)
361             {
362               drawnColour = featureColour;
363             }
364           /*}*/
365         }
366       }
367     }
368
369     if (transparency != 1.0f && g != null)
370     {
371       /*
372        * reset transparency
373        */
374       Graphics2D g2 = (Graphics2D) g;
375       g2.setComposite(NO_TRANSPARENCY);
376     }
377
378     return drawnColour;
379   }
380
381   /**
382    * Answers true if the feature belongs to a feature group which is not
383    * currently displayed, else false
384    * 
385    * @param sequenceFeature
386    * @return
387    */
388   protected boolean featureGroupNotShown(
389           final SequenceFeature sequenceFeature)
390   {
391     return featureGroups != null
392             && sequenceFeature.featureGroup != null
393             && sequenceFeature.featureGroup.length() != 0
394             && featureGroups.containsKey(sequenceFeature.featureGroup)
395             && !featureGroups.get(sequenceFeature.featureGroup)
396                     .booleanValue();
397   }
398
399   /**
400    * Called when alignment in associated view has new/modified features to
401    * discover and display.
402    * 
403    */
404   @Override
405   public void featuresAdded()
406   {
407     findAllFeatures();
408   }
409
410   /**
411    * Returns the sequence feature colour rendered at the given sequence
412    * position, or null if none found. The feature of highest render order (i.e.
413    * on top) is found, subject to both feature type and feature group being
414    * visible, and its colour returned.
415    * 
416    * @param seq
417    * @param pos
418    * @return
419    */
420   Color findFeatureColour(SequenceI seq, int pos)
421   {
422     /*
423      * check for new feature added while processing
424      */
425     updateFeatures();
426
427     /*
428      * inspect features in reverse renderOrder (the last in the array is 
429      * displayed on top) until we find one that is rendered at the position
430      */
431     for (int renderIndex = renderOrder.length - 1; renderIndex >= 0; renderIndex--)
432     {
433       String type = renderOrder[renderIndex];
434       if (!showFeatureOfType(type))
435       {
436         continue;
437       }
438
439       List<SequenceFeature> overlaps = seq.findFeatures(type, pos, pos);
440       for (SequenceFeature sequenceFeature : overlaps)
441       {
442         if (!featureGroupNotShown(sequenceFeature))
443         {
444           return getColour(sequenceFeature);
445         }
446       }
447     }
448   
449     /*
450      * no displayed feature found at position
451      */
452     return null;
453   }
454 }