Pinch-to-font-size (continuous, content-point pinned) + IME-open scroll fix
Two feature bodies accumulated in the working tree:
1. Pinch to change the app font size, continuously (no snapping):
- internal/ui/pinch_tracker.go: logic-free touch state machine.
Two-mover formation (the resting palm can land first or last;
movement is the only signal valid for both), pair = the mover
pair whose distance changed most, baseline = press distance
(formDist), lazy pending releases, survivor-scroll forwarding
after a pair break. Robust to ~1 fps frames: a whole pinch can
land in one drain (formDist/brokeFactor/lazy releases).
- render.go: pinch probe (raw pointer events) + grab lifecycle so
the pair is exclusive (scroll sees nothing of the pair) and the
survivor's finger keeps working as a scroll after the pinch.
- state.go/logic.go/session.go/frame.go: app-local float font
scale, content-point pin (buffer byte + offset from baseline,
not a layout point, so rewrap keeps the same character under
the center), restore/font pins, session persistence.
- pinch_test.go, pinch_font_test.go, tag_identity_test.go,
real_draw_probe_test.go: unit + real-Renderer/real-Router tests.
2. Soft keyboard must not shift content:
- Root cause: gioui.org/app calls Router.RevealFocus on any frame
the viewport shrinks (IME open under adjustResize) and
synthesizes a pointer.Scroll nudge aimed at the focused field's
stale pre-resize bounds; gesture.Scroll consumed it -> a 32 dp
content jump.
- Fix: main.go flags the shrink frame; render.go drains that one
synthetic scroll for the gesture's tag before Update (scroll-
range clamping cannot work: the router UNIONs ranges across
frames). Finger scroll (pointer.Drag) and the flinger are
untouched. reveal_focus_drain_test.go reproduces RevealFocus at
the router level and verifies the drain + zero delta.
Also: tools/touchinject (platform-signed emulator multi-touch
injection harness + e2e script, adb has no two-finger input),
docs (spec 2.2 + development_plan 18-20), .gitignore, gofmt.
This commit is contained in:
@@ -23,9 +23,13 @@ import (
|
||||
// with; the main goroutine compares it against the (main-owned) search
|
||||
// widget's text and forwards changes via SearchQueryChan.
|
||||
type Frame struct {
|
||||
Elems []ui.Element
|
||||
Scale float32
|
||||
FontScale float32 // user font-size setting the logic bookkeeping used
|
||||
Elems []ui.Element
|
||||
Scale float32
|
||||
FontScale float32 // user font-size setting the logic bookkeeping used
|
||||
// AppFontScale is the app-local pinch font scale (1.0 = default, 0 =
|
||||
// not set yet). The renderer multiplies the editor font size by it;
|
||||
// FontScale is already folded into gtx.Metric (PxPerSp).
|
||||
AppFontScale float32
|
||||
FocusedElementID string
|
||||
Query string
|
||||
// FindQuery: the in-file search query the logic goroutine has processed
|
||||
@@ -36,6 +40,10 @@ type Frame struct {
|
||||
// FindClearSeq mirrors EditorState.Find.ClearSeq: main wipes the widget
|
||||
// input once per NEW value (the X button cleared the logic-side query).
|
||||
FindClearSeq int
|
||||
// ScrollOffset is the editor scroll offset this frame's elements laid
|
||||
// out at, shipped with the shaped glyph layout (LayoutFeedback) so the
|
||||
// logic can express layout positions in content coordinates.
|
||||
ScrollOffset ui.Dp
|
||||
// WindowStartByte / WindowStartLine / EditSeq: the editor window this
|
||||
// frame's elements describe. The main goroutine forwards them with the
|
||||
// shaped glyph layout (LayoutFeedback) so the logic goroutine can apply
|
||||
@@ -61,10 +69,12 @@ func (l *Logic) frameOf(elems []ui.Element) Frame {
|
||||
Elems: elems,
|
||||
Scale: l.state.scale,
|
||||
FontScale: l.state.fontScale,
|
||||
AppFontScale: l.state.appFontScale,
|
||||
FocusedElementID: l.state.FocusedElementID,
|
||||
Query: l.state.Browser.Query,
|
||||
FindQuery: l.state.Editor.Find.Query,
|
||||
FindClearSeq: l.state.Editor.Find.ClearSeq,
|
||||
ScrollOffset: l.state.ScrollOffset,
|
||||
WindowStartByte: l.state.Editor.IMEWindowStartByte,
|
||||
WindowStartLine: l.state.WindowStartLine,
|
||||
WindowText: l.state.Editor.IMEWindowText,
|
||||
|
||||
@@ -123,9 +123,20 @@ type Logic struct {
|
||||
// restored window itself has shaped (or a timeout, or the user or a
|
||||
// search takes over), the offset is re-derived from the pinned line
|
||||
// after each correction.
|
||||
restoreScrollLine int
|
||||
restoreScrollSub float64
|
||||
restorePinDeadline time.Time
|
||||
restoreScrollLine int
|
||||
restoreScrollSub float64
|
||||
restorePinDeadline time.Time
|
||||
// fontPin/fontPinM implement the pinch font-pin (see
|
||||
// setFontPin/refreshFontPin in session.go): the CONTENT point under the
|
||||
// pinch center (glyph byte + offset from its baseline, with a
|
||||
// line/fragment/sub-line fallback) and the center's region-relative Y
|
||||
// (dp). While armed, every shaped layout re-derives the scroll offset to
|
||||
// keep that content point under the center as the font scale — and, a
|
||||
// few frames later, the rewrap — changes.
|
||||
fontPin contentPin
|
||||
fontPinM float64
|
||||
fontPinArmed bool
|
||||
fontPinDeadline time.Time
|
||||
scaleSeen bool
|
||||
restoreContentLanded bool
|
||||
sessionSaver func(SessionState)
|
||||
@@ -307,6 +318,12 @@ func (l *Logic) Run() {
|
||||
l.refreshRestorePin()
|
||||
}
|
||||
}
|
||||
// Pinch font-pin (see refreshFontPin): the fresh layout may
|
||||
// have rewrapped the pinned line; re-derive so the pinned
|
||||
// content point stays under the pinch center.
|
||||
if l.fontPinArmed {
|
||||
l.refreshFontPin(fb)
|
||||
}
|
||||
// Search settle (see EditorState.findSettle): the shaping above
|
||||
// may have corrected the wrap counts around a find-jumped
|
||||
// viewport; re-scroll while the correction still matters.
|
||||
@@ -372,6 +389,7 @@ func (l *Logic) openFile(path string) {
|
||||
if l.restoreFile != "" && l.restoreFile != path {
|
||||
l.abortRestore() // a different open cancels the in-flight one
|
||||
}
|
||||
l.releaseFontPin() // the pin names lines of the previous file
|
||||
// Discard find results for the previous file; the query is kept
|
||||
// (see EditorState.findReset) and re-scanned against the new file.
|
||||
TheState.Editor.findReset()
|
||||
@@ -492,10 +510,11 @@ func (l *Logic) EnableDebugCmdPoll(dir string) {
|
||||
}()
|
||||
}
|
||||
|
||||
// applyDebugCmd applies a one-shot debug scroll command from the cmd-file
|
||||
// poller. Commands: "open <path>" (any page), and, on the editor page,
|
||||
// "top", "bottom", "frac <0..1>", "dp <int>". Must be called on the logic
|
||||
// goroutine.
|
||||
// applyDebugCmd applies a one-shot debug command from the cmd-file poller.
|
||||
// Commands: "open <path>" (any page), and, on the editor page, "top",
|
||||
// "bottom", "frac <0..1>", "dp <int>", "pinch <factor>" (relative app font
|
||||
// scale, as the renderer's pinch probe would deliver) and "fontsize <v>"
|
||||
// (absolute app font scale). Must be called on the logic goroutine.
|
||||
func (l *Logic) applyDebugCmd(cmd string) {
|
||||
s := l.state
|
||||
fields := strings.Fields(cmd)
|
||||
@@ -515,6 +534,45 @@ func (l *Logic) applyDebugCmd(cmd string) {
|
||||
l.emitFrame() // OpenFile only mutates state (the tap path emits via its handler)
|
||||
return
|
||||
}
|
||||
// App-local font scale (pinch zoom). Drives the full logic->frame->render
|
||||
// path the same way a real pinch does (HandleFontPinch is the handler a
|
||||
// FontPinchEvent carries); adb has no two-finger input, so these
|
||||
// commands are the on-emulator test hook. `pinch` anchors at the CENTER
|
||||
// of the editor region (where a real pinch usually starts); `fontsize`
|
||||
// is an absolute top-anchored set.
|
||||
if fields[0] == "pinch" || fields[0] == "fontsize" {
|
||||
if s.page != EditorPage {
|
||||
log.Printf("DebugCmd: %q ignored (not on editor page)", cmd)
|
||||
return
|
||||
}
|
||||
if len(fields) < 2 {
|
||||
log.Printf("DebugCmd: %s needs a value", fields[0])
|
||||
return
|
||||
}
|
||||
f, err := strconv.ParseFloat(fields[1], 32)
|
||||
if err != nil || f <= 0 {
|
||||
log.Printf("DebugCmd: bad %s value %q", fields[0], fields[1])
|
||||
return
|
||||
}
|
||||
if fields[0] == "pinch" {
|
||||
if f > 100 { // a single frame's pinch never spans this much
|
||||
log.Printf("DebugCmd: pinch factor out of range: %v", f)
|
||||
return
|
||||
}
|
||||
HandleFontPinch(ui.FontPinchEvent{
|
||||
Scale: float32(f),
|
||||
Center: ui.Point{
|
||||
X: s.EditorRegion.X + s.EditorRegion.W/2,
|
||||
Y: s.EditorRegion.Y + s.EditorRegion.H/2,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
SetAppFontScale(float32(f))
|
||||
}
|
||||
log.Printf("DebugCmd: %q -> appFontScale=%.4f scroll=%d", cmd, s.appFontScale, int(s.ScrollOffset))
|
||||
l.emitFrame()
|
||||
return
|
||||
}
|
||||
if s.page != EditorPage {
|
||||
log.Printf("DebugCmd: %q ignored (not on editor page)", cmd)
|
||||
return
|
||||
@@ -555,6 +613,7 @@ func (l *Logic) applyDebugCmd(cmd string) {
|
||||
if target > s.MaxScroll {
|
||||
target = s.MaxScroll
|
||||
}
|
||||
l.releaseFontPin() // a debug scroll takes over the viewport
|
||||
s.ScrollOffset = target
|
||||
log.Printf("DebugCmd: %q -> scroll=%d maxScroll=%d", cmd, int(s.ScrollOffset), int(s.MaxScroll))
|
||||
l.emitFrame()
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
package editor
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"pad/internal/ui"
|
||||
)
|
||||
|
||||
// These tests cover the app-local pinch font scale: EffectiveLineHeight must
|
||||
// follow the product of the system font scale and the app scale, and the
|
||||
// pinch handler must apply the relative factor continuously (no rounding to
|
||||
// whole points) while keeping the viewport top anchored (scroll offset
|
||||
// rescaled in lockstep with the line height).
|
||||
|
||||
func TestEffectiveLineHeight_FollowsAppFontScale(t *testing.T) {
|
||||
TheLogic = nil
|
||||
TheState = NewState()
|
||||
defer func() { TheState.appFontScale = 1.0 }()
|
||||
|
||||
cases := []struct {
|
||||
sys, app float32
|
||||
want float64
|
||||
}{
|
||||
{0, 1.0, float64(EditorLineHeight())}, // both unknown/default
|
||||
{1.3, 1.0, float64(EditorLineHeight()) * 1.3},
|
||||
{1.0, 1.7, float64(EditorLineHeight()) * 1.7},
|
||||
{1.3, 1.7, float64(EditorLineHeight()) * 1.3 * 1.7},
|
||||
{1.0, 0.5, float64(EditorLineHeight()) * 0.5},
|
||||
}
|
||||
for _, c := range cases {
|
||||
TheState.fontScale = c.sys
|
||||
TheState.appFontScale = c.app
|
||||
got := float64(EffectiveLineHeight())
|
||||
if math.Abs(got-c.want) > 1e-5 {
|
||||
t.Errorf("sys=%v app=%v: EffectiveLineHeight=%v want %v", c.sys, c.app, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleFontPinch_ContinuousAndAnchored(t *testing.T) {
|
||||
TheLogic = nil
|
||||
TheState = NewState()
|
||||
defer func() { TheState.appFontScale = 1.0; TheState.ScrollOffset = 0 }()
|
||||
|
||||
// Start scrolled to a line boundary: 100 lines at the default pitch.
|
||||
lh := float64(EffectiveLineHeight())
|
||||
TheState.ScrollOffset = ui.Dp(100 * lh)
|
||||
|
||||
// A sequence of small relative factors: the product is 1.1^5 ~ 1.61051,
|
||||
// a non-representable float32 — rounding to whole points (or to any
|
||||
// fixed step) would not land here.
|
||||
for i := 0; i < 5; i++ {
|
||||
HandleFontPinch(ui.FontPinchEvent{Scale: 1.1})
|
||||
}
|
||||
want := float64(1.1) * 1.1 * 1.1 * 1.1 * 1.1
|
||||
if math.Abs(float64(TheState.appFontScale)-want) > 1e-6 {
|
||||
t.Errorf("appFontScale=%v want %v (continuous, no snapping)", TheState.appFontScale, want)
|
||||
}
|
||||
// The scroll offset rescaled by the same ratio: the same line (100) at
|
||||
// the same sub-line fraction (0) stays on top.
|
||||
wantOff := 100 * lh * want
|
||||
if got := float64(TheState.ScrollOffset); math.Abs(got-wantOff) > 1e-3 {
|
||||
t.Errorf("ScrollOffset=%v want %v (anchor preserved)", got, wantOff)
|
||||
}
|
||||
// EffectiveLineHeight follows the new scale.
|
||||
wantLH := lh * want
|
||||
if got := float64(EffectiveLineHeight()); math.Abs(got-wantLH) > 1e-5 {
|
||||
t.Errorf("EffectiveLineHeight=%v want %v", got, wantLH)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleFontPinch_Clamps(t *testing.T) {
|
||||
TheLogic = nil
|
||||
TheState = NewState()
|
||||
defer func() { TheState.appFontScale = 1.0; TheState.ScrollOffset = 0 }()
|
||||
|
||||
// Zoom out past the minimum.
|
||||
HandleFontPinch(ui.FontPinchEvent{Scale: 0.1})
|
||||
if TheState.appFontScale != MinAppFontScale {
|
||||
t.Errorf("appFontScale=%v want MinAppFontScale %v", TheState.appFontScale, MinAppFontScale)
|
||||
}
|
||||
// Zoom in past the maximum.
|
||||
HandleFontPinch(ui.FontPinchEvent{Scale: 100})
|
||||
if TheState.appFontScale != MaxAppFontScale {
|
||||
t.Errorf("appFontScale=%v want MaxAppFontScale %v", TheState.appFontScale, MaxAppFontScale)
|
||||
}
|
||||
// At the maximum, further zoom-in is a no-op (including the scroll).
|
||||
TheState.ScrollOffset = ui.Dp(123)
|
||||
HandleFontPinch(ui.FontPinchEvent{Scale: 1.5})
|
||||
if TheState.appFontScale != MaxAppFontScale {
|
||||
t.Errorf("appFontScale=%v want MaxAppFontScale %v", TheState.appFontScale, MaxAppFontScale)
|
||||
}
|
||||
if float64(TheState.ScrollOffset) != 123 {
|
||||
t.Errorf("ScrollOffset=%v want 123 (unchanged at the clamp)", TheState.ScrollOffset)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetAppFontScale_Absolute(t *testing.T) {
|
||||
TheLogic = nil
|
||||
TheState = NewState()
|
||||
defer func() { TheState.appFontScale = 1.0; TheState.ScrollOffset = 0 }()
|
||||
|
||||
lh := float64(EffectiveLineHeight())
|
||||
TheState.ScrollOffset = ui.Dp(50 * lh)
|
||||
SetAppFontScale(2.0)
|
||||
if TheState.appFontScale != 2.0 {
|
||||
t.Fatalf("appFontScale=%v want 2.0", TheState.appFontScale)
|
||||
}
|
||||
if got, want := float64(TheState.ScrollOffset), 50*lh*2.0; math.Abs(got-want) > 1e-3 {
|
||||
t.Errorf("ScrollOffset=%v want %v", got, want)
|
||||
}
|
||||
SetAppFontScale(0) // clamps to the minimum
|
||||
if TheState.appFontScale != MinAppFontScale {
|
||||
t.Errorf("appFontScale=%v want MinAppFontScale", TheState.appFontScale)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleFontPinch_IgnoresBadData(t *testing.T) {
|
||||
TheLogic = nil
|
||||
TheState = NewState()
|
||||
defer func() { TheState.appFontScale = 1.0 }()
|
||||
HandleFontPinch("not an event")
|
||||
HandleFontPinch(ui.FontPinchEvent{Scale: 0})
|
||||
HandleFontPinch(ui.FontPinchEvent{Scale: -2})
|
||||
if TheState.appFontScale != 1.0 {
|
||||
t.Errorf("appFontScale=%v want unchanged 1.0", TheState.appFontScale)
|
||||
}
|
||||
}
|
||||
|
||||
// The pinch CENTER stays fixed: the continuous content coordinate under the
|
||||
// center (display-line units) is invariant through the scale change. A
|
||||
// top-anchored zoom would move that coordinate by m*(1-ratio) display
|
||||
// lines — for a center 400dp below the region top at ×1.5 that is ~59
|
||||
// display lines off, which is exactly what this test rejects.
|
||||
func TestHandleFontPinch_CenterAnchor(t *testing.T) {
|
||||
TheLogic = nil
|
||||
TheState = NewState()
|
||||
defer func() {
|
||||
TheState.appFontScale = 1.0
|
||||
TheState.ScrollOffset = 0
|
||||
TheState.EditorRegion = ui.Region{}
|
||||
}()
|
||||
TheState.EditorRegion = ui.Region{Y: 100, H: 800}
|
||||
|
||||
lh := float64(EffectiveLineHeight())
|
||||
TheState.ScrollOffset = ui.Dp(100 * lh)
|
||||
// Center 400dp below the region top.
|
||||
const m = 400.0
|
||||
wantU := (float64(TheState.ScrollOffset) + m) / lh // content coord under the center
|
||||
|
||||
HandleFontPinch(ui.FontPinchEvent{Scale: 1.5, Center: ui.Point{Y: 100 + m}})
|
||||
|
||||
lhNew := float64(EffectiveLineHeight())
|
||||
gotU := (float64(TheState.ScrollOffset) + m) / lhNew
|
||||
// Tolerance is float32-scale + ui.Dp rounding accumulated over two
|
||||
// conversions — still 4 orders of magnitude smaller than the ~59-line
|
||||
// drift a top-anchored zoom would produce here.
|
||||
if math.Abs(gotU-wantU) > 1e-4 {
|
||||
t.Errorf("content under center: u=%v want %v (center must stay fixed)", gotU, wantU)
|
||||
}
|
||||
// Top-anchor sanity: the TOP moved (that is the point of center anchoring).
|
||||
if float64(TheState.ScrollOffset) == 100*lh*1.5 {
|
||||
t.Errorf("scroll=%v equals the top-anchored value; the center was not the anchor", TheState.ScrollOffset)
|
||||
}
|
||||
}
|
||||
|
||||
// With word wrap, the anchor must be the LOGICAL line under the center, not
|
||||
// the display line: when the font change re-wraps the lines above the
|
||||
// anchor (their fragment counts grow), the display-line index under the
|
||||
// center changes, but the same logical line / fragment / sub-line must stay
|
||||
// under it. applyFontPin is what the logic re-runs as rewrap corrections
|
||||
// land (the font-pin).
|
||||
func TestFontPin_SurvivesRewrap(t *testing.T) {
|
||||
TheLogic = nil
|
||||
TheState = NewState()
|
||||
defer func() {
|
||||
TheState.appFontScale = 1.0
|
||||
TheState.ScrollOffset = 0
|
||||
TheState.Editor.ChunkedBuffer = nil
|
||||
}()
|
||||
|
||||
// 1000 logical lines, each wrapped into 2 fragments at the current size.
|
||||
w := NewWrapIndex(1000)
|
||||
for i := 0; i < 1000; i++ {
|
||||
w.Set(i, 2)
|
||||
}
|
||||
TheState.Editor.ChunkedBuffer = &ChunkedBuffer{WrapIndex: w}
|
||||
|
||||
lh := float64(EffectiveLineHeight())
|
||||
const m = 200.0 // region top (EditorRegion zero) + 200dp
|
||||
// Anchor: logical line 60, its 1st fragment, 0.5 down it.
|
||||
TheState.ScrollOffset = ui.Dp(float64(w.VisualsBefore(60))*lh + 0.5*lh - m)
|
||||
|
||||
line, frag, sub, ok := TheState.captureFontPin(m)
|
||||
if !ok || line != 60 || frag != 0 || math.Abs(sub-0.5) > 1e-5 {
|
||||
t.Fatalf("capture: line=%d frag=%d sub=%v ok=%v, want line 60 frag 0 sub 0.5", line, frag, sub, ok)
|
||||
}
|
||||
|
||||
// The font grows ×1.5 (the line under the fingers keeps its 2 fragments
|
||||
// for now): the same point stays under m.
|
||||
TheState.appFontScale = 1.5
|
||||
TheState.applyFontPin(line, frag, sub, m)
|
||||
lhNew := float64(EffectiveLineHeight())
|
||||
u := (float64(TheState.ScrollOffset) + m) / lhNew
|
||||
if got := int(w.LineForVisual(int32(u))); got != 60 {
|
||||
t.Errorf("after scale: line under center=%d want 60", got)
|
||||
}
|
||||
|
||||
// Rewrap lands: every line now wraps into 3 fragments. The display-line
|
||||
// index under the center moves from 120.5 to 180.5, but re-applying the
|
||||
// pin must keep logical line 60 (fragment 0, sub 0.5) under the center.
|
||||
for i := 0; i < 1000; i++ {
|
||||
w.Set(i, 3)
|
||||
}
|
||||
TheState.applyFontPin(line, frag, sub, m)
|
||||
u = (float64(TheState.ScrollOffset) + m) / lhNew
|
||||
if got := int(w.LineForVisual(int32(u))); got != 60 {
|
||||
t.Errorf("after rewrap: line under center=%d want 60 (display-line anchoring would fail here)", got)
|
||||
}
|
||||
// And a display-line anchor (what NOT to do) would be off: at the new
|
||||
// counts, display line 120.5 is logical line 40, not 60.
|
||||
if got := int(w.LineForVisual(120)); got == 60 {
|
||||
t.Errorf("test is stale: display line 120 unexpectedly maps to line 60")
|
||||
}
|
||||
}
|
||||
|
||||
// fabLayout builds a GlyphLayout the way the shaper produces one: glyphsPerFrag
|
||||
// glyphs per fragment, baseline of fragment f at (f+0.8)*lh (ascent < lh, the
|
||||
// shaper's convention), 20dp advance each.
|
||||
func fabLayout(lh float64, fragments, glyphsPerFrag int, byte0 int) ui.GlyphLayout {
|
||||
gl := ui.GlyphLayout{LineHeight: ui.Dp(lh)}
|
||||
for f := 0; f < fragments; f++ {
|
||||
for g := 0; g < glyphsPerFrag; g++ {
|
||||
gl.ByteOffsets = append(gl.ByteOffsets, byte0+f*glyphsPerFrag+g)
|
||||
gl.X = append(gl.X, ui.Dp(10+20*float64(g)))
|
||||
gl.Y = append(gl.Y, ui.Dp((float64(f)+0.8)*lh))
|
||||
gl.Advance = append(gl.Advance, ui.Dp(20))
|
||||
}
|
||||
}
|
||||
return gl
|
||||
}
|
||||
|
||||
func TestGlyphAtLocalPoint(t *testing.T) {
|
||||
gl := fabLayout(16.8, 2, 4, 0) // bytes 0-3 on fragment 0, 4-7 on fragment 1
|
||||
if i, ok := glyphAtLocalPoint(gl, 50, 25); !ok || i != 6 {
|
||||
t.Errorf("(50,25): i=%d ok=%v, want glyph 6 (byte 6, X=50 on fragment 1)", i, ok)
|
||||
}
|
||||
if _, ok := glyphAtLocalPoint(gl, 5, 25); ok {
|
||||
t.Error("(5,25): left margin has no glyph, want not-ok")
|
||||
}
|
||||
if i, ok := glyphAtLocalPoint(gl, 1000, 25); !ok || i != 7 {
|
||||
t.Errorf("(1000,25): past the line end pins its last glyph, got i=%d ok=%v want 7", i, ok)
|
||||
}
|
||||
if _, ok := glyphAtLocalPoint(ui.GlyphLayout{}, 50, 25); ok {
|
||||
t.Error("empty layout: want not-ok")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureContentPin(t *testing.T) {
|
||||
TheLogic = nil
|
||||
TheState = NewState()
|
||||
defer func() {
|
||||
TheState.appFontScale = 1.0
|
||||
TheState.ScrollOffset = 0
|
||||
TheState.Editor.GlyphLayout = ui.GlyphLayout{}
|
||||
}()
|
||||
TheState.Editor.GlyphLayout = fabLayout(16.8, 2, 4, 0)
|
||||
TheState.ScrollOffset = 0
|
||||
|
||||
// Point at (x=50, y=25): fragment 1 (baseline 30.24), the glyph at X=50.
|
||||
pin := TheState.captureContentPin(50, 25)
|
||||
if !pin.HaveGlyph || pin.Byte != 6 {
|
||||
t.Fatalf("pin: byte=%d haveGlyph=%v, want byte 6", pin.Byte, pin.HaveGlyph)
|
||||
}
|
||||
if math.Abs(pin.Dy-(25-30.24)) > 1e-5 { // ui.Dp stores float32-precision values
|
||||
t.Errorf("dy=%v want %v (offset from the glyph baseline)", pin.Dy, 25-30.24)
|
||||
}
|
||||
// Fallback anchor (no WrapIndex): line 1, sub = 25/16.8 - 1 ~ 0.488.
|
||||
if pin.Line != 1 || pin.Frag != 0 || math.Abs(pin.Sub-(25/16.8-1)) > 1e-6 {
|
||||
t.Errorf("fallback: line=%d frag=%d sub=%v, want line 1 frag 0 sub %v", pin.Line, pin.Frag, pin.Sub, 25/16.8-1)
|
||||
}
|
||||
}
|
||||
|
||||
// The REFINEMENT is what makes the content point stay fixed across a rewrap:
|
||||
// the pinned byte moves to a different fragment in the new layout, and the
|
||||
// refined offset places that byte's baseline (plus the captured dy) exactly
|
||||
// at the pinch center — where the (line, fragment) anchor would leave a
|
||||
// different character there.
|
||||
func TestRefineContentPin_RewrapKeepsContentPoint(t *testing.T) {
|
||||
const m = 25.0 // region-relative pinch center
|
||||
const dy = 25.0 - 30.24 // from TestCaptureContentPin's point (above baseline)
|
||||
|
||||
// OLD layout (font 1.0x): byte 6 on fragment 1. (Capture would have
|
||||
// returned Byte=6, Dy=dy.)
|
||||
_ = fabLayout(16.8, 2, 4, 0)
|
||||
|
||||
// Font grows to 1.5x: the line re-wraps to 3 fragments x 3 glyphs; byte 6
|
||||
// lands on fragment 2 (a DIFFERENT fragment than the old fragment 1 it
|
||||
// was captured on... old frag index was 1, new is 2).
|
||||
glNew := fabLayout(25.2, 3, 3, 0)
|
||||
// The new layout is shaped for the window starting at document byte 0,
|
||||
// whose first visual line is visual line 3 of the document (vk=3):
|
||||
// the window top sits at content 3*25.2.
|
||||
vk := 3
|
||||
|
||||
off, ok := refineContentPin(glNew, vk, 0, dy, m, 6)
|
||||
if !ok {
|
||||
t.Fatal("refine: want ok")
|
||||
}
|
||||
// The pinned point (byte 6's baseline + dy) must sit exactly at m.
|
||||
contentY := float64(off) + m // content coordinate of the region-relative m
|
||||
// byte 6's baseline: window y = (2+0.8)*25.2, window top at content vk*lh.
|
||||
baselineContent := float64(vk)*float64(glNew.LineHeight) + float64(glNew.Y[6])
|
||||
if math.Abs(baselineContent+dy-contentY) > 1e-5 { // float32-precision layout Y
|
||||
t.Errorf("pinned point at content %v, want %v (baseline %v + dy)", contentY, baselineContent+dy, baselineContent)
|
||||
}
|
||||
// (A (line, fragment) anchor would have failed here: the byte captured on
|
||||
// the old fragment 1 sits on the NEW fragment 2, a full line further down.
|
||||
// Pinning the old fragment index would leave a different character at the
|
||||
// center — exactly the drift the content pin exists to remove.)
|
||||
}
|
||||
|
||||
// Steady state: a layout shaped at offset S with the pinned point at the
|
||||
// center must refine back to exactly S (the fixed point — no drift, no
|
||||
// oscillation while the pin is armed).
|
||||
func TestRefineContentPin_FixedPoint(t *testing.T) {
|
||||
const m = 25.0
|
||||
lh := ui.Dp(25.2)
|
||||
S := ui.Dp(100)
|
||||
vk, r := scrollDecompose(S, lh) // window's first visual line = v0 (no wrap)
|
||||
const dy = 3.0
|
||||
// Place byte 4 at window y = m + r - dy so the point sits at m when the
|
||||
// window (top at content vk*lh) is shaped at S.
|
||||
wantY := m + r - dy
|
||||
gl := ui.GlyphLayout{LineHeight: lh}
|
||||
for b := 0; b < 6; b++ {
|
||||
gl.ByteOffsets = append(gl.ByteOffsets, b)
|
||||
gl.X = append(gl.X, ui.Dp(10+20*float64(b%3)))
|
||||
gl.Y = append(gl.Y, ui.Dp(wantY)) // one line's worth for this test
|
||||
gl.Advance = append(gl.Advance, ui.Dp(20))
|
||||
}
|
||||
off, ok := refineContentPin(gl, int(vk), 0, dy, m, 4)
|
||||
if !ok {
|
||||
t.Fatal("refine: want ok")
|
||||
}
|
||||
if math.Abs(float64(off)-float64(S)) > 1e-9 {
|
||||
t.Errorf("fixed point: refine(S)=%v want S=%v (no drift)", off, S)
|
||||
}
|
||||
}
|
||||
|
||||
// Pinch-out clamp of the pinned fragment: a line that re-wraps to FEWER
|
||||
// fragments must not pin a fragment that no longer exists.
|
||||
func TestFontPin_FragmentClampedOnPinchOut(t *testing.T) {
|
||||
TheLogic = nil
|
||||
TheState = NewState()
|
||||
defer func() {
|
||||
TheState.appFontScale = 1.0
|
||||
TheState.ScrollOffset = 0
|
||||
TheState.Editor.ChunkedBuffer = nil
|
||||
}()
|
||||
w := NewWrapIndex(100)
|
||||
for i := 0; i < 100; i++ {
|
||||
w.Set(i, 3)
|
||||
}
|
||||
TheState.Editor.ChunkedBuffer = &ChunkedBuffer{WrapIndex: w}
|
||||
|
||||
// Pin line 5, fragment 2 (the third fragment).
|
||||
TheState.appFontScale = 1.0
|
||||
const m = 100.0
|
||||
TheState.applyFontPin(5, 2, 0.25, m)
|
||||
|
||||
// Pinch out: the line now wraps into 2 fragments.
|
||||
for i := 0; i < 100; i++ {
|
||||
w.Set(i, 2)
|
||||
}
|
||||
TheState.appFontScale = 0.8
|
||||
TheState.applyFontPin(5, 2, 0.25, m) // frag 2 must clamp to 1
|
||||
lh := float64(EffectiveLineHeight())
|
||||
u := (float64(TheState.ScrollOffset) + m) / lh
|
||||
// The anchor is now line 5, its LAST fragment (index 1), 0.25 down it.
|
||||
wantU := float64(w.VisualsBefore(5)+1) + 0.25
|
||||
if math.Abs(u-wantU) > 1e-6 {
|
||||
t.Errorf("anchor u=%v want %v (last remaining fragment of line 5)", u, wantU)
|
||||
}
|
||||
}
|
||||
+123
-15
@@ -24,6 +24,7 @@ package editor
|
||||
|
||||
import (
|
||||
"log"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"pad/internal/ui"
|
||||
@@ -56,12 +57,14 @@ type SessionState struct {
|
||||
Cursor int // cursor byte offset
|
||||
Scroll float64 // editor scroll offset, Dp
|
||||
ScrollLine int // logical line at the viewport top (-1 = unknown)
|
||||
ScrollSub float64 // Scroll's sub-line remainder, Dp (0 <= r < lineHeight)
|
||||
ScrollSub float64 // Scroll's sub-line remainder as a FRACTION of the line height (0 <= f < 1); font-independent. Snapshots written before the pinch feature stored Dp instead; restore converts values > 1.
|
||||
SelStart int // selection start byte (-1 = no selection)
|
||||
SelEnd int // selection end byte, exclusive
|
||||
FindQuery string // find bar query ("" = none)
|
||||
FindVisible bool // find bar was open
|
||||
FindCurByte int // start byte of the current find match (-1 = none)
|
||||
// AppFontScale is the app-local pinch font scale (0 = default 1.0).
|
||||
AppFontScale float64
|
||||
}
|
||||
|
||||
// SetSessionSaver registers the callback that persists snapshots (the cmd
|
||||
@@ -106,19 +109,24 @@ func (l *Logic) SnapshotSession() SessionState {
|
||||
if w := cb.WrapIndex; w != nil {
|
||||
scrollLine = w.LineForVisual(int32(v0))
|
||||
}
|
||||
scrollSub = r0
|
||||
// Store the sub-line remainder as a fraction of the line height so
|
||||
// it stays valid if the font scale changes between save and restore
|
||||
// (r0 < lh always, so the fraction is < 1 — that is also the legacy
|
||||
// Dp discriminator used on restore).
|
||||
scrollSub = r0 / float64(lh)
|
||||
}
|
||||
return SessionState{
|
||||
File: e.Filename,
|
||||
Cursor: cur,
|
||||
Scroll: float64(s.ScrollOffset),
|
||||
ScrollLine: scrollLine,
|
||||
ScrollSub: scrollSub,
|
||||
SelStart: e.SelectionStart,
|
||||
SelEnd: e.SelectionEnd,
|
||||
FindQuery: f.Query,
|
||||
FindVisible: f.Visible,
|
||||
FindCurByte: curByte,
|
||||
File: e.Filename,
|
||||
Cursor: cur,
|
||||
Scroll: float64(s.ScrollOffset),
|
||||
ScrollLine: scrollLine,
|
||||
ScrollSub: scrollSub,
|
||||
SelStart: e.SelectionStart,
|
||||
SelEnd: e.SelectionEnd,
|
||||
FindQuery: f.Query,
|
||||
FindVisible: f.Visible,
|
||||
FindCurByte: curByte,
|
||||
AppFontScale: float64(s.appFontScale),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,6 +237,17 @@ func (l *Logic) BeginRestore(s SessionState) {
|
||||
// struct).
|
||||
l.restoreScroll = ui.Dp(s.Scroll)
|
||||
l.restoreScrollArmed = s.Scroll > 0
|
||||
// The app-local font scale lands immediately, BEFORE any layout: the
|
||||
// restore's line-based offset math reads it through EffectiveLineHeight.
|
||||
if as := s.AppFontScale; as > 0 {
|
||||
if as < MinAppFontScale {
|
||||
as = MinAppFontScale
|
||||
}
|
||||
if as > MaxAppFontScale {
|
||||
as = MaxAppFontScale
|
||||
}
|
||||
l.state.appFontScale = float32(as)
|
||||
}
|
||||
l.state.page = EditorPage
|
||||
l.state.FocusedElementID = "editor_text"
|
||||
l.state.justOpenedAt = time.Now()
|
||||
@@ -297,12 +316,19 @@ func (l *Logic) maybeApplyRestoreScroll() bool {
|
||||
if cb := l.state.Editor.ChunkedBuffer; cb != nil && cb.WrapIndex != nil && s.ScrollLine < cb.WrapIndex.Len() {
|
||||
base = float64(cb.WrapIndex.VisualsBefore(s.ScrollLine))
|
||||
}
|
||||
l.restoreScroll = ui.Dp(base*float64(lh) + s.ScrollSub)
|
||||
sub := s.ScrollSub
|
||||
if sub > 1 {
|
||||
// Legacy snapshot: the sub-line remainder was stored in Dp, not
|
||||
// as a fraction. Convert with the current line height (the
|
||||
// error is a fraction of one sub-line line, at most).
|
||||
sub = sub / float64(lh)
|
||||
}
|
||||
l.restoreScroll = ui.Dp(base*float64(lh) + sub*float64(lh))
|
||||
// Arm the line-pin (see refreshRestorePin): wrap-count corrections
|
||||
// landing below this line would shift the mapping and drag the
|
||||
// viewport off the restored line while the index settles.
|
||||
l.restoreScrollLine = s.ScrollLine
|
||||
l.restoreScrollSub = float64(s.ScrollSub)
|
||||
l.restoreScrollSub = sub // fraction of the line height
|
||||
l.restorePinDeadline = time.Now().Add(restorePinTimeout)
|
||||
} else {
|
||||
l.restoreScrollLine = -1
|
||||
@@ -358,13 +384,95 @@ func (l *Logic) refreshRestorePin() {
|
||||
// stale and would under-clamp the re-derived offset; the layout pass of
|
||||
// the emitted frame clamps to the fresh value. An edit shrinking the
|
||||
// file mid-pin is covered the same way.
|
||||
off := ui.Dp(float64(w.VisualsBefore(l.restoreScrollLine))*float64(lh) + l.restoreScrollSub)
|
||||
off := ui.Dp(float64(w.VisualsBefore(l.restoreScrollLine))*float64(lh) + l.restoreScrollSub*float64(lh))
|
||||
if off != l.state.ScrollOffset {
|
||||
l.state.ScrollOffset = off
|
||||
l.emitFrame()
|
||||
}
|
||||
}
|
||||
|
||||
// fontPinTimeout bounds the pinch font-pin: rewrap corrections keep landing
|
||||
// for a while after the last pinch frame (shaping lags the font change);
|
||||
// after this long the user has moved on and the pin stands down.
|
||||
const fontPinTimeout = 2 * time.Second
|
||||
|
||||
// setFontPin arms/updates the pinch font-pin from a pre-change capture
|
||||
// (see captureContentPin: the glyph under the pinch center + offset from its
|
||||
// baseline) and applies the IMMEDIATE anchor: the continuous content
|
||||
// coordinate under the center scaled by the font ratio. Exact until the
|
||||
// rewrap lands; the shaped-layout feedback (refreshFontPin) then snaps the
|
||||
// pinned character exactly onto the center. Must be called on the logic
|
||||
// goroutine.
|
||||
func (l *Logic) setFontPin(pin contentPin, m float64, ratio float64) {
|
||||
l.fontPin = pin
|
||||
l.fontPinM = m
|
||||
l.fontPinArmed = true
|
||||
l.fontPinDeadline = time.Now().Add(fontPinTimeout)
|
||||
s := l.state
|
||||
s.rescaleScrollAnchored(ratio, float64(s.EditorRegion.Y)+m)
|
||||
// No emitFrame here: the caller (input path or debug command) emits the
|
||||
// frame carrying the new scale and the rescaled offset.
|
||||
}
|
||||
|
||||
// refreshFontPin re-derives the scroll offset from a freshly shaped layout so
|
||||
// the pinned content point stays under the pinch center (see
|
||||
// refineContentPin). Runs on every layout feedback while armed: the font
|
||||
// change's own re-shaping is the first, and rewrap corrections follow it. If
|
||||
// the pinned byte is not in the shaped window (no layout yet, or the point
|
||||
// is in a blank margin), the (line, fragment, sub-line) fallback anchor
|
||||
// stands in. An edit landing since the capture (EditSeq mismatch) or leaving
|
||||
// the editor page disarms the pin: its byte no longer names the same content.
|
||||
// No MaxScroll clamp: the layout pass of the emitted frame clamps to the
|
||||
// fresh value. Must be called on the logic goroutine.
|
||||
func (l *Logic) refreshFontPin(fb ui.LayoutFeedback) {
|
||||
if !l.fontPinArmed {
|
||||
return
|
||||
}
|
||||
if time.Now().After(l.fontPinDeadline) {
|
||||
l.fontPinArmed = false
|
||||
return
|
||||
}
|
||||
s := l.state
|
||||
if s.page != EditorPage || fb.EditSeq != l.fontPin.EditSeq {
|
||||
l.fontPinArmed = false
|
||||
return
|
||||
}
|
||||
l.fontPinDeadline = time.Now().Add(fontPinTimeout)
|
||||
// Skip feedback shaped at a DIFFERENT scale: during a pinch every frame
|
||||
// changes the scale, so all but the latest feedback carry layouts whose
|
||||
// LineHeight no longer matches the geometry the pin computes in. A
|
||||
// stale-scale layout would place the point by the old geometry for one
|
||||
// frame (a visible jump) before the next corrects it.
|
||||
if fb.GlyphLayout.LineHeight > 0 &&
|
||||
math.Abs(float64(fb.GlyphLayout.LineHeight)-float64(EffectiveLineHeight())) > 0.5 {
|
||||
return
|
||||
}
|
||||
old := s.ScrollOffset
|
||||
vk := -1
|
||||
if cb := s.Editor.ChunkedBuffer; cb != nil && cb.WrapIndex != nil && fb.WindowStartLine >= 0 {
|
||||
vk = int(cb.WrapIndex.VisualsBefore(fb.WindowStartLine))
|
||||
}
|
||||
if l.fontPin.HaveGlyph && vk >= 0 {
|
||||
if off, ok := refineContentPin(fb.GlyphLayout, vk, fb.WindowStartByte, l.fontPin.Dy, l.fontPinM, l.fontPin.Byte); ok {
|
||||
s.ScrollOffset = off
|
||||
} else {
|
||||
s.applyFontPin(l.fontPin.Line, l.fontPin.Frag, l.fontPin.Sub, l.fontPinM)
|
||||
}
|
||||
} else {
|
||||
s.applyFontPin(l.fontPin.Line, l.fontPin.Frag, l.fontPin.Sub, l.fontPinM)
|
||||
}
|
||||
if s.ScrollOffset != old {
|
||||
l.emitFrame()
|
||||
}
|
||||
}
|
||||
|
||||
// releaseFontPin disarms the pinch font-pin: the user (a scroll, a debug
|
||||
// command, a file switch) has taken over the viewport. Must be called on
|
||||
// the logic goroutine.
|
||||
func (l *Logic) releaseFontPin() {
|
||||
l.fontPinArmed = false
|
||||
}
|
||||
|
||||
// applyRestorePositions clamps the restored snapshot's cursor and selection
|
||||
// to a file of n bytes and applies them. Must be called on the logic
|
||||
// goroutine.
|
||||
|
||||
+311
-7
@@ -17,6 +17,15 @@ import (
|
||||
// EditorFontSize is the font size used for editor text.
|
||||
const EditorFontSize = 14 // unit.Sp
|
||||
|
||||
// App-local font-size scale bounds (pinch zoom), applied on top of the
|
||||
// system user font scale. The scale itself is a continuous float32 — it is
|
||||
// never rounded to a whole point value; the bounds only stop the pinch from
|
||||
// leaving the usable range.
|
||||
const (
|
||||
MinAppFontScale = 0.5
|
||||
MaxAppFontScale = 3.0
|
||||
)
|
||||
|
||||
// EditorLineHeightScale is the baseline-to-baseline spacing multiplier.
|
||||
const EditorLineHeightScale = 1.2
|
||||
|
||||
@@ -190,6 +199,7 @@ type State struct {
|
||||
PixelHeight int // raw pixel height from Gio ConfigEvent
|
||||
scale float32
|
||||
fontScale float32 // user font-size setting (PxPerSp/PxPerDp); 0 = unknown -> 1.0
|
||||
appFontScale float32 // app-local pinch font scale (1.0 = default); 0 = unknown -> 1.0
|
||||
page Page // current page (Browser or Editor)
|
||||
WordWrap bool
|
||||
ScrollOffset ui.Dp // vertical scroll position in Dp
|
||||
@@ -232,6 +242,7 @@ type State struct {
|
||||
func NewState() *State {
|
||||
return &State{
|
||||
scale: 1.0,
|
||||
appFontScale: 1.0,
|
||||
page: BrowserPage, // Reverted to BrowserPage
|
||||
WordWrap: true, // Enable word wrap by default
|
||||
lastEvictionTime: time.Now(),
|
||||
@@ -278,17 +289,306 @@ func stateFontScale() float32 {
|
||||
}
|
||||
|
||||
// EffectiveLineHeight is the editor line height in density-dp WITH the user
|
||||
// font-size setting applied. The shaper draws baselines at
|
||||
// Sp(EditorFontSize*LineHeightScale) physical px, which is
|
||||
// EditorLineHeight()*fontScale density-dp. Every piece of geometry
|
||||
// bookkeeping (window start, sub-line remainder, tap mapping, scroll
|
||||
// clamping, cursor vertical move) must use this value rather than the raw
|
||||
// EditorLineHeight; at a non-default font setting the two differ by the
|
||||
// font-size setting AND the app-local pinch scale applied. The shaper draws
|
||||
// baselines at Sp(EditorFontSize*appFontScale*LineHeightScale) physical px,
|
||||
// which is EditorLineHeight()*effectiveFontScale density-dp. Every piece of
|
||||
// geometry bookkeeping (window start, sub-line remainder, tap mapping,
|
||||
// scroll clamping, cursor vertical move) must use this value rather than the
|
||||
// raw EditorLineHeight; at a non-default font setting the two differ by the
|
||||
// font scale, which would misplace taps by up to (fontScale-1) viewportfuls
|
||||
// of lines and make scroll clamping stop short of (or run past) the file
|
||||
// ends.
|
||||
func EffectiveLineHeight() ui.Dp {
|
||||
return EffectiveLineHeightAt(stateFontScale())
|
||||
return EffectiveLineHeightAt(effectiveFontScale())
|
||||
}
|
||||
|
||||
// effectiveFontScale is the TOTAL font scale of the rendered line pitch:
|
||||
// the system user font scale times the app-local pinch scale. The system
|
||||
// part is already folded into gtx.Metric on the render side; the logic side
|
||||
// needs the product for its dp bookkeeping.
|
||||
func effectiveFontScale() float32 {
|
||||
fs := stateFontScale()
|
||||
as := float32(1)
|
||||
if TheState != nil && TheState.appFontScale > 0 {
|
||||
as = TheState.appFontScale
|
||||
}
|
||||
return fs * as
|
||||
}
|
||||
|
||||
// rescaleScrollAnchored scales the scroll offset by ratio while keeping the
|
||||
// content point under app-local Y anchorY fixed on screen. The document is
|
||||
// uniformly scaled by the font change (every line height and the sub-line
|
||||
// offset scale by the same factor), so the content coordinate under the
|
||||
// anchor scales by ratio; the new offset re-places that scaled coordinate
|
||||
// under the same app point. With anchorY at the region top this degenerates
|
||||
// to the plain top-anchor (new = old * ratio). A zero EditorRegion (not
|
||||
// laid out yet) likewise degenerates to the top anchor.
|
||||
func (s *State) rescaleScrollAnchored(ratio float64, anchorY float64) {
|
||||
regionTop := float64(s.EditorRegion.Y)
|
||||
dy := anchorY - regionTop
|
||||
contentY := float64(s.ScrollOffset) + dy
|
||||
s.ScrollOffset = ui.Dp(contentY*ratio - dy)
|
||||
}
|
||||
|
||||
// glyphAtLocalPoint returns the index of the glyph a window-frame point
|
||||
// (x, y in Dp; y relative to the window top, the same frame as GlyphLayout.Y)
|
||||
// sits on: the display line identified from y, and on that line the last
|
||||
// glyph whose X is at or before x. ok=false when the layout is empty, the
|
||||
// line has no glyph, or x is in the left margin before the line's first
|
||||
// glyph. (A point past the line's END still pins that line's last glyph:
|
||||
// the content there is the line itself.)
|
||||
func glyphAtLocalPoint(gl ui.GlyphLayout, x, y float64) (int, bool) {
|
||||
lh := float64(gl.LineHeight)
|
||||
if lh <= 0 || len(gl.ByteOffsets) == 0 {
|
||||
return 0, false
|
||||
}
|
||||
line := int(y / lh)
|
||||
if line < 0 {
|
||||
line = 0
|
||||
}
|
||||
// The baseline of display line j sits in (j*lh, (j+1)*lh]; all glyphs on
|
||||
// a line share one exact shaper value, so a range test finds the line's
|
||||
// baseline.
|
||||
base := -1.0
|
||||
for _, gy := range gl.Y {
|
||||
if f := float64(gy); f > float64(line)*lh && f <= float64(line+1)*lh {
|
||||
base = f
|
||||
break
|
||||
}
|
||||
}
|
||||
if base < 0 {
|
||||
return 0, false
|
||||
}
|
||||
best := -1
|
||||
for i, gy := range gl.Y {
|
||||
if float64(gy) != base {
|
||||
continue
|
||||
}
|
||||
if float64(gl.X[i]) <= x+1e-9 {
|
||||
best = i
|
||||
}
|
||||
}
|
||||
return best, best >= 0
|
||||
}
|
||||
|
||||
// contentPin is the anchor a pinch holds: a CONTENT point, not a layout
|
||||
// point. Byte/Dy name the glyph (ABSOLUTE buffer byte) under the fingers and
|
||||
// the point's offset from that glyph's baseline — both invariant under
|
||||
// rewrap, where a visual line is not (a rewrapped fragment holds different
|
||||
// text at the same fragment index). Line/Frag/Sub is the (logical line,
|
||||
// fragment, sub-line) fallback anchor for frames without a shaped glyph
|
||||
// under the point. EditSeq invalidates the pin on edits.
|
||||
type contentPin struct {
|
||||
Byte int
|
||||
Dy float64
|
||||
Line int
|
||||
Frag int
|
||||
Sub float64
|
||||
HaveGlyph bool
|
||||
EditSeq uint64
|
||||
}
|
||||
|
||||
// invalidateShapedLayout drops the last shaped GlyphLayout. Call it whenever
|
||||
// the SHAPING INPUTS change outside an edit (a font-scale change): the old
|
||||
// layout's LineHeight/X/Y belong to the old size, and every consumer that
|
||||
// falls back on it (window-start line, max scroll, tap mapping) would run
|
||||
// the new scroll offset through the OLD line height for a frame or two —
|
||||
// enough to put the shaped window ten thousand lines from the viewport.
|
||||
// The next frame re-shapes and the feedback refills it; until then the
|
||||
// logic-side geometry uses EffectiveLineHeight(), which tracks the scale.
|
||||
func (s *State) invalidateShapedLayout() {
|
||||
s.Editor.GlyphLayout = ui.GlyphLayout{}
|
||||
}
|
||||
|
||||
// captureContentPin identifies the content point at region-relative (x, y)
|
||||
// (dp from the editor region's left/top): the glyph under the point and the
|
||||
// point's offset from its baseline, plus the (line, fragment, sub-line)
|
||||
// fallback anchor. Must be called BEFORE the font change it will anchor.
|
||||
func (s *State) captureContentPin(x, y float64) contentPin {
|
||||
pin := contentPin{Byte: -1}
|
||||
// Window-frame y (the GlyphLayout frame): the point's region-relative y
|
||||
// plus the sub-line draw offset, the same convention as tapLocalY.
|
||||
_, r := scrollVisualDecompose()
|
||||
localY := y + r
|
||||
gl := s.Editor.GlyphLayout
|
||||
if i, ok := glyphAtLocalPoint(gl, x, localY); ok {
|
||||
// ByteOffsets are window-relative; IMEWindowStartByte is the absolute
|
||||
// byte of the window's first byte (the same value the Frame ships as
|
||||
// WindowStartByte).
|
||||
pin.Byte = s.Editor.IMEWindowStartByte + gl.ByteOffsets[i]
|
||||
pin.Dy = localY - float64(gl.Y[i])
|
||||
pin.HaveGlyph = true
|
||||
}
|
||||
if line, frag, sub, ok := s.captureFontPin(y); ok {
|
||||
pin.Line, pin.Frag, pin.Sub = line, frag, sub
|
||||
}
|
||||
pin.EditSeq = s.Editor.EditSeq
|
||||
return pin
|
||||
}
|
||||
|
||||
// captureFontPin identifies the fallback layout anchor at region-relative Y
|
||||
// m (dp from the top of the editor text region): the LOGICAL line under the
|
||||
// point (through the current WrapIndex), the display line (wrap fragment) of
|
||||
// that line the point is on, and the sub-line fraction within that fragment.
|
||||
func (s *State) captureFontPin(m float64) (line, frag int, sub float64, ok bool) {
|
||||
lh := float64(EffectiveLineHeight())
|
||||
if lh <= 0 {
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
u := (float64(s.ScrollOffset) + m) / lh // continuous display-line coordinate under the point
|
||||
k := int(u)
|
||||
if k < 0 {
|
||||
k = 0
|
||||
}
|
||||
sub = u - float64(k)
|
||||
if cb := s.Editor.ChunkedBuffer; cb != nil && cb.WrapIndex != nil && k < cb.WrapIndex.Len() {
|
||||
l := cb.WrapIndex.LineForVisual(int32(k))
|
||||
base := int(cb.WrapIndex.VisualsBefore(l))
|
||||
frag = k - base
|
||||
if frag < 0 {
|
||||
frag = 0
|
||||
}
|
||||
return l, frag, sub, true
|
||||
}
|
||||
return k, 0, sub, true // no wrap index: display line == logical line
|
||||
}
|
||||
|
||||
// refineContentPin computes the scroll offset that places the pinned CONTENT
|
||||
// point — absolute buffer byte byteOff, dy below its baseline — at
|
||||
// region-relative Y m, given a freshly shaped layout (gl) for the window
|
||||
// starting at windowStartByte (both from the same LayoutFeedback). The window
|
||||
// top (layout y=0) sits at the top of the window's FIRST visual line, whose
|
||||
// content coordinate is VisualsBefore(windowStartLine)*lh — the vk argument
|
||||
// (NOT floor(shapedScroll/lh), which is a different line whenever the
|
||||
// viewport top lands mid-way through a wrapped logical line) — so the glyph's
|
||||
// content coordinate is vk*lh + Y + dy, and setting the offset to that minus
|
||||
// m puts the point on the center exactly. This is what keeps the CHARACTER
|
||||
// under the fingers when a rewrap moves it to a different fragment: the byte
|
||||
// is invariant, its Y is read from the fresh layout. ok=false when the layout
|
||||
// is unusable or the byte is not in the shaped window (then the caller falls
|
||||
// back to the (line, frag, sub) anchor).
|
||||
func refineContentPin(gl ui.GlyphLayout, vk, windowStartByte int, dy, m float64, byteOff int) (ui.Dp, bool) {
|
||||
lh := gl.LineHeight
|
||||
if lh <= 0 || len(gl.ByteOffsets) == 0 || byteOff < 0 || vk < 0 {
|
||||
return 0, false
|
||||
}
|
||||
i := sort.Search(len(gl.ByteOffsets), func(i int) bool { return windowStartByte+gl.ByteOffsets[i] >= byteOff })
|
||||
if i >= len(gl.ByteOffsets) || windowStartByte+gl.ByteOffsets[i] != byteOff {
|
||||
return 0, false
|
||||
}
|
||||
contentY := float64(vk)*float64(lh) + float64(gl.Y[i]) + dy
|
||||
return ui.Dp(contentY - m), true
|
||||
}
|
||||
|
||||
// applyFontPin sets the scroll offset so the fallback anchor (logical line L,
|
||||
// its frag-th display line, sub-line fraction sub within it) sits at
|
||||
// region-relative Y m, under the CURRENT WrapIndex and line height. This is
|
||||
// the pin's stand-in for frames without a shaped glyph under the point; it is
|
||||
// re-runnable as wrap-count corrections land (the same mechanism as the
|
||||
// restore line-pin, aimed at a point mid-viewport). No MaxScroll clamp here:
|
||||
// the layout pass of the emitted frame clamps to the fresh value (a stale
|
||||
// MaxScroll would under-clamp).
|
||||
func (s *State) applyFontPin(line, frag int, sub, m float64) {
|
||||
lh := float64(EffectiveLineHeight())
|
||||
if lh <= 0 {
|
||||
return
|
||||
}
|
||||
base := float64(line)
|
||||
if cb := s.Editor.ChunkedBuffer; cb != nil && cb.WrapIndex != nil && line >= 0 && line < cb.WrapIndex.Len() {
|
||||
base = float64(cb.WrapIndex.VisualsBefore(line))
|
||||
// The line's fragment count may have shrunk (pinch out): keep the
|
||||
// pinned fragment inside the line's new fragment range.
|
||||
if line+1 < cb.WrapIndex.Len() {
|
||||
count := int(cb.WrapIndex.VisualsBefore(line+1) - cb.WrapIndex.VisualsBefore(line))
|
||||
if count > 0 && frag >= count {
|
||||
frag = count - 1
|
||||
}
|
||||
}
|
||||
}
|
||||
s.ScrollOffset = ui.Dp((base+float64(frag)+sub)*lh - m)
|
||||
}
|
||||
|
||||
// HandleFontPinch applies one frame's relative two-finger pinch factor to
|
||||
// the app-local font scale (ui.FontPinchEvent, delivered by the renderer's
|
||||
// pinch probe). The scale is a continuous float — multiplied by the
|
||||
// per-frame distance ratio, clamped to [MinAppFontScale, MaxAppFontScale],
|
||||
// never rounded — so the text size tracks the fingers smoothly. The content
|
||||
// under the pinch CENTER (event's Center point) stays anchored: the Logic
|
||||
// pins the logical line + fragment + sub-line under the center and
|
||||
// re-derives the scroll offset under it as the font — and, a few frames
|
||||
// later, the rewrap counts — change (see Logic.applyFontPinch).
|
||||
func HandleFontPinch(data any) {
|
||||
f, ok := data.(ui.FontPinchEvent)
|
||||
log.Printf("PINCH logic HandleFontPinch scale=%.4f center=(%.0f,%.0f) ok=%v", f.Scale, f.Center.X, f.Center.Y, ok)
|
||||
if !ok || f.Scale <= 0 {
|
||||
return
|
||||
}
|
||||
s := TheState
|
||||
// Region-relative (x, y) of the pinch center. Capture the CONTENT point
|
||||
// the fingers are on (the glyph under the point + offset from its
|
||||
// baseline) under the PRE-change layout; the scale change, then the
|
||||
// re-derivation, keep that same content point under the center.
|
||||
x := float64(f.Center.X - s.EditorRegion.X)
|
||||
m := float64(f.Center.Y - s.EditorRegion.Y)
|
||||
pin := s.captureContentPin(x, m)
|
||||
old := s.appFontScale
|
||||
if old <= 0 {
|
||||
old = 1
|
||||
}
|
||||
ns := old * f.Scale
|
||||
if ns < MinAppFontScale {
|
||||
ns = MinAppFontScale
|
||||
}
|
||||
if ns > MaxAppFontScale {
|
||||
ns = MaxAppFontScale
|
||||
}
|
||||
if ns == s.appFontScale {
|
||||
return // no change: nothing to re-derive
|
||||
}
|
||||
s.appFontScale = ns
|
||||
// The last shaped layout belongs to the old size (see
|
||||
// invalidateShapedLayout): without this, the next frame computes its
|
||||
// window start with the OLD line height and the new (rescaled) offset —
|
||||
// a window ten thousand lines from the viewport — and the pin chases it.
|
||||
s.invalidateShapedLayout()
|
||||
ratio := float64(ns) / float64(old)
|
||||
if TheLogic != nil {
|
||||
TheLogic.releaseRestorePin() // the user takes over the viewport
|
||||
TheLogic.setFontPin(pin, m, ratio) // re-derives the offset under it
|
||||
} else {
|
||||
// Test harness without a Logic: the immediate continuous anchor.
|
||||
s.rescaleScrollAnchored(ratio, float64(s.EditorRegion.Y)+m)
|
||||
}
|
||||
}
|
||||
|
||||
// SetAppFontScale sets the app-local font scale to an absolute value
|
||||
// (clamped to [MinAppFontScale, MaxAppFontScale]) with the VIEWPORT TOP as
|
||||
// the anchor (no fingers are involved). Used by the one-shot debug command.
|
||||
func SetAppFontScale(v float32) {
|
||||
s := TheState
|
||||
old := s.appFontScale
|
||||
if old <= 0 {
|
||||
old = 1
|
||||
}
|
||||
if v < MinAppFontScale {
|
||||
v = MinAppFontScale
|
||||
}
|
||||
if v > MaxAppFontScale {
|
||||
v = MaxAppFontScale
|
||||
}
|
||||
if v == s.appFontScale {
|
||||
return // no change
|
||||
}
|
||||
s.appFontScale = v
|
||||
// Same stale-layout hazard as HandleFontPinch: the window start for the
|
||||
// next frame must be computed with the NEW line height.
|
||||
s.invalidateShapedLayout()
|
||||
ratio := float64(s.appFontScale) / float64(old)
|
||||
s.rescaleScrollAnchored(ratio, float64(s.EditorRegion.Y))
|
||||
if TheLogic != nil {
|
||||
TheLogic.releaseRestorePin()
|
||||
TheLogic.releaseFontPin()
|
||||
}
|
||||
}
|
||||
|
||||
// EffectiveLineHeightAt is EffectiveLineHeight for an explicit font scale
|
||||
@@ -352,6 +652,7 @@ func HandleScroll(data any) {
|
||||
delta := data.(int) // pixels
|
||||
if TheLogic != nil {
|
||||
TheLogic.releaseRestorePin() // the user takes over the viewport
|
||||
TheLogic.releaseFontPin()
|
||||
}
|
||||
TheState.ScrollOffset += ui.ToDp(ui.Px(delta), TheState.scale)
|
||||
if TheState.ScrollOffset < 0 {
|
||||
@@ -2250,6 +2551,9 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
|
||||
}
|
||||
}},
|
||||
{Gesture: ui.SelDrag, Handler: HandleSelDragEvt},
|
||||
// Two-finger pinch changes the app-local font scale continuously
|
||||
// (the renderer owns the probe; see ui.Pinch).
|
||||
{Gesture: ui.Pinch, Handler: HandleFontPinch},
|
||||
},
|
||||
)
|
||||
// While the find bar is open, key focus belongs to the main-owned
|
||||
|
||||
Reference in New Issue
Block a user