JAL-2609 tweaks to, and tests for, calculateWrappedGeometry
[jalview.git] / src / jalview / gui / SeqCanvas.java
index 8c8b1d8..a4c7da5 100755 (executable)
@@ -73,14 +73,25 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
 
   boolean fastpainting = false;
 
-  int labelWidthWest;
-
-  int labelWidthEast;
-
   int cursorX = 0;
 
   int cursorY = 0;
 
+  private AnnotationPanel annotations;
+
+  /*
+   * measurements for drawing a wrapped alignment
+   */
+  int labelWidthWest; // label left width in pixels if shown
+
+  private int labelWidthEast; // label right width in pixels if shown
+
+  private int wrappedSpaceAboveAlignment; // gap between widths
+
+  private int wrappedRepeatHeightPx; // height in pixels of wrapped width
+
+  private int wrappedVisibleWidths; // number of wrapped widths displayed
+
   /**
    * Creates a new SeqCanvas object.
    * 
@@ -90,7 +101,6 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
   public SeqCanvas(AlignmentPanel ap)
   {
     this.av = ap.av;
-    updateViewport();
     fr = new FeatureRenderer(ap);
     sr = new SequenceRenderer(av);
     setLayout(new BorderLayout());
@@ -110,31 +120,36 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
     return fr;
   }
 
-  int charHeight = 0, charWidth = 0;
-
-  private void updateViewport()
-  {
-    charHeight = av.getCharHeight();
-    charWidth = av.getCharWidth();
-  }
-
   /**
-   * DOCUMENT ME!
+   * Draws the scale above a region of a wrapped alignment, consisting of a
+   * column number every major interval (10 columns).
    * 
    * @param g
-   *          DOCUMENT ME!
+   *          the graphics context to draw on, positioned at the start (bottom
+   *          left) of the line on which to draw any scale marks
    * @param startx
-   *          DOCUMENT ME!
+   *          start alignment column (0..)
    * @param endx
-   *          DOCUMENT ME!
+   *          end alignment column (0..)
    * @param ypos
-   *          DOCUMENT ME!
+   *          y offset to draw at
    */
   private void drawNorthScale(Graphics g, int startx, int endx, int ypos)
   {
-    updateViewport();
-    for (ScaleMark mark : new ScaleRenderer().calculateMarks(av, startx,
-            endx))
+    int charHeight = av.getCharHeight();
+    int charWidth = av.getCharWidth();
+
+    /*
+     * white fill the scale space (for the fastPaint case)
+     */
+    g.setColor(Color.white);
+    g.fillRect(0, ypos - charHeight - charHeight / 2, getWidth(),
+            charHeight * 3 / 2 + 2);
+    g.setColor(Color.black);
+
+    List<ScaleMark> marks = new ScaleRenderer().calculateMarks(av, startx,
+            endx);
+    for (ScaleMark mark : marks)
     {
       int mpos = mark.column; // (i - startx - 1)
       if (mpos < 0)
@@ -149,9 +164,13 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
         {
           g.drawString(mstring, mpos * charWidth, ypos - (charHeight / 2));
         }
-        g.drawLine((mpos * charWidth) + (charWidth / 2), (ypos + 2)
-                - (charHeight / 2), (mpos * charWidth) + (charWidth / 2),
-                ypos - 2);
+
+        /*
+         * draw a tick mark below the column number, centred on the column;
+         * height of tick mark is 4 pixels less than half a character
+         */
+        int xpos = (mpos * charWidth) + (charWidth / 2);
+        g.drawLine(xpos, (ypos + 2) - (charHeight / 2), xpos, ypos - 2);
       }
     }
   }
@@ -172,6 +191,9 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
   void drawVerticalScale(Graphics g, int startx, int endx, int ypos,
           boolean left)
   {
+    int charHeight = av.getCharHeight();
+    int charWidth = av.getCharWidth();
+
     ypos += charHeight;
 
     if (av.hasHiddenColumns())
@@ -209,20 +231,30 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
         }
       }
 
+      /*
+       * white fill the space for the scale
+       */
+      g.setColor(Color.white);
+      int y = (ypos + (i * charHeight)) - (charHeight / 5);
+      y -= charHeight; // fillRect: origin is top left of rectangle
+      int xpos = left ? 0 : labelWidthWest + charWidth
+              * av.getRanges().getViewportWidth();
+      g.fillRect(xpos, y, left ? labelWidthWest : labelWidthEast,
+              charHeight + 1);
+      y += charHeight; // drawString: origin is bottom left of text
+
       if (value != -1)
       {
+
         /*
-         * draw scale value, justified, with half a character width
+         * draw scale value, right justified, with half a character width
          * separation from the sequence data
          */
         String valueAsString = String.valueOf(value);
         int justify = fm.stringWidth(valueAsString) + charWidth;
-        int xpos = left ? labelWidthWest - justify + charWidth / 2
+        xpos = left ? labelWidthWest - justify + charWidth / 2
                 : getWidth() - justify - charWidth / 2;
 
-        g.setColor(Color.white);
-        int y = (ypos + (i * charHeight)) - (charHeight / 5);
-        g.fillRect(xpos, y, justify, charHeight);
         g.setColor(Color.black);
         g.drawString(valueAsString, xpos, y);
       }
@@ -230,13 +262,22 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
   }
 
   /**
-   * need to make this thread safe move alignment rendering in response to
-   * slider adjustment
+   * Does a fast paint of an alignment in response to a scroll. Most of the
+   * visible region is simply copied and shifted, and then any newly visible
+   * columns or rows are drawn. The scroll may be horizontal or vertical, but
+   * not both at once. Scrolling may be the result of
+   * <ul>
+   * <li>dragging a scroll bar</li>
+   * <li>clicking in the scroll bar</li>
+   * <li>scrolling by trackpad, middle mouse button, or other device</li>
+   * <li>by moving the box in the Overview window</li>
+   * <li>programmatically to make a highlighted position visible</li>
+   * </ul>
    * 
    * @param horizontal
-   *          shift along
+   *          columns to shift right (positive) or left (negative)
    * @param vertical
-   *          shift up or down in repaint
+   *          rows to shift down (positive) or up (negative)
    */
   public void fastPaint(int horizontal, int vertical)
   {
@@ -246,71 +287,78 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
     }
     fastpainting = true;
     fastPaint = true;
-    updateViewport();
 
-    ViewportRanges ranges = av.getRanges();
-    int startRes = ranges.getStartRes();
-    int endRes = ranges.getEndRes();
-    int startSeq = ranges.getStartSeq();
-    int endSeq = ranges.getEndSeq();
-    int transX = 0;
-    int transY = 0;
+    try
+    {
+      int charHeight = av.getCharHeight();
+      int charWidth = av.getCharWidth();
 
-    gg.copyArea(horizontal * charWidth, vertical * charHeight, imgWidth,
-            imgHeight, -horizontal * charWidth, -vertical * charHeight);
+      ViewportRanges ranges = av.getRanges();
+      int startRes = ranges.getStartRes();
+      int endRes = ranges.getEndRes();
+      int startSeq = ranges.getStartSeq();
+      int endSeq = ranges.getEndSeq();
+      int transX = 0;
+      int transY = 0;
 
-    if (horizontal > 0) // scrollbar pulled right, image to the left
-    {
-      transX = (endRes - startRes - horizontal) * charWidth;
-      startRes = endRes - horizontal;
-    }
-    else if (horizontal < 0)
-    {
-      endRes = startRes - horizontal;
-    }
-    else if (vertical > 0) // scroll down
-    {
-      startSeq = endSeq - vertical;
+      gg.copyArea(horizontal * charWidth, vertical * charHeight, imgWidth,
+              imgHeight, -horizontal * charWidth, -vertical * charHeight);
 
-      if (startSeq < ranges.getStartSeq())
-      { // ie scrolling too fast, more than a page at a time
-        startSeq = ranges.getStartSeq();
+      if (horizontal > 0) // scrollbar pulled right, image to the left
+      {
+        transX = (endRes - startRes - horizontal) * charWidth;
+        startRes = endRes - horizontal;
       }
-      else
+      else if (horizontal < 0)
       {
-        transY = imgHeight - ((vertical + 1) * charHeight);
+        endRes = startRes - horizontal;
       }
-    }
-    else if (vertical < 0)
-    {
-      endSeq = startSeq - vertical;
+      else if (vertical > 0) // scroll down
+      {
+        startSeq = endSeq - vertical;
 
-      if (endSeq > ranges.getEndSeq())
+        if (startSeq < ranges.getStartSeq())
+        { // ie scrolling too fast, more than a page at a time
+          startSeq = ranges.getStartSeq();
+        }
+        else
+        {
+          transY = imgHeight - ((vertical + 1) * charHeight);
+        }
+      }
+      else if (vertical < 0)
       {
-        endSeq = ranges.getEndSeq();
+        endSeq = startSeq - vertical;
+
+        if (endSeq > ranges.getEndSeq())
+        {
+          endSeq = ranges.getEndSeq();
+        }
       }
-    }
 
-    gg.translate(transX, transY);
-    drawPanel(gg, startRes, endRes, startSeq, endSeq, 0);
-    gg.translate(-transX, -transY);
+      gg.translate(transX, transY);
+      drawPanel(gg, startRes, endRes, startSeq, endSeq, 0);
+      gg.translate(-transX, -transY);
 
-    repaint();
-    fastpainting = false;
+      repaint();
+    } finally
+    {
+      fastpainting = false;
+    }
   }
 
   @Override
   public void paintComponent(Graphics g)
   {
-    updateViewport();
+    int charHeight = av.getCharHeight();
+    int charWidth = av.getCharWidth();
     BufferedImage lcimg = img; // take reference since other threads may null
     // img and call later.
     super.paintComponent(g);
 
-    if (lcimg != null
-            && (fastPaint
-                    || (getVisibleRect().width != g.getClipBounds().width) || (getVisibleRect().height != g
-                    .getClipBounds().height)))
+    if (lcimg != null && (fastPaint
+            || (getVisibleRect().width != g.getClipBounds().width)
+            || (getVisibleRect().height != g.getClipBounds().height)))
     {
       g.drawImage(lcimg, 0, 0, this);
       fastPaint = false;
@@ -383,6 +431,8 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
    */
   public int getWrappedCanvasWidth(int canvasWidth)
   {
+    int charWidth = av.getCharWidth();
+
     FontMetrics fm = getFontMetrics(av.getFont());
 
     labelWidthEast = 0;
@@ -433,125 +483,161 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
   }
 
   /**
-   * DOCUMENT ME!
+   * Draws as many widths of a wrapped alignment as can fit in the visible
+   * window
    * 
    * @param g
-   *          DOCUMENT ME!
    * @param canvasWidth
-   *          DOCUMENT ME!
+   *          available width in pixels
    * @param canvasHeight
-   *          DOCUMENT ME!
-   * @param startRes
-   *          DOCUMENT ME!
+   *          available height in pixels
+   * @param startColumn
+   *          the first column (0...) of the alignment to draw
    */
   public void drawWrappedPanel(Graphics g, int canvasWidth,
-          int canvasHeight, int startRes)
+          int canvasHeight, final int startColumn)
   {
-    updateViewport();
-    int labelWidth = 0;
-    if (av.getScaleRightWrapped() || av.getScaleLeftWrapped())
-    {
-      FontMetrics fm = getFontMetrics(av.getFont());
-      labelWidth = getLabelWidth(fm);
-    }
-
-    labelWidthEast = av.getScaleRightWrapped() ? labelWidth : 0;
-    labelWidthWest = av.getScaleLeftWrapped() ? labelWidth : 0;
+    int wrappedWidthInResidues = calculateWrappedGeometry(canvasWidth,
+            canvasHeight);
 
-    int hgap = charHeight;
-    if (av.getScaleAboveWrapped())
-    {
-      hgap += charHeight;
-    }
-
-    int cWidth = (canvasWidth - labelWidthEast - labelWidthWest) / charWidth;
+    av.setWrappedWidth(wrappedWidthInResidues);
 
-    av.setWrappedWidth(cWidth);
-
-    av.getRanges().setViewportStartAndWidth(startRes, cWidth);
+    ViewportRanges ranges = av.getRanges();
+    ranges.setViewportStartAndWidth(startColumn, wrappedWidthInResidues);
 
-    int ypos = hgap;
-    int maxwidth = av.getAlignment().getWidth();
+    /*
+     * draw one width at a time (including any scales or annotation shown),
+     * until we have run out of either alignment or vertical space available
+     */
+    int ypos = wrappedSpaceAboveAlignment;
+    int maxWidth = ranges.getVisibleAlignmentWidth();
 
-    if (av.hasHiddenColumns())
+    int start = startColumn;
+    int currentWidth = 0;
+    while ((currentWidth < wrappedVisibleWidths) && (start < maxWidth))
     {
-      maxwidth = av.getAlignment().getHiddenColumns()
-              .findColumnPosition(maxwidth);
+      int endColumn = Math
+              .min(maxWidth, start + wrappedWidthInResidues - 1);
+      drawWrappedWidth(g, ypos, start, endColumn, canvasHeight);
+      ypos += wrappedRepeatHeightPx;
+      start += wrappedWidthInResidues;
+      currentWidth++;
     }
 
-    int annotationHeight = getAnnotationHeight();
-    int sequencesHeight = av.getAlignment().getHeight() * charHeight;
-
-    while ((ypos <= canvasHeight) && (startRes < maxwidth))
-    {
-      drawWrappedWidth(g, startRes, canvasHeight, cWidth, maxwidth, ypos);
-
-      ypos += sequencesHeight + annotationHeight + hgap;
-
-      startRes += cWidth;
-    }
+    drawWrappedDecorators(g, startColumn);
   }
 
   /**
-   * @param g
-   * @param startRes
-   * @param canvasHeight
+   * Calculates and saves values needed when rendering a wrapped alignment.
+   * These depend on many factors, including
+   * <ul>
+   * <li>canvas width and height</li>
+   * <li>number of visible sequences, and height of annotations if shown</li>
+   * <li>font and character width</li>
+   * <li>whether scales are shown left, right or above the alignment</li>
+   * </ul>
+   * 
    * @param canvasWidth
-   * @param maxWidth
-   * @param ypos
+   * @param canvasHeight
+   * @return the number of residue columns in each width
    */
-  protected void drawWrappedWidth(Graphics g, int startRes,
-          int canvasHeight, int canvasWidth, int maxWidth, int ypos)
+  protected int calculateWrappedGeometry(int canvasWidth, int canvasHeight)
   {
-    int endx;
-    endx = startRes + canvasWidth - 1;
+    int charHeight = av.getCharHeight();
+    int charWidth = av.getCharWidth();
 
-    if (endx > maxWidth)
+    /*
+     * width of labels in pixels left and right (if shown)
+     */
+    int labelWidth = 0;
+    if (av.getScaleRightWrapped() || av.getScaleLeftWrapped())
     {
-      endx = maxWidth;
+      FontMetrics fm = getFontMetrics(av.getFont());
+      labelWidth = getLabelWidth(fm);
     }
+    labelWidthEast = av.getScaleRightWrapped() ? labelWidth : 0;
+    labelWidthWest = av.getScaleLeftWrapped() ? labelWidth : 0;
 
-    g.setFont(av.getFont());
-    g.setColor(Color.black);
+    /*
+     * vertical space in pixels between wrapped widths of alignment
+     * - one character height, or two if scale above is drawn
+     */
+    wrappedSpaceAboveAlignment = charHeight
+            * (av.getScaleAboveWrapped() ? 2 : 1);
 
-    if (av.getScaleLeftWrapped())
-    {
-      drawVerticalScale(g, startRes, endx, ypos, true);
-    }
+    /*
+     * height in pixels of the wrapped widths
+     */
+    wrappedRepeatHeightPx = wrappedSpaceAboveAlignment;
+    // add sequences
+    wrappedRepeatHeightPx += av.getRanges().getViewportHeight() * charHeight;
+    // add annotations panel height if shown
+    wrappedRepeatHeightPx += getAnnotationHeight();
 
-    if (av.getScaleRightWrapped())
+    /*
+     * number of residue columns we can show in each row;
+     * this is just canvas width less scale left and right (if shown), 
+     * as a whole multiple of character widths 
+     */
+    int wrappedWidthInResidues = (canvasWidth - labelWidthEast - labelWidthWest)
+            / charWidth;
+
+    /*
+     * number of visible widths (the last one may be part height),
+     * ensuring a part height includes at least one sequence
+     */
+    ViewportRanges ranges = av.getRanges();
+    int xMax = ranges.getVisibleAlignmentWidth();
+    wrappedVisibleWidths = canvasHeight / wrappedRepeatHeightPx;
+    int remainder = canvasHeight % wrappedRepeatHeightPx;
+    if (remainder >= (wrappedSpaceAboveAlignment + charHeight))
     {
-      drawVerticalScale(g, startRes, endx, ypos, false);
+      wrappedVisibleWidths++;
     }
 
-    g.translate(labelWidthWest, 0);
-
-    if (av.getScaleAboveWrapped())
+    /*
+     *  limit visibleWidths to not exceed width of alignment
+     */
+    int maxWidths = (xMax - ranges.getStartRes()) / wrappedWidthInResidues;
+    if (xMax % wrappedWidthInResidues > 0)
     {
-      drawNorthScale(g, startRes, endx, ypos);
+      maxWidths++;
     }
+    wrappedVisibleWidths = Math.min(wrappedVisibleWidths, maxWidths);
 
-    if (av.hasHiddenColumns() && av.getShowHiddenMarkers())
-    {
-      g.setColor(Color.blue);
-      HiddenColumns hidden = av.getAlignment().getHiddenColumns();
-      List<Integer> positions = hidden.findHiddenRegionPositions();
-      for (int pos : positions)
-      {
-        int res = pos - startRes;
+    return wrappedWidthInResidues;
+  }
 
-        if (res < 0 || res > endx - startRes)
-        {
-          continue;
-        }
+  /**
+   * Draws one width of a wrapped alignment, including sequences and
+   * annnotations, if shown, but not scales or hidden column markers
+   * 
+   * @param g
+   * @param ypos
+   * @param startColumn
+   * @param endColumn
+   * @param canvasHeight
+   */
+  protected void drawWrappedWidth(Graphics g, int ypos,
+          int startColumn, int endColumn, int canvasHeight)
+  {
+    int charHeight = av.getCharHeight();
+    int charWidth = av.getCharWidth();
 
-        gg.fillPolygon(new int[] { res * charWidth - charHeight / 4,
-            res * charWidth + charHeight / 4, res * charWidth }, new int[] {
-            ypos - (charHeight / 2), ypos - (charHeight / 2),
-            ypos - (charHeight / 2) + 8 }, 3);
+    ViewportRanges ranges = av.getRanges();
+    int viewportWidth = ranges.getViewportWidth();
 
-      }
-    }
+    int endx = Math.min(startColumn + viewportWidth - 1, endColumn);
+
+    /*
+     * move right before drawing by the width of the scale left (if any)
+     * plus column offset from left margin (usually zero, but may be non-zero
+     * when fast painting is drawing just a few columns)
+     */
+    int xOffset = labelWidthWest
+            + ((startColumn - ranges.getStartRes()) % viewportWidth)
+            * charWidth;
+    g.translate(xOffset, 0);
 
     // When printing we have an extra clipped region,
     // the Printable page which we need to account for here
@@ -559,15 +645,24 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
 
     if (clip == null)
     {
-      g.setClip(0, 0, canvasWidth * charWidth, canvasHeight);
+      g.setClip(0, 0, viewportWidth * charWidth, canvasHeight);
     }
     else
     {
-      g.setClip(0, (int) clip.getBounds().getY(), canvasWidth * charWidth,
-              (int) clip.getBounds().getHeight());
+      g.setClip(0, (int) clip.getBounds().getY(),
+              viewportWidth * charWidth, (int) clip.getBounds().getHeight());
     }
 
-    drawPanel(g, startRes, endx, 0, av.getAlignment().getHeight() - 1, ypos);
+    /*
+     * white fill the region to be drawn (so incremental fast paint doesn't
+     * scribble over an existing image)
+     */
+    gg.setColor(Color.white);
+    gg.fillRect(0, ypos, (endx - startColumn + 1) * charWidth,
+            wrappedRepeatHeightPx);
+
+    drawPanel(g, startColumn, endx, 0, av.getAlignment().getHeight() - 1,
+            ypos);
 
     int cHeight = av.getAlignment().getHeight() * charHeight;
 
@@ -579,15 +674,112 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
         annotations = new AnnotationPanel(av);
       }
 
-      annotations.renderer.drawComponent(annotations, av, g, -1, startRes,
-              endx + 1);
+      annotations.renderer.drawComponent(annotations, av, g, -1,
+              startColumn, endx + 1);
       g.translate(0, -cHeight - ypos - 3);
     }
     g.setClip(clip);
-    g.translate(-labelWidthWest, 0);
+    g.translate(-xOffset, 0);
+  }
+
+  /**
+   * Draws scales left, right and above (if shown), and any hidden column
+   * markers, on all widths of the wrapped alignment
+   * 
+   * @param g
+   * @param startColumn
+   */
+  protected void drawWrappedDecorators(Graphics g, int startColumn)
+  {
+    int charWidth = av.getCharWidth();
+
+    g.setFont(av.getFont());
+    g.setColor(Color.black);
+
+    int ypos = wrappedSpaceAboveAlignment;
+    ViewportRanges ranges = av.getRanges();
+    int viewportWidth = ranges.getViewportWidth();
+    int maxWidth = ranges.getVisibleAlignmentWidth();
+    int widthsDrawn = 0;
+    while (widthsDrawn < wrappedVisibleWidths)
+    {
+      int endColumn = Math.min(maxWidth, startColumn + viewportWidth - 1);
+
+      if (av.getScaleLeftWrapped())
+      {
+        drawVerticalScale(g, startColumn, endColumn - 1, ypos, true);
+      }
+
+      if (av.getScaleRightWrapped())
+      {
+        drawVerticalScale(g, startColumn, endColumn, ypos, false);
+      }
+
+      /*
+       * white fill region of scale above and hidden column markers
+       * (to support incremental fast paint of image)
+       */
+      g.setColor(Color.white);
+      g.fillRect(0, ypos - wrappedSpaceAboveAlignment, viewportWidth
+              * charWidth + labelWidthWest, wrappedSpaceAboveAlignment);
+      g.setColor(Color.black);
+
+      g.translate(labelWidthWest, 0);
+
+      if (av.getScaleAboveWrapped())
+      {
+        drawNorthScale(g, startColumn, endColumn, ypos);
+      }
+
+      if (av.hasHiddenColumns() && av.getShowHiddenMarkers())
+      {
+        drawHiddenColumnMarkers(g, ypos, startColumn, endColumn);
+      }
+
+      g.translate(-labelWidthWest, 0);
+
+      ypos += wrappedRepeatHeightPx;
+      startColumn += viewportWidth;
+      widthsDrawn++;
+    }
   }
 
-  AnnotationPanel annotations;
+  /**
+   * @param g
+   * @param ypos
+   * @param startColumn
+   * @param endColumn
+   */
+  protected void drawHiddenColumnMarkers(Graphics g, int ypos,
+          int startColumn, int endColumn)
+  {
+    int charHeight = av.getCharHeight();
+    int charWidth = av.getCharWidth();
+
+    g.setColor(Color.blue);
+    HiddenColumns hidden = av.getAlignment().getHiddenColumns();
+    List<Integer> positions = hidden.findHiddenRegionPositions();
+    for (int pos : positions)
+    {
+      int res = pos - startColumn;
+
+      if (res < 0 || res > endColumn - startColumn)
+      {
+        continue;
+      }
+
+      /*
+       * draw a downward-pointing triangle at the hidden columns location
+       * (before the following visible column)
+       */
+      int xMiddle = res * charWidth;
+      int[] xPoints = new int[] { xMiddle - charHeight / 4,
+          xMiddle + charHeight / 4, xMiddle };
+      int yTop = ypos - (charHeight / 2);
+      int[] yPoints = new int[] { yTop, yTop, yTop + 8 };
+      gg.fillPolygon(xPoints, yPoints, 3);
+    }
+  }
 
   int getAnnotationHeight()
   {
@@ -611,21 +803,24 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
    * marker.
    * 
    * @param g1
+   *          the graphics context, positioned at the first residue to be drawn
    * @param startRes
-   *          offset of the first column in the visible region (0..)
+   *          offset of the first column to draw (0..)
    * @param endRes
-   *          offset of the last column in the visible region (0..)
+   *          offset of the last column to draw (0..)
    * @param startSeq
-   *          offset of the first sequence in the visible region (0..)
+   *          offset of the first sequence to draw (0..)
    * @param endSeq
-   *          offset of the last sequence in the visible region (0..)
+   *          offset of the last sequence to draw (0..)
    * @param yOffset
    *          vertical offset at which to draw (for wrapped alignments)
    */
   public void drawPanel(Graphics g1, final int startRes, final int endRes,
           final int startSeq, final int endSeq, final int yOffset)
   {
-    updateViewport();
+    int charHeight = av.getCharHeight();
+    int charWidth = av.getCharWidth();
+
     if (!av.hasHiddenColumns())
     {
       draw(g1, startRes, endRes, startSeq, endSeq, yOffset);
@@ -715,6 +910,9 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
   private void draw(Graphics g, int startRes, int endRes, int startSeq,
           int endSeq, int offset)
   {
+    int charHeight = av.getCharHeight();
+    int charWidth = av.getCharWidth();
+
     g.setFont(av.getFont());
     sr.prepare(g, av.isRenderGaps());
 
@@ -736,8 +934,8 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
 
       if (av.isShowSequenceFeatures())
       {
-        fr.drawSequence(g, nextSeq, startRes, endRes, offset
-                + ((i - startSeq) * charHeight), false);
+        fr.drawSequence(g, nextSeq, startRes, endRes,
+                offset + ((i - startSeq) * charHeight), false);
       }
 
       /*
@@ -753,9 +951,9 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
           for (int r = 0; r < visibleResults.length; r += 2)
           {
             sr.drawHighlightedText(nextSeq, visibleResults[r],
-                    visibleResults[r + 1], (visibleResults[r] - startRes)
-                            * charWidth, offset
-                            + ((i - startSeq) * charHeight));
+                    visibleResults[r + 1],
+                    (visibleResults[r] - startRes) * charWidth,
+                    offset + ((i - startSeq) * charHeight));
           }
         }
       }
@@ -779,6 +977,9 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
   void drawGroupsBoundaries(Graphics g1, int startRes, int endRes,
           int startSeq, int endSeq, int offset)
   {
+    int charHeight = av.getCharHeight();
+    int charWidth = av.getCharWidth();
+
     Graphics2D g = (Graphics2D) g1;
     //
     // ///////////////////////////////////
@@ -812,7 +1013,8 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
         {
           sx = (group.getStartRes() - startRes) * charWidth;
           sy = offset + ((i - startSeq) * charHeight);
-          ex = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth) - 1;
+          ex = (((group.getEndRes() + 1) - group.getStartRes()) * charWidth)
+                  - 1;
 
           if (sx + ex < 0 || sx > visWidth)
           {
@@ -820,21 +1022,19 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
           }
 
           if ((sx <= (endRes - startRes) * charWidth)
-                  && group.getSequences(null).contains(
-                          av.getAlignment().getSequenceAt(i)))
+                  && group.getSequences(null)
+                          .contains(av.getAlignment().getSequenceAt(i)))
           {
-            if ((bottom == -1)
-                    && !group.getSequences(null).contains(
-                            av.getAlignment().getSequenceAt(i + 1)))
+            if ((bottom == -1) && !group.getSequences(null)
+                    .contains(av.getAlignment().getSequenceAt(i + 1)))
             {
               bottom = sy + charHeight;
             }
 
             if (!inGroup)
             {
-              if (((top == -1) && (i == 0))
-                      || !group.getSequences(null).contains(
-                              av.getAlignment().getSequenceAt(i - 1)))
+              if (((top == -1) && (i == 0)) || !group.getSequences(null)
+                      .contains(av.getAlignment().getSequenceAt(i - 1)))
               {
                 top = sy;
               }
@@ -845,8 +1045,8 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
               if (group == av.getSelectionGroup())
               {
                 g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
-                        BasicStroke.JOIN_ROUND, 3f, new float[] { 5f, 3f },
-                        0f));
+                        BasicStroke.JOIN_ROUND, 3f, new float[]
+                        { 5f, 3f }, 0f));
                 g.setColor(Color.RED);
               }
               else
@@ -987,14 +1187,11 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
       return false;
     }
     boolean wrapped = av.getWrapAlignment();
-
     try
     {
       fastPaint = !noFastPaint;
       fastpainting = fastPaint;
 
-      updateViewport();
-
       /*
        * to avoid redrawing the whole visible region, we instead
        * redraw just the minimal regions to remove previous highlights
@@ -1134,49 +1331,45 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
   {
     String eventName = evt.getPropertyName();
 
-    if (true/*!av.getWrapAlignment()*/)
+    int scrollX = 0;
+    if (eventName.equals(ViewportRanges.STARTRES))
     {
-      int scrollX = 0;
-      if (eventName.equals(ViewportRanges.STARTRES))
+      // Make sure we're not trying to draw a panel
+      // larger than the visible window
+      ViewportRanges vpRanges = av.getRanges();
+      scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
+      int range = vpRanges.getEndRes() - vpRanges.getStartRes();
+      if (scrollX > range)
       {
-        // Make sure we're not trying to draw a panel
-        // larger than the visible window
-        ViewportRanges vpRanges = av.getRanges();
-        scrollX = (int) evt.getNewValue() - (int) evt.getOldValue();
-        int range = vpRanges.getEndRes() - vpRanges.getStartRes();
-        if (scrollX > range)
-        {
-          scrollX = range;
-        }
-        else if (scrollX < -range)
-        {
-          scrollX = -range;
-        }
+        scrollX = range;
       }
+      else if (scrollX < -range)
+      {
+        scrollX = -range;
+      }
+    }
 
-      // Both scrolling and resizing change viewport ranges: scrolling changes
-      // both start and end points, but resize only changes end values.
-      // Here we only want to fastpaint on a scroll, with resize using a normal
-      // paint, so scroll events are identified as changes to the horizontal or
-      // vertical start value.
-      if (eventName.equals(ViewportRanges.STARTRES))
+    // Both scrolling and resizing change viewport ranges: scrolling changes
+    // both start and end points, but resize only changes end values.
+    // Here we only want to fastpaint on a scroll, with resize using a normal
+    // paint, so scroll events are identified as changes to the horizontal or
+    // vertical start value.
+    if (eventName.equals(ViewportRanges.STARTRES))
+    {
+      // scroll - startres and endres both change
+      if (av.getWrapAlignment())
       {
-        // scroll - startres and endres both change
-        if (av.getWrapAlignment())
-        {
-          fastPaintWrapped(scrollX);
-        }
-        else
-        {
-          fastPaint(scrollX, 0);
-        }
+        fastPaintWrapped(scrollX);
       }
-      else if (eventName.equals(ViewportRanges.STARTSEQ))
+      else
       {
-        // scroll
-        fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
+        fastPaint(scrollX, 0);
       }
     }
+    else if (eventName.equals(ViewportRanges.STARTSEQ))
+    {
+      fastPaint(0, (int) evt.getNewValue() - (int) evt.getOldValue());
+    }
   }
 
   /**
@@ -1190,30 +1383,163 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
    */
   protected void fastPaintWrapped(int scrollX)
   {
-    if (Math.abs(scrollX) > av.getRanges().getViewportWidth())
+    ViewportRanges ranges = av.getRanges();
+
+    if (Math.abs(scrollX) > ranges.getViewportWidth())
     {
       /*
-       * shift of more than one view width is too much
-       * to handle in this method
+       * shift of more than one view width is 
+       * overcomplicated to handle in this method
        */
       fastPaint = false;
       repaint();
       return;
     }
 
+    if (fastpainting || gg == null)
+    {
+      return;
+    }
+
     fastPaint = true;
-    shiftWrappedAlignment(-scrollX);
+    fastpainting = true;
+
+    try
+    {
+      calculateWrappedGeometry(getWidth(), getHeight());
+
+      /*
+       * relocate the regions of the alignment that are still visible
+       */
+      shiftWrappedAlignment(-scrollX);
+
+      /*
+       * add new columns (sequence, annotation)
+       * - at top left if scrollX < 0 
+       * - at right of last two widths if scrollX > 0
+       */
+      if (scrollX < 0)
+      {
+        int startRes = ranges.getStartRes();
+        drawWrappedWidth(gg, wrappedSpaceAboveAlignment, startRes, startRes
+                - scrollX - 1, getHeight());
+      }
+      else
+      {
+        fastPaintWrappedAddRight(scrollX);
+      }
+
+      /*
+       * draw all scales (if  shown) and hidden column markers
+       */
+      drawWrappedDecorators(gg, ranges.getStartRes());
+
+      repaint();
+    } finally
+    {
+      fastpainting = false;
+    }
+  }
+
+  /**
+   * Draws the specified number of columns at the 'end' (bottom right) of a
+   * wrapped alignment view, including sequences and annotations if shown, but
+   * not scales. Also draws the same number of columns at the right hand end of
+   * the second last width shown, if the last width is not full height (so
+   * cannot simply be copied from the graphics image).
+   * 
+   * @param columns
+   */
+  protected void fastPaintWrappedAddRight(int columns)
+  {
+    if (columns == 0)
+    {
+      return;
+    }
+
+    ViewportRanges ranges = av.getRanges();
+    int viewportWidth = ranges.getViewportWidth();
+    int charWidth = av.getCharWidth();
+
+    /**
+     * draw full height alignment in the second last row, last columns, if the
+     * last row was not full height
+     */
+    int visibleWidths = wrappedVisibleWidths;
+    int canvasHeight = getHeight();
+    boolean lastWidthPartHeight = (wrappedVisibleWidths * wrappedRepeatHeightPx) > canvasHeight;
+
+    if (lastWidthPartHeight)
+    {
+      int widthsAbove = Math.max(0, visibleWidths - 2);
+      int ypos = wrappedRepeatHeightPx * widthsAbove
+              + wrappedSpaceAboveAlignment;
+      int endRes = ranges.getEndRes();
+      endRes += widthsAbove * viewportWidth;
+      int startRes = endRes - columns;
+      int xOffset = ((startRes - ranges.getStartRes()) % viewportWidth)
+              * charWidth;
+
+      /*
+       * white fill first to erase annotations
+       */
+      gg.translate(xOffset, 0);
+      gg.setColor(Color.white);
+      gg.fillRect(labelWidthWest, ypos,
+              (endRes - startRes + 1) * charWidth, wrappedRepeatHeightPx);
+      gg.translate(-xOffset, 0);
+
+      drawWrappedWidth(gg, ypos, startRes, endRes, canvasHeight);
+    }
+
+    /*
+     * draw newly visible columns in last wrapped width (none if we
+     * have reached the end of the alignment)
+     * y-offset for drawing last width is height of widths above,
+     * plus one gap row
+     */
+    int widthsAbove = visibleWidths - 1;
+    int ypos = wrappedRepeatHeightPx * widthsAbove
+            + wrappedSpaceAboveAlignment;
+    int endRes = ranges.getEndRes();
+    endRes += widthsAbove * viewportWidth;
+    int startRes = endRes - columns + 1;
+
+    /*
+     * white fill first to erase annotations
+     */
+    int xOffset = ((startRes - ranges.getStartRes()) % viewportWidth)
+            * charWidth;
+    gg.translate(xOffset, 0);
+    gg.setColor(Color.white);
+    int width = viewportWidth * charWidth - xOffset;
+    gg.fillRect(labelWidthWest, ypos, width, wrappedRepeatHeightPx);
+    gg.translate(-xOffset, 0);
+
+    gg.setFont(av.getFont());
+    gg.setColor(Color.black);
 
-    // add new columns (scale above, sequence, annotation)
-    // at top left if scrollX < 0 or bottom right if scrollX > 0
+    if (startRes < ranges.getVisibleAlignmentWidth())
+    {
+      drawWrappedWidth(gg, ypos, startRes, endRes, canvasHeight);
+    }
 
-    repaint();
+    /*
+     * and finally, white fill any space below the visible alignment
+     */
+    int heightBelow = canvasHeight - visibleWidths * wrappedRepeatHeightPx;
+    if (heightBelow > 0)
+    {
+      gg.setColor(Color.white);
+      gg.fillRect(0, canvasHeight - heightBelow, getWidth(), heightBelow);
+    }
   }
 
   /**
    * Shifts the visible alignment by the specified number of columns - left if
-   * negative, right if positive. Includes scale above, left or right and
-   * annotations (if shown). Does not draw newly visible columns.
+   * negative, right if positive. Copies and moves sequences and annotations (if
+   * shown). Scales, hidden column markers and any newly visible columns must be
+   * drawn separately.
    * 
    * @param positions
    */
@@ -1223,18 +1549,15 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
     {
       return;
     }
+    int charWidth = av.getCharWidth();
 
-    int repeatHeight = getRepeatHeightWrapped();
+    int canvasHeight = getHeight();
     ViewportRanges ranges = av.getRanges();
+    int viewportWidth = ranges.getViewportWidth();
     int widthToCopy = (ranges.getViewportWidth() - Math.abs(positions))
             * charWidth;
-    int visibleWidths = getHeight() / repeatHeight;
-    if (getHeight() % repeatHeight > 0)
-    {
-      visibleWidths++;
-    }
-    int viewportWidth = ranges.getViewportWidth();
-    int hgap = charHeight * (av.getScaleAboveWrapped() ? 2 : 1);
+    int heightToCopy = wrappedRepeatHeightPx - wrappedSpaceAboveAlignment;
+    int xMax = ranges.getVisibleAlignmentWidth();
 
     if (positions > 0)
     {
@@ -1245,37 +1568,27 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
        * columns from the right margin of the row above (if any) to the 
        * left margin of the current row
        */
-      int xpos = ranges.getStartRes() + (visibleWidths - 1) * viewportWidth;
 
       /*
-       * get y-offset of last wrapped width
+       * get y-offset of last wrapped width, first row of sequences
        */
-      int y = getHeight() / repeatHeight * repeatHeight;
+      int y = canvasHeight / wrappedRepeatHeightPx * wrappedRepeatHeightPx;
+      y += wrappedSpaceAboveAlignment;
       int copyFromLeftStart = labelWidthWest;
       int copyFromRightStart = copyFromLeftStart + widthToCopy;
 
       while (y >= 0)
       {
-        // todo limit repeatHeight for a last part height width
-        gg.copyArea(copyFromLeftStart, y, widthToCopy, repeatHeight,
+        gg.copyArea(copyFromLeftStart, y, widthToCopy, heightToCopy,
                 positions * charWidth, 0);
         if (y > 0)
         {
-          gg.copyArea(copyFromRightStart, y - repeatHeight, positions
-                  * charWidth, repeatHeight, -widthToCopy, repeatHeight);
-        }
-
-        if (av.getScaleLeftWrapped())
-        {
-          drawVerticalScale(gg, xpos, xpos + viewportWidth, y + hgap, true);
-        }
-        if (av.getScaleRightWrapped())
-        {
-          drawVerticalScale(gg, xpos, xpos + viewportWidth, y + hgap, false);
+          gg.copyArea(copyFromRightStart, y - wrappedRepeatHeightPx,
+                  positions * charWidth, heightToCopy, -widthToCopy,
+                  wrappedRepeatHeightPx);
         }
 
-        y -= repeatHeight;
-        xpos -= viewportWidth;
+        y -= wrappedRepeatHeightPx;
       }
     }
     else
@@ -1287,32 +1600,24 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
        * columns from the left margin of the row below (if any) to the 
        * right margin of the current row
        */
-      int xpos = ranges.getStartRes();
-      int y = 0;
+      int xpos = av.getRanges().getStartRes();
+      int y = wrappedSpaceAboveAlignment;
       int copyFromRightStart = labelWidthWest - positions * charWidth;
 
-      while (y < getHeight())
+      while (y < canvasHeight)
       {
-        // todo limit repeatHeight for a last part height width
-        gg.copyArea(copyFromRightStart, y, widthToCopy, repeatHeight,
+        gg.copyArea(copyFromRightStart, y, widthToCopy, heightToCopy,
                 positions * charWidth, 0);
-        if (y + repeatHeight < getHeight())
-        {
-          gg.copyArea(labelWidthWest, y + repeatHeight, -positions
-                  * charWidth, repeatHeight, widthToCopy, -repeatHeight);
-        }
-
-        if (av.getScaleLeftWrapped())
-        {
-          drawVerticalScale(gg, xpos, xpos + viewportWidth, y + hgap, true);
-        }
-        if (av.getScaleRightWrapped())
+        if (y + wrappedRepeatHeightPx < canvasHeight - wrappedRepeatHeightPx
+                && (xpos + viewportWidth <= xMax))
         {
-          drawVerticalScale(gg, xpos, xpos + viewportWidth, y + hgap, false);
+          gg.copyArea(labelWidthWest, y + wrappedRepeatHeightPx, -positions
+                  * charWidth, heightToCopy, widthToCopy,
+                  -wrappedRepeatHeightPx);
         }
 
-        y += repeatHeight;
-        xpos += ranges.getViewportWidth();
+        y += wrappedRepeatHeightPx;
+        xpos += viewportWidth;
       }
     }
   }
@@ -1333,11 +1638,13 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
     {
       return false;
     }
-  
+    int charHeight = av.getCharHeight();
+
     boolean matchFound = false;
 
+    calculateWrappedGeometry(getWidth(), getHeight());
     int wrappedWidth = av.getWrappedWidth();
-    int wrappedHeight = getRepeatHeightWrapped();
+    int wrappedHeight = wrappedRepeatHeightPx;
 
     ViewportRanges ranges = av.getRanges();
     int canvasHeight = getHeight();
@@ -1434,25 +1741,4 @@ public class SeqCanvas extends JComponent implements ViewportListenerI
   
     return matchFound;
   }
-
-  /**
-   * Answers the height in pixels of a repeating section of the wrapped
-   * alignment, including space above, scale above if shown, sequences, and
-   * annotation panel if shown
-   * 
-   * @return
-   */
-  protected int getRepeatHeightWrapped()
-  {
-    // gap (and maybe scale) above
-    int repeatHeight = charHeight * (av.getScaleAboveWrapped() ? 2 : 1);
-
-    // add sequences
-    repeatHeight += av.getRanges().getViewportHeight() * charHeight;
-
-    // add annotations panel height if shown
-    repeatHeight += getAnnotationHeight();
-
-    return repeatHeight;
-  }
 }