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