JAL-3383 JAL-3253-applet
[jalview.git] / src / jalview / renderer / seqfeatures / FeatureRenderer.java
index 02cfd05..9988076 100644 (file)
 package jalview.renderer.seqfeatures;
 
 import jalview.api.AlignViewportI;
+import jalview.api.FeatureColourI;
+import jalview.datamodel.ContiguousI;
 import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
 import jalview.util.Comparison;
+import jalview.util.Platform;
 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
 
 import java.awt.AlphaComposite;
@@ -31,18 +34,14 @@ import java.awt.Color;
 import java.awt.FontMetrics;
 import java.awt.Graphics;
 import java.awt.Graphics2D;
+import java.util.ArrayList;
+import java.util.List;
 
 public class FeatureRenderer extends FeatureRendererModel
 {
   private static final AlphaComposite NO_TRANSPARENCY = AlphaComposite
           .getInstance(AlphaComposite.SRC_OVER, 1.0f);
 
-  protected SequenceI lastSeq;
-
-  private volatile SequenceFeature[] lastSequenceFeatures;
-
-  int sfSize;
-
   /**
    * Constructor given a viewport
    * 
@@ -93,34 +92,43 @@ public class FeatureRenderer extends FeatureRendererModel
     int pady = (y1 + charHeight) - charHeight / 5;
 
     FontMetrics fm = g.getFontMetrics();
+    char s = '\0';
     for (int i = featureStart; i <= featureEnd; i++)
     {
-      char s = seq.getCharAt(i);
 
-      if (Comparison.isGap(s))
+      // colourOnly is just for Overview -- no need to check this again
+
+      if (!colourOnly && Comparison.isGap(s = seq.getCharAt(i)))
       {
         continue;
       }
 
       g.setColor(featureColour);
 
-      g.fillRect((i - start) * charWidth, y1, charWidth,
-              charHeight);
+      g.fillRect((i - start) * charWidth, y1, charWidth, charHeight);
 
-      if (colourOnly || !validCharWidth)
+      if (colourOnly)
+      {
+        return true;
+      }
+
+      if (!validCharWidth)
       {
         continue;
       }
 
       g.setColor(Color.white);
       int charOffset = (charWidth - fm.charWidth(s)) / 2;
-      g.drawString(String.valueOf(s), charOffset
-              + (charWidth * (i - start)), pady);
+      g.drawString(String.valueOf(s),
+              charOffset + (charWidth * (i - start)), pady);
     }
     return true;
   }
 
   /**
+   * 
+   * BH - this method is never called?
+   * 
    * Renders the sequence using the given SCORE feature colour between the given
    * start and end columns. Returns true if at least one column is drawn, else
    * false (the feature range does not overlap the start and end positions).
@@ -203,8 +211,8 @@ public class FeatureRenderer extends FeatureRendererModel
 
       g.setColor(Color.black);
       int charOffset = (charWidth - fm.charWidth(s)) / 2;
-      g.drawString(String.valueOf(s), charOffset
-              + (charWidth * (i - start)), pady);
+      g.drawString(String.valueOf(s),
+              charOffset + (charWidth * (i - start)), pady);
     }
     return true;
   }
@@ -215,50 +223,30 @@ public class FeatureRenderer extends FeatureRendererModel
   @Override
   public Color findFeatureColour(SequenceI seq, int column, Graphics g)
   {
-    if (!av.isShowSequenceFeatures())
-    {
-      return null;
-    }
-
-    SequenceFeature[] sequenceFeatures = seq.getSequenceFeatures();
-    if (seq != lastSeq)
-    {
-      lastSeq = seq;
-      lastSequenceFeatures = sequenceFeatures;
-      if (lastSequenceFeatures != null)
-      {
-        sfSize = lastSequenceFeatures.length;
-      }
-    }
-    else
-    {
-      if (lastSequenceFeatures != sequenceFeatures)
-      {
-        lastSequenceFeatures = sequenceFeatures;
-        if (lastSequenceFeatures != null)
-        {
-          sfSize = lastSequenceFeatures.length;
-        }
-      }
-    }
-
-    if (lastSequenceFeatures == null || sfSize == 0)
+    // BH 2019.08.01
+    // this is already checked in FeatureColorFinder
+    // if (!av.isShowSequenceFeatures())
+    // {
+    // return null;
+    // }
+
+    // column is 'base 1' but getCharAt is an array index (ie from 0)
+    if (Comparison.isGap(seq.getCharAt(column - 1)))
     {
+      /*
+       * returning null allows the colour scheme to provide gap colour
+       * - normally white, but can be customised
+       */
       return null;
     }
 
-    if (Comparison.isGap(lastSeq.getCharAt(column)))
-    {
-      return Color.white;
-    }
-
     Color renderedColour = null;
     if (transparency == 1.0f)
     {
       /*
        * simple case - just find the topmost rendered visible feature colour
        */
-      renderedColour = findFeatureColour(seq, seq.findPosition(column));
+      renderedColour = findFeatureColour(seq, column);
     }
     else
     {
@@ -266,7 +254,7 @@ public class FeatureRenderer extends FeatureRendererModel
        * transparency case - draw all visible features in render order to
        * build up a composite colour on the graphics context
        */
-      renderedColour = drawSequence(g, lastSeq, column, column, 0, true);
+      renderedColour = drawSequence(g, seq, column, column, 0, true);
     }
     return renderedColour;
   }
@@ -278,7 +266,8 @@ public class FeatureRenderer extends FeatureRendererModel
    * applies), or null if no feature is drawn in the range given.
    * 
    * @param g
-   *          the graphics context to draw on (may be null if colourOnly==true)
+   *          the graphics context to draw on (may be null only if t == 1 from
+   *          colourOnly==true)
    * @param seq
    * @param start
    *          start column
@@ -295,94 +284,111 @@ public class FeatureRenderer extends FeatureRendererModel
           final SequenceI seq, int start, int end, int y1,
           boolean colourOnly)
   {
-    SequenceFeature[] sequenceFeatures = seq.getSequenceFeatures();
-    if (sequenceFeatures == null || sequenceFeatures.length == 0)
+    // from SeqCanvas and OverviewRender
+    /*
+     * if columns are all gapped, or sequence has no features, nothing to do
+     */
+    ContiguousI visiblePositions;
+    if (!seq.getFeatures().hasFeatures() || (visiblePositions = seq
+            .findPositions(start + 1, end + 1)) == null)
     {
       return null;
     }
 
-    updateFeatures();
+    int vp0 = visiblePositions.getBegin();
+    int vp1 = visiblePositions.getEnd();
 
-    if (lastSeq == null || seq != lastSeq
-            || sequenceFeatures != lastSequenceFeatures)
-    {
-      lastSeq = seq;
-      lastSequenceFeatures = sequenceFeatures;
-    }
+    updateFeatures();
 
-    if (transparency != 1f && g != null)
+    if (transparency != 1f) // g cannot be null here if trans == 1f - BH // && g
+                            // != null)
     {
-      Graphics2D g2 = (Graphics2D) g;
-      g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
+      ((Graphics2D) g).setComposite(
+              AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
               transparency));
     }
 
-    int startPos = lastSeq.findPosition(start);
-    int endPos = lastSeq.findPosition(end);
-
-    sfSize = lastSequenceFeatures.length;
     Color drawnColour = null;
 
     /*
      * iterate over features in ordering of their rendering (last is on top)
      */
-    for (int renderIndex = 0; renderIndex < renderOrder.length; renderIndex++)
+    for (int renderIndex = 0, n = renderOrder.length; renderIndex < n; renderIndex++)
     {
       String type = renderOrder[renderIndex];
-      if (!showFeatureOfType(type))
+      if (!seq.hasFeatures(type) || !showFeatureOfType(type))
       {
         continue;
       }
 
-      // loop through all features in sequence to find
-      // current feature to render
-      for (int sfindex = 0; sfindex < sfSize; sfindex++)
+      FeatureColourI fc = getFeatureStyle(type);
+      List<SequenceFeature> overlaps = seq.getFeatures().findFeatures(vp0,
+              vp1, type);
+
+      // colourOnly (i.e. Overview) can only be here if translucent, so
+      // there is no need to check for filtering
+      if (!colourOnly && fc.isSimpleColour())
       {
-        final SequenceFeature sequenceFeature = lastSequenceFeatures[sfindex];
-        if (!sequenceFeature.type.equals(type))
+        filterFeaturesForDisplay(overlaps);
+      }
+
+      for (int i = overlaps.size(); --i >= 0;)
+      {
+        SequenceFeature sf = overlaps.get(i);
+        Color featureColour = getColor(sf, fc);
+        if (featureColour == null)
         {
+          /*
+           * feature excluded by visibility settings, filters, or colour threshold
+           */
           continue;
         }
 
         /*
-         * a feature type may be flagged as shown but the group 
-         * an instance of it belongs to may be hidden
+         * if feature starts/ends outside the visible range,
+         * restrict to visible positions (or if a contact feature,
+         * to a single position)
          */
-        if (featureGroupNotShown(sequenceFeature))
+        int sf0 = sf.getBegin();
+        int sf1 = sf.getEnd();
+        int visibleStart = sf0;
+        if (visibleStart < vp0)
         {
-          continue;
+          visibleStart = sf.isContactFeature() ? sf1 : vp0;
         }
-
-        /*
-         * check feature overlaps the target range
-         * TODO: efficient retrieval of features overlapping a range
-         */
-        if (sequenceFeature.getBegin() > endPos
-                || sequenceFeature.getEnd() < startPos)
+        int visibleEnd = sf1;
+        if (visibleEnd > vp1)
         {
-          continue;
+          visibleEnd = sf.isContactFeature() ? sf0 : vp1;
         }
 
-        Color featureColour = getColour(sequenceFeature);
-        boolean isContactFeature = sequenceFeature.isContactFeature();
+        int featureStartCol = seq.findIndex(visibleStart);
+        int featureEndCol = (sf.begin == sf.end ? featureStartCol
+                : seq.findIndex(visibleEnd));
+
+        // Color featureColour = getColour(sequenceFeature);
+
+        boolean isContactFeature = sf.isContactFeature();
 
         if (isContactFeature)
         {
-          boolean drawn = renderFeature(g, seq,
-                  seq.findIndex(sequenceFeature.begin) - 1,
-                  seq.findIndex(sequenceFeature.begin) - 1, featureColour,
-                  start, end, y1, colourOnly);
-          drawn |= renderFeature(g, seq,
-                  seq.findIndex(sequenceFeature.end) - 1,
-                  seq.findIndex(sequenceFeature.end) - 1, featureColour,
-                  start, end, y1, colourOnly);
+          boolean drawn = renderFeature(g, seq, featureStartCol - 1,
+                  featureStartCol - 1, featureColour, start, end, y1,
+                  colourOnly);
+          drawn |= renderFeature(g, seq, featureEndCol - 1,
+                  featureEndCol - 1, featureColour, start, end, y1,
+                  colourOnly);
           if (drawn)
           {
             drawnColour = featureColour;
           }
         }
-        else if (showFeature(sequenceFeature))
+        else
         {
+          /*
+           * showing feature score by height of colour
+           * is not implemented as a selectable option 
+           *
           if (av.isShowSequenceFeaturesHeight()
                   && !Float.isNaN(sequenceFeature.score))
           {
@@ -398,50 +404,31 @@ public class FeatureRenderer extends FeatureRendererModel
           }
           else
           {
-            boolean drawn = renderFeature(g, seq,
-                    seq.findIndex(sequenceFeature.begin) - 1,
-                    seq.findIndex(sequenceFeature.end) - 1, featureColour,
-                    start, end, y1, colourOnly);
-            if (drawn)
-            {
-              drawnColour = featureColour;
-            }
+          */
+          boolean drawn = renderFeature(g, seq, featureStartCol - 1,
+                  featureEndCol - 1, featureColour, start, end, y1,
+                  colourOnly);
+          if (drawn)
+          {
+            drawnColour = featureColour;
           }
+          /*}*/
         }
       }
     }
 
-    if (transparency != 1.0f && g != null)
+    if (transparency != 1.0f)
     {
       /*
        * reset transparency
        */
-      Graphics2D g2 = (Graphics2D) g;
-      g2.setComposite(NO_TRANSPARENCY);
+      ((Graphics2D) g).setComposite(NO_TRANSPARENCY);
     }
 
     return drawnColour;
   }
 
   /**
-   * Answers true if the feature belongs to a feature group which is not
-   * currently displayed, else false
-   * 
-   * @param sequenceFeature
-   * @return
-   */
-  protected boolean featureGroupNotShown(
-          final SequenceFeature sequenceFeature)
-  {
-    return featureGroups != null
-            && sequenceFeature.featureGroup != null
-            && sequenceFeature.featureGroup.length() != 0
-            && featureGroups.containsKey(sequenceFeature.featureGroup)
-            && !featureGroups.get(sequenceFeature.featureGroup)
-                    .booleanValue();
-  }
-
-  /**
    * Called when alignment in associated view has new/modified features to
    * discover and display.
    * 
@@ -449,28 +436,37 @@ public class FeatureRenderer extends FeatureRendererModel
   @Override
   public void featuresAdded()
   {
-    lastSeq = null;
     findAllFeatures();
   }
 
+  private List<SequenceFeature> overlaps = (Platform.isJS()
+          ? new ArrayList<>()
+          : null);
+
   /**
-   * Returns the sequence feature colour rendered at the given sequence
-   * position, or null if none found. The feature of highest render order (i.e.
-   * on top) is found, subject to both feature type and feature group being
-   * visible, and its colour returned.
+   * Returns the sequence feature colour rendered at the given column position,
+   * or null if none found. The feature of highest render order (i.e. on top) is
+   * found, subject to both feature type and feature group being visible, and
+   * its colour returned. This method is suitable when no feature transparency
+   * applied (only the topmost visible feature colour is rendered).
+   * <p>
+   * Note this method does not check for a gap in the column so would return the
+   * colour for features enclosing a gapped column. Check for gap before calling
+   * if different behaviour is wanted.
+   * 
+   * BH 2019.07.30
+   * 
+   * Adds a result ArrayList to parameters in order to avoid an unnecessary
+   * construction of that for every pixel checked.
+   * 
    * 
    * @param seq
-   * @param pos
+   * @param column
+   *          (1..)
    * @return
    */
-  Color findFeatureColour(SequenceI seq, int pos)
+  private Color findFeatureColour(SequenceI seq, int column)
   {
-    SequenceFeature[] sequenceFeatures = seq.getSequenceFeatures();
-    if (sequenceFeatures == null || sequenceFeatures.length == 0)
-    {
-      return null;
-    }
-  
     /*
      * check for new feature added while processing
      */
@@ -480,45 +476,37 @@ public class FeatureRenderer extends FeatureRendererModel
      * inspect features in reverse renderOrder (the last in the array is 
      * displayed on top) until we find one that is rendered at the position
      */
-    for (int renderIndex = renderOrder.length - 1; renderIndex >= 0; renderIndex--)
+    for (int renderIndex = renderOrder.length; --renderIndex >= 0;)
     {
       String type = renderOrder[renderIndex];
-      if (!showFeatureOfType(type))
+      if (!seq.hasFeatures(type) || !showFeatureOfType(type))
       {
         continue;
       }
 
-      for (int sfindex = 0; sfindex < sequenceFeatures.length; sfindex++)
+      if (overlaps != null)
       {
-        SequenceFeature sequenceFeature = sequenceFeatures[sfindex];
-        if (!sequenceFeature.type.equals(type))
-        {
-          continue;
-        }
-
-        if (featureGroupNotShown(sequenceFeature))
-        {
-          continue;
-        }
-
-        /*
-         * check the column position is within the feature range
-         * (or is one of the two contact positions for a contact feature)
-         */
-        boolean featureIsAtPosition = sequenceFeature.begin <= pos
-                && sequenceFeature.end >= pos;
-        if (sequenceFeature.isContactFeature())
-        {
-          featureIsAtPosition = sequenceFeature.begin == pos
-                  || sequenceFeature.end == pos;
-        }
-        if (featureIsAtPosition)
+        overlaps.clear();
+      }
+      List<SequenceFeature> list = seq.findFeatures(column, type, overlaps);
+      if (list.size() > 0)
+      {
+        for (int i = 0, n = list.size(); i < n; i++)
         {
-          return getColour(sequenceFeature);
+          SequenceFeature sf = list.get(i);
+          if (featureGroupNotShown(sf))
+          {
+            continue;
+          }
+          Color col = getColour(sf);
+          if (col != null)
+          {
+            return col;
+          }
         }
       }
     }
-  
+
     /*
      * no displayed feature found at position
      */