Fix word-wrap scroll jump: visual-line mapping via WrapIndex

Every scroll<->content mapping site (window start, sub-line shift, tap
mapping, max-scroll clamp, selection menu/handle positions) assumed
1 logical line = 1 visual line. When the viewport top crossed the
bottom of a wrapped line, the view jumped past the wrapped remainder
(jump magnitude (count-1)*lh) instead of moving pixel-by-pixel.

- WrapIndex (internal/editor/wrap_index.go): Fenwick tree of
  per-logical-line visual-line counts, parallel to the LineIndex;
  built at index-build time, bookkept by the same
  UpdateLineIndexAfter{Insert,Delete} hooks (never under-stale: every
  touched line resets to the estimate, the next shaping pass
  re-corrects it).
- scrollVisualDecompose: the scroll offset lives in visual-line space:
  k = LineForVisual(floor(s/lh)), r = s - V(k)*lh. All mapping sites
  go through it, so the viewport top is always exactly s into the
  document's visual space (V(k)*lh + r = s) — the jump invariant.
  All-ones index reduces to the legacy 1:1 mapping (pre-shaping and
  non-wrapped behavior unchanged by construction).
- Correction pipeline: the renderer's per-frame VisualLineStarts are
  grouped per logical line and written back (applyWrapCounts). The
  layout feedback now carries the exact window text the layout was
  shaped for (carried in the frame) plus the window start line and the
  content-edit counter; corrections apply only on edit-counter match,
  and grouping over the current window text (wrong after a scroll moved
  the window) is no longer possible.
- bytePosToScreenXY now applies the sub-line shift and the scaled line
  pitch: the selection menu/handles were off by up to a full line.
- maxScroll uses TotalVisuals() with the effective (font-scaled) line
  height; the bottom clamp lands exactly on the file end for wrapped
  content.
- VisibleByteRange returns the real start line (was hardcoded 0).
- emitFrame: replace the unread handoff frame with the newer snapshot
  instead of dropping it — a dropped final frame was never re-emitted
  (emission is event-driven), leaving the consumer one state behind
  forever; fixes the pre-existing TestRealFile_ShiftSelectionInsert
  failure. Still non-blocking.

Tests (mutation-verified where practical): wrap_index_test.go (Fenwick
vs naive model, 3000 ops), wrap_bookkeeping_test.go (edit hooks vs
shadow-string oracle, 400 ops — caught a real m=0 under-marking),
wrap_mapping_test.go (the jump regression: V(k)*lh + r == s over sweeps
+ random offsets; legacy-identity pin; boundary sweep), wrap_apply_test.go
(VisualLineStarts grouping + guards — the first version exposed the
always-true WindowStartByte guard that blocked all post-scroll
corrections). go test -race ./... green.

On-device (emulator, 60 wrapped lines): dp sweep 0/17/50/67/134/340
lands on LINE000-vl0/1/3, LINE001-vl0, LINE002-vl0, LINE005-vl0 —
pixel-exact 1:1, no jump (dp 134 is where the old code jumped to
LINE008); bottom clamp exact.

Docs: architecture.md §6.2 (visual-line space invariant),
development_plan.md (Phase 13), spec.md (wrap + clamp lines).
This commit is contained in:
gmp
2026-08-17 19:46:47 -04:00
parent 95a2143e16
commit 83f7affee9
15 changed files with 1390 additions and 67 deletions
+47 -7
View File
@@ -234,18 +234,58 @@ Only the visible byte range is shaped and drawn each frame:
endLine]` via the `LineIndex`, then to a byte range. The range is always
bounded by real lines of the document.
- **Scroll decomposition invariant.** The scroll offset s is split into a
content line k and sub-line remainder r (k·lh ≤ s < (k+1)·lh) by a single
float64 floor decomposition, and the three consumers of that split MUST
stay in lockstep: the window start line (VisibleByteRange), the renderer's
sub-line shift (the windowed layout is drawn shifted up by r), and the tap
mapping (`tapLocalY` adds r). With them consistent, a tap a dp below the
region top always maps to content line k + ⌊(a+r)/lh⌋ =
⌊(a+s)/lh⌋ — the line actually under the finger — for every s ≥ 0. The
content line k and sub-line remainder r by a single float64 floor
decomposition, and all consumers of that split MUST stay in lockstep: the
window start line (VisibleByteRange), the renderer's sub-line shift (the
windowed layout is drawn shifted up by r), the tap mapping (`tapLocalY`
adds r), the selection menu/handle positions (`bytePosToScreenXY`), and the
max-scroll clamp. With them consistent, a tap a dp below the region top
always maps to the line actually under the finger for every s ≥ 0. The
decomposition must be computed in float64: a raw `int(s/lh)` in the Dp
float32 domain can round the quotient UP across an integer boundary while
a float64 mod still reflects the line below, so the window start and the
remainder disagree by one line in a sub-pixel-wide band of offsets and the
whole rendered window (hence every tapped line) shifts by one.
- **Word wrap: the visual-line space (WrapIndex).** A wrapped logical line
occupies several visual lines, so the scroll offset lives in VISUAL-line
space, not logical-line space. Every scroll↔content mapping site
(window start, sub-line shift, tap-to-line, max scroll) MUST go through
the same conversion, or the content jumps: when the viewport top crosses
the bottom of a wrapped line, a 1:1 logical↔visual mapping skips the
wrapped remainder (jump magnitude (count-1)·lh) instead of moving
pixel-by-pixel. The conversion is backed by the `WrapIndex`, a Fenwick
tree of per-logical-line visual-line counts (built parallel to the
LineIndex, same line set, updated by the same edit hooks):
- **Invariant:** with k the logical line at the viewport top and r the
sub-line shift, the viewport top is ALWAYS exactly s into the document's
visual space: `V(k)·lh + r = s`, where V(k) is the prefix sum of counts
before line k. Equivalently k = LineForVisual(⌊s/lh⌋) and r = s − V(k)·lh
(0 ≤ r < count(k)·lh: a wrapped line's top may sit several visual lines
above the viewport). Any mapping that breaks the identity silently skips
or re-shows content — the scroll jump. An all-ones WrapIndex (the state
before any shaping correction lands) makes V(k)=k and the mapping
reduces to the legacy 1:1 behavior, so pre-shaping and non-wrapped files
are unchanged by construction.
- **Correction pipeline:** the renderer's per-frame `VisualLineStarts`
(one entry per visual line, window-relative) are grouped per logical
line and written back into the WrapIndex (the layout feedback carries
the exact window text it was shaped for, the window's first logical
line, and the content-edit counter; the correction is applied only if
the edit counter matches, so a layout shaped before an edit never
stamps shifted lines). Counts are content- and width-dependent, not
window-dependent: once known they are globally valid until an edit or a
wrap-width change.
- **Edit staleness:** the UpdateLineIndexAfter{Insert,Delete} hooks
bookkeep the WrapIndex in the same pass as the LineIndex (line inserts/
deletes shift counts; touched lines reset to the estimate 1). The rule
is never under-stale: every line whose content changed is reset, and
extra resets (over-stale) are always safe — the next frame that shapes
the line re-corrects it. A stale estimate is an under-count (count 1),
which only shortens maxScroll and compresses the mapping until the
correction lands (a self-heating warm-up, never corruption).
- Max scroll is `TotalVisuals()·lh − regionH + lh/2` with the
font-scale-effective line height; it grows incrementally as shaped
counts arrive (pre-shaping it equals the no-wrap estimate).
- **Font-scale axis.** The shaper draws baselines in sp, so on Android the
rendered line pitch in density-dp is `EditorLineHeight()*fontScale`
(`fontScale = Metric.PxPerSp/PxPerDp`, the user font-size setting).
+61
View File
@@ -565,6 +565,67 @@ Insert and one entry in UpdateLineIndexAfterInsert are both caught in ms.
with a straggling write can only lose freshness (unique temps keep every
rename a complete snapshot).
### Phase 13 — word-wrap scroll jump — DONE (2026-08-17)
**Bug (user-reported, content-dependent, not a performance problem):**
scrolling a wrapped file, the viewport jumped past the wrapped remainder of a
logical line the moment its bottom crossed the viewport top, instead of moving
pixel-by-pixel with the finger. Jump magnitude = (count−1)·lh, where count is
the line's visual-line count. Root cause: every scroll↔content mapping site
assumed 1 logical line = 1 visual line (V(k)=k): the window start line
(`visibleByteRangePrecise`), the renderer sub-line shift, the tap mapping
(`tapLocalY`), the max-scroll clamp, and `bytePosToScreenXY` (which also
ignored the sub-line shift entirely — the selection menu/handles were off by
up to a full line, a second latent bug fixed in the same change).
**Fix:** a `WrapIndex` (Fenwick tree of per-logical-line visual-line counts,
parallel to the LineIndex) routes every mapping site through one conversion:
the scroll offset lives in visual-line space, k = LineForVisual(⌊s/lh⌋),
r = s − V(k)·lh. Counts are corrected per frame from the renderer's
`VisualLineStarts` (the layout feedback now carries the exact window text the
layout was shaped for, its first logical line, and the content-edit counter;
corrections apply only when the edit counter matches). The edit hooks
(UpdateLineIndexAfter{Insert,Delete}) bookkeep the index in the same pass as
the LineIndex under the never-under-stale rule. Invariant (see
architecture.md §6.2): the viewport top is always exactly s into the
document's visual space (V(k)·lh + r = s); an all-ones index reduces to the
legacy 1:1 mapping, so pre-shaping and non-wrapped behavior are unchanged by
construction.
**Tests (all mutation-verified where practical):**
- `wrap_index_test.go`: Fenwick ops (Set/SetRange/Insert/Delete/LineForVisual/
prefixes) vs a naive model, 3000 random ops; all-ones-is-identity pin.
- `wrap_bookkeeping_test.go`: the edit hooks vs a shadow-string oracle (400
random insert/delete ops; changed lines must be re-stamped, survivors keep
counts). Caught a real under-marking: an insertion with no newline left the
containing line's stale count (m=0 skip).
- `wrap_mapping_test.go`: the jump regression — V(k)·lh + r == s over a 4000-
step sweep + 2000 random offsets on a fabricated wrapped file; the legacy
identity pin (all-ones and no-index reduce to the old mapping); a
boundary sweep across every wrapped-line boundary (no skip, no repeat,
fixed lines move exactly finger-speed).
- `wrap_apply_test.go`: VisualLineStarts→logical-line grouping (multi-wrap
line, empty line, trailing-newline edge, guard early-outs). The first
version of the test exposed a production bug: the correlation guard
(`WindowStartByte > len(windowText)`) was always true at non-zero scroll,
so corrections could never apply after scrolling; and grouping over the
CURRENT window text (instead of the shaped one) mis-attributes counts
whenever a scroll moved the window between shaping and delivery. Both
fixed by carrying the shaped window text in the frame/feedback.
- Also fixed a pre-existing e2e failure (`TestRealFile_ShiftSelectionInsert`):
`emitFrame` dropped a frame when the handoff buffer was full and, since
emission is event-driven, a dropped FINAL frame was never re-emitted — the
consumer could sit one state behind forever. `emitFrame` now replaces the
unread frame with the newer snapshot (latest frame wins) instead of
dropping; still non-blocking.
**On-device (emulator, wraptest.txt: 60 logical lines × 4 visual lines):**
dp sweep via the debug cmd poller: dp 0/17/50/67/134/340 land on
LINE000-vl0 / LINE000-vl1 / LINE000-vl3 / LINE001-vl0 / LINE002-vl0 /
LINE005-vl0 — pixel-exact 1:1 finger↔content, no jump at the wrapped
boundaries (dp 134 is where the old code jumped to LINE008); bottom clamp
lands exactly on the file end via the wrap-aware TotalVisuals().
## 6. File-size decision (re-framed)
v1 framed this as "accept a limit vs build a windowed editor." The live repo
+11 -4
View File
@@ -48,7 +48,11 @@ elsewhere.
(Swipe-typing support follows from the same IME path; final sign-off on a
physical device is the one open validation item.)
- **Word wrap:** on by default; wrapped lines are virtual — the buffer stores
only real newlines.
only real newlines. Scrolling wrapped content is continuous: the viewport
moves pixel-by-pixel with the finger, including across the bottom of a
wrapped line (no jumping over wrapped remainders) — the scroll offset maps
to content through the per-line visual-line counts corrected by the
renderer every frame (architecture.md §6.2).
- **Virtualized viewport:** only the visible byte range is shaped and drawn
each frame (typically ~4 KB of a large file), keeping frame cost and shaper
memory constant regardless of file size.
@@ -141,9 +145,12 @@ Full details, channel topology, and ownership rules: [`architecture.md`](./archi
6. **Logic work stays < 16 ms.** Anything that can block or scan more than the
viewport goes to the worker pool.
7. **Scroll offset is always clamped to `[0, maxScroll]`,** where
`maxScroll = contentHeight − viewportHeight` floored at 0. A file whose
content fits the viewport has `maxScroll = 0` and cannot scroll. Verified
on-device across 2→130,955 lines (`development_plan.md` Phase 6).
`maxScroll = contentHeight − viewportHeight` floored at 0 and
`contentHeight` counts VISUAL lines (a wrapped line is taller than one
line pitch). A file whose content fits the viewport has `maxScroll = 0`
and cannot scroll. Verified on-device across 2→130,955 lines
(`development_plan.md` Phase 6); the wrap-aware clamp lands exactly on the
file end for wrapped content (Phase 13).
## 6. Performance expectations (validated on-device)