From af959a6e3c1afe225fd7748eede31118c2afa9fe Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 11:32:42 +0100 Subject: [PATCH 01/21] chore(example): update the Podfile lock to 0.1.10 --- example/ios/Podfile.lock | 88 ++++++++++++++++++++-------------------- 1 file changed, 44 insertions(+), 44 deletions(-) diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index f8d71c37..4ff2c284 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -1,7 +1,7 @@ PODS: - - Codepad (0.1.9): - - Codepad/Core (= 0.1.9) - - Codepad/TreeSitter (= 0.1.9) + - Codepad (0.1.10): + - Codepad/Core (= 0.1.10) + - Codepad/TreeSitter (= 0.1.10) - hermes-engine - NitroModules - RCTRequired @@ -25,7 +25,7 @@ PODS: - ReactCommon/turbomodule/core - ReactNativeDependencies - Yoga - - Codepad/Core (0.1.9): + - Codepad/Core (0.1.10): - hermes-engine - NitroModules - RCTRequired @@ -49,7 +49,7 @@ PODS: - ReactCommon/turbomodule/core - ReactNativeDependencies - Yoga - - Codepad/TreeSitter (0.1.9): + - Codepad/TreeSitter (0.1.10): - hermes-engine - NitroModules - RCTRequired @@ -73,45 +73,45 @@ PODS: - ReactCommon/turbomodule/core - ReactNativeDependencies - Yoga - - CodepadLangC (0.1.9): + - CodepadLangC (0.1.10): - Codepad - - CodepadLangCss (0.1.9): + - CodepadLangCss (0.1.10): - Codepad - - CodepadLangGo (0.1.9): + - CodepadLangGo (0.1.10): - Codepad - - CodepadLangHtml (0.1.9): + - CodepadLangHtml (0.1.10): - Codepad - - CodepadLangIni (0.1.9): + - CodepadLangIni (0.1.10): - Codepad - - CodepadLangJava (0.1.9): + - CodepadLangJava (0.1.10): - Codepad - - CodepadLangJavascript (0.1.9): + - CodepadLangJavascript (0.1.10): - Codepad - - CodepadLangJson (0.1.9): + - CodepadLangJson (0.1.10): - Codepad - - CodepadLangKotlin (0.1.9): + - CodepadLangKotlin (0.1.10): - Codepad - CodepadLangKvLite (1.0.0): - Codepad - - CodepadLangMarkdown (0.1.9): + - CodepadLangMarkdown (0.1.10): - Codepad - - CodepadLangPhp (0.1.9): + - CodepadLangPhp (0.1.10): - Codepad - - CodepadLangPython (0.1.9): + - CodepadLangPython (0.1.10): - Codepad - - CodepadLangRust (0.1.9): + - CodepadLangRust (0.1.10): - Codepad - - CodepadLangSql (0.1.9): + - CodepadLangSql (0.1.10): - Codepad - - CodepadLangSwift (0.1.9): + - CodepadLangSwift (0.1.10): - Codepad - - CodepadLangTsx (0.1.9): + - CodepadLangTsx (0.1.10): - Codepad - - CodepadLangTypescript (0.1.9): + - CodepadLangTypescript (0.1.10): - Codepad - - CodepadLangXml (0.1.9): + - CodepadLangXml (0.1.10): - Codepad - - CodepadLangYaml (0.1.9): + - CodepadLangYaml (0.1.10): - Codepad - EXConstants (57.0.22): - ExpoModulesCore @@ -2679,27 +2679,27 @@ EXTERNAL SOURCES: :path: "../node_modules/react-native/ReactCommon/yoga" SPEC CHECKSUMS: - Codepad: 1043b36ec3f0608600359a4f492594861e0b25c0 - CodepadLangC: 638fcbca785a7bffbaaca7137ea750d809b3d6b8 - CodepadLangCss: 09d9cf6e5f9ea20446459774aadd6190e69253a4 - CodepadLangGo: 0df746a14622ff8d7c9e609ee944bfbba6f5588e - CodepadLangHtml: e1a2889626fb966e3ed8fdfc917754c4522a8549 - CodepadLangIni: 0fe1f2e26453a76d5b8243a2d258a1d8228a64a4 - CodepadLangJava: 694afd2f8c17eb0934f041bc044a94e3ed98135f - CodepadLangJavascript: 5a281593774ce64f9c3a8d4619c87de3316b2c37 - CodepadLangJson: cc81b9791055bf99eea25c9fbad10dc1733efef7 - CodepadLangKotlin: 7036e6ce57f954ce9350b08e7c6bc3bbc0ab2202 + Codepad: be9c515420bb5d080a7d97aa43a4f78488df0276 + CodepadLangC: e918e5efa94718d3072a2cfbcde5aa78d56ec5ac + CodepadLangCss: 89a9d02af97f5f89f92cc18932a315bb26a47654 + CodepadLangGo: c35773dd80d618ac404223896774957ecd849134 + CodepadLangHtml: abb387f12be8ed8aa8671bddf5eec0c4fb3d0c05 + CodepadLangIni: 303ffdea4421bfb153ed1538a1f571f2072cfd94 + CodepadLangJava: b0b86325c2325eb831ed22d949a4081da64805f7 + CodepadLangJavascript: af1f3035769f3b4938f6ef9254e8d9f547766cda + CodepadLangJson: 0723a0d9c1b5294aec9a59dae36277d52d6faa3a + CodepadLangKotlin: 3e18e799bf41571666a342f3066ffb5159d15e51 CodepadLangKvLite: 9253cabc0ae1762339d0d732631ee140a7dbd173 - CodepadLangMarkdown: 1d797849b4bc1553b6076d555de5ea8c54014540 - CodepadLangPhp: 9c76adb491a481460b105c6f4b50bc164ba1c235 - CodepadLangPython: f4499a28e349ac54788f9b3194d4620aa135edd1 - CodepadLangRust: b38ea0e31b493baadae36c2eb64ae9ded6c648ab - CodepadLangSql: f0510f9090d3f19f0b11d96247a1ee71a446e7a0 - CodepadLangSwift: b5876ebcad891c4eb3515e1a698797d56ea585c8 - CodepadLangTsx: d0220af418df06c6fcc9a9a0185c16b1d232f45c - CodepadLangTypescript: 80b7a0b065ae2100606b1497eaa89d666038fe91 - CodepadLangXml: c449df5e8d0f534421aafc0bf5ce07801591c781 - CodepadLangYaml: 91725e8d3dd9b65bd286c8562d7246ca308516c1 + CodepadLangMarkdown: 2649a34a3f98b0e456317fe9b04ecf31f8c5f999 + CodepadLangPhp: b5d9a91c6bf067dba508821ae9b922c394b0c1a4 + CodepadLangPython: 17d7787e07844c404aedb322c9e25d5263ceb9dd + CodepadLangRust: de1890b1899b57813927531820f0f7808df8952a + CodepadLangSql: 941eb8ad8b5590a0050cc10f2c9a31cc89031696 + CodepadLangSwift: d9066d58690b0cad9b7c0a80ff268160a8330c1b + CodepadLangTsx: e07c416da04dcda466c54025d433c2beb7b863d8 + CodepadLangTypescript: 2267726874223138f267a04d7231bcfc52c7cb0b + CodepadLangXml: 11131a1d0b4fd8de36144c2e3a3ea8f9c656918e + CodepadLangYaml: 969e6d3a1726343194610f7e69a850c0ca9c1b2a EXConstants: 8a0eb5e2553569c0e6710b73a8d90d1ce358c153 Expo: 83ceec8498d39a83bfcdf6ad56118bc6c5c81c72 ExpoAsset: 2581425f9b581b4fce3c83ffc9f28528d1c4ee68 From 68a37256eeed8c51309b781c5d268078a4da3956 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 11:32:43 +0100 Subject: [PATCH 02/21] perf: log draw time in microseconds --- .../java/me/sectiontn/codepad/view/CodeEditorView.kt | 8 +++++++- ios/Codepad/view/CodeEditorView.swift | 6 ++++-- scripts/bench-ios.sh | 5 +++-- scripts/bench.sh | 12 +++++++++++- 4 files changed, 25 insertions(+), 6 deletions(-) diff --git a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt index 5ef639ee..aeb0488e 100644 --- a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt +++ b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt @@ -1102,11 +1102,13 @@ class CodeEditorView(context: Context) : View(context) { override fun computeScroll() { if (!scroller.step()) return + val start = System.nanoTime() val wasTop = viewport.scrollY == 0 val wasBottom = viewport.scrollY == viewport.maxScrollY val wasLeft = viewport.scrollX == 0 val wasRight = viewport.scrollX == viewport.maxScrollX - if (viewport.scrollTo(scroller.currX, scroller.currY)) onScrolled() + val moved = viewport.scrollTo(scroller.currX, scroller.currY) + if (moved) onScrolled() val v = scroller.currVelocity.toInt() if (scroller.flinging && v > 0) { if (!wasTop && viewport.scrollY == 0) scroller.absorbTop(v) @@ -1114,6 +1116,7 @@ class CodeEditorView(context: Context) : View(context) { if (!wasLeft && viewport.scrollX == 0) scroller.absorbLeft(v) if (!wasRight && viewport.scrollX == viewport.maxScrollX) scroller.absorbRight(v) } + if (moved && debugSwitch()) Log.i(DebugSwitch.TAG, "{\"call\":\"fling\",\"us\":${(System.nanoTime() - start) / 1000}}") postInvalidateOnAnimation() } @@ -1261,6 +1264,7 @@ class CodeEditorView(context: Context) : View(context) { override fun onDraw(canvas: Canvas) { if (dropped) return drawStart = SystemClock.uptimeMillis() + val drawNanos = System.nanoTime() // React Native parents leave clipChildren off, so an unclipped drawColor would cover siblings. canvas.clipRect(0, 0, width, height) canvas.drawColor(theme.background) @@ -1299,6 +1303,7 @@ class CodeEditorView(context: Context) : View(context) { core.document.drawingThread = null drawFrame = null flushIme(m) + val scrolled = scrollDirty if (scrollDirty) { scrollDirty = false onScrollListener?.invoke(frame) @@ -1319,6 +1324,7 @@ class CodeEditorView(context: Context) : View(context) { drawn = true onFirstDraw?.let { post(it) } } + if (scrolled && debugSwitch()) Log.i(DebugSwitch.TAG, "{\"call\":\"draw\",\"us\":${(System.nanoTime() - drawNanos) / 1000}}") } /** diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index 53e5dd3f..1fd33291 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -1360,7 +1360,9 @@ final class CodeEditorView: UIScrollView { /// One line per scrolled frame with its layout time, for the scroll bench. private func logFrame() { if !debugSwitch() { return } - let ms = Int(((CACurrentMediaTime() - frameStart) * 1000).rounded()) - DebugSwitch.log.info("{\"call\":\"frame\",\"ms\":\(ms, privacy: .public)}") + let elapsed = CACurrentMediaTime() - frameStart + let ms = Int((elapsed * 1000).rounded()) + let us = Int((elapsed * 1_000_000).rounded()) + DebugSwitch.log.info("{\"call\":\"frame\",\"ms\":\(ms, privacy: .public),\"us\":\(us, privacy: .public)}") } } diff --git a/scripts/bench-ios.sh b/scripts/bench-ios.sh index 0af5c277..afbcc879 100755 --- a/scripts/bench-ios.sh +++ b/scripts/bench-ios.sh @@ -10,9 +10,9 @@ bundle=${CODEPAD_BUNDLE:-me.sectiontn.codepad.example} seconds=${CODEPAD_BENCH_SECONDS:-30} summary() { - sort -n | awk -v name="$1" '{ v[NR] = $1 } END { + sort -n | awk -v name="$1" -v unit="${2:-ms}" '{ v[NR] = $1 } END { if (NR == 0) exit - printf "%-8s p50 %d ms p90 %d ms p95 %d ms p99 %d ms max %d ms\n", name, v[int(NR * 0.5 + 0.5)], v[int(NR * 0.9 + 0.5)], v[int(NR * 0.95 + 0.5)], v[int(NR * 0.99 + 0.5)], v[NR] + printf "%-8s p50 %d %s p90 %d %s p95 %d %s p99 %d %s max %d %s\n", name, v[int(NR * 0.5 + 0.5)], unit, v[int(NR * 0.9 + 0.5)], unit, v[int(NR * 0.95 + 0.5)], unit, v[int(NR * 0.99 + 0.5)], unit, v[NR], unit }' } @@ -42,6 +42,7 @@ case "$cmd" in [ -n "$frames" ] || { echo "no frame lines: scroll the editor while it streams"; exit 1; } echo "frames $(echo "$frames" | wc -l | tr -d ' ') over 16 ms $(echo "$frames" | awk '$1 > 16 { n++ } END { print n + 0 }')" echo "$frames" | summary frame + sed -n 's/.*"call":"frame","ms":[0-9]*,"us":\([0-9]*\).*/\1/p' "$raw" | summary frame us ;; memory) pid=$(pgrep -f "CodepadExample.app/CodepadExample" | head -n 1) diff --git a/scripts/bench.sh b/scripts/bench.sh index 4bc3efd3..22c0c148 100755 --- a/scripts/bench.sh +++ b/scripts/bench.sh @@ -6,6 +6,8 @@ set -euo pipefail pkg=${CODEPAD_PACKAGE:-me.sectiontn.codepad.example} cmd=${1:-scroll} +summary() { sort -n | awk -v name="$1" -v unit="${2:-ms}" '{ v[NR] = $1 } END { if (NR == 0) exit; printf "%-8s p50 %d %s p95 %d %s max %d %s n %d\n", name, v[int(NR * 0.5 + 0.5)], unit, v[int(NR * 0.95 + 0.5)], unit, v[NR], unit, NR }'; } + case "$cmd" in scroll) swipes=${2:-8} @@ -14,13 +16,22 @@ case "$cmd" in x=$((width / 2)) from=$((height * 8 / 10)) to=$((height * 2 / 10)) + adb shell settings put global codepad_debug 1 + # The view re-reads the setting at most once a second. + sleep 1.2 + adb logcat -c adb shell dumpsys gfxinfo "$pkg" reset > /dev/null for ((i = 0; i < swipes; i++)); do adb shell input swipe "$x" "$from" "$x" "$to" 80 sleep 1.5 done sleep 1 + adb shell settings put global codepad_debug 0 adb shell dumpsys gfxinfo "$pkg" | sed -n '/Total frames rendered/,/99th percentile/p' + log=$(adb logcat -d -v raw -s codepad-ime:I) + # draw is a whole onDraw of a scrolled frame, fling one computeScroll that moved the scroll. + echo "$log" | sed -n 's/.*"call":"draw","us":\([0-9]*\).*/\1/p' | summary draw us + echo "$log" | sed -n 's/.*"call":"fling","us":\([0-9]*\).*/\1/p' | summary fling us ;; memory) adb shell dumpsys meminfo "$pkg" | grep -E 'Java Heap:|Native Heap:|Graphics:|TOTAL PSS' @@ -41,7 +52,6 @@ case "$cmd" in lines=$(adb logcat -d -v raw -s codepad-ime:I | sed -n 's/.*"call":"paint","latency":\([0-9]*\),"work":\([0-9]*\).*/\1 \2/p') [ -n "$lines" ] || { echo "no paint lines: focus the editor first"; exit 1; } # latency runs from the key event time to the end of the draw, so it includes the wait for the next vsync; work is the time in the key handler and onDraw. - summary() { sort -n | awk -v name="$1" '{ v[NR] = $1 } END { printf "%-8s p50 %d ms p95 %d ms max %d ms\n", name, v[int(NR * 0.5 + 0.5)], v[int(NR * 0.95 + 0.5)], v[NR] }'; } echo "frames $(echo "$lines" | wc -l)" echo "$lines" | awk '{ print $1 }' | summary latency echo "$lines" | awk '{ print $2 }' | summary work From 5ed3f4fe428c994ad54ccdb1b83c3ecdcdd2381b Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 12:05:19 +0100 Subject: [PATCH 03/21] test: pin the layout in shared vectors --- .../me/sectiontn/codepad/core/VectorRunner.kt | 76 ++++++++++++++++- tests/swift/VectorRunner.swift | 85 ++++++++++++++++++- tests/swift/VectorTest.swift | 1 + tests/vectors/layout.json | 20 +++++ 4 files changed, 180 insertions(+), 2 deletions(-) create mode 100644 tests/vectors/layout.json diff --git a/android/src/test/java/me/sectiontn/codepad/core/VectorRunner.kt b/android/src/test/java/me/sectiontn/codepad/core/VectorRunner.kt index 07df29b5..a08de61b 100644 --- a/android/src/test/java/me/sectiontn/codepad/core/VectorRunner.kt +++ b/android/src/test/java/me/sectiontn/codepad/core/VectorRunner.kt @@ -1,5 +1,7 @@ package me.sectiontn.codepad.core +import me.sectiontn.codepad.layout.HeightMap +import me.sectiontn.codepad.layout.Viewport import org.json.JSONArray import org.json.JSONObject import org.junit.Assert.assertArrayEquals @@ -14,8 +16,40 @@ class VectorRunner(private val case: JSONObject) { private var lastResult: Any? = null private var lastError: String? = null + // Created by the first layout op. Until the layout moves into the core, the runner keeps it in step as the view does. + private var heights: HeightMap? = null + private var viewport: Viewport? = null + private var anchor: Viewport.Anchor? = null + private var widthChanged = false + init { - core.onChange = { change, origin -> changes.add(change to origin) } + core.onChange = { change, origin -> + changes.add(change to origin) + heights?.let { h -> + h.replaceLines(core.document.lineAt(change.start), lineSpan(change.removed), lineSpan(change.inserted)) + h.setGaps(core.decorations.gapRows()) + viewport!!.clamp() + } + } + } + + private fun lineSpan(text: String): Int = 1 + text.count { it == '\n' } + + private fun layout(op: JSONObject) { + val h = heights ?: HeightMap(core.document.lineCount).also { + it.setGaps(core.decorations.gapRows()) + heights = it + } + val vp = viewport ?: Viewport(h).also { viewport = it } + val before = vp.textAreaWidth + val insets = op.getJSONArray("insets") + vp.rowHeight = op.getInt("rowHeight") + vp.gutterWidth = op.getInt("gutter") + vp.textPadding = op.getInt("padding") + vp.wrap = op.getBoolean("wrap") + vp.resize(op.getInt("width"), op.getInt("height")) + vp.setInsets(insets.getInt(0), insets.getInt(1), insets.getInt(2), insets.getInt(3)) + widthChanged = vp.textAreaWidth != before } fun run() { @@ -81,7 +115,25 @@ class VectorRunner(private val case: JSONObject) { val arr = op.getJSONArray("items") val items = (0 until arr.length()).map { i -> decorationOf(arr.getJSONObject(i)) } core.setDecorations(items, op.optInt("revision", -1)) + viewport?.let { vp -> + val a = vp.anchor() + vp.heights.setGaps(core.decorations.gapRows()) + vp.restore(a) + } + } + "layout" -> layout(op) + "measure" -> { + val vp = viewport!! + val pairs = op.getJSONArray("pairs") + for (i in 0 until pairs.length()) vp.measured(pairs.getJSONArray(i).getInt(0), pairs.getJSONArray(i).getInt(1)) + if (op.has("widest") && !vp.wrap) vp.widestLine = maxOf(vp.widestLine, op.getInt("widest")) } + "scrollTo" -> lastResult = viewport!!.scrollTo(op.getInt("x"), op.getInt("y")) + "scrollBy" -> lastResult = viewport!!.scrollBy(op.getInt("dx"), op.getInt("dy")) + "reveal" -> lastResult = viewport!!.reveal(op.getInt("left"), op.getInt("top"), op.getInt("right"), op.getInt("bottom")) + "anchor" -> anchor = viewport!!.anchor() + "restore" -> viewport!!.restore(anchor!!) + "resetRows" -> heights!!.resetAll() else -> fail("op not implemented: $name") } } @@ -173,5 +225,27 @@ class VectorRunner(private val case: JSONObject) { if (expect.getBoolean("error")) assertEquals("error expected $where", true, lastError != null) else assertNull("no error expected $where", lastError) } + checkLayout(expect, where) + } + + private fun checkLayout(expect: JSONObject, where: String) { + val vp = viewport ?: return + val h = vp.heights + fun pair(key: String) = expect.getJSONArray(key).let { listOf(it.getInt(0), it.getInt(1)) } + fun keyed(key: String, actual: (Int) -> Any) { + val o = expect.getJSONObject(key) + val expected = o.keys().asSequence().associate { it.toInt() to o.get(it) } + assertEquals("$key $where", expected, expected.mapValues { (k, _) -> actual(k) }) + } + if (expect.has("widthChanged")) assertEquals("widthChanged $where", expect.getBoolean("widthChanged"), widthChanged) + if (expect.has("scroll")) assertEquals("scroll $where", pair("scroll"), listOf(vp.scrollX, vp.scrollY)) + if (expect.has("maxScroll")) assertEquals("maxScroll $where", pair("maxScroll"), listOf(vp.maxScrollX, vp.maxScrollY)) + if (expect.has("content")) assertEquals("content $where", pair("content"), listOf(vp.contentWidth, vp.contentHeight)) + if (expect.has("visible")) assertEquals("visible $where", pair("visible"), listOf(vp.firstVisibleLine(), vp.lastVisibleLine())) + if (expect.has("totalRows")) assertEquals("totalRows $where", expect.getInt("totalRows"), h.totalRows) + if (expect.has("rowStart")) keyed("rowStart") { h.rowStart(it) } + if (expect.has("lineAtRow")) keyed("lineAtRow") { h.lineAtRow(it) } + if (expect.has("isGapRow")) keyed("isGapRow") { h.isGapRow(it) } + if (expect.has("lineTop")) keyed("lineTop") { vp.lineTop(it) } } } diff --git a/tests/swift/VectorRunner.swift b/tests/swift/VectorRunner.swift index 1afcc6d0..087d778d 100644 --- a/tests/swift/VectorRunner.swift +++ b/tests/swift/VectorRunner.swift @@ -16,12 +16,58 @@ final class VectorRunner { private var lastResult: Any? = nil private var lastError: String? = nil + // Created by the first layout op. Until the layout moves into the core, the runner keeps it in step as the view does. + private var heights: HeightMap? = nil + private var viewport: Viewport? = nil + private var anchor: Viewport.Anchor? = nil + private var widthChanged = false + init(_ testCase: [String: Any]) { self.testCase = testCase let clock = Clock() self.clock = clock core = EditorCore(testCase["text"] as? String ?? "", clock: { clock.now }) - core.onChange = { [weak self] change, origin in self?.changes.append((change, origin)) } + core.onChange = { [weak self] change, origin in + guard let self else { return } + self.changes.append((change, origin)) + if let h = self.heights { + let first = self.core.document.lineAt(change.start) + h.replaceLines(first: first, oldCount: Self.lineSpan(change.removed), newCount: Self.lineSpan(change.inserted)) + h.setGaps(self.core.decorations.gapRows()) + self.viewport?.clamp() + } + } + } + + private static func lineSpan(_ text: String) -> Int { + text.utf16.reduce(1) { $0 + ($1 == 10 ? 1 : 0) } + } + + private func layout(_ op: [String: Any]) { + let h: HeightMap + if let existing = heights { + h = existing + } else { + h = HeightMap(lineCount: core.document.lineCount) + h.setGaps(core.decorations.gapRows()) + heights = h + } + let vp: Viewport + if let existing = viewport { + vp = existing + } else { + vp = Viewport(heights: h) + viewport = vp + } + let before = vp.textAreaWidth + let insets = op["insets"] as? [Int] ?? [0, 0, 0, 0] + vp.rowHeight = int(op, "rowHeight") + vp.gutterWidth = int(op, "gutter") + vp.textPadding = int(op, "padding") + vp.wrap = bool(op, "wrap", false) + _ = vp.resize(width: int(op, "width"), height: int(op, "height")) + _ = vp.setInsets(top: insets[0], bottom: insets[1], left: insets[2], right: insets[3]) + widthChanged = vp.textAreaWidth != before } func run() { @@ -93,6 +139,27 @@ final class VectorRunner { case "decorate": let items = (op["items"] as? [[String: Any]] ?? []).map(decorationOf) _ = core.setDecorations(items, revision: op["revision"] as? Int ?? -1) + if let vp = viewport { + let a = vp.anchor() + vp.heights.setGaps(core.decorations.gapRows()) + vp.restore(a) + } + case "layout": layout(op) + case "measure": + guard let vp = viewport else { return XCTFail("measure before layout") } + for pair in op["pairs"] as? [[Int]] ?? [] { vp.measured(pair[0], pair[1]) } + if let widest = op["widest"] as? Int, !vp.wrap { vp.widestLine = max(vp.widestLine, widest) } + case "scrollTo": + if let vp = viewport { lastResult = vp.scrollTo(int(op, "x"), int(op, "y")) } + case "scrollBy": + if let vp = viewport { lastResult = vp.scrollTo(vp.scrollX + int(op, "dx"), vp.scrollY + int(op, "dy")) } + case "reveal": + if let vp = viewport { + lastResult = vp.reveal(left: int(op, "left"), top: int(op, "top"), right: int(op, "right"), bottom: int(op, "bottom")) + } + case "anchor": anchor = viewport?.anchor() + case "restore": if let a = anchor { viewport?.restore(a) } + case "resetRows": heights?.resetAll() default: XCTFail("op not implemented: \(name)") } } @@ -192,6 +259,22 @@ final class VectorRunner { XCTAssertNil(lastError, "no error expected \(at)") } } + checkLayout(expect, at) + } + + private func checkLayout(_ expect: [String: Any], _ at: String) { + guard let vp = viewport else { return } + let h = vp.heights + if let v = expect["widthChanged"] as? Bool { XCTAssertEqual(widthChanged, v, "widthChanged \(at)") } + if let v = expect["scroll"] as? [Int] { XCTAssertEqual([vp.scrollX, vp.scrollY], v, "scroll \(at)") } + if let v = expect["maxScroll"] as? [Int] { XCTAssertEqual([vp.maxScrollX, vp.maxScrollY], v, "maxScroll \(at)") } + if let v = expect["content"] as? [Int] { XCTAssertEqual([vp.contentWidth, vp.contentHeight], v, "content \(at)") } + if let v = expect["visible"] as? [Int] { XCTAssertEqual([vp.firstVisibleLine(), vp.lastVisibleLine()], v, "visible \(at)") } + if let v = expect["totalRows"] as? Int { XCTAssertEqual(h.totalRows, v, "totalRows \(at)") } + for (k, v) in expect["rowStart"] as? [String: Int] ?? [:] { XCTAssertEqual(h.rowStart(Int(k)!), v, "rowStart \(k) \(at)") } + for (k, v) in expect["lineAtRow"] as? [String: Int] ?? [:] { XCTAssertEqual(h.lineAtRow(Int(k)!), v, "lineAtRow \(k) \(at)") } + for (k, v) in expect["isGapRow"] as? [String: Bool] ?? [:] { XCTAssertEqual(h.isGapRow(Int(k)!), v, "isGapRow \(k) \(at)") } + for (k, v) in expect["lineTop"] as? [String: Int] ?? [:] { XCTAssertEqual(vp.lineTop(Int(k)!), v, "lineTop \(k) \(at)") } } // JSON booleans and integers both arrive as NSNumber; only a CFBoolean compares as a Bool. diff --git a/tests/swift/VectorTest.swift b/tests/swift/VectorTest.swift index 9724c5ee..0b05dd29 100644 --- a/tests/swift/VectorTest.swift +++ b/tests/swift/VectorTest.swift @@ -15,6 +15,7 @@ final class VectorTest: XCTestCase { func testBrackets() { runFile("brackets") } func testSearch() { runFile("search") } func testDecorations() { runFile("decorations") } + func testLayout() { runFile("layout") } private func runFile(_ area: String) { let url = URL(fileURLWithPath: #filePath) diff --git a/tests/vectors/layout.json b/tests/vectors/layout.json new file mode 100644 index 00000000..4d4de2cf --- /dev/null +++ b/tests/vectors/layout.json @@ -0,0 +1,20 @@ +{ + "area": "layout", + "cases": [ + { "name": "unmeasured lines count one row each", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }], "expect": { "widthChanged": true, "totalRows": 20, "rowStart": { "10": 10, "20": 20 }, "content": [100, 200], "maxScroll": [0, 150], "visible": [0, 4] } }, + { "name": "a line measured below the viewport leaves the scroll", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "scrollTo", "x": 0, "y": 30, "expect": { "result": true, "scroll": [0, 30], "visible": [3, 7] } }, { "op": "measure", "pairs": [[10, 3]] }], "expect": { "scroll": [0, 30], "totalRows": 22, "rowStart": { "11": 13 }, "content": [100, 220] } }, + { "name": "a line measured above the viewport keeps the visible text in place", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "scrollTo", "x": 0, "y": 50, "expect": { "visible": [5, 9], "lineTop": { "5": 0 } } }, { "op": "measure", "pairs": [[2, 3]] }], "expect": { "scroll": [0, 70], "visible": [5, 9], "lineTop": { "5": 0 }, "maxScroll": [0, 170] } }, + { "name": "a batch with a growth above and a shrink at the first visible line keeps that line in place", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "measure", "pairs": [[5, 3]] }, { "op": "scrollTo", "x": 0, "y": 50, "expect": { "visible": [5, 7], "lineTop": { "5": 0 } } }, { "op": "measure", "pairs": [[2, 2], [5, 1]] }], "expect": { "scroll": [0, 60], "lineTop": { "5": 0 }, "totalRows": 21, "content": [100, 210], "maxScroll": [0, 160] } }, + { "name": "gap rows sit beside wrap rows", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": true }, { "op": "decorate", "items": [{ "kind": "gap", "line": 3, "rows": 2 }] }, { "op": "measure", "pairs": [[3, 2]] }], "expect": { "rowStart": { "3": 3, "4": 7 }, "isGapRow": { "3": false, "4": false, "5": true, "6": true, "7": false }, "totalRows": 23 } }, + { "name": "deleting a gap's line at the end and undoing keeps the rows in range", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "decorate", "items": [{ "kind": "gap", "line": 19, "rows": 2 }] }, { "op": "scrollTo", "x": 0, "y": 1000, "expect": { "scroll": [0, 170], "totalRows": 22 } }, { "op": "replace", "start": 29, "end": 39, "text": "", "expect": { "lineCount": 15, "gapRows": {}, "totalRows": 15, "scroll": [0, 100], "isGapRow": { "14": false, "15": false } } }, { "op": "undo" }], "expect": { "lineCount": 20, "gapRows": {}, "totalRows": 20, "scroll": [0, 100], "maxScroll": [0, 150] } }, + { "name": "an edit makes fresh one-row lines and moves gap lines with their text", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": true }, { "op": "decorate", "items": [{ "kind": "gap", "line": 10, "rows": 2 }] }, { "op": "measure", "pairs": [[5, 3], [12, 2]] }, { "op": "replace", "start": 10, "end": 10, "text": "y\ny\n" }], "expect": { "lineCount": 22, "gapRows": { "12": 2 }, "rowStart": { "5": 5, "8": 8, "12": 12, "13": 15, "14": 16, "15": 18 }, "totalRows": 25 } }, + { "name": "rows map to the view through the insets", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [8, 4, 6, 2], "gutter": 10, "padding": 3, "wrap": false, "expect": { "content": [82, 200], "maxScroll": [0, 162], "lineTop": { "0": 8, "3": 38 }, "visible": [0, 3] } }, { "op": "scrollTo", "x": 0, "y": 25 }], "expect": { "lineTop": { "3": 13 }, "visible": [2, 6] } }, + { "name": "layout reports only a text area width change", "text": "x\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false, "expect": { "widthChanged": true } }, { "op": "layout", "rowHeight": 10, "width": 100, "height": 80, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false, "expect": { "widthChanged": false } }, { "op": "layout", "rowHeight": 10, "width": 100, "height": 80, "insets": [0, 0, 4, 0], "gutter": 0, "padding": 0, "wrap": false, "expect": { "widthChanged": true } }, { "op": "layout", "rowHeight": 10, "width": 120, "height": 80, "insets": [0, 0, 4, 0], "gutter": 0, "padding": 0, "wrap": false, "expect": { "widthChanged": true } }] }, + { "name": "the widest line sets the content width without wrap only", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 4, "wrap": false }, { "op": "measure", "pairs": [[0, 1]], "widest": 180, "expect": { "content": [188, 200], "maxScroll": [88, 150] } }, { "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 4, "wrap": true }], "expect": { "widthChanged": false, "content": [100, 200], "maxScroll": [0, 150] } }, + { "name": "reveal takes the smallest scroll that shows the rect with padding", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 4, "wrap": false }, { "op": "measure", "pairs": [[0, 1]], "widest": 300 }, { "op": "reveal", "left": 150, "top": 120, "right": 160, "bottom": 130, "expect": { "result": true, "scroll": [68, 80] } }, { "op": "reveal", "left": 10, "top": 20, "right": 20, "bottom": 30 }], "expect": { "scroll": [10, 20] } }, + { "name": "scrollTo clamps to zero and to the maximum", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "scrollTo", "x": -5, "y": -5, "expect": { "result": false, "scroll": [0, 0] } }, { "op": "scrollTo", "x": 0, "y": 1000, "expect": { "result": true, "scroll": [0, 150] } }, { "op": "scrollBy", "dx": 0, "dy": 10, "expect": { "result": false, "scroll": [0, 150] } }] }, + { "name": "the anchor survives resetRows", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": true }, { "op": "measure", "pairs": [[1, 3], [2, 2]] }, { "op": "scrollTo", "x": 0, "y": 65, "expect": { "visible": [3, 8] } }, { "op": "anchor" }, { "op": "resetRows" }, { "op": "restore" }], "expect": { "scroll": [0, 35], "totalRows": 20, "lineTop": { "3": -5 } } }, + { "name": "restore inside a gap keeps the offset in the gap", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": true }, { "op": "decorate", "items": [{ "kind": "gap", "line": 2, "rows": 3 }] }, { "op": "scrollTo", "x": 0, "y": 45 }, { "op": "anchor" }, { "op": "resetRows" }, { "op": "restore" }], "expect": { "scroll": [0, 45], "isGapRow": { "4": true } } }, + { "name": "a gap re-measured at the top of the viewport shifts the text below (known, kept)", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": true }, { "op": "decorate", "items": [{ "kind": "gap", "line": 2, "rows": 3 }] }, { "op": "scrollTo", "x": 0, "y": 40, "expect": { "visible": [2, 5], "lineTop": { "3": 20 } } }, { "op": "measure", "pairs": [[2, 2]] }], "expect": { "scroll": [0, 40], "lineTop": { "3": 30 } } } + ] +} From 2a4e0770ceffe2956a2d7a67e78ec30754ae6e97 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 12:29:35 +0100 Subject: [PATCH 04/21] feat(core): move the row heights and the viewport into the core --- cpp/core/include/codepad.h | 74 +++++ cpp/core/src/capi_editor.cpp | 2 +- cpp/core/src/capi_layout.cpp | 97 +++++++ cpp/core/src/editor.cpp | 21 ++ cpp/core/src/editor.hpp | 6 + cpp/core/src/layout.cpp | 265 ++++++++++++++++++ cpp/core/src/layout.hpp | 98 +++++++ .../ios/CodepadTests/ContentSizeTests.swift | 20 ++ ios/Codepad/layout/HeightMap.swift | 129 --------- ios/Codepad/layout/Viewport.swift | 229 ++++++++------- ios/Codepad/view/CodeEditorView.swift | 69 ++--- tests/swift/CoreLayoutTests.swift | 36 +++ tests/swift/HeightMapTests.swift | 99 ------- tests/swift/VectorRunner.swift | 38 +-- tests/swift/ViewportTests.swift | 143 +--------- tests/vectors/layout.json | 1 + 16 files changed, 785 insertions(+), 542 deletions(-) create mode 100644 cpp/core/src/capi_layout.cpp create mode 100644 cpp/core/src/layout.cpp create mode 100644 cpp/core/src/layout.hpp delete mode 100644 ios/Codepad/layout/HeightMap.swift create mode 100644 tests/swift/CoreLayoutTests.swift delete mode 100644 tests/swift/HeightMapTests.swift diff --git a/cpp/core/include/codepad.h b/cpp/core/include/codepad.h index 57095157..9a75aade 100644 --- a/cpp/core/include/codepad.h +++ b/cpp/core/include/codepad.h @@ -170,6 +170,80 @@ CP_API uint32_t cp_editor_decorations(const cp_editor *editor, cp_decoration *ou // Moves whenever the decorations change. CP_API int32_t cp_editor_decorations_version(const cp_editor *editor); +// The layout of one view: rows per line, the gaps under lines, the scroll and the view metrics, in the platform's +// integer view units. Main thread only. The platform's scroller stays the authority. The layout keeps a clamped copy. +typedef struct cp_layout cp_layout; +typedef struct { + int32_t row_height; + int32_t width; + int32_t height; + int32_t inset_top; + int32_t inset_bottom; + int32_t inset_left; + int32_t inset_right; + int32_t gutter_width; + int32_t text_padding; + int32_t wrap; +} cp_layout_config; +// text_left is the view x of layout x 0. first_line and last_line are the visible lines. +typedef struct { + int32_t scroll_x; + int32_t scroll_y; + int32_t max_scroll_x; + int32_t max_scroll_y; + int32_t content_width; + int32_t content_height; + int32_t first_line; + int32_t last_line; + int32_t text_area_left; + int32_t text_area_width; + int32_t viewport_height; + int32_t wrap_width; + int32_t text_left; + int32_t total_rows; + int32_t line_count; + int32_t row_height; + int32_t widest_line; +} cp_geometry; +CP_API cp_layout *cp_layout_new(void); +// The layout lives on while an editor still holds it. +CP_API void cp_layout_free(cp_layout *layout); +// Resets the rows to the editor's lines and takes its gaps. Every later edit and gap change of the editor updates +// the rows before the change callback runs. NULL detaches. +CP_API void cp_editor_attach_layout(cp_editor *editor, cp_layout *layout); +// Returns 1 when the text area width changed, which is when line layouts must be rebuilt. +CP_API int32_t cp_layout_configure(cp_layout *layout, const cp_layout_config *config); +CP_API void cp_layout_geometry(const cp_layout *layout, cp_geometry *out); +// Returns 1 when the clamped scroll moved. out may be NULL. +CP_API int32_t cp_layout_scroll_to(cp_layout *layout, int32_t x, int32_t y, cp_geometry *out); +// The smallest scroll that shows a rect in layout coordinates with the text padding around it. Returns 1 when it moved. +CP_API int32_t cp_layout_reveal(cp_layout *layout, int32_t left, int32_t top, int32_t right, int32_t bottom, + cp_geometry *out); +// Applies (line, rows) pairs in order, as successive measurements would, then raises the widest line to widest +// when widest >= 0 and the layout does not wrap. Writes the view tops of first_line..last_line + 1, then the text +// rows of first_line..last_line, and returns how many ints that needs. A short buffer gets nothing written. +CP_API uint32_t cp_layout_measure(cp_layout *layout, const int32_t *pairs, uint32_t pair_count, int32_t widest, + int32_t first_line, int32_t last_line, cp_geometry *out, int32_t *tops_rows, + uint32_t cap); +CP_API void cp_layout_set_widest(cp_layout *layout, int32_t widest); +// Rows of a line outside the layout are 0. +CP_API int32_t cp_layout_rows(const cp_layout *layout, int32_t line); +CP_API int32_t cp_layout_gap_rows(const cp_layout *layout, int32_t line); +// Clamped to [0, line_count]. line_count gives the total rows. +CP_API int32_t cp_layout_row_start(const cp_layout *layout, int32_t line); +CP_API int32_t cp_layout_line_at_row(const cp_layout *layout, int32_t row); +CP_API int32_t cp_layout_is_gap_row(const cp_layout *layout, int32_t row); +CP_API int32_t cp_layout_row_top(const cp_layout *layout, int32_t row); +CP_API int32_t cp_layout_line_top(const cp_layout *layout, int32_t line); +// The content row under view y, possibly outside the rows. +CP_API int32_t cp_layout_row_at(const cp_layout *layout, int32_t y); +// The top visible line and how far the scroll sits below its top, so a relayout can put it back. +CP_API void cp_layout_anchor(const cp_layout *layout, int32_t *line, int32_t *offset); +// Returns 1 when the scroll moved. +CP_API int32_t cp_layout_restore(cp_layout *layout, int32_t line, int32_t offset); +// Every line back to one row. Gaps stay. +CP_API void cp_layout_reset_rows(cp_layout *layout); + // Search, a PCRE2 regex or plain text, in Unicode mode with any newline ending a line. Empty matches are skipped. typedef struct cp_search cp_search; enum { CP_SEARCH_REGEX = 1, CP_SEARCH_CASE = 2, CP_SEARCH_WORD = 4 }; diff --git a/cpp/core/src/capi_editor.cpp b/cpp/core/src/capi_editor.cpp index 932ea9b3..56e32209 100644 --- a/cpp/core/src/capi_editor.cpp +++ b/cpp/core/src/capi_editor.cpp @@ -150,7 +150,7 @@ void cp_editor_attach(cp_editor *editor, cp_engine *engine) { } int32_t cp_editor_set_decorations(cp_editor *editor, const cp_decoration *items, uint32_t count, int32_t revision) { - return editor->decorations.set(items, count, revision, editor->doc) ? 1 : 0; + return editor->set_decorations(items, count, revision) ? 1 : 0; } uint32_t cp_editor_decorations(const cp_editor *editor, cp_decoration *out, uint32_t cap) { diff --git a/cpp/core/src/capi_layout.cpp b/cpp/core/src/capi_layout.cpp new file mode 100644 index 00000000..c2c2fb4e --- /dev/null +++ b/cpp/core/src/capi_layout.cpp @@ -0,0 +1,97 @@ +// The layout half of the C API in codepad.h. + +#include + +#include "codepad.h" +#include "editor.hpp" +#include "layout.hpp" + +using codepad::Layout; + +namespace { + +void fill(const Layout &l, cp_geometry *out) { + if (out != nullptr) l.geometry(*out); +} + +} // namespace + +extern "C" { + +cp_layout *cp_layout_new(void) { return new cp_layout{std::make_shared()}; } + +void cp_layout_free(cp_layout *layout) { delete layout; } + +void cp_editor_attach_layout(cp_editor *editor, cp_layout *layout) { + editor->attach_layout(layout != nullptr ? layout->layout : nullptr); +} + +int32_t cp_layout_configure(cp_layout *layout, const cp_layout_config *config) { + return layout->layout->configure(*config) ? 1 : 0; +} + +void cp_layout_geometry(const cp_layout *layout, cp_geometry *out) { fill(*layout->layout, out); } + +int32_t cp_layout_scroll_to(cp_layout *layout, int32_t x, int32_t y, cp_geometry *out) { + bool moved = layout->layout->scroll_to(x, y); + fill(*layout->layout, out); + return moved ? 1 : 0; +} + +int32_t cp_layout_reveal(cp_layout *layout, int32_t left, int32_t top, int32_t right, int32_t bottom, + cp_geometry *out) { + bool moved = layout->layout->reveal(left, top, right, bottom); + fill(*layout->layout, out); + return moved ? 1 : 0; +} + +uint32_t cp_layout_measure(cp_layout *layout, const int32_t *pairs, uint32_t pair_count, int32_t widest, + int32_t first_line, int32_t last_line, cp_geometry *out, int32_t *tops_rows, + uint32_t cap) { + Layout &l = *layout->layout; + for (uint32_t i = 0; i < pair_count; i++) l.measured(pairs[2 * i], pairs[2 * i + 1]); + if (widest >= 0 && l.config().wrap == 0) l.widest_line = std::max(l.widest_line, widest); + fill(l, out); + if (first_line > last_line) return 0; + auto lines = static_cast(last_line - first_line + 1); + uint32_t needed = 2 * lines + 1; + if (tops_rows == nullptr || cap < needed) return needed; + for (uint32_t i = 0; i <= lines; i++) tops_rows[i] = l.line_top(first_line + static_cast(i)); + for (uint32_t i = 0; i < lines; i++) tops_rows[lines + 1 + i] = l.rows(first_line + static_cast(i)); + return needed; +} + +void cp_layout_set_widest(cp_layout *layout, int32_t widest) { layout->layout->widest_line = widest; } + +int32_t cp_layout_rows(const cp_layout *layout, int32_t line) { return layout->layout->rows(line); } + +int32_t cp_layout_gap_rows(const cp_layout *layout, int32_t line) { return layout->layout->gap_rows(line); } + +int32_t cp_layout_row_start(const cp_layout *layout, int32_t line) { return layout->layout->row_start(line); } + +int32_t cp_layout_line_at_row(const cp_layout *layout, int32_t row) { return layout->layout->line_at_row(row); } + +int32_t cp_layout_is_gap_row(const cp_layout *layout, int32_t row) { return layout->layout->is_gap_row(row) ? 1 : 0; } + +int32_t cp_layout_row_top(const cp_layout *layout, int32_t row) { return layout->layout->row_top(row); } + +int32_t cp_layout_line_top(const cp_layout *layout, int32_t line) { return layout->layout->line_top(line); } + +int32_t cp_layout_row_at(const cp_layout *layout, int32_t y) { return layout->layout->row_at(y); } + +void cp_layout_anchor(const cp_layout *layout, int32_t *line, int32_t *offset) { + Layout::Anchor a = layout->layout->anchor(); + *line = a.line; + *offset = a.offset; +} + +int32_t cp_layout_restore(cp_layout *layout, int32_t line, int32_t offset) { + int32_t x = layout->layout->scroll_x(); + int32_t y = layout->layout->scroll_y(); + layout->layout->restore({line, offset}); + return x != layout->layout->scroll_x() || y != layout->layout->scroll_y() ? 1 : 0; +} + +void cp_layout_reset_rows(cp_layout *layout) { layout->layout->reset_rows(); } + +} // extern "C" diff --git a/cpp/core/src/editor.cpp b/cpp/core/src/editor.cpp index be95a362..1f0182cf 100644 --- a/cpp/core/src/editor.cpp +++ b/cpp/core/src/editor.cpp @@ -70,6 +70,24 @@ void Editor::attach(std::shared_ptr engine) { epoch_ = engine_ ? engine_attach(*engine_, doc.view(), doc.revision()) : 0; } +void Editor::attach_layout(std::shared_ptr layout) { + layout_ = std::move(layout); + if (!layout_) return; + layout_->reset(doc.line_count()); + layout_->set_gaps(decorations.items()); + layout_->clamp(); +} + +bool Editor::set_decorations(const cp_decoration *items, uint32_t count, int32_t revision) { + if (!decorations.set(items, count, revision, doc)) return false; + if (layout_) { + Layout::Anchor a = layout_->anchor(); + layout_->set_gaps(decorations.items()); + layout_->restore(a); + } + return true; +} + void Editor::forward(const Document::Pending &p) { if (engine_) engine_edit(*engine_, epoch_, p.change, p.start_point, p.old_end_point, p.new_end_point, doc.view()); } @@ -94,6 +112,7 @@ Change Editor::replace(uint32_t start, uint32_t end, std::u16string_view text, i } forward(p); decorations.edited(p.change, doc); + if (layout_) layout_->edited(p.change, doc, decorations.items()); move_selection(after, true); if (origin == CP_ORIGIN_INPUT || origin == CP_ORIGIN_API) { undo_.record(p.change, before, after, typing); @@ -112,6 +131,7 @@ void Editor::replay(uint32_t start, uint32_t end, const std::u16string &text, in } forward(p); decorations.edited(p.change, doc); + if (layout_) layout_->edited(p.change, doc, decorations.items()); notify(p.change, origin); } @@ -123,6 +143,7 @@ void Editor::set_text(std::u16string_view text, bool keep_history) { sync_history(); } decorations.reset(doc.revision()); + if (layout_) layout_->set_gaps(decorations.items()); } void Editor::insert(std::u16string_view text, int32_t origin) { diff --git a/cpp/core/src/editor.hpp b/cpp/core/src/editor.hpp index b7dfce4e..05f129c1 100644 --- a/cpp/core/src/editor.hpp +++ b/cpp/core/src/editor.hpp @@ -14,6 +14,7 @@ #include "document.hpp" #include "engine.hpp" #include "indenter.hpp" +#include "layout.hpp" #include "search.hpp" #include "undo.hpp" @@ -53,6 +54,10 @@ class Editor { BracketPair bracket_match(const cp_snapshot *snapshot, uint32_t caret) const; // The engine parses the current text and hears every later edit. nullptr detaches. void attach(std::shared_ptr engine); + // The layout takes this document's lines and gaps, then follows every edit before the change callback. + void attach_layout(std::shared_ptr layout); + // False when the edits since revision are no longer known. A change moves the gaps and keeps the top line. + bool set_decorations(const cp_decoration *items, uint32_t count, int32_t revision); // False with PCRE2's message in error when the regex does not compile, which also clears the search. bool set_search(std::u16string_view text, int32_t flags, std::string &error); @@ -102,6 +107,7 @@ class Editor { std::optional search_; std::shared_ptr engine_; uint64_t epoch_ = 0; + std::shared_ptr layout_; }; } // namespace codepad diff --git a/cpp/core/src/layout.cpp b/cpp/core/src/layout.cpp new file mode 100644 index 00000000..401f9f64 --- /dev/null +++ b/cpp/core/src/layout.cpp @@ -0,0 +1,265 @@ +#include "layout.hpp" + +#include +#include + +namespace codepad { + +bool Layout::configure(const cp_layout_config &config) { + int32_t before = text_area_width(); + config_ = config; + // Rows are divided by the row height. + config_.row_height = std::max(config_.row_height, 1); + return text_area_width() != before; +} + +int32_t Layout::rows(int32_t line) const { return line >= 0 && line < line_count_ ? rows_[line] : 0; } + +int32_t Layout::gap_rows(int32_t line) const { return line >= 0 && line < line_count_ ? gaps_[line] : 0; } + +int32_t Layout::row_start(int32_t line) const { + int32_t l = std::clamp(line, 0, line_count_); + ensure(l); + return starts_[l]; +} + +int32_t Layout::line_at_row(int32_t row) const { + ensure(line_count_); + int32_t r = std::clamp(row, 0, std::max(starts_[line_count_] - 1, 0)); + int32_t lo = 0; + int32_t hi = line_count_ - 1; + while (lo < hi) { + int32_t mid = static_cast((static_cast(lo) + static_cast(hi) + 1) >> 1); + if (starts_[mid] <= r) { + lo = mid; + } else { + hi = mid - 1; + } + } + return lo; +} + +bool Layout::is_gap_row(int32_t row) const { + if (row < 0 || row >= total_rows()) return false; + int32_t line = line_at_row(row); + return row >= row_start(line) + rows_[line]; +} + +int32_t Layout::set_rows(int32_t line, int32_t count) { + if (line < 0 || line >= line_count_) return count; + int32_t old = rows_[line]; + if (old != count) { + rows_[line] = count; + clean_lines_ = std::min(clean_lines_, line + 1); + } + return old; +} + +void Layout::set_gaps(const std::vector &items) { + std::map next; + for (const cp_decoration &d : items) { + if (d.kind == CP_DECORATION_GAP) next[d.a] += d.b; + } + auto in_map = [this](int32_t line) { return line >= 0 && line < line_count_; }; + int32_t dirty = line_count_; + for (int32_t line : gap_lines_) { + auto it = next.find(line); + if ((it == next.end() ? 0 : it->second) != gaps_[line]) dirty = std::min(dirty, line); + } + for (const auto &[line, count] : next) { + if (in_map(line) && gaps_[line] != count) dirty = std::min(dirty, line); + } + if (dirty == line_count_) return; + for (int32_t line : gap_lines_) gaps_[line] = 0; + gap_lines_.clear(); + for (const auto &[line, count] : next) { + if (in_map(line) && count > 0) { + gaps_[line] = count; + gap_lines_.push_back(line); + } + } + clean_lines_ = std::min(clean_lines_, dirty + 1); +} + +void Layout::replace_lines(int32_t first, int32_t old_count, int32_t new_count) { + first = std::clamp(first, 0, line_count_); + old_count = std::clamp(old_count, 0, line_count_ - first); + new_count = std::max(new_count, 0); + int32_t tail = line_count_ - first - old_count; + int32_t next = line_count_ - old_count + new_count; + if (static_cast(next) > rows_.size()) { + size_t size = std::max(static_cast(next), rows_.size() * 2); + rows_.resize(size, 1); + gaps_.resize(size, 0); + } + if (new_count != old_count && tail > 0) { + auto from = static_cast(first + old_count); + auto to = static_cast(first + new_count); + auto n = static_cast(tail); + if (to < from) { + std::copy(rows_.begin() + from, rows_.begin() + from + n, rows_.begin() + to); + std::copy(gaps_.begin() + from, gaps_.begin() + from + n, gaps_.begin() + to); + } else { + std::copy_backward(rows_.begin() + from, rows_.begin() + from + n, rows_.begin() + to + n); + std::copy_backward(gaps_.begin() + from, gaps_.begin() + from + n, gaps_.begin() + to + n); + } + } + for (int32_t i = first; i < first + new_count; i++) { + rows_[i] = 1; + gaps_[i] = 0; + } + std::vector shifted; + for (int32_t line : gap_lines_) { + if (line < first) { + shifted.push_back(line); + } else if (line >= first + old_count) { + shifted.push_back(line + new_count - old_count); + } + } + gap_lines_ = std::move(shifted); + line_count_ = next; + clean_lines_ = std::min(clean_lines_, first + 1); +} + +void Layout::reset_rows() { + std::fill(rows_.begin(), rows_.begin() + line_count_, 1); + clean_lines_ = 0; +} + +void Layout::reset(int32_t line_count) { + line_count_ = std::max(line_count, 1); + size_t size = std::max(static_cast(line_count_), static_cast(16)); + rows_.assign(size, 1); + gaps_.assign(size, 0); + gap_lines_.clear(); + clean_lines_ = 0; +} + +void Layout::edited(const Change &change, const Document &doc, const std::vector &gaps) { + auto span = [](const std::u16string &text) { + return 1 + static_cast(std::count(text.begin(), text.end(), u'\n')); + }; + replace_lines(doc.line_at(change.start), span(change.removed), span(change.inserted)); + set_gaps(gaps); + clamp(); +} + +int32_t Layout::text_area_width() const { + return std::max(0, config_.width - text_area_left() - config_.inset_right); +} + +int32_t Layout::viewport_height() const { + return std::max(0, config_.height - config_.inset_top - config_.inset_bottom); +} + +int32_t Layout::wrap_width() const { + return config_.wrap != 0 ? std::max(1, text_area_width() - 2 * config_.text_padding) : 0; +} + +int32_t Layout::content_width() const { + if (config_.wrap != 0) return text_area_width(); + return std::max(text_area_width(), widest_line + 2 * config_.text_padding); +} + +int32_t Layout::max_scroll_x() const { return std::max(0, content_width() - text_area_width()); } + +int32_t Layout::max_scroll_y() const { return std::max(0, content_height() - viewport_height()); } + +bool Layout::scroll_to(int32_t x, int32_t y) { + int32_t nx = std::max(0, std::min(x, max_scroll_x())); + int32_t ny = std::max(0, std::min(y, max_scroll_y())); + if (nx == scroll_x_ && ny == scroll_y_) return false; + scroll_x_ = nx; + scroll_y_ = ny; + return true; +} + +int32_t Layout::row_top(int32_t row) const { return config_.inset_top + row * config_.row_height - scroll_y_; } + +int32_t Layout::row_at(int32_t y) const { + int32_t n = y + scroll_y_ - config_.inset_top; + int32_t h = config_.row_height; + return n >= 0 ? n / h : -((-n + h - 1) / h); +} + +int32_t Layout::first_visible_row() const { return std::max(0, row_at(config_.inset_top)); } + +int32_t Layout::last_visible_line() const { + return line_at_row(std::max(first_visible_row(), row_at(config_.height - config_.inset_bottom - 1))); +} + +bool Layout::reveal(int32_t left, int32_t top, int32_t right, int32_t bottom) { + int32_t x = scroll_x_; + int32_t y = scroll_y_; + int32_t vh = viewport_height(); + int32_t vw = text_area_width(); + int32_t r = right + 2 * config_.text_padding; + if (bottom - top >= vh || top < y) { + y = top; + } else if (bottom > y + vh) { + y = bottom - vh; + } + if (r - left >= vw || left < x) { + x = left; + } else if (r > x + vw) { + x = r - vw; + } + return scroll_to(x, y); +} + +Layout::Anchor Layout::anchor() const { + int32_t line = first_visible_line(); + return {line, scroll_y_ - row_start(line) * config_.row_height}; +} + +void Layout::restore(Anchor anchor) { + int32_t line = std::clamp(anchor.line, 0, line_count_ - 1); + int32_t span = (rows(line) + gap_rows(line)) * config_.row_height; + int32_t within = anchor.offset >= 0 && anchor.offset < span ? anchor.offset : 0; + scroll_to(scroll_x_, row_start(line) * config_.row_height + within); +} + +void Layout::measured(int32_t line, int32_t rows) { + int32_t first = first_visible_line(); + int32_t old = set_rows(line, rows); + if (old != rows && line < first) { + scroll_y_ = std::clamp(scroll_y_ + (rows - old) * config_.row_height, 0, max_scroll_y()); + } +} + +void Layout::geometry(cp_geometry &out) const { + out.scroll_x = scroll_x_; + out.scroll_y = scroll_y_; + out.max_scroll_x = max_scroll_x(); + out.max_scroll_y = max_scroll_y(); + out.content_width = content_width(); + out.content_height = content_height(); + out.first_line = first_visible_line(); + out.last_line = last_visible_line(); + out.text_area_left = text_area_left(); + out.text_area_width = text_area_width(); + out.viewport_height = viewport_height(); + out.wrap_width = wrap_width(); + out.text_left = text_area_left() + config_.text_padding - scroll_x_; + out.total_rows = total_rows(); + out.line_count = line_count_; + out.row_height = config_.row_height; + out.widest_line = widest_line; +} + +void Layout::ensure(int32_t up_to) const { + if (starts_.size() < static_cast(line_count_) + 1) { + starts_.resize(std::max(static_cast(line_count_) + 1, starts_.size() * 2)); + } + if (clean_lines_ == 0) { + starts_[0] = 0; + clean_lines_ = 1; + } + while (clean_lines_ <= up_to) { + int32_t i = clean_lines_; + starts_[i] = starts_[i - 1] + rows_[i - 1] + gaps_[i - 1]; + clean_lines_++; + } +} + +} // namespace codepad diff --git a/cpp/core/src/layout.hpp b/cpp/core/src/layout.hpp new file mode 100644 index 00000000..8bcba693 --- /dev/null +++ b/cpp/core/src/layout.hpp @@ -0,0 +1,98 @@ +#pragma once + +#include +#include +#include + +#include "codepad.h" +#include "document.hpp" + +namespace codepad { + +// Rows per line, the gaps under lines, the scroll and the mapping between rows and view units. Main thread only. +// An unmeasured line counts as one row, so every line has a position before layout and only moves once measured. +class Layout { + public: + struct Anchor { + int32_t line; + int32_t offset; + }; + + // True when the text area width changed, which is when line layouts must be rebuilt. + bool configure(const cp_layout_config &config); + const cp_layout_config &config() const { return config_; } + int32_t widest_line = 0; + + int32_t line_count() const { return line_count_; } + int32_t total_rows() const { return row_start(line_count_); } + // Zero for a line outside the map. + int32_t rows(int32_t line) const; + int32_t gap_rows(int32_t line) const; + int32_t row_start(int32_t line) const; + int32_t line_at_row(int32_t row) const; + bool is_gap_row(int32_t row) const; + // Lines outside the map are ignored. Returns the previous count. + int32_t set_rows(int32_t line, int32_t count); + // Replaces every gap from the decorations. Gaps on lines outside the map are ignored. + void set_gaps(const std::vector &items); + // Lines [first, first + old_count) became new_count fresh lines of one row each, without gaps. + void replace_lines(int32_t first, int32_t old_count, int32_t new_count); + // Every line back to one row. Gaps stay. + void reset_rows(); + // A new document: one row per line and no gaps. + void reset(int32_t line_count); + // An edit of the attached document: fresh rows for the lines it touched, the gaps, then a clamped scroll. + void edited(const Change &change, const Document &doc, const std::vector &gaps); + + int32_t scroll_x() const { return scroll_x_; } + int32_t scroll_y() const { return scroll_y_; } + int32_t text_area_left() const { return config_.inset_left + config_.gutter_width; } + int32_t text_area_width() const; + int32_t viewport_height() const; + // Zero means no wrapping. + int32_t wrap_width() const; + int32_t content_width() const; + int32_t content_height() const { return total_rows() * config_.row_height; } + int32_t max_scroll_x() const; + int32_t max_scroll_y() const; + + // Clamps and applies. True when the position moved. + bool scroll_to(int32_t x, int32_t y); + bool clamp() { return scroll_to(scroll_x_, scroll_y_); } + // View y of the top of row, and the content row under view y, possibly outside [0, total_rows). + int32_t row_top(int32_t row) const; + int32_t line_top(int32_t line) const { return row_top(row_start(line)); } + int32_t row_at(int32_t y) const; + int32_t first_visible_row() const; + int32_t first_visible_line() const { return line_at_row(first_visible_row()); } + int32_t last_visible_line() const; + // Smallest scroll that shows a rect in layout coordinates (x from the text start, y from row 0) with the + // text padding around it. + bool reveal(int32_t left, int32_t top, int32_t right, int32_t bottom); + Anchor anchor() const; + void restore(Anchor anchor); + // Records a measurement. A line above the viewport shifts the scroll so the visible text stays put. + void measured(int32_t line, int32_t rows); + void geometry(cp_geometry &out) const; + + private: + void ensure(int32_t up_to) const; + + cp_layout_config config_{1, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + int32_t scroll_x_ = 0; + int32_t scroll_y_ = 0; + int32_t line_count_ = 1; + std::vector rows_ = std::vector(16, 1); + std::vector gaps_ = std::vector(16, 0); + std::vector gap_lines_; + // Prefix sums of rows plus gaps, valid below clean_lines_. + mutable std::vector starts_ = std::vector(17, 0); + mutable int32_t clean_lines_ = 0; +}; + +} // namespace codepad + +// The C handle shares the layout with the editor it is attached to. +struct cp_layout { + std::shared_ptr layout; +}; diff --git a/example/ios/CodepadTests/ContentSizeTests.swift b/example/ios/CodepadTests/ContentSizeTests.swift index e37f6f47..4e19f298 100644 --- a/example/ios/CodepadTests/ContentSizeTests.swift +++ b/example/ios/CodepadTests/ContentSizeTests.swift @@ -42,6 +42,26 @@ final class ContentSizeTests: XCTestCase { XCTAssertEqual(sizes[1].height, 2 * row + 24, accuracy: 0.5) } + // setInitialText swaps the editor under the view: the insets stay, the rows start over and the scroll goes home. + func testSetInitialTextWhileScrolledKeepsTheInsetsAndStartsAtTheTop() { + let editor = launch() + var sizes: [CGSize] = [] + editor.onContentSizeChange = { sizes.append($0) } + editor.setContentInsets(top: 0, bottom: 24, left: 0, right: 0) + editor.setInitialText((0..<1000).map { "line \($0)" }.joined(separator: "\n")) + layout(editor) + draw(editor) + editor.scrollToLine(500, animated: false) + draw(editor) + XCTAssertGreaterThan(editor.contentOffset.y, 0) + let row = (sizes[0].height - 24) / 1000 + editor.setInitialText((0..<10).map { "line \($0)" }.joined(separator: "\n")) + draw(editor) + XCTAssertEqual(editor.contentOffset.y, 0) + XCTAssertEqual(sizes.last?.width ?? 0, 300, accuracy: 0.5) + XCTAssertEqual(sizes.last?.height ?? 0, 10 * row + 24, accuracy: 0.5) + } + // A note under the last line, as a checker would open after the final line of an exercise. func testGapRowsCountInTheContentHeight() { let editor = launch() diff --git a/ios/Codepad/layout/HeightMap.swift b/ios/Codepad/layout/HeightMap.swift deleted file mode 100644 index e6aed978..00000000 --- a/ios/Codepad/layout/HeightMap.swift +++ /dev/null @@ -1,129 +0,0 @@ -import Foundation - -/// Rows per line with lazily rebuilt prefix sums. Unmeasured lines count as one row, so every line has a -/// y position before layout and only moves once it is measured. Gap rows under a line count beside its wrap rows. -final class HeightMap { - private var rows: [Int] - private var gaps: [Int] - private var gapLines: [Int] = [] - private var starts: [Int] - private var cleanLines = 0 - private(set) var lineCount: Int - - init(lineCount: Int) { - self.lineCount = lineCount - rows = [Int](repeating: 1, count: max(lineCount, 16)) - gaps = [Int](repeating: 0, count: rows.count) - starts = [Int](repeating: 0, count: rows.count + 1) - } - - var totalRows: Int { rowStart(lineCount) } - - func rows(_ line: Int) -> Int { - rows[line] - } - - func gapRows(_ line: Int) -> Int { - gaps[line] - } - - /// Replaces every gap: line to rows of empty space under it. Lines outside the map are ignored. - func setGaps(_ next: [Int: Int]) { - var dirty = lineCount - for line in gapLines where (next[line] ?? 0) != gaps[line] { dirty = min(dirty, line) } - for (line, count) in next where line >= 0 && line < lineCount && gaps[line] != count { dirty = min(dirty, line) } - if dirty == lineCount { return } - for line in gapLines { gaps[line] = 0 } - var kept: [Int] = [] - for (line, count) in next where line >= 0 && line < lineCount && count > 0 { - gaps[line] = count - kept.append(line) - } - gapLines = kept - cleanLines = min(cleanLines, dirty + 1) - } - - /// True when `row` is empty space under a line rather than one of its text rows. - func isGapRow(_ row: Int) -> Bool { - if row < 0 || row >= totalRows { return false } - let line = lineAtRow(row) - return row >= rowStart(line) + rows[line] - } - - /// Returns the previous count so the caller can keep the viewport anchored. - @discardableResult - func setRows(_ line: Int, _ count: Int) -> Int { - let old = rows[line] - if old != count { - rows[line] = count - cleanLines = min(cleanLines, line + 1) - } - return old - } - - /// First row of `line`. line == lineCount yields the total row count. - func rowStart(_ line: Int) -> Int { - let l = max(0, min(line, lineCount)) - ensure(l) - return starts[l] - } - - func lineAtRow(_ row: Int) -> Int { - ensure(lineCount) - let r = max(0, min(row, max(starts[lineCount] - 1, 0))) - var lo = 0 - var hi = lineCount - 1 - while lo < hi { - let mid = (lo + hi + 1) >> 1 - if starts[mid] <= r { lo = mid } else { hi = mid - 1 } - } - return lo - } - - /// Lines [first, first + oldCount) became newCount fresh lines of one row each, without gaps. - func replaceLines(first: Int, oldCount: Int, newCount: Int) { - let tail = lineCount - first - oldCount - let next = lineCount - oldCount + newCount - if next > rows.count { - rows += [Int](repeating: 1, count: max(next, rows.count * 2) - rows.count) - gaps += [Int](repeating: 0, count: rows.count - gaps.count) - } - if newCount != oldCount && tail > 0 { - let moved = Array(rows[(first + oldCount)..<(first + oldCount + tail)]) - rows.replaceSubrange((first + newCount)..<(first + newCount + tail), with: moved) - let movedGaps = Array(gaps[(first + oldCount)..<(first + oldCount + tail)]) - gaps.replaceSubrange((first + newCount)..<(first + newCount + tail), with: movedGaps) - } - for i in first..<(first + newCount) { - rows[i] = 1 - gaps[i] = 0 - } - if !gapLines.isEmpty { - var shifted: [Int] = [] - for line in gapLines where line < first || line >= first + oldCount { - shifted.append(line >= first + oldCount ? line + newCount - oldCount : line) - } - gapLines = shifted - } - lineCount = next - cleanLines = min(cleanLines, first + 1) - } - - func resetAll() { - for i in 0.. Bool { @@ -48,104 +96,93 @@ final class Viewport { /// Clamps and applies. Returns true when the position moved. @discardableResult func scrollTo(_ x: Int, _ y: Int) -> Bool { - let nx = max(0, min(x, maxScrollX)) - let ny = max(0, min(y, maxScrollY)) - if nx == scrollX && ny == scrollY { return false } - scrollX = nx - scrollY = ny - return true + cp_layout_scroll_to(handle, Int32(clamping: x), Int32(clamping: y), nil) != 0 } @discardableResult func clamp() -> Bool { - scrollTo(scrollX, scrollY) + let g = geometry() + return cp_layout_scroll_to(handle, g.scroll_x, g.scroll_y, nil) != 0 } /// Stores a view size. True when the text area width changed, which is when layouts must be rebuilt. + @discardableResult func resize(width: Int, height: Int) -> Bool { - let before = textAreaWidth - self.width = width - self.height = height - return textAreaWidth != before + config.width = Int32(clamping: width) + config.height = Int32(clamping: height) + return configure() } /// Stores the insets. True when the text area width changed. + @discardableResult func setInsets(top: Int, bottom: Int, left: Int, right: Int) -> Bool { - let before = textAreaWidth - insetTop = top - insetBottom = bottom - insetLeft = left - insetRight = right - return textAreaWidth != before - } - - /// View y of the top of `row`. - func rowTop(_ row: Int) -> Int { - insetTop + row * rowHeight - scrollY - } - - func lineTop(_ line: Int) -> Int { - rowTop(heights.rowStart(line)) - } - + config.inset_top = Int32(clamping: top) + config.inset_bottom = Int32(clamping: bottom) + config.inset_left = Int32(clamping: left) + config.inset_right = Int32(clamping: right) + return configure() + } + + func rowStart(_ line: Int) -> Int { Int(cp_layout_row_start(handle, Int32(clamping: line))) } + func rows(_ line: Int) -> Int { Int(cp_layout_rows(handle, Int32(clamping: line))) } + func gapRows(_ line: Int) -> Int { Int(cp_layout_gap_rows(handle, Int32(clamping: line))) } + func lineAtRow(_ row: Int) -> Int { Int(cp_layout_line_at_row(handle, Int32(clamping: row))) } + /// True when `row` is empty space under a line rather than one of its text rows. + func isGapRow(_ row: Int) -> Bool { cp_layout_is_gap_row(handle, Int32(clamping: row)) != 0 } + func rowTop(_ row: Int) -> Int { Int(cp_layout_row_top(handle, Int32(clamping: row))) } + func lineTop(_ line: Int) -> Int { Int(cp_layout_line_top(handle, Int32(clamping: line))) } /// Content row under view y, possibly outside [0, totalRows). - func rowAt(_ y: Int) -> Int { - Int((Double(y + scrollY - insetTop) / Double(rowHeight)).rounded(.down)) - } + func rowAt(_ y: Int) -> Int { Int(cp_layout_row_at(handle, Int32(clamping: y))) } /// Layout x for a view x. - func contentX(_ x: CGFloat) -> CGFloat { - x - CGFloat(textAreaLeft + textPadding - scrollX) - } + func contentX(_ x: CGFloat) -> CGFloat { x - CGFloat(geometry().text_left) } /// View x for a layout x. - func viewX(_ x: CGFloat) -> CGFloat { - x + CGFloat(textAreaLeft + textPadding - scrollX) - } + func viewX(_ x: CGFloat) -> CGFloat { x + CGFloat(geometry().text_left) } - func firstVisibleRow() -> Int { - max(0, rowAt(insetTop)) - } + func firstVisibleLine() -> Int { Int(geometry().first_line) } - func firstVisibleLine() -> Int { - heights.lineAtRow(firstVisibleRow()) - } - - func lastVisibleLine() -> Int { - heights.lineAtRow(max(firstVisibleRow(), rowAt(height - insetBottom - 1))) - } + func lastVisibleLine() -> Int { Int(geometry().last_line) } /// Smallest scroll that shows a rect in layout coordinates (x from the text start, y from row 0) with the text padding around it. @discardableResult func reveal(left: Int, top: Int, right: Int, bottom: Int) -> Bool { - var x = scrollX - var y = scrollY - let vh = viewportHeight - let vw = textAreaWidth - let l = left - let r = right + 2 * textPadding - if bottom - top >= vh || top < y { y = top } else if bottom > y + vh { y = bottom - vh } - if r - l >= vw || l < x { x = l } else if r > x + vw { x = r - vw } - return scrollTo(x, y) + cp_layout_reveal( + handle, Int32(clamping: left), Int32(clamping: top), Int32(clamping: right), Int32(clamping: bottom), nil) != 0 } /// Remembers the top visible line so a width or font change can put it back. func anchor() -> Anchor { - let line = firstVisibleLine() - return Anchor(line: line, offset: scrollY - heights.rowStart(line) * rowHeight) + var line: Int32 = 0 + var offset: Int32 = 0 + cp_layout_anchor(handle, &line, &offset) + return Anchor(line: Int(line), offset: Int(offset)) } func restore(_ anchor: Anchor) { - let line = max(0, min(anchor.line, heights.lineCount - 1)) - let span = (heights.rows(line) + heights.gapRows(line)) * rowHeight - let within = anchor.offset >= 0 && anchor.offset < span ? anchor.offset : 0 - scrollTo(scrollX, heights.rowStart(line) * rowHeight + within) + cp_layout_restore(handle, Int32(clamping: anchor.line), Int32(clamping: anchor.offset)) } /// Records a measurement. A line above the viewport shifts the scroll so the visible text stays put. func measured(_ line: Int, _ rows: Int) { - let first = firstVisibleLine() - let old = heights.setRows(line, rows) - if old != rows && line < first { scrollY = max(0, min(scrollY + (rows - old) * rowHeight, maxScrollY)) } + var pair: [Int32] = [Int32(clamping: line), Int32(clamping: rows)] + cp_layout_measure(handle, &pair, 1, -1, 0, -1, nil, nil, 0) + } + + /// Every line back to one row. Gaps stay. + func resetRows() { + cp_layout_reset_rows(handle) + } + + private func geometry() -> cp_geometry { + var g = cp_geometry() + cp_layout_geometry(handle, &g) + return g + } + + @discardableResult + private func configure() -> Bool { + var c = config + return cp_layout_configure(handle, &c) != 0 } } diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index 1fd33291..3fdf734a 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -37,7 +37,7 @@ final class CodeEditorView: UIScrollView { func lineAt(_ offset: Int) -> Int { view.docLineAt(offset) } func lineStart(_ line: Int) -> Int { view.docLineStart(line) } func lineLength(_ line: Int) -> Int { view.docLineLength(line) } - func lineTop(_ line: Int) -> Int { view.heights.rowStart(line) * rowHeight } + func lineTop(_ line: Int) -> Int { view.viewport.rowStart(line) * rowHeight } func rowCount(_ line: Int) -> Int { view.cache[line]?.layout.rowCount ?? 0 } func rowSpans(line: Int, from: Int, to: Int, _ out: (_ row: Int, _ left: CGFloat, _ right: CGFloat) -> Void) { view.cache[line]?.layout.selectionRows(from: from, to: to, out) @@ -108,8 +108,7 @@ final class CodeEditorView: UIScrollView { private let frameReader = FrameReader() // Set from the frame call to the end of publish. private var drawFrame: EditorFrame? - private var heights: HeightMap - private let viewport: Viewport + private let viewport = Viewport() private let cache = LayoutCache(capacity: 64) private var nextEntryId = 0 private var brackets: BracketHighlight @@ -137,7 +136,6 @@ final class CodeEditorView: UIScrollView { private var selectionViewsDirty = false private var contentDirty = false private var gapsDirty = false - private var syncedDecorations = -1 private var revealPending = false private var autoFocusPending = false private var lastContentSize = CGSize(width: -1, height: -1) @@ -151,9 +149,6 @@ final class CodeEditorView: UIScrollView { let core = EditorCore() coreLock = OSAllocatedUnfairLock(initialState: core) font = CTFontCreateWithName("Menlo" as CFString, 14, nil) - let heights = HeightMap(lineCount: 1) - self.heights = heights - viewport = Viewport(heights: heights) brackets = BracketHighlight(core: core) textInput = TextInputView(core: core) super.init(frame: frame) @@ -198,7 +193,6 @@ final class CodeEditorView: UIScrollView { func setText(_ text: String, keepHistory: Bool) { textInput.session.reset() core.setText(text, keepHistory: keepHistory) - syncGaps() viewport.scrollTo(0, 0) pushScroll() setNeedsLayout() @@ -514,7 +508,7 @@ final class CodeEditorView: UIScrollView { } func scrollToLine(_ line: Int, animated: Bool) { - let target = heights.rowStart(max(0, min(line, core.document.lineCount - 1))) * viewport.rowHeight + let target = viewport.rowStart(max(0, min(line, core.document.lineCount - 1))) * viewport.rowHeight if animated { setContentOffset(CGPoint(x: viewport.scrollX, y: min(target, viewport.maxScrollY)), animated: true) } else if viewport.scrollTo(viewport.scrollX, target) { @@ -533,7 +527,7 @@ final class CodeEditorView: UIScrollView { let col = head - doc.lineStart(line) let row = entry.layout.rowOf(col) let x = Int(entry.layout.caretX(col).rounded()) - let top = (heights.rowStart(line) + row) * m.rowHeight + let top = (viewport.rowStart(line) + row) * m.rowHeight if viewport.reveal(left: x, top: top, right: x + Int(CodeEditorView.caretWidth), bottom: top + m.rowHeight) { pushScroll() onScrolled() @@ -554,10 +548,10 @@ final class CodeEditorView: UIScrollView { private func offsetAt(row: Int, contentX: CGFloat) -> Int { let doc = core.document if row < 0 { return 0 } - if row >= heights.totalRows { return doc.length } - let line = heights.lineAtRow(row) + if row >= viewport.totalRows { return doc.length } + let line = viewport.lineAtRow(row) let entry = cache[line] ?? layoutLine(line) - let rowInLine = max(0, min(row - heights.rowStart(line), entry.layout.rowCount - 1)) + let rowInLine = max(0, min(row - viewport.rowStart(line), entry.layout.rowCount - 1)) return doc.lineStart(line) + entry.layout.columnAt(row: rowInLine, x: contentX) } @@ -567,7 +561,7 @@ final class CodeEditorView: UIScrollView { let line = docLineAt(offset) let entry = cache[line] ?? layoutLine(line) let col = offset - docLineStart(line) - let top = CGFloat((heights.rowStart(line) + entry.layout.rowOf(col)) * m.rowHeight) + let top = CGFloat((viewport.rowStart(line) + entry.layout.rowOf(col)) * m.rowHeight) return CGRect( x: textPadding + entry.layout.caretX(col), y: top, width: CodeEditorView.caretWidth, height: CGFloat(m.rowHeight)) @@ -583,7 +577,7 @@ final class CodeEditorView: UIScrollView { // The last rect carries the end only when the end's row was reached, not cut off by the view bottom. var endTop: CGFloat = -1 if let entry = cache[endLine] { - endTop = CGFloat((heights.rowStart(endLine) + entry.layout.rowOf(end - docLineStart(endLine))) * m.rowHeight) + endTop = CGFloat((viewport.rowStart(endLine) + entry.layout.rowOf(end - docLineStart(endLine))) * m.rowHeight) } return rects.enumerated().map { i, rect in CPSelectionRect( @@ -656,14 +650,13 @@ final class CodeEditorView: UIScrollView { if viewport.scrollTo(Int(contentOffset.x.rounded()), Int(contentOffset.y.rounded())) { scrollDirty = true } let scrolled = scrollDirty if w == 0 || h == 0 { return } - syncGaps() let m = rowMetrics() if revealPending { revealPending = false revealSelection() } let first = viewport.firstVisibleLine() - let lastBound = min(heights.lineCount - 1, first + h / m.rowHeight + 1) + let lastBound = min(viewport.lineCount - 1, first + h / m.rowHeight + 1) let scrollBefore = viewport.scrollY // One core call for the whole draw. Until publish returns, every read comes from it. let frame = readFrame(first, lastBound) @@ -710,6 +703,7 @@ final class CodeEditorView: UIScrollView { } private func wire(_ core: EditorCore) { + viewport.attach(core) core.onChange = { [weak self] change, origin in self?.onDocumentChange(change, origin) } core.onSelectionChange = { [weak self] _ in self?.onSelectionMoved() } let enabled = brackets.enabled @@ -741,12 +735,11 @@ final class CodeEditorView: UIScrollView { let first = doc.lineAt(change.start) let oldCount = lineSpan(change.removed) let newCount = lineSpan(change.inserted) - heights.replaceLines(first: first, oldCount: oldCount, newCount: newCount) - syncGaps() keepSpans(first, oldCount, newCount, change) cache.shift(first: first, oldCount: oldCount, newCount: newCount) search?.onChange(change) - if updateGutter() { relayout() } else { viewport.clamp() } + // The core already moved the rows and gaps with the edit and clamped the scroll. + if updateGutter() { relayout() } if origin != .api { revealPending = true } // A change the keyboard did not make: it ends a composition it touched and the keyboard hears of it. let session = textInput.session @@ -770,30 +763,17 @@ final class CodeEditorView: UIScrollView { /// Replaces the decorations. `revision` is the one they were computed for, below zero for the current text. func setDecorations(_ items: [Decoration], revision: Int) { + // The core moves the gaps and keeps the top visible line where it was. if !core.setDecorations(items, revision: revision) { return } - let anchor = viewport.anchor() - if syncGaps() { - viewport.restore(anchor) - pushScroll() - } + pushScroll() selectionViewsDirty = true updateContentSize() setNeedsLayout() } - /// Pushes the gap rows of a changed decoration set into the height map. True when it pushed. - @discardableResult - private func syncGaps() -> Bool { - let set = core.decorations - if set.version == syncedDecorations { return false } - syncedDecorations = set.version - heights.setGaps(set.gapRows()) - return true - } - /// True when a point in content view coordinates is in a gap, where taps leave the caret alone. func inGap(contentY: CGFloat) -> Bool { - heights.isGapRow(Int((contentY / CGFloat(rowMetrics().rowHeight)).rounded(.down))) + viewport.isGapRow(Int((contentY / CGFloat(rowMetrics().rowHeight)).rounded(.down))) } /// The gap under `line` in view points from the last frame, or nil. @@ -802,9 +782,6 @@ final class CodeEditorView: UIScrollView { } private func resetDocument() { - heights = HeightMap(lineCount: core.document.lineCount) - syncedDecorations = -1 - viewport.heights = heights cache.clear() viewport.widestLine = 0 updateGutter() @@ -820,7 +797,7 @@ final class CodeEditorView: UIScrollView { let scrollX = viewport.scrollX viewport.rowHeight = rowMetrics().rowHeight cache.clear() - heights.resetAll() + viewport.resetRows() viewport.widestLine = 0 updateGutter() viewport.restore(anchor) @@ -1093,7 +1070,7 @@ final class CodeEditorView: UIScrollView { if viewport.lineTop(line) >= viewport.height { break } guard let entry = cache[line] else { break } let full = CGRect( - x: 0, y: CGFloat(heights.rowStart(line) * m.rowHeight), width: CGFloat(viewport.contentWidth), + x: 0, y: CGFloat(viewport.rowStart(line) * m.rowHeight), width: CGFloat(viewport.contentWidth), height: CGFloat(entry.layout.rowCount * m.rowHeight)) let clipped = full.intersection(clip) place(entry, clipped.isNull || clipped.isEmpty ? full : clipped, full, scale) @@ -1173,8 +1150,8 @@ final class CodeEditorView: UIScrollView { if highlightActiveLine && sel.isEmpty { d.setActiveLine( CGRect( - x: 0, y: CGFloat(heights.rowStart(caretLine) * m.rowHeight), width: CGFloat(viewport.contentWidth), - height: CGFloat(heights.rows(caretLine) * m.rowHeight))) + x: 0, y: CGFloat(viewport.rowStart(caretLine) * m.rowHeight), width: CGFloat(viewport.contentWidth), + height: CGFloat(viewport.rows(caretLine) * m.rowHeight))) } else { d.setActiveLine(nil) } @@ -1207,8 +1184,8 @@ final class CodeEditorView: UIScrollView { case .lineBackground(let line, let color): if line < first || line > lastLine { continue } let rect = CGRect( - x: 0, y: CGFloat(heights.rowStart(line) * m.rowHeight), width: CGFloat(viewport.contentWidth), - height: CGFloat(heights.rows(line) * m.rowHeight)) + x: 0, y: CGFloat(viewport.rowStart(line) * m.rowHeight), width: CGFloat(viewport.contentWidth), + height: CGFloat(viewport.rows(line) * m.rowHeight)) backgrounds.path(DecorationLayers.Paint(color: color, width: 0)).addRect(rect) case .underline(let u): let thickness = CGFloat(u.thickness) @@ -1313,7 +1290,7 @@ final class CodeEditorView: UIScrollView { if rows.isEmpty { return [] } var out: [GapRect] = [] for line in rows.keys.sorted() { - let top = CGFloat(viewport.rowTop(heights.rowStart(line) + heights.rows(line))) + let top = CGFloat(viewport.rowTop(viewport.rowStart(line) + viewport.rows(line))) let height = CGFloat((rows[line] ?? 0) * m.rowHeight) out.append(GapRect(line: line, rect: CGRect(x: 0, y: top, width: bounds.width, height: height))) } diff --git a/tests/swift/CoreLayoutTests.swift b/tests/swift/CoreLayoutTests.swift new file mode 100644 index 00000000..a5b5d225 --- /dev/null +++ b/tests/swift/CoreLayoutTests.swift @@ -0,0 +1,36 @@ +import XCTest + +@testable import Codepad + +@MainActor +final class CoreLayoutTests: XCTestCase { + // The view repaints from the change callback, so the rows must already follow the edit when it runs. + func testRowsFollowAnEditBeforeTheChangeCallback() { + let core = EditorCore("a") + let viewport = Viewport() + viewport.attach(core) + var seen = -1 + core.onChange = { _, _ in seen = viewport.totalRows } + core.replace(1, 1, "\nb\nc") + XCTAssertEqual(seen, 3) + } + + // setInitialText swaps the editor under the same view: its size and metrics stay, its rows start over. + func testAReattachedLayoutKeepsItsMetrics() { + let first = EditorCore("a\nb\nc") + let viewport = Viewport() + viewport.attach(first) + viewport.rowHeight = 10 + _ = viewport.resize(width: 100, height: 50) + viewport.measured(1, 3) + XCTAssertEqual(viewport.totalRows, 5) + let second = EditorCore("a\nb\nc\nd\ne") + viewport.attach(second) + XCTAssertEqual(viewport.width, 100) + XCTAssertEqual(viewport.rowHeight, 10) + XCTAssertEqual(viewport.rows(1), 1) + XCTAssertEqual(viewport.totalRows, 5) + first.replace(0, 0, "x\n") + XCTAssertEqual(viewport.lineCount, 5, "the old editor no longer reaches the layout") + } +} diff --git a/tests/swift/HeightMapTests.swift b/tests/swift/HeightMapTests.swift deleted file mode 100644 index 062bc1c0..00000000 --- a/tests/swift/HeightMapTests.swift +++ /dev/null @@ -1,99 +0,0 @@ -import XCTest - -@testable import Codepad - -final class HeightMapTests: XCTestCase { - func testUnmeasuredLinesCountOneRow() { - let h = HeightMap(lineCount: 5) - XCTAssertEqual(h.totalRows, 5) - XCTAssertEqual(h.rowStart(3), 3) - XCTAssertEqual(h.rowStart(5), 5) - XCTAssertEqual(h.lineAtRow(4), 4) - XCTAssertEqual(h.lineAtRow(99), 4) - XCTAssertEqual(h.lineAtRow(-1), 0) - } - - func testMeasuredRowsShiftLaterLines() { - let h = HeightMap(lineCount: 5) - XCTAssertEqual(h.setRows(1, 3), 1) - XCTAssertEqual(h.setRows(1, 3), 3) - XCTAssertEqual(h.totalRows, 7) - XCTAssertEqual(h.rowStart(2), 4) - XCTAssertEqual(h.lineAtRow(1), 1) - XCTAssertEqual(h.lineAtRow(3), 1) - XCTAssertEqual(h.lineAtRow(4), 2) - XCTAssertEqual(h.lineAtRow(6), 4) - } - - func testReplaceLinesKeepsTheTail() { - let h = HeightMap(lineCount: 4) - h.setRows(3, 2) - h.replaceLines(first: 1, oldCount: 1, newCount: 3) - XCTAssertEqual(h.lineCount, 6) - XCTAssertEqual(h.rows(1), 1) - XCTAssertEqual(h.rows(3), 1) - XCTAssertEqual(h.rows(5), 2) - XCTAssertEqual(h.totalRows, 7) - h.replaceLines(first: 0, oldCount: 3, newCount: 1) - XCTAssertEqual(h.lineCount, 4) - XCTAssertEqual(h.rows(3), 2) - XCTAssertEqual(h.totalRows, 5) - XCTAssertEqual(h.rowStart(3), 3) - } - - func testResetAllForgetsMeasurements() { - let h = HeightMap(lineCount: 3) - h.setRows(0, 4) - XCTAssertEqual(h.totalRows, 6) - h.resetAll() - XCTAssertEqual(h.totalRows, 3) - XCTAssertEqual(h.rowStart(1), 1) - } - - func testGrowsPastTheInitialCapacity() { - let h = HeightMap(lineCount: 1) - h.replaceLines(first: 0, oldCount: 1, newCount: 40) - XCTAssertEqual(h.lineCount, 40) - XCTAssertEqual(h.totalRows, 40) - XCTAssertEqual(h.rowStart(39), 39) - h.replaceLines(first: 39, oldCount: 1, newCount: 30) - XCTAssertEqual(h.lineCount, 69) - XCTAssertEqual(h.totalRows, 69) - } - - func testGapRowsCountInRowStartsAndTotal() { - let h = HeightMap(lineCount: 4) - h.setGaps([1: 2]) - XCTAssertEqual(h.rowStart(1), 1) - XCTAssertEqual(h.rowStart(2), 4) - XCTAssertEqual(h.totalRows, 6) - XCTAssertEqual(h.lineAtRow(3), 1) - XCTAssertTrue(h.isGapRow(3)) - XCTAssertFalse(h.isGapRow(1)) - } - - func testRelayoutKeepsGaps() { - let h = HeightMap(lineCount: 3) - h.setGaps([0: 2]) - h.setRows(0, 3) - h.resetAll() - XCTAssertEqual(h.gapRows(0), 2) - XCTAssertEqual(h.rowStart(1), 3) - } - - func testReplaceLinesMovesGapsWithTheirLines() { - let h = HeightMap(lineCount: 4) - h.setGaps([2: 1]) - h.replaceLines(first: 0, oldCount: 1, newCount: 3) - XCTAssertEqual(h.gapRows(4), 1) - XCTAssertEqual(h.gapRows(2), 0) - } - - func testSetGapsReplacesThePreviousGaps() { - let h = HeightMap(lineCount: 4) - h.setGaps([0: 2]) - h.setGaps([2: 1]) - XCTAssertEqual(h.gapRows(0), 0) - XCTAssertEqual(h.totalRows, 5) - } -} diff --git a/tests/swift/VectorRunner.swift b/tests/swift/VectorRunner.swift index 087d778d..b799f28a 100644 --- a/tests/swift/VectorRunner.swift +++ b/tests/swift/VectorRunner.swift @@ -16,8 +16,7 @@ final class VectorRunner { private var lastResult: Any? = nil private var lastError: String? = nil - // Created by the first layout op. Until the layout moves into the core, the runner keeps it in step as the view does. - private var heights: HeightMap? = nil + // Created and attached by the first layout op. The core keeps its rows and gaps in step with the edits. private var viewport: Viewport? = nil private var anchor: Viewport.Anchor? = nil private var widthChanged = false @@ -27,36 +26,16 @@ final class VectorRunner { let clock = Clock() self.clock = clock core = EditorCore(testCase["text"] as? String ?? "", clock: { clock.now }) - core.onChange = { [weak self] change, origin in - guard let self else { return } - self.changes.append((change, origin)) - if let h = self.heights { - let first = self.core.document.lineAt(change.start) - h.replaceLines(first: first, oldCount: Self.lineSpan(change.removed), newCount: Self.lineSpan(change.inserted)) - h.setGaps(self.core.decorations.gapRows()) - self.viewport?.clamp() - } - } - } - - private static func lineSpan(_ text: String) -> Int { - text.utf16.reduce(1) { $0 + ($1 == 10 ? 1 : 0) } + core.onChange = { [weak self] change, origin in self?.changes.append((change, origin)) } } private func layout(_ op: [String: Any]) { - let h: HeightMap - if let existing = heights { - h = existing - } else { - h = HeightMap(lineCount: core.document.lineCount) - h.setGaps(core.decorations.gapRows()) - heights = h - } let vp: Viewport if let existing = viewport { vp = existing } else { - vp = Viewport(heights: h) + vp = Viewport() + vp.attach(core) viewport = vp } let before = vp.textAreaWidth @@ -139,11 +118,6 @@ final class VectorRunner { case "decorate": let items = (op["items"] as? [[String: Any]] ?? []).map(decorationOf) _ = core.setDecorations(items, revision: op["revision"] as? Int ?? -1) - if let vp = viewport { - let a = vp.anchor() - vp.heights.setGaps(core.decorations.gapRows()) - vp.restore(a) - } case "layout": layout(op) case "measure": guard let vp = viewport else { return XCTFail("measure before layout") } @@ -159,7 +133,7 @@ final class VectorRunner { } case "anchor": anchor = viewport?.anchor() case "restore": if let a = anchor { viewport?.restore(a) } - case "resetRows": heights?.resetAll() + case "resetRows": viewport?.resetRows() default: XCTFail("op not implemented: \(name)") } } @@ -264,7 +238,7 @@ final class VectorRunner { private func checkLayout(_ expect: [String: Any], _ at: String) { guard let vp = viewport else { return } - let h = vp.heights + let h = vp if let v = expect["widthChanged"] as? Bool { XCTAssertEqual(widthChanged, v, "widthChanged \(at)") } if let v = expect["scroll"] as? [Int] { XCTAssertEqual([vp.scrollX, vp.scrollY], v, "scroll \(at)") } if let v = expect["maxScroll"] as? [Int] { XCTAssertEqual([vp.maxScrollX, vp.maxScrollY], v, "maxScroll \(at)") } diff --git a/tests/swift/ViewportTests.swift b/tests/swift/ViewportTests.swift index ce4c0987..41645db6 100644 --- a/tests/swift/ViewportTests.swift +++ b/tests/swift/ViewportTests.swift @@ -2,69 +2,12 @@ import XCTest @testable import Codepad +// The layout math runs on the shared vectors. Only the iOS gesture rule stays here. final class ViewportTests: XCTestCase { - private func viewport(lines: Int = 100, rowHeight: Int = 20, height: Int = 200, width: Int = 400) -> Viewport { - let v = Viewport(heights: HeightMap(lineCount: lines)) - v.rowHeight = rowHeight - v.height = height - v.width = width - return v - } - - func testClampsScrollToTheContent() { - let v = viewport() - XCTAssertEqual(v.contentHeight, 2000) - XCTAssertEqual(v.maxScrollY, 1800) - XCTAssertTrue(v.scrollTo(0, 5000)) - XCTAssertEqual(v.scrollY, 1800) - XCTAssertFalse(v.scrollTo(-10, 1800)) - XCTAssertEqual(v.scrollX, 0) - XCTAssertEqual(v.maxScrollX, 0) - XCTAssertTrue(v.scrollTo(0, 800)) - XCTAssertEqual(v.scrollY, 800) - v.scrollTo(0, 5000) - v.height = 300 - XCTAssertTrue(v.clamp()) - XCTAssertEqual(v.scrollY, 1700) - } - - func testMapsRowsToViewPointsThroughInsets() { - let v = viewport() - v.insetTop = 30 - v.insetBottom = 50 - XCTAssertEqual(v.viewportHeight, 120) - XCTAssertEqual(v.maxScrollY, 1880) - XCTAssertEqual(v.lineTop(0), 30) - XCTAssertEqual(v.rowAt(0), -2) - _ = v.scrollTo(0, 45) - XCTAssertEqual(v.firstVisibleLine(), 2) - XCTAssertEqual(v.lineTop(2), 25) - XCTAssertEqual(v.lastVisibleLine(), 8) - XCTAssertEqual(v.rowAt(55), 3) - XCTAssertEqual(v.rowAt(0), 0) - } - - func testHorizontalRangeFollowsTheWidestLine() { - let v = viewport() - v.gutterWidth = 40 - v.textPadding = 8 - v.widestLine = 1000 - XCTAssertEqual(v.textAreaLeft, 40) - XCTAssertEqual(v.textAreaWidth, 360) - XCTAssertEqual(v.contentWidth, 1016) - XCTAssertEqual(v.maxScrollX, 656) - XCTAssertEqual(v.wrapWidth, 0) - XCTAssertEqual(v.contentX(148), 100) - _ = v.scrollTo(100, 0) - XCTAssertEqual(v.viewX(0), -52) - v.wrap = true - XCTAssertEqual(v.maxScrollX, 0) - XCTAssertEqual(v.wrapWidth, 344) - XCTAssertEqual(v.contentWidth, 360) - } - func testPansSidewaysOnlyForAMostlyHorizontalDragOverWideText() { - let v = viewport() + let v = Viewport() + v.rowHeight = 20 + v.resize(width: 400, height: 200) v.widestLine = 1000 XCTAssertTrue(v.pansSideways(dx: 30, dy: 12)) XCTAssertTrue(v.pansSideways(dx: -30, dy: 12)) @@ -73,82 +16,4 @@ final class ViewportTests: XCTestCase { v.widestLine = 100 XCTAssertFalse(v.pansSideways(dx: 30, dy: 0)) } - - func testRevealScrollsTheMinimumDistance() { - let v = viewport() - v.textPadding = 8 - v.widestLine = 1000 - XCTAssertTrue(v.reveal(left: 0, top: 500, right: 10, bottom: 520)) - XCTAssertEqual(v.scrollY, 320) - XCTAssertTrue(v.reveal(left: 0, top: 100, right: 10, bottom: 120)) - XCTAssertEqual(v.scrollY, 100) - XCTAssertFalse(v.reveal(left: 0, top: 150, right: 10, bottom: 170)) - XCTAssertTrue(v.reveal(left: 490, top: 150, right: 500, bottom: 170)) - XCTAssertEqual(v.scrollX, 116) - XCTAssertTrue(v.reveal(left: 0, top: 0, right: 10, bottom: 20)) - XCTAssertEqual(v.scrollX, 0) - XCTAssertEqual(v.scrollY, 0) - } - - func testAnchorSurvivesARelayout() { - let v = viewport() - v.heights.setRows(3, 4) - _ = v.scrollTo(0, 80) - let a = v.anchor() - XCTAssertEqual(a.line, 3) - XCTAssertEqual(a.offset, 20) - v.heights.resetAll() - v.restore(a) - XCTAssertEqual(v.scrollY, 60) - v.heights.setRows(3, 4) - v.restore(a) - XCTAssertEqual(v.scrollY, 80) - } - - func testMeasuringALineAboveKeepsTheViewportStill() { - let v = viewport() - _ = v.scrollTo(0, 400) - XCTAssertEqual(v.firstVisibleLine(), 20) - v.measured(5, 3) - XCTAssertEqual(v.scrollY, 440) - XCTAssertEqual(v.firstVisibleLine(), 20) - v.measured(20, 2) - XCTAssertEqual(v.scrollY, 440) - v.measured(5, 3) - XCTAssertEqual(v.scrollY, 440) - } - - func testResizeAndInsetsReportOnlyTextAreaWidthChanges() { - let v = viewport() - XCTAssertFalse(v.resize(width: 400, height: 300)) - XCTAssertEqual(v.height, 300) - XCTAssertTrue(v.resize(width: 500, height: 300)) - XCTAssertEqual(v.width, 500) - XCTAssertFalse(v.setInsets(top: 10, bottom: 20, left: 0, right: 0)) - XCTAssertEqual(v.insetBottom, 20) - XCTAssertTrue(v.setInsets(top: 10, bottom: 20, left: 8, right: 0)) - XCTAssertEqual(v.insetLeft, 8) - XCTAssertTrue(v.setInsets(top: 10, bottom: 20, left: 8, right: 4)) - XCTAssertFalse(v.setInsets(top: 0, bottom: 0, left: 8, right: 4)) - } - - func testMeasuringAWrappedLineAboveKeepsTheGapAndTheVisibleText() { - let v = viewport(lines: 40, rowHeight: 10, height: 100) - v.heights.setGaps([5: 2]) - _ = v.scrollTo(0, v.heights.rowStart(20) * 10) - let before = v.scrollY - v.measured(3, 3) - XCTAssertEqual(v.scrollY, before + 20) - XCTAssertEqual(v.lineTop(6) - v.lineTop(5), 30) - } - - func testAnchorRestoreInsideAGapStaysInIt() { - let v = viewport(lines: 10, rowHeight: 10, height: 50) - v.heights.setGaps([1: 2]) - _ = v.scrollTo(0, 25) - let a = v.anchor() - v.heights.resetAll() - v.restore(a) - XCTAssertEqual(v.scrollY, 25) - } } diff --git a/tests/vectors/layout.json b/tests/vectors/layout.json index 4d4de2cf..6c1e4eb5 100644 --- a/tests/vectors/layout.json +++ b/tests/vectors/layout.json @@ -6,6 +6,7 @@ { "name": "a line measured above the viewport keeps the visible text in place", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "scrollTo", "x": 0, "y": 50, "expect": { "visible": [5, 9], "lineTop": { "5": 0 } } }, { "op": "measure", "pairs": [[2, 3]] }], "expect": { "scroll": [0, 70], "visible": [5, 9], "lineTop": { "5": 0 }, "maxScroll": [0, 170] } }, { "name": "a batch with a growth above and a shrink at the first visible line keeps that line in place", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "measure", "pairs": [[5, 3]] }, { "op": "scrollTo", "x": 0, "y": 50, "expect": { "visible": [5, 7], "lineTop": { "5": 0 } } }, { "op": "measure", "pairs": [[2, 2], [5, 1]] }], "expect": { "scroll": [0, 60], "lineTop": { "5": 0 }, "totalRows": 21, "content": [100, 210], "maxScroll": [0, 160] } }, { "name": "gap rows sit beside wrap rows", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": true }, { "op": "decorate", "items": [{ "kind": "gap", "line": 3, "rows": 2 }] }, { "op": "measure", "pairs": [[3, 2]] }], "expect": { "rowStart": { "3": 3, "4": 7 }, "isGapRow": { "3": false, "4": false, "5": true, "6": true, "7": false }, "totalRows": 23 } }, + { "name": "a new decoration set replaces the gaps", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "decorate", "items": [{ "kind": "gap", "line": 2, "rows": 2 }], "expect": { "totalRows": 22 } }, { "op": "decorate", "items": [{ "kind": "gap", "line": 5, "rows": 1 }] }], "expect": { "totalRows": 21, "rowStart": { "3": 3, "6": 7 }, "isGapRow": { "3": false, "6": true } } }, { "name": "deleting a gap's line at the end and undoing keeps the rows in range", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "decorate", "items": [{ "kind": "gap", "line": 19, "rows": 2 }] }, { "op": "scrollTo", "x": 0, "y": 1000, "expect": { "scroll": [0, 170], "totalRows": 22 } }, { "op": "replace", "start": 29, "end": 39, "text": "", "expect": { "lineCount": 15, "gapRows": {}, "totalRows": 15, "scroll": [0, 100], "isGapRow": { "14": false, "15": false } } }, { "op": "undo" }], "expect": { "lineCount": 20, "gapRows": {}, "totalRows": 20, "scroll": [0, 100], "maxScroll": [0, 150] } }, { "name": "an edit makes fresh one-row lines and moves gap lines with their text", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": true }, { "op": "decorate", "items": [{ "kind": "gap", "line": 10, "rows": 2 }] }, { "op": "measure", "pairs": [[5, 3], [12, 2]] }, { "op": "replace", "start": 10, "end": 10, "text": "y\ny\n" }], "expect": { "lineCount": 22, "gapRows": { "12": 2 }, "rowStart": { "5": 5, "8": 8, "12": 12, "13": 15, "14": 16, "15": 18 }, "totalRows": 25 } }, { "name": "rows map to the view through the insets", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [8, 4, 6, 2], "gutter": 10, "padding": 3, "wrap": false, "expect": { "content": [82, 200], "maxScroll": [0, 162], "lineTop": { "0": 8, "3": 38 }, "visible": [0, 3] } }, { "op": "scrollTo", "x": 0, "y": 25 }], "expect": { "lineTop": { "3": 13 }, "visible": [2, 6] } }, From 4efdd7977c4a37e92e26e11b7ce3ca6b9c0a9694 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 13:47:35 +0100 Subject: [PATCH 05/21] perf(ios): lay out a draw with one frame call and one measure call The layout now picks the frame's lines. After the view lays them out, one measure call pushes the rows and the widest line and returns the tops, the rows and every gap. The painters read that copy until the draw ends, and debug builds trap past eight other layout calls in one draw. The selection ends' lines are laid out before the measure call, so a handle line above the view no longer moves the scroll under layers already placed. --- android/src/main/cpp/core_jni.cpp | 7 +- cpp/core/include/codepad.h | 28 ++- cpp/core/src/capi_layout.cpp | 9 +- cpp/core/src/frame.cpp | 73 ++++-- cpp/core/src/layout.hpp | 2 + .../ios/CodepadTests/ContentSizeTests.swift | 12 + .../CodepadTests/SelectionGeometryTests.swift | 23 ++ ios/Codepad/core/EditorFrame.swift | 50 +++- ios/Codepad/layout/LayoutCache.swift | 5 + ios/Codepad/layout/Viewport.swift | 218 ++++++++++++++++-- ios/Codepad/view/CodeEditorView.swift | 93 +++++--- tests/swift/CoreLayoutTests.swift | 74 ++++++ tests/swift/FrameTests.swift | 56 +++++ tests/swift/LayoutCacheTests.swift | 17 ++ 14 files changed, 580 insertions(+), 87 deletions(-) diff --git a/android/src/main/cpp/core_jni.cpp b/android/src/main/cpp/core_jni.cpp index 47f4c56b..27217af6 100644 --- a/android/src/main/cpp/core_jni.cpp +++ b/android/src/main/cpp/core_jni.cpp @@ -565,9 +565,10 @@ FN(editorFrame)(JNIEnv *e, jclass, jlong editor, jlong snapshot, jint first, jin uint32_t units = 0; auto *o = static_cast(e->GetPrimitiveArrayCritical(out, nullptr)); auto *t = static_cast(e->GetPrimitiveArrayCritical(text, nullptr)); - uint32_t needed = cp_editor_frame(ed(editor), ptr(snapshot), first, last, applied, use_changed ? 1 : 0, - revisions.data(), reinterpret_cast(o), static_cast(cap), - reinterpret_cast(t), static_cast(text_cap), &units); + uint32_t needed = cp_editor_frame_range(ed(editor), ptr(snapshot), first, last, applied, + use_changed ? 1 : 0, revisions.data(), reinterpret_cast(o), + static_cast(cap), reinterpret_cast(t), + static_cast(text_cap), &units); e->ReleasePrimitiveArrayCritical(text, t, 0); e->ReleasePrimitiveArrayCritical(out, o, 0); auto length = static_cast(units); diff --git a/cpp/core/include/codepad.h b/cpp/core/include/codepad.h index 9a75aade..91774989 100644 --- a/cpp/core/include/codepad.h +++ b/cpp/core/include/codepad.h @@ -220,8 +220,9 @@ CP_API int32_t cp_layout_scroll_to(cp_layout *layout, int32_t x, int32_t y, cp_g CP_API int32_t cp_layout_reveal(cp_layout *layout, int32_t left, int32_t top, int32_t right, int32_t bottom, cp_geometry *out); // Applies (line, rows) pairs in order, as successive measurements would, then raises the widest line to widest -// when widest >= 0 and the layout does not wrap. Writes the view tops of first_line..last_line + 1, then the text -// rows of first_line..last_line, and returns how many ints that needs. A short buffer gets nothing written. +// when widest >= 0 and the layout does not wrap. Writes the view tops of first_line..last_line + 1, the text rows of +// first_line..last_line, then (line, view top, rows) for every gap in line order, and returns how many ints that +// needs. A short buffer gets nothing written. first_line > last_line writes nothing and returns 0. CP_API uint32_t cp_layout_measure(cp_layout *layout, const int32_t *pairs, uint32_t pair_count, int32_t widest, int32_t first_line, int32_t last_line, cp_geometry *out, int32_t *tops_rows, uint32_t cap); @@ -331,20 +332,27 @@ CP_API void cp_snapshot_injected_get(const cp_snapshot *snapshot, uint32_t index CP_API uint32_t cp_highlight(const cp_snapshot *snapshot, int32_t first_line, int32_t last_line, uint32_t first_line_start, int32_t *out, uint32_t cap); enum { CP_NO_ENTRY = -2147483647 - 1 }; -// Main thread, one call per draw over lines [first_line, last_line] clamped to the document. entry_revisions[i] is -// the cached revision of line first_line + i: CP_NO_ENTRY without one, -1 for a line laid out plain. use_changed -// is 1 when the snapshot is based on applied_revision. out receives, in order: -// a header: revision, length, line_count, anchor, head, caret_line, decorations_version, history -// the line starts of the clamped first..last + 1 (line_count gives length + 1) +// Main thread, one call per draw. The layout picks the lines: its first visible line through the lines one view +// height of rows can show, clamped to the document. entries holds entry_count (line, revision) pairs of the view's +// cache in any order: a line without a pair has no entry, -1 marks a line laid out plain. use_changed is 1 when the +// snapshot is based on applied_revision. out receives, in order: +// a header: revision, length, line_count, anchor, head, caret_line, decorations_version, history, first, last +// the line starts of first..last + 1 (line_count gives length + 1) // the dirty runs: run_count, run_count inclusive (lo, hi) pairs, then for each line of each run its spans as // cp_highlight. snapshot NULL or at another revision than the document: the runs are the lines with no entry // and every span count is 0 // for each line of each run, its text's offset and length in text_out // Returns the ints needed and sets *text_len to the units needed. Nothing is written unless both fit. -CP_API uint32_t cp_editor_frame(const cp_editor *editor, const cp_snapshot *snapshot, int32_t first_line, - int32_t last_line, int32_t applied_revision, int32_t use_changed, - const int32_t *entry_revisions, int32_t *out, uint32_t cap, cp_unit *text_out, +CP_API uint32_t cp_editor_frame(const cp_editor *editor, const cp_layout *layout, const cp_snapshot *snapshot, + int32_t applied_revision, int32_t use_changed, const int32_t *entries, + uint32_t entry_count, int32_t *out, uint32_t cap, cp_unit *text_out, uint32_t text_cap, uint32_t *text_len); +// cp_editor_frame over lines [first_line, last_line] clamped to the document, with no first and last in the +// header. entry_revisions[i] is the cached revision of line first_line + i. +CP_API uint32_t cp_editor_frame_range(const cp_editor *editor, const cp_snapshot *snapshot, int32_t first_line, + int32_t last_line, int32_t applied_revision, int32_t use_changed, + const int32_t *entry_revisions, int32_t *out, uint32_t cap, cp_unit *text_out, + uint32_t text_cap, uint32_t *text_len); // A line's triples after an edit inside it replaced removed units at start with inserted units. CP_API uint32_t cp_shift_spans(const int32_t *spans, uint32_t count, int32_t start, int32_t removed, int32_t inserted, int32_t *out, uint32_t cap); diff --git a/cpp/core/src/capi_layout.cpp b/cpp/core/src/capi_layout.cpp index c2c2fb4e..c14a9e23 100644 --- a/cpp/core/src/capi_layout.cpp +++ b/cpp/core/src/capi_layout.cpp @@ -54,10 +54,17 @@ uint32_t cp_layout_measure(cp_layout *layout, const int32_t *pairs, uint32_t pai fill(l, out); if (first_line > last_line) return 0; auto lines = static_cast(last_line - first_line + 1); - uint32_t needed = 2 * lines + 1; + const std::vector &gaps = l.gap_lines(); + uint32_t needed = 2 * lines + 1 + 3 * static_cast(gaps.size()); if (tops_rows == nullptr || cap < needed) return needed; for (uint32_t i = 0; i <= lines; i++) tops_rows[i] = l.line_top(first_line + static_cast(i)); for (uint32_t i = 0; i < lines; i++) tops_rows[lines + 1 + i] = l.rows(first_line + static_cast(i)); + int32_t *gap = tops_rows + 2 * lines + 1; + for (int32_t line : gaps) { + *gap++ = line; + *gap++ = l.row_top(l.row_start(line) + l.rows(line)); + *gap++ = l.gap_rows(line); + } return needed; } diff --git a/cpp/core/src/frame.cpp b/cpp/core/src/frame.cpp index 80c26b78..82bf6caa 100644 --- a/cpp/core/src/frame.cpp +++ b/cpp/core/src/frame.cpp @@ -5,6 +5,7 @@ #include "codepad.h" #include "editor.hpp" #include "highlighter.hpp" +#include "layout.hpp" #include "spans.hpp" namespace codepad { @@ -95,32 +96,31 @@ extern "C" uint32_t cp_highlight(const cp_snapshot *snapshot, int32_t first_line return deliver(ints, out, cap); } -extern "C" uint32_t cp_editor_frame(const cp_editor *editor, const cp_snapshot *snapshot, int32_t first_line, - int32_t last_line, int32_t applied_revision, int32_t use_changed, - const int32_t *entry_revisions, int32_t *out, uint32_t cap, cp_unit *text_out, - uint32_t text_cap, uint32_t *text_len) { +static std::vector frame_header(const cp_editor *editor) { const codepad::Document &doc = editor->doc; - int32_t line_count = doc.line_count(); - int32_t first = std::clamp(first_line, 0, line_count - 1); - int32_t last = std::clamp(last_line, first, line_count - 1); codepad::Selection sel = editor->selection(); - std::vector ints{doc.revision(), - static_cast(doc.length()), - line_count, - sel.anchor, - sel.head, - doc.line_at(static_cast(std::max(sel.head, 0))), - editor->decorations.version(), - editor->history()}; + return {doc.revision(), + static_cast(doc.length()), + doc.line_count(), + sel.anchor, + sel.head, + doc.line_at(static_cast(std::max(sel.head, 0))), + editor->decorations.version(), + editor->history()}; +} + +// The frame of lines first..last, already clamped, after the header in ints. entries holds one revision per line. +static uint32_t build_frame(const cp_editor *editor, const cp_snapshot *snapshot, int32_t first, int32_t last, + const std::vector &entries, int32_t applied_revision, int32_t use_changed, + std::vector &ints, int32_t *out, uint32_t cap, cp_unit *text_out, + uint32_t text_cap, uint32_t *text_len) { + const codepad::Document &doc = editor->doc; auto count = static_cast(last - first + 1); codepad::Lines lines; - std::vector entries(count); for (size_t k = 0; k < count; k++) { int32_t line = first + static_cast(k); lines.start.push_back(static_cast(doc.line_start(line))); lines.length.push_back(static_cast(doc.line_length(line))); - bool requested = line >= first_line && line <= last_line; - entries[k] = requested ? entry_revisions[line - first_line] : CP_NO_ENTRY; } for (int32_t line = first; line <= last + 1; line++) ints.push_back(static_cast(doc.line_start(line))); bool consistent = snapshot != nullptr && snapshot->text && snapshot->revision == doc.revision(); @@ -180,6 +180,43 @@ extern "C" uint32_t cp_editor_frame(const cp_editor *editor, const cp_snapshot * return size; } +extern "C" uint32_t cp_editor_frame_range(const cp_editor *editor, const cp_snapshot *snapshot, int32_t first_line, + int32_t last_line, int32_t applied_revision, int32_t use_changed, + const int32_t *entry_revisions, int32_t *out, uint32_t cap, + cp_unit *text_out, uint32_t text_cap, uint32_t *text_len) { + int32_t line_count = editor->doc.line_count(); + int32_t first = std::clamp(first_line, 0, line_count - 1); + int32_t last = std::clamp(last_line, first, line_count - 1); + std::vector entries(static_cast(last - first + 1)); + for (int32_t line = first; line <= last; line++) { + bool requested = line >= first_line && line <= last_line; + entries[static_cast(line - first)] = requested ? entry_revisions[line - first_line] : CP_NO_ENTRY; + } + std::vector ints = frame_header(editor); + return build_frame(editor, snapshot, first, last, entries, applied_revision, use_changed, ints, out, cap, text_out, + text_cap, text_len); +} + +extern "C" uint32_t cp_editor_frame(const cp_editor *editor, const cp_layout *layout, const cp_snapshot *snapshot, + int32_t applied_revision, int32_t use_changed, const int32_t *entries, + uint32_t entry_count, int32_t *out, uint32_t cap, cp_unit *text_out, + uint32_t text_cap, uint32_t *text_len) { + const codepad::Layout &l = *layout->layout; + int32_t line_count = editor->doc.line_count(); + int32_t first = std::clamp(l.first_visible_line(), 0, line_count - 1); + int32_t last = std::clamp(first + l.config().height / l.config().row_height + 1, first, line_count - 1); + std::vector dense(static_cast(last - first + 1), CP_NO_ENTRY); + for (uint32_t i = 0; i < entry_count; i++) { + int32_t line = entries[2 * i]; + if (line >= first && line <= last) dense[static_cast(line - first)] = entries[2 * i + 1]; + } + std::vector ints = frame_header(editor); + ints.push_back(first); + ints.push_back(last); + return build_frame(editor, snapshot, first, last, dense, applied_revision, use_changed, ints, out, cap, text_out, + text_cap, text_len); +} + extern "C" uint32_t cp_shift_spans(const int32_t *spans, uint32_t count, int32_t start, int32_t removed, int32_t inserted, int32_t *out, uint32_t cap) { return deliver(codepad::shift_spans(spans, count, start, removed, inserted), out, cap); diff --git a/cpp/core/src/layout.hpp b/cpp/core/src/layout.hpp index 8bcba693..b3854bb8 100644 --- a/cpp/core/src/layout.hpp +++ b/cpp/core/src/layout.hpp @@ -28,6 +28,8 @@ class Layout { // Zero for a line outside the map. int32_t rows(int32_t line) const; int32_t gap_rows(int32_t line) const; + // The lines with a gap, ascending. + const std::vector &gap_lines() const { return gap_lines_; } int32_t row_start(int32_t line) const; int32_t line_at_row(int32_t row) const; bool is_gap_row(int32_t row) const; diff --git a/example/ios/CodepadTests/ContentSizeTests.swift b/example/ios/CodepadTests/ContentSizeTests.swift index 4e19f298..59572f58 100644 --- a/example/ios/CodepadTests/ContentSizeTests.swift +++ b/example/ios/CodepadTests/ContentSizeTests.swift @@ -62,6 +62,18 @@ final class ContentSizeTests: XCTestCase { XCTAssertEqual(sizes.last?.height ?? 0, 10 * row + 24, accuracy: 0.5) } + // UIScrollView owns the rubber band past the top. The layout clamps its own copy and leaves the offset alone. + func testBounceOffsetIsNotPushedBack() { + let editor = launch() + editor.setInitialText((0..<200).map { "line \($0)" }.joined(separator: "\n")) + layout(editor) + draw(editor) + editor.contentOffset = CGPoint(x: 0, y: -40) + draw(editor) + XCTAssertEqual(editor.contentOffset.y, -40) + XCTAssertEqual(editor.latestFrame.scrollY, 0) + } + // A note under the last line, as a checker would open after the final line of an exercise. func testGapRowsCountInTheContentHeight() { let editor = launch() diff --git a/example/ios/CodepadTests/SelectionGeometryTests.swift b/example/ios/CodepadTests/SelectionGeometryTests.swift index 64760198..8ba33402 100644 --- a/example/ios/CodepadTests/SelectionGeometryTests.swift +++ b/example/ios/CodepadTests/SelectionGeometryTests.swift @@ -85,6 +85,29 @@ extension SelectionGeometryTests { XCTAssertEqual(handles.map(\.isHidden), [true, true], "no handles on a collapsed selection") } + // A selection end in a wrapped line above the view gets its layout before the layers are placed. Measured after + // them, its extra rows would move the scroll under the placed layers and leave the bottom of the view empty. + func testHandleLineAboveTheViewIsMeasuredBeforeTheLayers() { + let editor = launch() + editor.setSoftWrap(true) + let long = String(repeating: "word ", count: 80) + editor.setInitialText(([long] + (0..<100).map { "line \($0)" }).joined(separator: "\n")) + editor.contentOffset = CGPoint(x: 0, y: 600) + layout(editor) + editor.focus() + editor.core.setSelection(anchor: 3, head: editor.core.document.lineStart(30)) + editor.layoutIfNeeded() + // A relayout drops every layout, so the next draw meets the anchor's line uncached. + editor.setTextPadding(12) + let before = editor.contentOffset.y + editor.layoutIfNeeded() + let layers = editor.textInput.textHost.sublayers?.compactMap { $0 as? LineLayer } ?? [] + let bottom = layers.map(\.frame.maxY).max() ?? 0 + XCTAssertGreaterThan(editor.contentOffset.y, before, "the wrapped line above grew in this draw") + XCTAssertGreaterThanOrEqual(bottom, editor.contentOffset.y + editor.bounds.height) + XCTAssertEqual(editor.latestFrame.scrollY, editor.contentOffset.y) + } + func testSystemLollipopsStayInvisible() { let editor = launch() editor.setContentInsets(top: 20, bottom: 0, left: 0, right: 0) diff --git a/ios/Codepad/core/EditorFrame.swift b/ios/Codepad/core/EditorFrame.swift index 9ffdc7c8..eeb62072 100644 --- a/ios/Codepad/core/EditorFrame.swift +++ b/ios/Codepad/core/EditorFrame.swift @@ -60,6 +60,21 @@ final class FrameReader { self.units = [UInt16](repeating: 0, count: max(units, 1)) } + /// The draw's frame: the layout picks the lines, `pairs` holds (line, revision) for each cached line. + func read( + core: EditorCore, layout: Viewport, snapshot: Snapshot?, applied: Int, useChanged: Bool, pairs: [Int32] + ) -> EditorFrame { + while true { + var textLength: UInt32 = 0 + let needed = callLayout(core, layout, snapshot, applied, useChanged, pairs, &textLength) + let fits = Int(needed) <= ints.count && Int(textLength) <= units.count + if fits { return decode(nil) } + if Int(needed) > ints.count { ints = [Int32](repeating: 0, count: Int(needed)) } + if Int(textLength) > units.count { units = [UInt16](repeating: 0, count: Int(textLength)) } + } + } + + /// A frame of lines [first, last], with one entry per line. func read( core: EditorCore, snapshot: Snapshot?, first: Int, last: Int, applied: Int, useChanged: Bool, entries: [Int32] ) -> EditorFrame { @@ -67,12 +82,38 @@ final class FrameReader { var textLength: UInt32 = 0 let needed = call(core, snapshot, first, last, applied, useChanged, entries, &textLength) let fits = Int(needed) <= ints.count && Int(textLength) <= units.count - if fits { return decode(first, last) } + if fits { return decode((first, last)) } if Int(needed) > ints.count { ints = [Int32](repeating: 0, count: Int(needed)) } if Int(textLength) > units.count { units = [UInt16](repeating: 0, count: Int(textLength)) } } } + private func callLayout( + _ core: EditorCore, _ layout: Viewport, _ snapshot: Snapshot?, _ applied: Int, _ useChanged: Bool, + _ pairs: [Int32], _ textLength: inout UInt32 + ) -> UInt32 { + let handle: OpaquePointer = core.document.handle + let layoutHandle: OpaquePointer = layout.handle + let snap: OpaquePointer? = snapshot?.pointer + let appliedRevision = Int32(clamping: applied) + let changed: Int32 = useChanged ? 1 : 0 + let pairCount = UInt32(pairs.count / 2) + var length: UInt32 = 0 + let needed: UInt32 = pairs.withUnsafeBufferPointer { p in + ints.withUnsafeMutableBufferPointer { o in + units.withUnsafeMutableBufferPointer { t in + let intCap = UInt32(o.count) + let textCap = UInt32(t.count) + return cp_editor_frame( + handle, layoutHandle, snap, appliedRevision, changed, p.baseAddress, pairCount, o.baseAddress, intCap, + t.baseAddress, textCap, &length) + } + } + } + textLength = length + return needed + } + private func call( _ core: EditorCore, _ snapshot: Snapshot?, _ first: Int, _ last: Int, _ applied: Int, _ useChanged: Bool, _ entries: [Int32], _ textLength: inout UInt32 @@ -89,7 +130,7 @@ final class FrameReader { units.withUnsafeMutableBufferPointer { t in let intCap = UInt32(o.count) let textCap = UInt32(t.count) - return cp_editor_frame( + return cp_editor_frame_range( handle, snap, firstLine, lastLine, appliedRevision, changed, e.baseAddress, o.baseAddress, intCap, t.baseAddress, textCap, &length) } @@ -99,7 +140,8 @@ final class FrameReader { return needed } - private func decode(_ first: Int, _ last: Int) -> EditorFrame { + /// `window` is the range a range call asked for. The layout's call writes its own after the header. + private func decode(_ window: (Int, Int)?) -> EditorFrame { var i = 0 func next() -> Int { let v = Int(ints[i]) @@ -114,6 +156,8 @@ final class FrameReader { let caretLine = next() let decorationsVersion = next() let history = next() + let first = window?.0 ?? next() + let last = window?.1 ?? next() let lo = min(max(first, 0), lineCount - 1) let hi = min(max(last, lo), lineCount - 1) var starts: [Int] = [] diff --git a/ios/Codepad/layout/LayoutCache.swift b/ios/Codepad/layout/LayoutCache.swift index 28a489d8..fed073c9 100644 --- a/ios/Codepad/layout/LayoutCache.swift +++ b/ios/Codepad/layout/LayoutCache.swift @@ -27,6 +27,11 @@ final class LayoutCache { trim() } + /// Every entry in no particular order. The eviction order stays as it is. + func forEachEntry(_ body: (Int, T) -> Void) { + for (line, value) in map { body(line, value) } + } + func clear() { map.removeAll() order.removeAll() diff --git a/ios/Codepad/layout/Viewport.swift b/ios/Codepad/layout/Viewport.swift index ed6b78a3..38826a80 100644 --- a/ios/Codepad/layout/Viewport.swift +++ b/ios/Codepad/layout/Viewport.swift @@ -6,19 +6,41 @@ import Foundation #endif /// Scroll position, rows per line and the mapping between rows and view points, held by the core's layout. -/// Attached to the view's editor, so edits and gaps update the rows inside the core. Each member is one core call. +/// Attached to the view's editor, so edits and gaps update the rows inside the core. Outside a draw each member is +/// one core call. Inside one, the members read the copy the draw's scroll and measure calls returned. final class Viewport { struct Anchor { let line: Int let offset: Int } + /// A gap under a line: the view y where it starts and its height in rows. + struct Gap: Equatable { + let line: Int + let top: Int + let rows: Int + } + + /// Core calls a draw may make besides its scroll and measure calls. Debug builds trap past it. + static let drawCallLimit = 8 + let handle: OpaquePointer private var config = cp_layout_config( row_height: 1, width: 0, height: 0, inset_top: 0, inset_bottom: 0, inset_left: 0, inset_right: 0, gutter_width: 0, text_padding: 0, wrap: 0) private weak var attached: EditorCore? + // The draw's copy. known holds the geometry while cached, buffer the measure call's output for first...last. + private var drawing = false + private var cached = false + private var known = cp_geometry() + private var first = 0 + private var last = -1 + private var buffer = [Int32](repeating: 0, count: 256) + private var needed = 0 + /// Core calls this draw made besides its scroll and measure calls. + private(set) var drawCalls = 0 + init() { handle = cp_layout_new()! } @@ -30,6 +52,7 @@ final class Viewport { /// Takes the editor's lines, one row each, and its gaps. The size, insets and metrics stay. func attach(_ core: EditorCore) { + changing() if let old = attached, old !== core { cp_editor_attach_layout(old.document.handle, nil) } attached = core cp_editor_attach_layout(core.document.handle, handle) @@ -71,7 +94,10 @@ final class Viewport { } var widestLine: Int { get { Int(geometry().widest_line) } - set { cp_layout_set_widest(handle, Int32(clamping: newValue)) } + set { + changing() + cp_layout_set_widest(handle, Int32(clamping: newValue)) + } } var scrollX: Int { Int(geometry().scroll_x) } @@ -93,16 +119,48 @@ final class Viewport { maxScrollX > 0 && abs(dx) > abs(dy) } + /// Starts a draw with the scroll view's offset, clamped. True when the position moved. + @discardableResult + func beginDraw(scrollX x: Int, scrollY y: Int) -> Bool { + drawing = true + drawCalls = 0 + last = first - 1 + let moved = cp_layout_scroll_to(handle, Int32(clamping: x), Int32(clamping: y), &known) != 0 + cached = true + return moved + } + + /// The draw's measure call: the rows laid out in this draw and the widest line, then the tops and rows of + /// first...last and every gap. True when a measured line above the view moved the scroll. + @discardableResult + func measure(pairs: [Int32], widest: Int, first: Int, last: Int) -> Bool { + let before = scrollY + self.first = first + self.last = last + fill(pairs, widest: widest) + return known.scroll_y != Int32(clamping: before) + } + + func endDraw() { + drawing = false + cached = false + last = first - 1 + } + /// Clamps and applies. Returns true when the position moved. @discardableResult func scrollTo(_ x: Int, _ y: Int) -> Bool { - cp_layout_scroll_to(handle, Int32(clamping: x), Int32(clamping: y), nil) != 0 + crossed() + var g = cp_geometry() + let moved = cp_layout_scroll_to(handle, Int32(clamping: x), Int32(clamping: y), &g) != 0 + moving(g, moved) + return moved } @discardableResult func clamp() -> Bool { let g = geometry() - return cp_layout_scroll_to(handle, g.scroll_x, g.scroll_y, nil) != 0 + return scrollTo(Int(g.scroll_x), Int(g.scroll_y)) } /// Stores a view size. True when the text area width changed, which is when layouts must be rebuilt. @@ -123,16 +181,64 @@ final class Viewport { return configure() } - func rowStart(_ line: Int) -> Int { Int(cp_layout_row_start(handle, Int32(clamping: line))) } - func rows(_ line: Int) -> Int { Int(cp_layout_rows(handle, Int32(clamping: line))) } - func gapRows(_ line: Int) -> Int { Int(cp_layout_gap_rows(handle, Int32(clamping: line))) } - func lineAtRow(_ row: Int) -> Int { Int(cp_layout_line_at_row(handle, Int32(clamping: row))) } + func rowStart(_ line: Int) -> Int { + if let top = drawnTop(line) { return (top - insetTop + Int(known.scroll_y)) / rowHeight } + crossed() + return Int(cp_layout_row_start(handle, Int32(clamping: line))) + } + + func rows(_ line: Int) -> Int { + if cached, line >= first, line <= last { return Int(buffer[last - first + 2 + line - first]) } + crossed() + return Int(cp_layout_rows(handle, Int32(clamping: line))) + } + + func gapRows(_ line: Int) -> Int { + crossed() + return Int(cp_layout_gap_rows(handle, Int32(clamping: line))) + } + + func lineAtRow(_ row: Int) -> Int { + crossed() + return Int(cp_layout_line_at_row(handle, Int32(clamping: row))) + } + /// True when `row` is empty space under a line rather than one of its text rows. - func isGapRow(_ row: Int) -> Bool { cp_layout_is_gap_row(handle, Int32(clamping: row)) != 0 } - func rowTop(_ row: Int) -> Int { Int(cp_layout_row_top(handle, Int32(clamping: row))) } - func lineTop(_ line: Int) -> Int { Int(cp_layout_line_top(handle, Int32(clamping: line))) } + func isGapRow(_ row: Int) -> Bool { + crossed() + return cp_layout_is_gap_row(handle, Int32(clamping: row)) != 0 + } + + func rowTop(_ row: Int) -> Int { + if cached { return insetTop + row * rowHeight - Int(known.scroll_y) } + crossed() + return Int(cp_layout_row_top(handle, Int32(clamping: row))) + } + + func lineTop(_ line: Int) -> Int { + if let top = drawnTop(line) { return top } + crossed() + return Int(cp_layout_line_top(handle, Int32(clamping: line))) + } + /// Content row under view y, possibly outside [0, totalRows). - func rowAt(_ y: Int) -> Int { Int(cp_layout_row_at(handle, Int32(clamping: y))) } + func rowAt(_ y: Int) -> Int { + crossed() + return Int(cp_layout_row_at(handle, Int32(clamping: y))) + } + + /// Every gap in line order. + func gaps() -> [Gap] { + if !cached || last < first { + crossed() + var none: [Int32] = [] + let count = Int(cp_layout_measure(handle, &none, 0, -1, 0, 0, nil, nil, 0)) + var out = [Int32](repeating: 0, count: count) + cp_layout_measure(handle, &none, 0, -1, 0, 0, nil, &out, UInt32(count)) + return Viewport.parseGaps(out, from: 3) + } + return Viewport.parseGaps(buffer[0.. CGFloat { x - CGFloat(geometry().text_left) } @@ -147,12 +253,18 @@ final class Viewport { /// Smallest scroll that shows a rect in layout coordinates (x from the text start, y from row 0) with the text padding around it. @discardableResult func reveal(left: Int, top: Int, right: Int, bottom: Int) -> Bool { - cp_layout_reveal( - handle, Int32(clamping: left), Int32(clamping: top), Int32(clamping: right), Int32(clamping: bottom), nil) != 0 + crossed() + var g = cp_geometry() + let moved = + cp_layout_reveal( + handle, Int32(clamping: left), Int32(clamping: top), Int32(clamping: right), Int32(clamping: bottom), &g) != 0 + moving(g, moved) + return moved } /// Remembers the top visible line so a width or font change can put it back. func anchor() -> Anchor { + crossed() var line: Int32 = 0 var offset: Int32 = 0 cp_layout_anchor(handle, &line, &offset) @@ -160,28 +272,98 @@ final class Viewport { } func restore(_ anchor: Anchor) { + changing() cp_layout_restore(handle, Int32(clamping: anchor.line), Int32(clamping: anchor.offset)) } - /// Records a measurement. A line above the viewport shifts the scroll so the visible text stays put. - func measured(_ line: Int, _ rows: Int) { - var pair: [Int32] = [Int32(clamping: line), Int32(clamping: rows)] - cp_layout_measure(handle, &pair, 1, -1, 0, -1, nil, nil, 0) + /// Records a measurement and raises the widest line to `widest` when not wrapping. A line above the viewport + /// shifts the scroll so the visible text stays put. + func measured(_ line: Int, _ rows: Int, widest: Int = -1) { + crossed() + let pair: [Int32] = [Int32(clamping: line), Int32(clamping: rows)] + if drawing { + fill(pair, widest: widest) + } else { + var p = pair + cp_layout_measure(handle, &p, 1, Int32(clamping: widest), 0, -1, nil, nil, 0) + } } /// Every line back to one row. Gaps stay. func resetRows() { + changing() cp_layout_reset_rows(handle) } + /// One measure call that refreshes the draw's copy, grown and repeated when the buffer is short. Applying the + /// same rows and widest line again changes nothing. + private func fill(_ pairs: [Int32], widest: Int) { + var p = pairs + let pairCount = UInt32(pairs.count / 2) + let wide = Int32(clamping: widest) + let lo = Int32(clamping: first) + let hi = Int32(clamping: last) + var n = Int(cp_layout_measure(handle, &p, pairCount, wide, lo, hi, &known, &buffer, UInt32(buffer.count))) + if n > buffer.count { + crossed() + buffer = [Int32](repeating: 0, count: n) + n = Int(cp_layout_measure(handle, &p, pairCount, wide, lo, hi, &known, &buffer, UInt32(buffer.count))) + } + needed = n + cached = true + } + + private func drawnTop(_ line: Int) -> Int? { + cached && line >= first && line <= last + 1 ? Int(buffer[line - first]) : nil + } + + private static func parseGaps(_ ints: ArraySlice, from start: Int) -> [Gap] { + var out: [Gap] = [] + var i = ints.startIndex + start + while i + 2 < ints.endIndex { + out.append(Gap(line: Int(ints[i]), top: Int(ints[i + 1]), rows: Int(ints[i + 2]))) + i += 3 + } + return out + } + + private static func parseGaps(_ ints: [Int32], from start: Int) -> [Gap] { parseGaps(ints[...], from: start) } + private func geometry() -> cp_geometry { + if cached { return known } + crossed() var g = cp_geometry() cp_layout_geometry(handle, &g) return g } + /// A scroll inside a draw refreshes the geometry. Tops taken before a move are stale. + private func moving(_ g: cp_geometry, _ moved: Bool) { + guard drawing else { return } + known = g + cached = true + if moved { last = first - 1 } + } + + /// A size, metric or row change has no place inside a draw: the copy would go stale. + private func changing() { + guard drawing else { return } + assertionFailure("layout changed inside a draw") + cached = false + last = first - 1 + } + + private func crossed() { + guard drawing else { return } + drawCalls += 1 + #if DEBUG + if drawCalls > Viewport.drawCallLimit { assertionFailure("\(drawCalls) layout calls in one draw") } + #endif + } + @discardableResult private func configure() -> Bool { + changing() var c = config return cp_layout_configure(handle, &c) != 0 } diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index 3fdf734a..489bdcbf 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -647,23 +647,27 @@ final class CodeEditorView: UIScrollView { let w = Int(bounds.width.rounded()) let h = Int(bounds.height.rounded()) if w != viewport.width || h != viewport.height { sizeChanged(w, h) } - if viewport.scrollTo(Int(contentOffset.x.rounded()), Int(contentOffset.y.rounded())) { scrollDirty = true } - let scrolled = scrollDirty - if w == 0 || h == 0 { return } let m = rowMetrics() + // The layout's three calls of a draw: this scroll, the frame, then the measure call in prepare. Until endDraw, + // the layout reads come from them. + if viewport.beginDraw(scrollX: Int(contentOffset.x.rounded()), scrollY: Int(contentOffset.y.rounded())) { + scrollDirty = true + } + let scrolled = scrollDirty + if w == 0 || h == 0 { + viewport.endDraw() + return + } if revealPending { revealPending = false revealSelection() } - let first = viewport.firstVisibleLine() - let lastBound = min(viewport.lineCount - 1, first + h / m.rowHeight + 1) - let scrollBefore = viewport.scrollY - // One core call for the whole draw. Until publish returns, every read comes from it. - let frame = readFrame(first, lastBound) + let frame = readFrame() drawFrame = frame core.document.drawing = true - prepare(frame, m) - if viewport.scrollY != scrollBefore { pushScroll() } else { updateContentSize() } + let first = frame.first + let lastBound = frame.last + if prepare(frame, m) { pushScroll() } else { updateContentSize() } let caretLine = frame.caretLine let lastLine = placeLayers(first, lastBound, m) placeGutter(first, lastLine, caretLine) @@ -672,6 +676,7 @@ final class CodeEditorView: UIScrollView { placeHandles() placePlaceholder(frame, m) publish(first, lastLine, caretLine, m) + viewport.endDraw() core.document.drawing = false drawFrame = nil if scrollDirty { @@ -867,16 +872,18 @@ final class CodeEditorView: UIScrollView { return m } - /// The draw's frame: the lines in the window and whether each needs a layout, its spans and text. - private func readFrame(_ first: Int, _ last: Int) -> EditorFrame { + /// The draw's frame: the layout picks the lines, the frame says which need a layout and brings their spans and text. + private func readFrame() -> EditorFrame { let usable = highlighter != nil ? snapshot : nil - var entries: [Int32] = [] - entries.reserveCapacity(last - first + 1) - for line in first...last { entries.append(cache[line].map { Int32($0.revision) } ?? Int32(CP_NO_ENTRY)) } + var pairs: [Int32] = [] + pairs.reserveCapacity(2 * cache.size) + cache.forEachEntry { line, entry in + pairs.append(Int32(clamping: line)) + pairs.append(Int32(clamping: entry.revision)) + } let incremental = usable.map { $0.basedOn >= 0 && $0.basedOn == appliedRevision } ?? false return frameReader.read( - core: core, snapshot: usable, first: first, last: last, applied: appliedRevision, useChanged: incremental, - entries: entries) + core: core, layout: viewport, snapshot: usable, applied: appliedRevision, useChanged: incremental, pairs: pairs) } // Line reads for the geometry and UIKit: from the frame while a draw runs, else one core call. Neither goes @@ -911,19 +918,25 @@ final class CodeEditorView: UIScrollView { /// Lays out one line plain, for hit tests and reveals on lines outside the drawn range. @discardableResult private func layoutLine(_ line: Int) -> Entry { + let entry = plainEntry(line) + let scrollBefore = viewport.scrollY + viewport.measured(line, entry.layout.rowCount, widest: offeredWidth(entry.layout)) + if viewport.scrollY != scrollBefore { pushScroll() } else { updateContentSize() } + return entry + } + + /// A plain layout put in the cache and not yet measured. + private func plainEntry(_ line: Int) -> Entry { let spans = keptSpans(line, revision: drawFrame?.revision) let text = drawFrame?.text(line) ?? core.document.lineOutsideFrame(line) let entry = Entry(id: takeEntryId(), layout: makeLayout(text, spans: spans, rowMetrics()), spans: spans, revision: -1) cache.put(line, entry) - let scrollBefore = viewport.scrollY - measured(line, entry.layout) - if viewport.scrollY != scrollBefore { pushScroll() } else { updateContentSize() } return entry } - private func measured(_ line: Int, _ layout: LineLayout) { - viewport.measured(line, layout.rowCount) - if !viewport.wrap { viewport.widestLine = max(viewport.widestLine, Int(layout.width().rounded())) } + /// The width a layout offers as the widest line, or -1 while wrapping. + private func offeredWidth(_ layout: LineLayout) -> Int { + viewport.wrap ? -1 : Int(layout.width().rounded()) } private func onScrolled() { @@ -978,14 +991,22 @@ final class CodeEditorView: UIScrollView { } } - /// Builds missing layouts for [first, last] with one highlight query per run of dirty lines: when the snapshot follows - /// the one last applied, only the lines its regions meet; otherwise every line not at its revision. - private func prepare(_ frame: EditorFrame, _ m: RowMetrics) { + /// Builds missing layouts for [first, last] with one highlight query per run of dirty lines: the lines the snapshot's + /// regions meet when it follows the one last applied, else every line not at its revision. Ends with the draw's + /// measure call and returns true when it moved the scroll. + private func prepare(_ frame: EditorFrame, _ m: RowMetrics) -> Bool { // The core paints from the snapshot only when it is at the frame's revision. Otherwise its runs are the lines // with no layout, and those take the spans keepSpans kept. let consistent = highlighter != nil && snapshot?.revision == frame.revision let revision = consistent ? frame.revision : -1 let runs = frame.runs + var pairs: [Int32] = [] + var widest = -1 + func measured(_ line: Int, _ layout: LineLayout) { + pairs.append(Int32(clamping: line)) + pairs.append(Int32(clamping: layout.rowCount)) + widest = max(widest, offeredWidth(layout)) + } var r = 0 // The spans and text of the run lines arrive in line order, one entry per line. var next = 0 @@ -1019,6 +1040,15 @@ final class CodeEditorView: UIScrollView { pendingSpans = nil pendingTail = nil } + // The handles' lines too, so placeHandles finds their layouts without a measurement inside the draw. + let sel = core.selection + if hasFocus && !sel.isEmpty { + for offset in [sel.min, sel.max] { + let line = docLineAt(offset) + if cache[line] == nil { measured(line, plainEntry(line).layout) } + } + } + return viewport.measure(pairs: pairs, widest: widest, first: frame.first, last: frame.last) } /// The spans keepSpans kept for a line of the current revision, or nil. @@ -1286,15 +1316,10 @@ final class CodeEditorView: UIScrollView { /// Every gap in view points, sorted by line, the full view width wide. private func gapRects(_ m: RowMetrics) -> [GapRect] { - let rows = core.decorations.gapRows() - if rows.isEmpty { return [] } - var out: [GapRect] = [] - for line in rows.keys.sorted() { - let top = CGFloat(viewport.rowTop(viewport.rowStart(line) + viewport.rows(line))) - let height = CGFloat((rows[line] ?? 0) * m.rowHeight) - out.append(GapRect(line: line, rect: CGRect(x: 0, y: top, width: bounds.width, height: height))) + viewport.gaps().map { gap in + let rect = CGRect(x: 0, y: CGFloat(gap.top), width: bounds.width, height: CGFloat(gap.rows * m.rowHeight)) + return GapRect(line: gap.line, rect: rect) } - return out } private func publish(_ first: Int, _ last: Int, _ caretLine: Int, _ m: RowMetrics) { diff --git a/tests/swift/CoreLayoutTests.swift b/tests/swift/CoreLayoutTests.swift index a5b5d225..db52c848 100644 --- a/tests/swift/CoreLayoutTests.swift +++ b/tests/swift/CoreLayoutTests.swift @@ -1,3 +1,4 @@ +import CodepadCore import XCTest @testable import Codepad @@ -33,4 +34,77 @@ final class CoreLayoutTests: XCTestCase { first.replace(0, 0, "x\n") XCTAssertEqual(viewport.lineCount, 5, "the old editor no longer reaches the layout") } + + // A draw retries the measure call with a grown buffer. The short call must leave the buffer alone, and the + // retry must not apply the measurement twice. + func testMeasureWritesNothingIntoAShortBuffer() { + let core = EditorCore((0..<20).map { _ in "x" }.joined(separator: "\n")) + let viewport = Viewport() + viewport.attach(core) + viewport.rowHeight = 10 + viewport.resize(width: 100, height: 50) + viewport.scrollTo(0, 50) + var pairs: [Int32] = [2, 3] + var short = [Int32](repeating: -7, count: 4) + let needed = cp_layout_measure(viewport.handle, &pairs, 1, -1, 5, 9, nil, &short, UInt32(short.count)) + XCTAssertEqual(needed, 11) + XCTAssertEqual(short, [-7, -7, -7, -7]) + var out = [Int32](repeating: 0, count: Int(needed)) + cp_layout_measure(viewport.handle, &pairs, 1, -1, 5, 9, nil, &out, UInt32(out.count)) + XCTAssertEqual(viewport.scrollY, 70, "one shift of two rows for the line above") + XCTAssertEqual(Array(out[0...5]), [0, 10, 20, 30, 40, 50]) + XCTAssertEqual(Array(out[6...10]), [1, 1, 1, 1, 1]) + } + + // onGapLayout publishes every gap on each draw, the ones off screen too, so the measure call carries them all. + func testMeasureWritesEveryGapAfterTheRows() { + let core = EditorCore((0..<20).map { _ in "x" }.joined(separator: "\n")) + XCTAssertTrue(core.setDecorations([.gap(line: 1, rows: 2), .gap(line: 15, rows: 1)], revision: -1)) + let viewport = Viewport() + viewport.attach(core) + viewport.rowHeight = 10 + viewport.resize(width: 100, height: 50) + viewport.scrollTo(0, 50) + var none: [Int32] = [] + var out = [Int32](repeating: 0, count: 32) + let needed = cp_layout_measure(viewport.handle, &none, 0, -1, 5, 6, nil, &out, UInt32(out.count)) + XCTAssertEqual(needed, 2 * 2 + 1 + 2 * 3) + XCTAssertEqual(Array(out[0...2]), [20, 30, 40]) + XCTAssertEqual(Array(out[3...4]), [1, 1]) + XCTAssertEqual(Array(out[5...10]), [1, -30, 2, 15, 130, 1]) + } + + // Between measure and endDraw the painters read the draw's copy. A copy that drifts from the core puts a line, + // the gutter or a gap at the wrong height, and a read that still crosses into the core costs a call per line. + func testDrawReadsMatchTheCoreWithoutCalls() { + let core = EditorCore((0..<60).map { "line \($0)" }.joined(separator: "\n")) + XCTAssertTrue(core.setDecorations([.gap(line: 2, rows: 2), .gap(line: 21, rows: 1), .gap(line: 50, rows: 3)], revision: -1)) + let viewport = Viewport() + viewport.attach(core) + viewport.rowHeight = 10 + viewport.resize(width: 100, height: 60) + viewport.setInsets(top: 7, bottom: 5, left: 3, right: 0) + viewport.gutterWidth = 20 + viewport.beginDraw(scrollX: 0, scrollY: 205) + let first = viewport.firstVisibleLine() + let last = first + 60 / 10 + 1 + let moved = viewport.measure(pairs: [Int32(first - 3), 2, Int32(first + 1), 3], widest: 400, first: first, last: last) + XCTAssertTrue(moved, "a line above the view grew") + func reads() -> [Int] { + var out = [ + viewport.scrollX, viewport.scrollY, viewport.maxScrollY, viewport.contentWidth, viewport.contentHeight, + viewport.textAreaLeft, viewport.textAreaWidth, viewport.wrapWidth, viewport.firstVisibleLine(), + viewport.lastVisibleLine(), viewport.widestLine, Int(viewport.viewX(0)), viewport.rowTop(30), + ] + for line in first...(last + 1) { out += [viewport.lineTop(line), viewport.rowStart(line)] } + for line in first...last { out.append(viewport.rows(line)) } + for gap in viewport.gaps() { out += [gap.line, gap.top, gap.rows] } + return out + } + let drawn = reads() + XCTAssertEqual(viewport.drawCalls, 0) + viewport.endDraw() + XCTAssertEqual(drawn, reads()) + XCTAssertEqual(viewport.gaps().map(\.line), [2, 21, 50]) + } } diff --git a/tests/swift/FrameTests.swift b/tests/swift/FrameTests.swift index a79d2049..15d25896 100644 --- a/tests/swift/FrameTests.swift +++ b/tests/swift/FrameTests.swift @@ -84,6 +84,62 @@ final class FrameTests: XCTestCase { } } + // The draw hands the cache to the layout's frame call as (line, revision) pairs and lets the layout pick the + // window. Read densely over that window, the frame must paint the same lines with the same spans and text. + func testSparseEntriesMatchDenseEntries() throws { + var rng = SplitMix(state: 11) + let block = ["function f(a, b) {", " const s = `x${a}`; // c", " return a + b * 2;", "}", "let re = /ab+c/g;", ""] + let text = (0..<10_000).map { block[$0 % block.count] }.joined(separator: "\n") + let core = EditorCore(text) + let snapshots = SnapshotQueue() + let engine = SyntaxEngine(postToMain: { $0() }, onSnapshot: { snapshots.add($0) }) + defer { engine.close() } + engine.setLanguage("javascript") + engine.attach(core) + let viewport = Viewport() + viewport.attach(core) + viewport.rowHeight = 1 + viewport.resize(width: 100, height: 29) + let reader = FrameReader(ints: 4, units: 4) + let inserts = ["", "x", "\n", "/*", "\"", "ab\ncd", "}"] + for step in 0..<500 { + let doc = core.document + let at = Int.random(in: 0...doc.length, using: &rng) + core.replace(at, min(doc.length, at + Int.random(in: 0...3, using: &rng)), inserts.randomElement(using: &rng)!) + viewport.scrollTo(0, Int.random(in: 0..(capacity: 8) + for i in 0..<8 { c.put(i, "l\(i)") } + _ = c[0] + var seen: [Int: String] = [:] + c.forEachEntry { line, value in seen[line] = value } + XCTAssertEqual(seen, Dictionary(uniqueKeysWithValues: (0..<8).map { ($0, "l\($0)") })) + c.put(8, "l8") + c.put(9, "l9") + XCTAssertNil(c[1]) + XCTAssertNil(c[2]) + XCTAssertEqual(c[0], "l0") + XCTAssertEqual(c[3], "l3") + } + func testCapacityChangeTrims() { let c = LayoutCache(capacity: 4) for i in 0..<4 { c.put(i, "x") } From 6146e737d9e5b4c715f56c853b48fd071ac95a3f Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 14:03:37 +0100 Subject: [PATCH 06/21] fix(ios): skip underlines that start below the window in a draw Each one cost a layout call to find out it was off screen, so a file with many diagnostics below the view went past the draw's call budget. --- .../ios/CodepadTests/DecorationPaintTests.swift | 17 +++++++++++++++++ ios/Codepad/view/CodeEditorView.swift | 5 ++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/example/ios/CodepadTests/DecorationPaintTests.swift b/example/ios/CodepadTests/DecorationPaintTests.swift index 8025554d..d19b0f48 100644 --- a/example/ios/CodepadTests/DecorationPaintTests.swift +++ b/example/ios/CodepadTests/DecorationPaintTests.swift @@ -27,6 +27,23 @@ final class DecorationPaintTests: XCTestCase { searchMatchActive: d.searchMatchActive, tokens: [:]) } + // A checker underlines lines all over a file. Each one below the window cost a layout call per draw, and nine of + // them trapped Debug builds. + func testUnderlinesBelowTheWindowCostNoLayoutCall() { + let editor = launch() + editor.setInitialText((0..<200).map { "line \($0)" }.joined(separator: "\n")) + layout(editor) + draw(editor) + let doc = editor.core.document + let items = (100..<106).map { line in + Decoration.underline( + Underline(start: doc.lineStart(line), end: doc.lineStart(line) + 4, color: red, style: .solid, thickness: 2, offset: 4)) + } + editor.setDecorations(items, revision: -1) + draw(editor) + XCTAssertEqual(editor.viewport.drawCalls, 0) + } + func testSolidUnderlineSitsOffsetBelowTheBaseline() { let editor = launch() editor.setLineNumbers(false) diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index 489bdcbf..31e0b74c 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -108,7 +108,7 @@ final class CodeEditorView: UIScrollView { private let frameReader = FrameReader() // Set from the frame call to the end of publish. private var drawFrame: EditorFrame? - private let viewport = Viewport() + let viewport = Viewport() private let cache = LayoutCache(capacity: 64) private var nextEntryId = 0 private var brackets: BracketHighlight @@ -1207,6 +1207,8 @@ final class CodeEditorView: UIScrollView { return } let scale = displayScale() + // An underline starting below the window would cost a layout call to find that out. + let windowEnd = docLineStart(lastLine) + docLineLength(lastLine) var backgrounds = DecorationLayers.Batch() var underlines = DecorationLayers.Batch() for item in items { @@ -1218,6 +1220,7 @@ final class CodeEditorView: UIScrollView { height: CGFloat(viewport.rows(line) * m.rowHeight)) backgrounds.path(DecorationLayers.Paint(color: color, width: 0)).addRect(rect) case .underline(let u): + if u.start > windowEnd { continue } let thickness = CGFloat(u.thickness) RangeRects.forEach(geometry, start: u.start, end: u.end, firstLine: first, padNewline: false) { left, top, right, _ in let lineTop = top + m.ascent + CGFloat(u.offset) From ad04797de5a582df3d1b6371b1d2a126df2fd2e8 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 14:22:22 +0100 Subject: [PATCH 07/21] perf(android): run the viewport on the core with two calls per draw The Kotlin Viewport is now a facade over the core's layout, like the Swift one, and HeightMap is gone. A draw makes the frame call and one measure call, and the painters read the copy it returns. A fling frame makes one scroll call, which now reports each axis that moved, so the edge glow needs no second read. Line backgrounds and underlines below the window are skipped, and the debug switch throws past eight other layout calls in one draw. The dense frame read survives only as a test hook. --- android/src/main/cpp/core_jni.cpp | 115 ++++- .../me/sectiontn/codepad/core/EditorCore.kt | 3 + .../me/sectiontn/codepad/core/EditorFrame.kt | 25 +- .../me/sectiontn/codepad/layout/HeightMap.kt | 119 ----- .../sectiontn/codepad/layout/LayoutCache.kt | 5 + .../me/sectiontn/codepad/layout/Viewport.kt | 466 +++++++++++++++--- .../me/sectiontn/codepad/syntax/CoreNative.kt | 27 +- .../sectiontn/codepad/view/CodeEditorView.kt | 150 +++--- .../codepad/view/DecorationPainter.kt | 19 +- .../sectiontn/codepad/view/EditorPainter.kt | 2 +- .../sectiontn/codepad/core/EditorFrameTest.kt | 16 +- .../me/sectiontn/codepad/core/VectorRunner.kt | 51 +- .../sectiontn/codepad/layout/HeightMapTest.kt | 111 ----- .../codepad/layout/LayoutCacheTest.kt | 18 + .../sectiontn/codepad/layout/ViewportTest.kt | 210 +++----- cpp/core/include/codepad.h | 14 +- cpp/core/src/capi_layout.cpp | 9 +- cpp/core/src/frame.cpp | 34 +- .../java/codepad/example/ContentSizeTest.kt | 28 ++ .../codepad/example/DecorationPaintTest.kt | 20 + .../codepad/example/InputConnectionTest.kt | 21 + ios/Codepad/core/EditorFrame.swift | 80 +-- tests/swift/CoreLayoutTests.swift | 14 + tests/swift/FrameTests.swift | 20 + 24 files changed, 901 insertions(+), 676 deletions(-) delete mode 100644 android/src/main/java/me/sectiontn/codepad/layout/HeightMap.kt delete mode 100644 android/src/test/java/me/sectiontn/codepad/layout/HeightMapTest.kt diff --git a/android/src/main/cpp/core_jni.cpp b/android/src/main/cpp/core_jni.cpp index 27217af6..a6a5f6c6 100644 --- a/android/src/main/cpp/core_jni.cpp +++ b/android/src/main/cpp/core_jni.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -554,24 +555,118 @@ FN(searchFind)(JNIEnv *e, jclass, jlong search, jlong text, jintArray scan, jint return n; } -// Main thread, once per draw. No Kotlin runs inside, so both outputs stay critical. text_len[0] gets the units needed. -FN(editorFrame)(JNIEnv *e, jclass, jlong editor, jlong snapshot, jint first, jint last, jint applied, - jboolean use_changed, jintArray entries, jintArray out, jcharArray text, jintArray text_len) -> jint { - jsize n = e->GetArrayLength(entries); - std::vector revisions(static_cast(n)); - if (n > 0) e->GetIntArrayRegion(entries, 0, n, reinterpret_cast(revisions.data())); +// Main thread, once per draw. No Kotlin runs inside, so the arrays stay critical. The first pair_count (line, +// revision) pairs of pairs are read. text_len[0] gets the units needed. +FN(editorFrame)(JNIEnv *e, jclass, jlong editor, jlong layout, jlong snapshot, jint applied, jboolean use_changed, + jintArray pairs, jint pair_count, jintArray out, jcharArray text, jintArray text_len) -> jint { + auto count = static_cast(std::max(0, std::min(pair_count, e->GetArrayLength(pairs) / 2))); jsize cap = e->GetArrayLength(out); jsize text_cap = e->GetArrayLength(text); uint32_t units = 0; + auto *p = static_cast(e->GetPrimitiveArrayCritical(pairs, nullptr)); auto *o = static_cast(e->GetPrimitiveArrayCritical(out, nullptr)); auto *t = static_cast(e->GetPrimitiveArrayCritical(text, nullptr)); - uint32_t needed = cp_editor_frame_range(ed(editor), ptr(snapshot), first, last, applied, - use_changed ? 1 : 0, revisions.data(), reinterpret_cast(o), - static_cast(cap), reinterpret_cast(t), - static_cast(text_cap), &units); + uint32_t needed = cp_editor_frame(ed(editor), ptr(layout), ptr(snapshot), applied, + use_changed ? 1 : 0, reinterpret_cast(p), count, + reinterpret_cast(o), static_cast(cap), + reinterpret_cast(t), static_cast(text_cap), &units); e->ReleasePrimitiveArrayCritical(text, t, 0); e->ReleasePrimitiveArrayCritical(out, o, 0); + e->ReleasePrimitiveArrayCritical(pairs, p, JNI_ABORT); auto length = static_cast(units); e->SetIntArrayRegion(text_len, 0, 1, &length); return static_cast(needed); } + +// The layout. Main thread only. Geometry crosses as the 17 ints of cp_geometry, in its field order. +static_assert(sizeof(cp_geometry) == 17 * sizeof(int32_t), "cp_geometry is 17 packed ints"); +static_assert(sizeof(cp_layout_config) == 10 * sizeof(int32_t), "cp_layout_config is 10 packed ints"); + +namespace { + +cp_layout *lay(jlong v) { return ptr(v); } + +void put(JNIEnv *e, jintArray out, const cp_geometry &g) { + if (out != nullptr) e->SetIntArrayRegion(out, 0, 17, reinterpret_cast(&g)); +} + +} // namespace + +FN(layoutNew)(JNIEnv *, jclass) -> jlong { return reinterpret_cast(cp_layout_new()); } +FN(layoutFree)(JNIEnv *, jclass, jlong layout) -> void { cp_layout_free(lay(layout)); } + +FN(editorAttachLayout)(JNIEnv *, jclass, jlong editor, jlong layout) -> void { + cp_editor_attach_layout(ed(editor), layout != 0 ? lay(layout) : nullptr); +} + +FN(layoutConfigure)(JNIEnv *e, jclass, jlong layout, jintArray config) -> jboolean { + cp_layout_config c; + e->GetIntArrayRegion(config, 0, 10, reinterpret_cast(&c)); + return cp_layout_configure(lay(layout), &c) != 0; +} + +FN(layoutGeometry)(JNIEnv *e, jclass, jlong layout, jintArray out) -> void { + cp_geometry g; + cp_layout_geometry(lay(layout), &g); + put(e, out, g); +} + +FN(layoutScrollTo)(JNIEnv *e, jclass, jlong layout, jint x, jint y, jintArray out) -> jint { + cp_geometry g; + int32_t axes = cp_layout_scroll_to(lay(layout), x, y, &g); + put(e, out, g); + return axes; +} + +FN(layoutReveal)(JNIEnv *e, jclass, jlong layout, jint left, jint top, jint right, jint bottom, jintArray out) + -> jboolean { + cp_geometry g; + int32_t moved = cp_layout_reveal(lay(layout), left, top, right, bottom, &g); + put(e, out, g); + return moved != 0; +} + +// The draw's measure call. The first pair_count (line, rows) pairs of pairs are applied. tops_rows may be short, then +// it gets nothing and the return says how many ints it needs. +FN(layoutMeasure)(JNIEnv *e, jclass, jlong layout, jintArray pairs, jint pair_count, jint widest, jint first, + jint last, jintArray geometry, jintArray tops_rows) -> jint { + auto count = static_cast(std::max(0, std::min(pair_count, e->GetArrayLength(pairs) / 2))); + jsize cap = e->GetArrayLength(tops_rows); + cp_geometry g; + auto *p = static_cast(e->GetPrimitiveArrayCritical(pairs, nullptr)); + auto *o = static_cast(e->GetPrimitiveArrayCritical(tops_rows, nullptr)); + uint32_t needed = cp_layout_measure(lay(layout), reinterpret_cast(p), count, widest, first, last, + &g, reinterpret_cast(o), static_cast(cap)); + e->ReleasePrimitiveArrayCritical(tops_rows, o, 0); + e->ReleasePrimitiveArrayCritical(pairs, p, JNI_ABORT); + put(e, geometry, g); + return static_cast(needed); +} + +FN(layoutSetWidest)(JNIEnv *, jclass, jlong layout, jint widest) -> void { cp_layout_set_widest(lay(layout), widest); } +FN(layoutRows)(JNIEnv *, jclass, jlong layout, jint line) -> jint { return cp_layout_rows(lay(layout), line); } +FN(layoutGapRows)(JNIEnv *, jclass, jlong layout, jint line) -> jint { return cp_layout_gap_rows(lay(layout), line); } +FN(layoutRowStart)(JNIEnv *, jclass, jlong layout, jint line) -> jint { + return cp_layout_row_start(lay(layout), line); +} +FN(layoutLineAtRow)(JNIEnv *, jclass, jlong layout, jint row) -> jint { + return cp_layout_line_at_row(lay(layout), row); +} +FN(layoutIsGapRow)(JNIEnv *, jclass, jlong layout, jint row) -> jboolean { + return cp_layout_is_gap_row(lay(layout), row) != 0; +} +FN(layoutRowTop)(JNIEnv *, jclass, jlong layout, jint row) -> jint { return cp_layout_row_top(lay(layout), row); } +FN(layoutLineTop)(JNIEnv *, jclass, jlong layout, jint line) -> jint { return cp_layout_line_top(lay(layout), line); } +FN(layoutRowAt)(JNIEnv *, jclass, jlong layout, jint y) -> jint { return cp_layout_row_at(lay(layout), y); } + +FN(layoutAnchor)(JNIEnv *e, jclass, jlong layout, jintArray out) -> void { + int32_t anchor[2] = {0, 0}; + cp_layout_anchor(lay(layout), &anchor[0], &anchor[1]); + e->SetIntArrayRegion(out, 0, 2, reinterpret_cast(anchor)); +} + +FN(layoutRestore)(JNIEnv *, jclass, jlong layout, jint line, jint offset) -> jboolean { + return cp_layout_restore(lay(layout), line, offset) != 0; +} + +FN(layoutResetRows)(JNIEnv *, jclass, jlong layout) -> void { cp_layout_reset_rows(lay(layout)); } diff --git a/android/src/main/java/me/sectiontn/codepad/core/EditorCore.kt b/android/src/main/java/me/sectiontn/codepad/core/EditorCore.kt index f9f7eb26..b81f7425 100644 --- a/android/src/main/java/me/sectiontn/codepad/core/EditorCore.kt +++ b/android/src/main/java/me/sectiontn/codepad/core/EditorCore.kt @@ -52,6 +52,9 @@ class EditorCore(initialText: String = "", clock: (() -> Long)? = null) : AutoCl val canUndo: Boolean get() = life.read { CoreNative.editorHistory(handle()) and 1 != 0 } val canRedo: Boolean get() = life.read { CoreNative.editorHistory(handle()) and 2 != 0 } + /** False once [close] freed the core. Main thread. */ + internal val isOpen: Boolean get() = native != 0L + internal fun handle(): Long { val h = native check(h != 0L) { "the editor core is closed" } diff --git a/android/src/main/java/me/sectiontn/codepad/core/EditorFrame.kt b/android/src/main/java/me/sectiontn/codepad/core/EditorFrame.kt index 4fd6c630..6f28108e 100644 --- a/android/src/main/java/me/sectiontn/codepad/core/EditorFrame.kt +++ b/android/src/main/java/me/sectiontn/codepad/core/EditorFrame.kt @@ -1,5 +1,6 @@ package me.sectiontn.codepad.core +import me.sectiontn.codepad.layout.Viewport import me.sectiontn.codepad.syntax.CoreNative /** @@ -48,11 +49,6 @@ class EditorFrame internal constructor( val i = runLines.indexOf(line) return if (i < 0) null else texts[i] } - - companion object { - /** CP_NO_ENTRY: a line with no layout. */ - const val NO_ENTRY = Int.MIN_VALUE - } } /** Makes the frame call, with buffers kept across draws and grown when the core asks for more. */ @@ -61,17 +57,22 @@ class FrameReader(ints: Int = 4096, units: Int = 16384) { private var units = CharArray(maxOf(units, 1)) private val textLength = IntArray(1) - /** [snapshot] is a snapshot pointer or 0. [entries] holds the cached revision of each line of [first, last]. */ - fun read(core: EditorCore, snapshot: Long, first: Int, last: Int, applied: Int, useChanged: Boolean, entries: IntArray): EditorFrame { + /** + * The draw's frame: the layout picks the lines. [pairs] holds [pairCount] (line, revision) pairs of the view's cache + * in any order. [snapshot] is a snapshot pointer or 0. + */ + fun read(core: EditorCore, layout: Viewport, snapshot: Long, applied: Int, useChanged: Boolean, pairs: IntArray, pairCount: Int): EditorFrame { while (true) { - val needed = CoreNative.editorFrame(core.handle(), snapshot, first, last, applied, useChanged, entries, ints, units, textLength) - if (needed <= ints.size && textLength[0] <= units.size) return decode(first, last) + val needed = CoreNative.editorFrame( + core.handle(), layout.nativeHandle(), snapshot, applied, useChanged, pairs, pairCount, ints, units, textLength, + ) + if (needed <= ints.size && textLength[0] <= units.size) return decode() if (needed > ints.size) ints = IntArray(needed) if (textLength[0] > units.size) units = CharArray(textLength[0]) } } - private fun decode(first: Int, last: Int): EditorFrame { + private fun decode(): EditorFrame { var i = 0 fun next(): Int = ints[i++] val revision = next() @@ -82,8 +83,8 @@ class FrameReader(ints: Int = 4096, units: Int = 16384) { val caretLine = next() val decorationsVersion = next() val history = next() - val lo = first.coerceIn(0, lineCount - 1) - val hi = last.coerceIn(lo, lineCount - 1) + val lo = next() + val hi = next() val starts = IntArray(hi - lo + 2) { next() } val runs = IntArray(next() * 2) { next() } var count = 0 diff --git a/android/src/main/java/me/sectiontn/codepad/layout/HeightMap.kt b/android/src/main/java/me/sectiontn/codepad/layout/HeightMap.kt deleted file mode 100644 index e975db14..00000000 --- a/android/src/main/java/me/sectiontn/codepad/layout/HeightMap.kt +++ /dev/null @@ -1,119 +0,0 @@ -package me.sectiontn.codepad.layout - -import java.util.Arrays - -/** - * Rows per line with lazily rebuilt prefix sums. Unmeasured lines count as one row, so every line has a - * y position before layout and only moves once it is measured. Gap rows under a line count beside its wrap rows. - */ -class HeightMap(lineCount: Int) { - private var rows = IntArray(maxOf(lineCount, 16)).also { Arrays.fill(it, 1) } - private var gaps = IntArray(rows.size) - private var gapLines = IntArray(0) - private var starts = IntArray(rows.size + 1) - private var cleanLines = 0 - - var lineCount: Int = lineCount - private set - - val totalRows: Int get() = rowStart(lineCount) - - fun rows(line: Int): Int = rows[line] - - fun gapRows(line: Int): Int = gaps[line] - - /** Replaces every gap: line to rows of empty space under it. Lines outside the map are ignored. */ - fun setGaps(next: Map) { - var dirty = lineCount - for (line in gapLines) if ((next[line] ?: 0) != gaps[line]) dirty = minOf(dirty, line) - for ((line, count) in next) if (line in 0 until lineCount && gaps[line] != count) dirty = minOf(dirty, line) - if (dirty == lineCount) return - for (line in gapLines) gaps[line] = 0 - val kept = ArrayList(next.size) - for ((line, count) in next) { - if (line in 0 until lineCount && count > 0) { - gaps[line] = count - kept.add(line) - } - } - gapLines = kept.toIntArray() - cleanLines = minOf(cleanLines, dirty + 1) - } - - /** True when [row] is empty space under a line rather than one of its text rows. */ - fun isGapRow(row: Int): Boolean { - if (row < 0 || row >= totalRows) return false - val line = lineAtRow(row) - return row >= rowStart(line) + rows[line] - } - - /** Returns the previous count so the caller can keep the viewport anchored. */ - fun setRows(line: Int, count: Int): Int { - val old = rows[line] - if (old != count) { - rows[line] = count - cleanLines = minOf(cleanLines, line + 1) - } - return old - } - - /** First row of [line]. line == lineCount yields the total row count. */ - fun rowStart(line: Int): Int { - val l = line.coerceIn(0, lineCount) - ensure(l) - return starts[l] - } - - fun lineAtRow(row: Int): Int { - ensure(lineCount) - val r = row.coerceIn(0, maxOf(starts[lineCount] - 1, 0)) - var lo = 0 - var hi = lineCount - 1 - while (lo < hi) { - val mid = (lo + hi + 1) ushr 1 - if (starts[mid] <= r) lo = mid else hi = mid - 1 - } - return lo - } - - /** Lines [first, first + oldCount) became newCount fresh lines of one row each, without gaps. */ - fun replaceLines(first: Int, oldCount: Int, newCount: Int) { - val tail = lineCount - first - oldCount - val next = lineCount - oldCount + newCount - if (next > rows.size) { - rows = rows.copyOf(maxOf(next, rows.size * 2)) - gaps = gaps.copyOf(rows.size) - } - if (newCount != oldCount) { - System.arraycopy(rows, first + oldCount, rows, first + newCount, tail) - System.arraycopy(gaps, first + oldCount, gaps, first + newCount, tail) - } - Arrays.fill(rows, first, first + newCount, 1) - Arrays.fill(gaps, first, first + newCount, 0) - if (gapLines.isNotEmpty()) { - gapLines = gapLines.filter { it < first || it >= first + oldCount } - .map { if (it >= first + oldCount) it + newCount - oldCount else it } - .toIntArray() - } - lineCount = next - cleanLines = minOf(cleanLines, first + 1) - } - - fun resetAll() { - Arrays.fill(rows, 0, lineCount, 1) - cleanLines = 0 - } - - private fun ensure(upTo: Int) { - if (starts.size < lineCount + 1) starts = starts.copyOf(maxOf(lineCount + 1, starts.size * 2)) - if (cleanLines == 0) { - starts[0] = 0 - cleanLines = 1 - } - while (cleanLines <= upTo) { - val i = cleanLines - starts[i] = starts[i - 1] + rows[i - 1] + gaps[i - 1] - cleanLines++ - } - } -} diff --git a/android/src/main/java/me/sectiontn/codepad/layout/LayoutCache.kt b/android/src/main/java/me/sectiontn/codepad/layout/LayoutCache.kt index 7b68f345..8311fd74 100644 --- a/android/src/main/java/me/sectiontn/codepad/layout/LayoutCache.kt +++ b/android/src/main/java/me/sectiontn/codepad/layout/LayoutCache.kt @@ -19,6 +19,11 @@ class LayoutCache(capacity: Int) { trim() } + /** Every entry, least recently used first. The eviction order stays as it is. */ + fun forEachEntry(body: (line: Int, value: T) -> Unit) { + for ((line, value) in map) body(line, value) + } + fun clear() = map.clear() /** Lines [first, first + oldCount) changed. Their entries drop and later entries move with their text. */ diff --git a/android/src/main/java/me/sectiontn/codepad/layout/Viewport.kt b/android/src/main/java/me/sectiontn/codepad/layout/Viewport.kt index d8eea6c9..ae9f76c2 100644 --- a/android/src/main/java/me/sectiontn/codepad/layout/Viewport.kt +++ b/android/src/main/java/me/sectiontn/codepad/layout/Viewport.kt @@ -1,124 +1,438 @@ package me.sectiontn.codepad.layout -/** Scroll position and the mapping between rows and view pixels. Pure arithmetic over a HeightMap. */ -class Viewport(var heights: HeightMap) { +import me.sectiontn.codepad.core.EditorCore +import me.sectiontn.codepad.syntax.CoreNative + +/** + * Scroll position, rows per line and the mapping between rows and view pixels, held by the core's layout. Attached to + * the view's editor, so edits and gaps update the rows inside the core. Outside a draw each member is one core call. + * Inside one, the members read the copy the draw's measure call returned. Main thread only. + */ +class Viewport { class Anchor(val line: Int, val offset: Int) - var rowHeight = 1 - var width = 0 - var height = 0 - var insetTop = 0 - var insetBottom = 0 - var insetLeft = 0 - var insetRight = 0 - var gutterWidth = 0 - var textPadding = 0 - var wrap = false - var widestLine = 0 - - var scrollX = 0 - private set - var scrollY = 0 + /** A gap under a line: the view y where it starts and its height in rows. */ + data class Gap(val line: Int, val top: Int, val rows: Int) + + /** The result of the last [scrollTo], [scrollBy] or [scroll], read without another call. */ + class Scroll { + var x = 0 + var y = 0 + var maxX = 0 + var maxY = 0 + /** Bit 1: x moved, bit 2: y moved. */ + var axes = 0 + var dx = 0 + var dy = 0 + } + + private var handle: Long = CoreNative.layoutNew() + // cp_layout_config: row height, width, height, insets top, bottom, left, right, gutter, text padding, wrap. + private val config = IntArray(10).also { it[ROW_HEIGHT] = 1 } + private var attached: EditorCore? = null + + // The last geometry the core returned. Its config-only fields hold until the next configure, the rest only inside + // the draw that cached it. + private val known = IntArray(GEOMETRY) + private var configKnown = false + private var drawing = false + private var cached = false + private var first = 0 + private var last = -1 + private var buffer = IntArray(256) + private var needed = 0 + private var checksCalls = false + private val anchorOut = IntArray(2) + private val measuredPair = IntArray(2) + + /** Core calls this draw made besides its frame and measure calls. */ + var drawCalls = 0 private set - val textAreaLeft: Int get() = insetLeft + gutterWidth - val textAreaWidth: Int get() = maxOf(0, width - textAreaLeft - insetRight) - val viewportHeight: Int get() = maxOf(0, height - insetTop - insetBottom) + val lastScroll = Scroll() + + private fun handle(): Long { + val h = handle + check(h != 0L) { "the layout is closed" } + return h + } + /** For the frame call, which takes the layout. */ + internal fun nativeHandle(): Long = handle() + + /** Frees the layout. An editor it is still attached to keeps its rows until that editor goes. */ + fun close() { + val h = handle + if (h == 0L) return + handle = 0L + attached = null + CoreNative.layoutFree(h) + } + + /** Takes the editor's lines, one row each, and its gaps. The size, insets and metrics stay. */ + fun attach(core: EditorCore) { + changing() + val old = attached + if (old != null && old !== core && old.isOpen) CoreNative.editorAttachLayout(old.handle(), 0L) + attached = core + CoreNative.editorAttachLayout(core.handle(), handle()) + } + + var rowHeight: Int + get() = config[ROW_HEIGHT] + set(value) { + config[ROW_HEIGHT] = value + configure() + } + val width: Int get() = config[WIDTH] + val height: Int get() = config[HEIGHT] + val insetTop: Int get() = config[INSET_TOP] + val insetBottom: Int get() = config[INSET_BOTTOM] + val insetLeft: Int get() = config[INSET_LEFT] + val insetRight: Int get() = config[INSET_RIGHT] + var gutterWidth: Int + get() = config[GUTTER] + set(value) { + config[GUTTER] = value + configure() + } + var textPadding: Int + get() = config[PADDING] + set(value) { + config[PADDING] = value + configure() + } + var wrap: Boolean + get() = config[WRAP] != 0 + set(value) { + config[WRAP] = if (value) 1 else 0 + configure() + } + var widestLine: Int + get() = field(WIDEST) + set(value) { + changing() + CoreNative.layoutSetWidest(handle(), value) + } + + val scrollX: Int get() = field(SCROLL_X) + val scrollY: Int get() = field(SCROLL_Y) + val maxScrollX: Int get() = field(MAX_X) + val maxScrollY: Int get() = field(MAX_Y) + val contentWidth: Int get() = field(CONTENT_WIDTH) + val contentHeight: Int get() = field(CONTENT_HEIGHT) + val totalRows: Int get() = field(TOTAL_ROWS) + val lineCount: Int get() = field(LINE_COUNT) + val textAreaLeft: Int get() = configField(TEXT_AREA_LEFT) + val textAreaWidth: Int get() = configField(TEXT_AREA_WIDTH) + val viewportHeight: Int get() = configField(VIEWPORT_HEIGHT) /** Width handed to LineLayout. Zero means no wrapping. */ - val wrapWidth: Int get() = if (wrap) maxOf(1, textAreaWidth - 2 * textPadding) else 0 + val wrapWidth: Int get() = configField(WRAP_WIDTH) + + /** Starts a draw. With [checksCalls], a ninth single layout call before [endDraw] throws. */ + fun beginDraw(checksCalls: Boolean) { + drawing = true + this.checksCalls = checksCalls + drawCalls = 0 + cached = false + last = first - 1 + } - val contentWidth: Int get() = if (wrap) textAreaWidth else maxOf(textAreaWidth, widestLine + 2 * textPadding) - val contentHeight: Int get() = heights.totalRows * rowHeight - val maxScrollX: Int get() = maxOf(0, contentWidth - textAreaWidth) - val maxScrollY: Int get() = maxOf(0, contentHeight - viewportHeight) + /** + * The draw's measure call: the first [pairCount] (line, rows) pairs and the widest line, then the tops and rows of + * [first]..[last] and every gap. + */ + fun measure(pairs: IntArray, pairCount: Int, widest: Int, first: Int, last: Int) { + this.first = first + this.last = last + fill(pairs, pairCount, widest) + } + + fun endDraw() { + drawing = false + cached = false + last = first - 1 + } - /** Clamps and applies. Returns true when the position moved. */ + /** Clamps and applies, with the result in [lastScroll]. Returns true when the position moved. */ fun scrollTo(x: Int, y: Int): Boolean { - val nx = x.coerceIn(0, maxScrollX) - val ny = y.coerceIn(0, maxScrollY) - if (nx == scrollX && ny == scrollY) return false - scrollX = nx - scrollY = ny - return true + crossed() + val axes = CoreNative.layoutScrollTo(handle(), x, y, known) + took(axes != 0) + record(axes) + return axes != 0 } - fun scrollBy(dx: Int, dy: Int): Boolean = scrollTo(scrollX + dx, scrollY + dy) + /** Moves by a content delta, with the applied delta in [lastScroll]. */ + fun scrollBy(dx: Int, dy: Int): Boolean { + val s = scroll() + val x = s.x + val y = s.y + val moved = scrollTo(x + dx, y + dy) + lastScroll.dx = lastScroll.x - x + lastScroll.dy = lastScroll.y - y + return moved + } - fun clamp(): Boolean = scrollTo(scrollX, scrollY) + /** The scroll and its bounds in one read, into [lastScroll]. */ + fun scroll(): Scroll { + geometry() + record(0) + return lastScroll + } + + fun clamp(): Boolean { + val s = scroll() + return scrollTo(s.x, s.y) + } /** Stores a view size. True when the text area width changed, which is when layouts must be rebuilt. */ fun resize(width: Int, height: Int): Boolean { - val before = textAreaWidth - this.width = width - this.height = height - return textAreaWidth != before + config[WIDTH] = width + config[HEIGHT] = height + return configure() } /** Stores the insets. True when the text area width changed. */ fun setInsets(top: Int, bottom: Int, left: Int, right: Int): Boolean { - val before = textAreaWidth - insetTop = top - insetBottom = bottom - insetLeft = left - insetRight = right - return textAreaWidth != before + config[INSET_TOP] = top + config[INSET_BOTTOM] = bottom + config[INSET_LEFT] = left + config[INSET_RIGHT] = right + return configure() } /** Content deltas: positive dy means the content moves up, so the finger moved up. */ - fun canScroll(dx: Float, dy: Float): Boolean = - (dx < 0 && scrollX > 0) || (dx > 0 && scrollX < maxScrollX) || - (dy < 0 && scrollY > 0) || (dy > 0 && scrollY < maxScrollY) + fun canScroll(dx: Float, dy: Float): Boolean { + val s = scroll() + return (dx < 0 && s.x > 0) || (dx > 0 && s.x < s.maxX) || (dy < 0 && s.y > 0) || (dy > 0 && s.y < s.maxY) + } + + fun rowStart(line: Int): Int { + drawnTop(line)?.let { return (it - insetTop + known[SCROLL_Y]) / rowHeight } + crossed() + return CoreNative.layoutRowStart(handle(), line) + } + + fun rows(line: Int): Int { + if (cached && line in first..last) return buffer[last - first + 2 + line - first] + crossed() + return CoreNative.layoutRows(handle(), line) + } + + fun gapRows(line: Int): Int { + crossed() + return CoreNative.layoutGapRows(handle(), line) + } + + fun lineAtRow(row: Int): Int { + crossed() + return CoreNative.layoutLineAtRow(handle(), row) + } + + /** True when [row] is empty space under a line rather than one of its text rows. */ + fun isGapRow(row: Int): Boolean { + crossed() + return CoreNative.layoutIsGapRow(handle(), row) + } /** View y of the top of [row]. */ - fun rowTop(row: Int): Int = insetTop + row * rowHeight - scrollY + fun rowTop(row: Int): Int { + if (cached) return insetTop + row * rowHeight - known[SCROLL_Y] + crossed() + return CoreNative.layoutRowTop(handle(), row) + } - fun lineTop(line: Int): Int = rowTop(heights.rowStart(line)) + fun lineTop(line: Int): Int { + drawnTop(line)?.let { return it } + crossed() + return CoreNative.layoutLineTop(handle(), line) + } /** Content row under view y, possibly outside [0, totalRows). */ - fun rowAt(y: Int): Int = Math.floorDiv(y + scrollY - insetTop, rowHeight) + fun rowAt(y: Int): Int { + crossed() + return CoreNative.layoutRowAt(handle(), y) + } + + /** Every gap in line order. */ + fun gaps(): List { + if (cached && last >= first) return parseGaps(buffer, needed, 2 * (last - first + 1) + 1) + crossed() + val count = CoreNative.layoutMeasure(handle(), IntArray(0), 0, -1, 0, 0, known, IntArray(0)) + val out = IntArray(count) + CoreNative.layoutMeasure(handle(), IntArray(0), 0, -1, 0, 0, known, out) + configKnown = true + return parseGaps(out, count, 3) + } /** Layout x for a view x. */ - fun contentX(x: Float): Float = x - textAreaLeft - textPadding + scrollX + fun contentX(x: Float): Float = x - field(TEXT_LEFT) /** View x for a layout x. */ - fun viewX(x: Float): Float = x + textAreaLeft + textPadding - scrollX - - fun firstVisibleRow(): Int = maxOf(0, rowAt(insetTop)) + fun viewX(x: Float): Float = x + field(TEXT_LEFT) - fun firstVisibleLine(): Int = heights.lineAtRow(firstVisibleRow()) + fun firstVisibleLine(): Int = field(FIRST_LINE) - fun lastVisibleLine(): Int = heights.lineAtRow(maxOf(firstVisibleRow(), rowAt(height - insetBottom - 1))) + fun lastVisibleLine(): Int = field(LAST_LINE) - /** Smallest scroll that shows a rect in layout coordinates (x from the text start, y from row 0) with the text padding around it. */ + /** Smallest scroll that shows a rect in layout coordinates (x from the text start, y from row 0) with the text padding. */ fun reveal(left: Int, top: Int, right: Int, bottom: Int): Boolean { - var x = scrollX - var y = scrollY - val vh = viewportHeight - val vw = textAreaWidth - val l = left - val r = right + 2 * textPadding - if (bottom - top >= vh || top < y) y = top else if (bottom > y + vh) y = bottom - vh - if (r - l >= vw || l < x) x = l else if (r > x + vw) x = r - vw - return scrollTo(x, y) + crossed() + val moved = CoreNative.layoutReveal(handle(), left, top, right, bottom, known) + took(moved) + return moved } /** Remembers the top visible line so a width or font change can put it back. */ fun anchor(): Anchor { - val line = firstVisibleLine() - return Anchor(line, scrollY - heights.rowStart(line) * rowHeight) + crossed() + CoreNative.layoutAnchor(handle(), anchorOut) + return Anchor(anchorOut[0], anchorOut[1]) } fun restore(anchor: Anchor) { - val line = anchor.line.coerceIn(0, heights.lineCount - 1) - val within = if (anchor.offset in 0 until (heights.rows(line) + heights.gapRows(line)) * rowHeight) anchor.offset else 0 - scrollTo(scrollX, heights.rowStart(line) * rowHeight + within) + changing() + CoreNative.layoutRestore(handle(), anchor.line, anchor.offset) + } + + /** + * Records a measurement and raises the widest line to [widest] when not wrapping. A line above the viewport shifts + * the scroll so the visible text stays put. + */ + fun measured(line: Int, rows: Int, widest: Int = -1) { + crossed() + measuredPair[0] = line + measuredPair[1] = rows + if (drawing) { + fill(measuredPair, 1, widest) + } else { + CoreNative.layoutMeasure(handle(), measuredPair, 1, widest, 0, -1, known, buffer) + configKnown = true + } } - /** Records a measurement. A line above the viewport shifts the scroll so the visible text stays put. */ - fun measured(line: Int, rows: Int) { - val first = firstVisibleLine() - val old = heights.setRows(line, rows) - if (old != rows && line < first) scrollY = (scrollY + (rows - old) * rowHeight).coerceIn(0, maxScrollY) + /** Every line back to one row. Gaps stay. */ + fun resetRows() { + changing() + CoreNative.layoutResetRows(handle()) + } + + // One measure call that refreshes the draw's copy, grown and repeated when the buffer is short. Applying the same + // rows and widest line again changes nothing. + private fun fill(pairs: IntArray, pairCount: Int, widest: Int) { + var n = CoreNative.layoutMeasure(handle(), pairs, pairCount, widest, first, last, known, buffer) + if (n > buffer.size) { + crossed() + buffer = IntArray(n) + n = CoreNative.layoutMeasure(handle(), pairs, pairCount, widest, first, last, known, buffer) + } + needed = n + cached = drawing + configKnown = true + } + + private fun drawnTop(line: Int): Int? = if (cached && line >= first && line <= last + 1) buffer[line - first] else null + + private fun field(i: Int): Int { + if (!cached) geometry() + return known[i] + } + + // Text area, viewport height and wrap width follow the config alone, so any geometry since the last configure holds. + private fun configField(i: Int): Int { + if (!configKnown && !cached) geometry() + return known[i] + } + + private fun geometry() { + if (cached) return + crossed() + CoreNative.layoutGeometry(handle(), known) + configKnown = true + } + + private fun record(axes: Int) { + lastScroll.x = known[SCROLL_X] + lastScroll.y = known[SCROLL_Y] + lastScroll.maxX = known[MAX_X] + lastScroll.maxY = known[MAX_Y] + lastScroll.axes = axes + lastScroll.dx = 0 + lastScroll.dy = 0 + } + + // A scroll call wrote the geometry into known. Inside a draw the copy stays, but tops taken before a move are stale. + private fun took(moved: Boolean) { + configKnown = true + if (!drawing) return + cached = true + if (moved) last = first - 1 + } + + // A size, metric or row change has no place inside a draw: the copy would go stale. + private fun changing() { + if (!drawing) return + check(!checksCalls) { "layout changed inside a draw" } + cached = false + configKnown = false + last = first - 1 + } + + private fun crossed() { + if (!drawing) return + drawCalls++ + check(!checksCalls || drawCalls <= DRAW_CALL_LIMIT) { "$drawCalls layout calls in one draw" } + } + + private fun configure(): Boolean { + changing() + configKnown = false + return CoreNative.layoutConfigure(handle(), config) + } + + companion object { + /** Single layout calls a draw may make besides its frame and measure calls. */ + const val DRAW_CALL_LIMIT = 8 + + private const val ROW_HEIGHT = 0 + private const val WIDTH = 1 + private const val HEIGHT = 2 + private const val INSET_TOP = 3 + private const val INSET_BOTTOM = 4 + private const val INSET_LEFT = 5 + private const val INSET_RIGHT = 6 + private const val GUTTER = 7 + private const val PADDING = 8 + private const val WRAP = 9 + + // cp_geometry, in its field order. + private const val SCROLL_X = 0 + private const val SCROLL_Y = 1 + private const val MAX_X = 2 + private const val MAX_Y = 3 + private const val CONTENT_WIDTH = 4 + private const val CONTENT_HEIGHT = 5 + private const val FIRST_LINE = 6 + private const val LAST_LINE = 7 + private const val TEXT_AREA_LEFT = 8 + private const val TEXT_AREA_WIDTH = 9 + private const val VIEWPORT_HEIGHT = 10 + private const val WRAP_WIDTH = 11 + private const val TEXT_LEFT = 12 + private const val TOTAL_ROWS = 13 + private const val LINE_COUNT = 14 + private const val WIDEST = 16 + private const val GEOMETRY = 17 + + private fun parseGaps(ints: IntArray, size: Int, start: Int): List { + val out = ArrayList() + var i = start + while (i + 2 < size) { + out.add(Gap(ints[i], ints[i + 1], ints[i + 2])) + i += 3 + } + return out + } } } diff --git a/android/src/main/java/me/sectiontn/codepad/syntax/CoreNative.kt b/android/src/main/java/me/sectiontn/codepad/syntax/CoreNative.kt index 271a23ac..11b521c0 100644 --- a/android/src/main/java/me/sectiontn/codepad/syntax/CoreNative.kt +++ b/android/src/main/java/me/sectiontn/codepad/syntax/CoreNative.kt @@ -69,10 +69,33 @@ internal object CoreNative { @JvmStatic external fun textRelease(text: Long) @JvmStatic external fun searchFind(search: Long, text: Long, scan: IntArray, out: IntArray): Int @JvmStatic external fun editorFrame( - editor: Long, snapshot: Long, first: Int, last: Int, applied: Int, useChanged: Boolean, entries: IntArray, out: IntArray, - text: CharArray, textLength: IntArray, + editor: Long, layout: Long, snapshot: Long, applied: Int, useChanged: Boolean, pairs: IntArray, pairCount: Int, + out: IntArray, text: CharArray, textLength: IntArray, ): Int + @JvmStatic external fun layoutNew(): Long + @JvmStatic external fun layoutFree(layout: Long) + @JvmStatic external fun editorAttachLayout(editor: Long, layout: Long) + @JvmStatic external fun layoutConfigure(layout: Long, config: IntArray): Boolean + @JvmStatic external fun layoutGeometry(layout: Long, out: IntArray) + @JvmStatic external fun layoutScrollTo(layout: Long, x: Int, y: Int, out: IntArray): Int + @JvmStatic external fun layoutReveal(layout: Long, left: Int, top: Int, right: Int, bottom: Int, out: IntArray): Boolean + @JvmStatic external fun layoutMeasure( + layout: Long, pairs: IntArray, pairCount: Int, widest: Int, first: Int, last: Int, geometry: IntArray, topsRows: IntArray, + ): Int + @JvmStatic external fun layoutSetWidest(layout: Long, widest: Int) + @JvmStatic external fun layoutRows(layout: Long, line: Int): Int + @JvmStatic external fun layoutGapRows(layout: Long, line: Int): Int + @JvmStatic external fun layoutRowStart(layout: Long, line: Int): Int + @JvmStatic external fun layoutLineAtRow(layout: Long, row: Int): Int + @JvmStatic external fun layoutIsGapRow(layout: Long, row: Int): Boolean + @JvmStatic external fun layoutRowTop(layout: Long, row: Int): Int + @JvmStatic external fun layoutLineTop(layout: Long, line: Int): Int + @JvmStatic external fun layoutRowAt(layout: Long, y: Int): Int + @JvmStatic external fun layoutAnchor(layout: Long, out: IntArray) + @JvmStatic external fun layoutRestore(layout: Long, line: Int, offset: Int): Boolean + @JvmStatic external fun layoutResetRows(layout: Long) + @JvmStatic external fun abiRange(): IntArray @JvmStatic external fun languageLoad(id: String, pointer: Long, highlights: ByteArray, injections: ByteArray?, error: Array): Long @JvmStatic external fun languageId(language: Long): String diff --git a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt index aeb0488e..ef0f2c70 100644 --- a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt +++ b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt @@ -39,7 +39,6 @@ import me.sectiontn.codepad.input.KeyCommand import me.sectiontn.codepad.input.KeyCommands import me.sectiontn.codepad.layout.CaretMover import me.sectiontn.codepad.layout.GutterMetrics -import me.sectiontn.codepad.layout.HeightMap import me.sectiontn.codepad.layout.LayoutCache import me.sectiontn.codepad.layout.LineGeometry import me.sectiontn.codepad.layout.LineLayout @@ -108,9 +107,11 @@ class CodeEditorView(context: Context) : View(context) { var engine: SyntaxEngine? = null private set - private var heights = HeightMap(1) - private val viewport = Viewport(heights) + private val viewport = Viewport() private val cache = LayoutCache(64) + // The draw's (line, revision) pairs for the frame call and (line, rows) pairs for the measure call, kept across draws. + private var framePairs = IntArray(256) + private var measurePairs = IntArray(64) private val frameReader = FrameReader() // The frame of the draw in progress: from the frame call to the end of publish, every read comes from it. private var drawFrame: EditorFrame? = null @@ -182,7 +183,6 @@ class CodeEditorView(context: Context) : View(context) { private var lastContentWidth = -1f private var lastContentHeight = -1f private var gapsDirty = false - private var syncedDecorations = -1 private var grabDy = 0f private var dragFixed = 0 private var anchorX = 0f @@ -271,7 +271,6 @@ class CodeEditorView(context: Context) : View(context) { fun setText(text: String, keepHistory: Boolean) { ime.reset() core.setText(text, keepHistory) - syncGaps() viewport.scrollTo(0, 0) restartInput() invalidate() @@ -448,11 +447,12 @@ class CodeEditorView(context: Context) : View(context) { } fun scrollToLine(line: Int, animated: Boolean) { - val target = heights.rowStart(line.coerceIn(0, core.document.lineCount - 1)) * viewport.rowHeight + val target = viewport.rowStart(line.coerceIn(0, core.document.lineCount - 1)) * viewport.rowHeight scroller.abort() + val s = viewport.scroll() if (animated) { - scroller.animateTo(viewport.scrollX, viewport.scrollY, viewport.scrollX, target.coerceIn(0, viewport.maxScrollY)) - } else if (viewport.scrollTo(viewport.scrollX, target)) { + scroller.animateTo(s.x, s.y, s.x, target.coerceIn(0, s.maxY)) + } else if (viewport.scrollTo(s.x, target)) { onScrolled() } } @@ -466,7 +466,7 @@ class CodeEditorView(context: Context) : View(context) { val col = head - core.document.lineStart(line) val row = entry.layout.rowOf(col) val x = Math.round(entry.layout.caretX(col)) - val top = (heights.rowStart(line) + row) * m.rowHeight + val top = (viewport.rowStart(line) + row) * m.rowHeight scroller.abort() if (viewport.reveal(x, top, x + dp(EditorPainter.CARET_WIDTH_DP), top + m.rowHeight)) onScrolled() } @@ -476,10 +476,10 @@ class CodeEditorView(context: Context) : View(context) { val doc = core.document val row = viewport.rowAt(y.toInt()) if (row < 0) return 0 - if (row >= heights.totalRows) return doc.length - val line = heights.lineAtRow(row) + if (row >= viewport.totalRows) return doc.length + val line = viewport.lineAtRow(row) val entry = cache[line] ?: layoutLine(line) - val rowInLine = (row - heights.rowStart(line)).coerceIn(0, entry.layout.rowCount - 1) + val rowInLine = (row - viewport.rowStart(line)).coerceIn(0, entry.layout.rowCount - 1) return doc.lineStart(line) + entry.layout.columnAt(rowInLine, viewport.contentX(x)) } @@ -532,6 +532,7 @@ class CodeEditorView(context: Context) : View(context) { private fun wire(core: EditorCore) { core.onChange = { change, origin -> onDocumentChange(change, origin) } core.onSelectionChange = { onSelectionMoved() } + viewport.attach(core) ime = ImeSession(core) brackets = BracketHighlight(core).also { it.enabled = brackets.enabled } search?.close() @@ -560,12 +561,11 @@ class CodeEditorView(context: Context) : View(context) { val first = doc.lineAt(change.start) val oldCount = lineSpan(change.removed) val newCount = lineSpan(change.inserted) - heights.replaceLines(first, oldCount, newCount) - syncGaps() + // The core already moved the rows and gaps and clamped the scroll. keepSpans(first, oldCount, newCount, change) cache.shift(first, oldCount, newCount) search?.onChange(change) - if (updateGutter()) relayout() else viewport.clamp() + if (updateGutter()) relayout() hideInsertionHandle() menu.hide() restartBlink() @@ -585,25 +585,12 @@ class CodeEditorView(context: Context) : View(context) { /** Replaces the decorations. [revision] is the one they were computed for, below zero for the current text. */ fun setDecorations(items: List, revision: Int) { + // The core moves the gaps and keeps the top visible line in place. if (!core.setDecorations(items, revision)) return - val anchor = viewport.anchor() - if (syncGaps()) viewport.restore(anchor) invalidate() } - /** Pushes the gap rows of a changed decoration set into the height map. True when it pushed. */ - private fun syncGaps(): Boolean { - val set = core.decorations - if (set.version == syncedDecorations) return false - syncedDecorations = set.version - heights.setGaps(set.gapRows()) - return true - } - private fun resetDocument() { - heights = HeightMap(core.document.lineCount) - syncedDecorations = -1 - viewport.heights = heights cache.clear() viewport.widestLine = 0 updateGutter() @@ -618,7 +605,7 @@ class CodeEditorView(context: Context) : View(context) { val scrollX = viewport.scrollX viewport.rowHeight = rowMetrics().rowHeight cache.clear() - heights.resetAll() + viewport.resetRows() viewport.widestLine = 0 updateGutter() viewport.restore(anchor) @@ -697,11 +684,13 @@ class CodeEditorView(context: Context) : View(context) { val layout = LineLayout(text, spans, paint, theme, viewport.wrapWidth, core.settings.tabSize, rowMetrics()) val entry = Entry(layout, spans, -1) cache.put(line, entry) - viewport.measured(line, layout.rowCount) - if (!viewport.wrap) viewport.widestLine = maxOf(viewport.widestLine, Math.round(layout.width())) + viewport.measured(line, layout.rowCount, offeredWidth(layout)) return entry } + /** The width a layout offers as the widest line, or -1 while wrapping. */ + private fun offeredWidth(layout: LineLayout): Int = if (viewport.wrap) -1 else Math.round(layout.width()) + private fun onScrolled() { anchorDirty = true hideInsertionHandle() @@ -711,23 +700,23 @@ class CodeEditorView(context: Context) : View(context) { } private fun scrollByTouch(dx: Float, dy: Float) { - val oldX = viewport.scrollX - val oldY = viewport.scrollY val rx = Math.round(dx) val ry = Math.round(dy) - viewport.scrollBy(rx, ry) - val overX = if (viewport.maxScrollX > 0) rx - (viewport.scrollX - oldX) else 0 - val overY = if (viewport.maxScrollY > 0) ry - (viewport.scrollY - oldY) else 0 + val moved = viewport.scrollBy(rx, ry) + val s = viewport.lastScroll + val overX = if (s.maxX > 0) rx - s.dx else 0 + val overY = if (s.maxY > 0) ry - s.dy else 0 if (overX != 0 || overY != 0) scroller.pull(overX.toFloat(), overY.toFloat(), touchX, touchY, width, height) - if (oldX != viewport.scrollX || oldY != viewport.scrollY) onScrolled() + if (moved) onScrolled() } private fun fling(velocityX: Float, velocityY: Float) { val min = viewConfig.scaledMinimumFlingVelocity - val vx = if (abs(velocityX) > min && viewport.maxScrollX > 0) -velocityX.toInt() else 0 - val vy = if (abs(velocityY) > min && viewport.maxScrollY > 0) -velocityY.toInt() else 0 + val s = viewport.scroll() + val vx = if (abs(velocityX) > min && s.maxX > 0) -velocityX.toInt() else 0 + val vy = if (abs(velocityY) > min && s.maxY > 0) -velocityY.toInt() else 0 if (vx == 0 && vy == 0) return - scroller.fling(viewport.scrollX, viewport.scrollY, vx, vy, viewport.maxScrollX, viewport.maxScrollY) + scroller.fling(s.x, s.y, vx, vy, s.maxX, s.maxY) } /** Shows the caret at once and restarts the blink cycle. Runs on focus, edits and caret moves. */ @@ -951,7 +940,7 @@ class CodeEditorView(context: Context) : View(context) { private inner class GestureHost : GestureMachine.Host { override fun offsetAt(x: Float, y: Float): Int = this@CodeEditorView.offsetAt(x, y) - override fun inGap(x: Float, y: Float): Boolean = heights.isGapRow(viewport.rowAt(y.toInt())) + override fun inGap(x: Float, y: Float): Boolean = viewport.isGapRow(viewport.rowAt(y.toInt())) // Runs on touch down, so this is where the grab offset and the fixed selection end are captured. override fun handleAt(x: Float, y: Float): GestureMachine.Handle? { @@ -1103,18 +1092,18 @@ class CodeEditorView(context: Context) : View(context) { override fun computeScroll() { if (!scroller.step()) return val start = System.nanoTime() - val wasTop = viewport.scrollY == 0 - val wasBottom = viewport.scrollY == viewport.maxScrollY - val wasLeft = viewport.scrollX == 0 - val wasRight = viewport.scrollX == viewport.maxScrollX + // One core call. An axis that moved onto an edge reached it in this step. val moved = viewport.scrollTo(scroller.currX, scroller.currY) + val s = viewport.lastScroll if (moved) onScrolled() val v = scroller.currVelocity.toInt() if (scroller.flinging && v > 0) { - if (!wasTop && viewport.scrollY == 0) scroller.absorbTop(v) - if (!wasBottom && viewport.scrollY == viewport.maxScrollY) scroller.absorbBottom(v) - if (!wasLeft && viewport.scrollX == 0) scroller.absorbLeft(v) - if (!wasRight && viewport.scrollX == viewport.maxScrollX) scroller.absorbRight(v) + val movedX = s.axes and 1 != 0 + val movedY = s.axes and 2 != 0 + if (movedY && s.y == 0) scroller.absorbTop(v) + if (movedY && s.y == s.maxY) scroller.absorbBottom(v) + if (movedX && s.x == 0) scroller.absorbLeft(v) + if (movedX && s.x == s.maxX) scroller.absorbRight(v) } if (moved && debugSwitch()) Log.i(DebugSwitch.TAG, "{\"call\":\"fling\",\"us\":${(System.nanoTime() - start) / 1000}}") postInvalidateOnAnimation() @@ -1237,6 +1226,7 @@ class CodeEditorView(context: Context) : View(context) { snapshot = null if (dropped) { core.close() + viewport.close() coreReleased = true } } @@ -1258,6 +1248,7 @@ class CodeEditorView(context: Context) : View(context) { snapshot?.close() snapshot = null core.close() + viewport.close() coreReleased = true } @@ -1269,27 +1260,36 @@ class CodeEditorView(context: Context) : View(context) { canvas.clipRect(0, 0, width, height) canvas.drawColor(theme.background) if (width == 0 || height == 0) return - syncGaps() val m = rowMetrics() + // The layout's two calls of a draw: the frame, then the measure call in prepare. Until endDraw, the layout reads + // come from them. With the debug switch on, a ninth single call throws. + viewport.beginDraw(checksCalls = debugSwitch()) if (revealPending) { revealPending = false revealSelection() } - val firstLine = viewport.firstVisibleLine() - val lastBound = minOf(heights.lineCount - 1, firstLine + height / m.rowHeight + 1) - // One core call for the whole draw. Until publish returns, every read comes from it. - val f = readFrame(firstLine, lastBound) + // One core call for the document. Until publish returns, every document read comes from it. + val f = readFrame() drawFrame = f if (debugSwitch()) core.document.drawingThread = Thread.currentThread() prepare(f, m) + val firstLine = f.first + val lastBound = f.last val caretLine = f.caretLine val caretOnly = f.anchor == f.head - if (highlightActiveLine && caretOnly) painter.drawActiveLine(canvas, caretLine, width, height) + if (highlightActiveLine && caretOnly && caretLine in firstLine..lastBound) { + painter.drawActiveLine(canvas, caretLine, width, height) + } val decorated = core.decorations.items - if (decorated.isNotEmpty()) decorationPainter.drawLineBackgrounds(canvas, decorated, viewport, width, height) + if (decorated.isNotEmpty()) { + decorationPainter.drawLineBackgrounds(canvas, decorated, viewport, firstLine, lastBound, width, height) + } drawFills(canvas, f, firstLine, lastBound) if (decorated.isNotEmpty()) { - clippedToText(canvas) { decorationPainter.drawUnderlines(canvas, decorated, rowGeometry, firstLine, -m.ascent) } + val windowEnd = docLineStart(lastBound) + docLineLength(lastBound) + clippedToText(canvas) { + decorationPainter.drawUnderlines(canvas, decorated, rowGeometry, firstLine, windowEnd, -m.ascent) + } } val lastLine = painter.drawText(canvas, f.lineCount, firstLine, width, height) drawComposing(canvas, firstLine) @@ -1300,6 +1300,7 @@ class CodeEditorView(context: Context) : View(context) { placeholder?.let { if (f.length == 0) painter.drawPlaceholder(canvas, m, it) } if (scroller.draw(canvas, width, height)) postInvalidateOnAnimation() publish(firstLine, lastLine, caretLine, m) + viewport.endDraw() core.document.drawingThread = null drawFrame = null flushIme(m) @@ -1331,19 +1332,28 @@ class CodeEditorView(context: Context) : View(context) { * Builds missing layouts for [first, last] with one highlight query per run of dirty lines: when the snapshot follows * the one last applied, only the lines its regions meet; otherwise every line not at its revision. */ - private fun readFrame(first: Int, last: Int): EditorFrame { + private fun readFrame(): EditorFrame { val usable = if (highlighter != null) snapshot else null - val entries = IntArray(last - first + 1) { cache[first + it]?.revision ?: EditorFrame.NO_ENTRY } + if (framePairs.size < 2 * cache.size) framePairs = IntArray(2 * maxOf(cache.size, cache.capacity)) + var n = 0 + cache.forEachEntry { line, entry -> + framePairs[2 * n] = line + framePairs[2 * n + 1] = entry.revision + n++ + } val incremental = usable != null && usable.basedOn >= 0 && usable.basedOn == appliedRevision - return frameReader.read(core, usable?.pointer ?: 0L, first, last, appliedRevision, incremental, entries) + return frameReader.read(core, viewport, usable?.pointer ?: 0L, appliedRevision, incremental, framePairs, n) } + /** Ends with the draw's measure call, which takes the rows of every line laid out here and the widest one. */ private fun prepare(frame: EditorFrame, m: RowMetrics) { // The core paints from the snapshot only when it is at the frame's revision. Otherwise its runs are the lines // with no layout, and those take the spans keepSpans kept. val consistent = highlighter != null && snapshot?.revision == frame.revision val revision = if (consistent) frame.revision else -1 val runs = frame.runs + var count = 0 + var widest = -1 var r = 0 // The spans and text of the run lines arrive in line order, one entry per line. var next = 0 @@ -1370,14 +1380,18 @@ class CodeEditorView(context: Context) : View(context) { } val layout = LineLayout(frame.text(line) ?: "", fresh, paint, theme, viewport.wrapWidth, core.settings.tabSize, m) cache.put(line, Entry(layout, fresh, if (consistent) revision else -1)) - viewport.measured(line, layout.rowCount) - if (!viewport.wrap) viewport.widestLine = maxOf(viewport.widestLine, Math.round(layout.width())) + if (2 * count + 2 > measurePairs.size) measurePairs = measurePairs.copyOf(2 * measurePairs.size) + measurePairs[2 * count] = line + measurePairs[2 * count + 1] = layout.rowCount + count++ + widest = maxOf(widest, offeredWidth(layout)) } if (revision >= 0) { appliedRevision = revision pendingSpans = null pendingTail = null } + viewport.measure(measurePairs, count, widest, frame.first, frame.last) } /** The spans [keepSpans] kept for a line of [revision], the current one, or null. */ @@ -1444,13 +1458,9 @@ class CodeEditorView(context: Context) : View(context) { private fun caretRect(m: RowMetrics, line: Int): RectF? = painter.caretRect(m, line, core.selection.head - docLineStart(line)) /** Every gap in view dp, sorted by line, the full view width wide. */ - private fun gapRects(m: RowMetrics): List { - val rows = core.decorations.gapRows() - if (rows.isEmpty()) return emptyList() - return rows.keys.sorted().map { line -> - val top = viewport.rowTop(heights.rowStart(line) + heights.rows(line)).toFloat() - GapRect(line, RectF(0f, top / density, width / density, (top + rows.getValue(line) * m.rowHeight) / density)) - } + private fun gapRects(m: RowMetrics): List = viewport.gaps().map { gap -> + val top = gap.top.toFloat() + GapRect(gap.line, RectF(0f, top / density, width / density, (top + gap.rows * m.rowHeight) / density)) } /** The gap under [line] in view dp from the last frame, or null. */ diff --git a/android/src/main/java/me/sectiontn/codepad/view/DecorationPainter.kt b/android/src/main/java/me/sectiontn/codepad/view/DecorationPainter.kt index 68afbc48..5fd417be 100644 --- a/android/src/main/java/me/sectiontn/codepad/view/DecorationPainter.kt +++ b/android/src/main/java/me/sectiontn/codepad/view/DecorationPainter.kt @@ -29,22 +29,27 @@ class DecorationPainter(private val density: Float) { private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } private val path = Path() - /** Full width tints over each line's text rows, drawn above the active line. */ - fun drawLineBackgrounds(canvas: Canvas, items: List, viewport: Viewport, width: Int, height: Int) { + /** Full width tints over the text rows of each line in [first]..[last], drawn above the active line. */ + fun drawLineBackgrounds( + canvas: Canvas, items: List, viewport: Viewport, first: Int, last: Int, width: Int, height: Int, + ) { for (d in items) { - if (d !is LineBackground) continue + if (d !is LineBackground || d.line < first || d.line > last) continue val top = viewport.lineTop(d.line) - val bottom = top + viewport.heights.rows(d.line) * viewport.rowHeight + val bottom = top + viewport.rows(d.line) * viewport.rowHeight if (bottom <= 0 || top >= height) continue fill.color = d.color canvas.drawRect(viewport.textAreaLeft.toFloat(), top.toFloat(), width.toFloat(), bottom.toFloat(), fill) } } - /** [baseline] is the distance from a row's top to its baseline in pixels. */ - fun drawUnderlines(canvas: Canvas, items: List, g: RowGeometry, firstLine: Int, baseline: Int) { + /** + * [baseline] is the distance from a row's top to its baseline in pixels. An underline starting past [windowEnd] is + * skipped, since finding its line's top would cost a layout call. + */ + fun drawUnderlines(canvas: Canvas, items: List, g: RowGeometry, firstLine: Int, windowEnd: Int, baseline: Int) { for (d in items) { - if (d !is Underline) continue + if (d !is Underline || d.start > windowEnd) continue RangeRects.forEach(g, d.start, d.end, firstLine, padNewline = false) { left, top, right, _ -> val lineTop = top + baseline + d.offset * density if (d.style == UnderlineStyle.Solid) { diff --git a/android/src/main/java/me/sectiontn/codepad/view/EditorPainter.kt b/android/src/main/java/me/sectiontn/codepad/view/EditorPainter.kt index ff34a7e8..a9ef9fa5 100644 --- a/android/src/main/java/me/sectiontn/codepad/view/EditorPainter.kt +++ b/android/src/main/java/me/sectiontn/codepad/view/EditorPainter.kt @@ -21,7 +21,7 @@ internal class EditorPainter( fun drawActiveLine(canvas: Canvas, line: Int, width: Int, height: Int) { val top = viewport.lineTop(line) - val bottom = top + viewport.heights.rows(line) * viewport.rowHeight + val bottom = top + viewport.rows(line) * viewport.rowHeight if (bottom <= 0 || top >= height) return fill.color = theme.activeLine canvas.drawRect(viewport.textAreaLeft.toFloat(), top.toFloat(), width.toFloat(), bottom.toFloat(), fill) diff --git a/android/src/test/java/me/sectiontn/codepad/core/EditorFrameTest.kt b/android/src/test/java/me/sectiontn/codepad/core/EditorFrameTest.kt index 80208164..95328452 100644 --- a/android/src/test/java/me/sectiontn/codepad/core/EditorFrameTest.kt +++ b/android/src/test/java/me/sectiontn/codepad/core/EditorFrameTest.kt @@ -1,6 +1,7 @@ package me.sectiontn.codepad.core import kotlin.random.Random +import me.sectiontn.codepad.layout.Viewport import org.junit.Assert.assertEquals import org.junit.Test @@ -12,6 +13,10 @@ class EditorFrameTest { val random = Random(7) val core = EditorCore("fun a() {\n return 1\n}\n\nval b = 2\n") val reader = FrameReader(ints = 1, units = 1) + // One unit rows, so the layout's window is the first visible line and six more. + val layout = Viewport() + layout.attach(core) + layout.resize(100, 5) val pieces = listOf("x", "\n", "ab\ncd", "", "\n\n", "é😀", " ") repeat(500) { val doc = core.document @@ -19,16 +24,16 @@ class EditorFrameTest { val b = minOf(doc.length, a + random.nextInt(4)) core.replace(a, b, pieces[random.nextInt(pieces.size)]) if (random.nextInt(3) == 0) core.setSelection(random.nextInt(doc.length + 1), random.nextInt(doc.length + 1)) - val first = random.nextInt(doc.lineCount + 2) - 1 - val last = first + random.nextInt(6) - val entries = IntArray(last - first + 1) { EditorFrame.NO_ENTRY } - val frame = reader.read(core, 0L, first, last, -1, false, entries) + layout.scrollTo(0, random.nextInt(doc.lineCount + 2) - 1) + val first = layout.firstVisibleLine() + val frame = reader.read(core, layout, 0L, -1, false, IntArray(0), 0) assertEquals(doc.revision, frame.revision) assertEquals(doc.length, frame.length) assertEquals(doc.lineCount, frame.lineCount) assertEquals(core.selection, Selection(frame.anchor, frame.head)) assertEquals(doc.lineAt(core.selection.head), frame.caretLine) - assertEquals(first.coerceIn(0, doc.lineCount - 1), frame.first) + assertEquals(first, frame.first) + assertEquals(minOf(doc.lineCount - 1, first + 6), frame.last) for (line in frame.first..frame.last) { assertEquals(doc.lineStart(line), frame.lineStart(line)) assertEquals(doc.lineLength(line), frame.lineLength(line)) @@ -38,6 +43,7 @@ class EditorFrameTest { assertEquals(doc.lineStart(frame.last + 1), frame.lineStart(frame.last + 1)) assertEquals(null, frame.lineStart(frame.last + 2)) } + layout.close() core.close() } } diff --git a/android/src/test/java/me/sectiontn/codepad/core/VectorRunner.kt b/android/src/test/java/me/sectiontn/codepad/core/VectorRunner.kt index a08de61b..d3048263 100644 --- a/android/src/test/java/me/sectiontn/codepad/core/VectorRunner.kt +++ b/android/src/test/java/me/sectiontn/codepad/core/VectorRunner.kt @@ -1,6 +1,5 @@ package me.sectiontn.codepad.core -import me.sectiontn.codepad.layout.HeightMap import me.sectiontn.codepad.layout.Viewport import org.json.JSONArray import org.json.JSONObject @@ -16,31 +15,21 @@ class VectorRunner(private val case: JSONObject) { private var lastResult: Any? = null private var lastError: String? = null - // Created by the first layout op. Until the layout moves into the core, the runner keeps it in step as the view does. - private var heights: HeightMap? = null + // Created by the first layout op and attached to the editor, which keeps its rows in step. private var viewport: Viewport? = null private var anchor: Viewport.Anchor? = null private var widthChanged = false + private val pairs = IntArray(64) init { - core.onChange = { change, origin -> - changes.add(change to origin) - heights?.let { h -> - h.replaceLines(core.document.lineAt(change.start), lineSpan(change.removed), lineSpan(change.inserted)) - h.setGaps(core.decorations.gapRows()) - viewport!!.clamp() - } - } + core.onChange = { change, origin -> changes.add(change to origin) } } - private fun lineSpan(text: String): Int = 1 + text.count { it == '\n' } - private fun layout(op: JSONObject) { - val h = heights ?: HeightMap(core.document.lineCount).also { - it.setGaps(core.decorations.gapRows()) - heights = it + val vp = viewport ?: Viewport().also { + it.attach(core) + viewport = it } - val vp = viewport ?: Viewport(h).also { viewport = it } val before = vp.textAreaWidth val insets = op.getJSONArray("insets") vp.rowHeight = op.getInt("rowHeight") @@ -115,25 +104,26 @@ class VectorRunner(private val case: JSONObject) { val arr = op.getJSONArray("items") val items = (0 until arr.length()).map { i -> decorationOf(arr.getJSONObject(i)) } core.setDecorations(items, op.optInt("revision", -1)) - viewport?.let { vp -> - val a = vp.anchor() - vp.heights.setGaps(core.decorations.gapRows()) - vp.restore(a) - } } "layout" -> layout(op) + // Through the draw's batch call, so the vectors cover the pair marshalling. "measure" -> { val vp = viewport!! - val pairs = op.getJSONArray("pairs") - for (i in 0 until pairs.length()) vp.measured(pairs.getJSONArray(i).getInt(0), pairs.getJSONArray(i).getInt(1)) - if (op.has("widest") && !vp.wrap) vp.widestLine = maxOf(vp.widestLine, op.getInt("widest")) + val list = op.getJSONArray("pairs") + for (i in 0 until list.length()) { + pairs[2 * i] = list.getJSONArray(i).getInt(0) + pairs[2 * i + 1] = list.getJSONArray(i).getInt(1) + } + vp.beginDraw(checksCalls = true) + vp.measure(pairs, list.length(), op.optInt("widest", -1), 0, -1) + vp.endDraw() } "scrollTo" -> lastResult = viewport!!.scrollTo(op.getInt("x"), op.getInt("y")) "scrollBy" -> lastResult = viewport!!.scrollBy(op.getInt("dx"), op.getInt("dy")) "reveal" -> lastResult = viewport!!.reveal(op.getInt("left"), op.getInt("top"), op.getInt("right"), op.getInt("bottom")) "anchor" -> anchor = viewport!!.anchor() "restore" -> viewport!!.restore(anchor!!) - "resetRows" -> heights!!.resetAll() + "resetRows" -> viewport!!.resetRows() else -> fail("op not implemented: $name") } } @@ -230,7 +220,6 @@ class VectorRunner(private val case: JSONObject) { private fun checkLayout(expect: JSONObject, where: String) { val vp = viewport ?: return - val h = vp.heights fun pair(key: String) = expect.getJSONArray(key).let { listOf(it.getInt(0), it.getInt(1)) } fun keyed(key: String, actual: (Int) -> Any) { val o = expect.getJSONObject(key) @@ -242,10 +231,10 @@ class VectorRunner(private val case: JSONObject) { if (expect.has("maxScroll")) assertEquals("maxScroll $where", pair("maxScroll"), listOf(vp.maxScrollX, vp.maxScrollY)) if (expect.has("content")) assertEquals("content $where", pair("content"), listOf(vp.contentWidth, vp.contentHeight)) if (expect.has("visible")) assertEquals("visible $where", pair("visible"), listOf(vp.firstVisibleLine(), vp.lastVisibleLine())) - if (expect.has("totalRows")) assertEquals("totalRows $where", expect.getInt("totalRows"), h.totalRows) - if (expect.has("rowStart")) keyed("rowStart") { h.rowStart(it) } - if (expect.has("lineAtRow")) keyed("lineAtRow") { h.lineAtRow(it) } - if (expect.has("isGapRow")) keyed("isGapRow") { h.isGapRow(it) } + if (expect.has("totalRows")) assertEquals("totalRows $where", expect.getInt("totalRows"), vp.totalRows) + if (expect.has("rowStart")) keyed("rowStart") { vp.rowStart(it) } + if (expect.has("lineAtRow")) keyed("lineAtRow") { vp.lineAtRow(it) } + if (expect.has("isGapRow")) keyed("isGapRow") { vp.isGapRow(it) } if (expect.has("lineTop")) keyed("lineTop") { vp.lineTop(it) } } } diff --git a/android/src/test/java/me/sectiontn/codepad/layout/HeightMapTest.kt b/android/src/test/java/me/sectiontn/codepad/layout/HeightMapTest.kt deleted file mode 100644 index 4a0425e0..00000000 --- a/android/src/test/java/me/sectiontn/codepad/layout/HeightMapTest.kt +++ /dev/null @@ -1,111 +0,0 @@ -package me.sectiontn.codepad.layout - -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class HeightMapTest { - @Test - fun unmeasuredLinesCountOneRow() { - val h = HeightMap(5) - assertEquals(5, h.totalRows) - assertEquals(3, h.rowStart(3)) - assertEquals(5, h.rowStart(5)) - assertEquals(4, h.lineAtRow(4)) - assertEquals(4, h.lineAtRow(99)) - assertEquals(0, h.lineAtRow(-1)) - } - - @Test - fun measuredRowsShiftLaterLines() { - val h = HeightMap(5) - assertEquals(1, h.setRows(1, 3)) - assertEquals(3, h.setRows(1, 3)) - assertEquals(7, h.totalRows) - assertEquals(4, h.rowStart(2)) - assertEquals(1, h.lineAtRow(1)) - assertEquals(1, h.lineAtRow(3)) - assertEquals(2, h.lineAtRow(4)) - assertEquals(4, h.lineAtRow(6)) - } - - @Test - fun replaceLinesKeepsTheTail() { - val h = HeightMap(4) - h.setRows(3, 2) - h.replaceLines(1, 1, 3) - assertEquals(6, h.lineCount) - assertEquals(1, h.rows(1)) - assertEquals(1, h.rows(3)) - assertEquals(2, h.rows(5)) - assertEquals(7, h.totalRows) - h.replaceLines(0, 3, 1) - assertEquals(4, h.lineCount) - assertEquals(2, h.rows(3)) - assertEquals(5, h.totalRows) - assertEquals(3, h.rowStart(3)) - } - - @Test - fun resetAllForgetsMeasurements() { - val h = HeightMap(3) - h.setRows(0, 4) - assertEquals(6, h.totalRows) - h.resetAll() - assertEquals(3, h.totalRows) - assertEquals(1, h.rowStart(1)) - } - - @Test - fun growsPastTheInitialCapacity() { - val h = HeightMap(1) - h.replaceLines(0, 1, 40) - assertEquals(40, h.lineCount) - assertEquals(40, h.totalRows) - assertEquals(39, h.rowStart(39)) - h.replaceLines(39, 1, 30) - assertEquals(69, h.lineCount) - assertEquals(69, h.totalRows) - } - - @Test - fun gapRowsCountInRowStartsAndTotal() { - val h = HeightMap(4) - h.setGaps(mapOf(1 to 2)) - assertEquals(1, h.rowStart(1)) - assertEquals(4, h.rowStart(2)) - assertEquals(6, h.totalRows) - assertEquals(1, h.lineAtRow(3)) - assertTrue(h.isGapRow(3)) - assertFalse(h.isGapRow(1)) - } - - @Test - fun relayoutKeepsGaps() { - val h = HeightMap(3) - h.setGaps(mapOf(0 to 2)) - h.setRows(0, 3) - h.resetAll() - assertEquals(2, h.gapRows(0)) - assertEquals(3, h.rowStart(1)) - } - - @Test - fun replaceLinesMovesGapsWithTheirLines() { - val h = HeightMap(4) - h.setGaps(mapOf(2 to 1)) - h.replaceLines(0, 1, 3) - assertEquals(1, h.gapRows(4)) - assertEquals(0, h.gapRows(2)) - } - - @Test - fun setGapsReplacesThePreviousGaps() { - val h = HeightMap(4) - h.setGaps(mapOf(0 to 2)) - h.setGaps(mapOf(2 to 1)) - assertEquals(0, h.gapRows(0)) - assertEquals(5, h.totalRows) - } -} diff --git a/android/src/test/java/me/sectiontn/codepad/layout/LayoutCacheTest.kt b/android/src/test/java/me/sectiontn/codepad/layout/LayoutCacheTest.kt index 119ed723..4a96c004 100644 --- a/android/src/test/java/me/sectiontn/codepad/layout/LayoutCacheTest.kt +++ b/android/src/test/java/me/sectiontn/codepad/layout/LayoutCacheTest.kt @@ -37,6 +37,24 @@ class LayoutCacheTest { assertEquals(3, c.size) } + // The draw lists the cache for the frame call before it lays anything out. A listing that refreshed the order + // would evict the lines just drawn instead of the stale ones. + @Test + fun forEachEntryLeavesTheEvictionOrder() { + val c = LayoutCache(8) + for (i in 0 until 8) c.put(i, "l$i") + c[0] + val seen = HashMap() + c.forEachEntry { line, value -> seen[line] = value } + assertEquals((0 until 8).associateWith { "l$it" }, seen) + c.put(8, "l8") + c.put(9, "l9") + assertNull(c[1]) + assertNull(c[2]) + assertEquals("l0", c[0]) + assertEquals("l3", c[3]) + } + @Test fun capacityChangeTrims() { val c = LayoutCache(4) diff --git a/android/src/test/java/me/sectiontn/codepad/layout/ViewportTest.kt b/android/src/test/java/me/sectiontn/codepad/layout/ViewportTest.kt index e25ca15f..73da7388 100644 --- a/android/src/test/java/me/sectiontn/codepad/layout/ViewportTest.kt +++ b/android/src/test/java/me/sectiontn/codepad/layout/ViewportTest.kt @@ -1,165 +1,83 @@ package me.sectiontn.codepad.layout +import me.sectiontn.codepad.core.EditorCore +import me.sectiontn.codepad.core.Gap import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Test class ViewportTest { - private fun viewport(lines: Int = 100, rowHeight: Int = 20, height: Int = 200, width: Int = 400): Viewport = - Viewport(HeightMap(lines)).apply { - this.rowHeight = rowHeight - this.height = height - this.width = width - } - - @Test - fun clampsScrollToTheContent() { - val v = viewport() - assertEquals(2000, v.contentHeight) - assertEquals(1800, v.maxScrollY) - assertTrue(v.scrollTo(0, 5000)) - assertEquals(1800, v.scrollY) - assertFalse(v.scrollTo(-10, 1800)) - assertEquals(0, v.scrollX) - assertEquals(0, v.maxScrollX) - assertTrue(v.scrollBy(0, -1000)) - assertEquals(800, v.scrollY) - v.scrollTo(0, 5000) - v.height = 300 - assertTrue(v.clamp()) - assertEquals(1700, v.scrollY) - } - - @Test - fun mapsRowsToViewPixelsThroughInsets() { - val v = viewport() - v.insetTop = 30 - v.insetBottom = 50 - assertEquals(120, v.viewportHeight) - assertEquals(1880, v.maxScrollY) - assertEquals(30, v.lineTop(0)) - assertEquals(-2, v.rowAt(0)) - v.scrollTo(0, 45) - assertEquals(2, v.firstVisibleLine()) - assertEquals(25, v.lineTop(2)) - assertEquals(8, v.lastVisibleLine()) - assertEquals(3, v.rowAt(55)) - assertEquals(0, v.rowAt(0)) - } - - @Test - fun horizontalRangeFollowsTheWidestLine() { - val v = viewport() - v.gutterWidth = 40 - v.textPadding = 8 - v.widestLine = 1000 - assertEquals(40, v.textAreaLeft) - assertEquals(360, v.textAreaWidth) - assertEquals(1016, v.contentWidth) - assertEquals(656, v.maxScrollX) - assertEquals(0, v.wrapWidth) - assertEquals(100f, v.contentX(148f), 0f) - v.scrollTo(100, 0) - assertEquals(-52f, v.viewX(0f), 0f) - v.wrap = true - assertEquals(0, v.maxScrollX) - assertEquals(344, v.wrapWidth) - assertEquals(360, v.contentWidth) - } + private fun lines(n: Int) = EditorCore(List(n) { "line $it" }.joinToString("\n")) @Test fun canScrollLooksAtTheDragDirection() { - val v = viewport() - assertTrue(v.canScroll(0f, 1f)) - assertFalse(v.canScroll(0f, -1f)) - assertFalse(v.canScroll(1f, 0f)) - v.scrollTo(0, 1800) - assertFalse(v.canScroll(0f, 1f)) - assertTrue(v.canScroll(0f, -1f)) - } - - @Test - fun revealScrollsTheMinimumDistance() { - val v = viewport() - v.textPadding = 8 - v.widestLine = 1000 - assertTrue(v.reveal(0, 500, 10, 520)) - assertEquals(320, v.scrollY) - assertTrue(v.reveal(0, 100, 10, 120)) - assertEquals(100, v.scrollY) - assertFalse(v.reveal(0, 150, 10, 170)) - assertTrue(v.reveal(490, 150, 500, 170)) - assertEquals(116, v.scrollX) - assertTrue(v.reveal(0, 0, 10, 20)) - assertEquals(0, v.scrollX) - assertEquals(0, v.scrollY) - } - - @Test - fun anchorSurvivesARelayout() { - val v = viewport() - v.heights.setRows(3, 4) - v.scrollTo(0, 80) - val a = v.anchor() - assertEquals(3, a.line) - assertEquals(20, a.offset) - v.heights.resetAll() - v.restore(a) - assertEquals(60, v.scrollY) - v.heights.setRows(3, 4) - v.restore(a) - assertEquals(80, v.scrollY) - } - - @Test - fun measuringALineAboveKeepsTheViewportStill() { - val v = viewport() - v.scrollTo(0, 400) - assertEquals(20, v.firstVisibleLine()) - v.measured(5, 3) - assertEquals(440, v.scrollY) - assertEquals(20, v.firstVisibleLine()) - v.measured(20, 2) - assertEquals(440, v.scrollY) - v.measured(5, 3) - assertEquals(440, v.scrollY) - } - - @Test - fun resizeAndInsetsReportOnlyTextAreaWidthChanges() { - val v = viewport() - assertFalse(v.resize(400, 300)) - assertEquals(300, v.height) - assertTrue(v.resize(500, 300)) - assertEquals(500, v.width) - assertFalse(v.setInsets(10, 20, 0, 0)) - assertEquals(20, v.insetBottom) - assertTrue(v.setInsets(10, 20, 8, 0)) - assertEquals(8, v.insetLeft) - assertTrue(v.setInsets(10, 20, 8, 4)) - assertFalse(v.setInsets(0, 0, 8, 4)) + lines(100).use { core -> + val v = Viewport() + v.attach(core) + v.rowHeight = 20 + v.resize(400, 200) + assertTrue(v.canScroll(0f, 1f)) + assertFalse(v.canScroll(0f, -1f)) + assertFalse(v.canScroll(1f, 0f)) + v.scrollTo(0, 1800) + assertFalse(v.canScroll(0f, 1f)) + assertTrue(v.canScroll(0f, -1f)) + v.close() + } } + // Between measure and endDraw the painters read the draw's copy. A copy that drifts from the core puts a line, the + // gutter or a gap at the wrong height, and a read that still crosses costs a JNI call per line. @Test - fun measuringAWrappedLineAboveKeepsTheGapAndTheVisibleText() { - val v = viewport(lines = 40, rowHeight = 10, height = 100) - v.heights.setGaps(mapOf(5 to 2)) - v.scrollTo(0, v.heights.rowStart(20) * 10) - val before = v.scrollY - v.measured(3, 3) - assertEquals(before + 20, v.scrollY) - assertEquals(30, v.lineTop(6) - v.lineTop(5)) + fun drawReadsMatchTheCoreWithoutCalls() { + lines(60).use { core -> + assertTrue(core.setDecorations(listOf(Gap(2, 2), Gap(21, 1), Gap(50, 3)), -1)) + val v = Viewport() + v.attach(core) + v.rowHeight = 10 + v.resize(100, 60) + v.setInsets(7, 5, 3, 0) + v.gutterWidth = 20 + v.scrollTo(0, 205) + val first = v.firstVisibleLine() + val last = first + 60 / 10 + 1 + v.beginDraw(checksCalls = true) + v.measure(intArrayOf(first - 3, 2, first + 1, 3), 2, 400, first, last) + fun reads(): List { + val out = mutableListOf( + v.scrollX, v.scrollY, v.maxScrollY, v.contentWidth, v.contentHeight, v.textAreaLeft, v.textAreaWidth, + v.wrapWidth, v.firstVisibleLine(), v.lastVisibleLine(), v.widestLine, v.viewX(0f).toInt(), v.rowTop(30), + ) + for (line in first..last + 1) out += listOf(v.lineTop(line), v.rowStart(line)) + for (line in first..last) out += v.rows(line) + for (gap in v.gaps()) out += listOf(gap.line, gap.top, gap.rows) + return out + } + val drawn = reads() + assertEquals(0, v.drawCalls) + v.endDraw() + assertEquals(reads(), drawn) + assertEquals(listOf(2, 21, 50), v.gaps().map { it.line }) + v.close() + } } + // With the debug switch on, a ninth single layout call in one draw throws: a per-line crossing crept into the draw. @Test - fun anchorRestoreInsideAGapStaysInIt() { - val v = viewport(lines = 10, rowHeight = 10, height = 50) - v.heights.setGaps(mapOf(1 to 2)) - v.scrollTo(0, 25) - val a = v.anchor() - v.heights.resetAll() - v.restore(a) - assertEquals(25, v.scrollY) + fun aNinthCallInsideADrawThrowsInDebug() { + lines(100).use { core -> + val v = Viewport() + v.attach(core) + v.rowHeight = 20 + v.resize(400, 200) + v.beginDraw(checksCalls = true) + v.measure(IntArray(0), 0, -1, 0, 11) + repeat(Viewport.DRAW_CALL_LIMIT) { v.gapRows(50) } + assertThrows(IllegalStateException::class.java) { v.gapRows(50) } + v.endDraw() + v.close() + } } } diff --git a/cpp/core/include/codepad.h b/cpp/core/include/codepad.h index 91774989..62bc0103 100644 --- a/cpp/core/include/codepad.h +++ b/cpp/core/include/codepad.h @@ -214,7 +214,7 @@ CP_API void cp_editor_attach_layout(cp_editor *editor, cp_layout *layout); // Returns 1 when the text area width changed, which is when line layouts must be rebuilt. CP_API int32_t cp_layout_configure(cp_layout *layout, const cp_layout_config *config); CP_API void cp_layout_geometry(const cp_layout *layout, cp_geometry *out); -// Returns 1 when the clamped scroll moved. out may be NULL. +// Clamps and applies. Returns 1 when x moved, 2 when y moved, 3 when both did. out may be NULL. CP_API int32_t cp_layout_scroll_to(cp_layout *layout, int32_t x, int32_t y, cp_geometry *out); // The smallest scroll that shows a rect in layout coordinates with the text padding around it. Returns 1 when it moved. CP_API int32_t cp_layout_reveal(cp_layout *layout, int32_t left, int32_t top, int32_t right, int32_t bottom, @@ -347,17 +347,17 @@ CP_API uint32_t cp_editor_frame(const cp_editor *editor, const cp_layout *layout int32_t applied_revision, int32_t use_changed, const int32_t *entries, uint32_t entry_count, int32_t *out, uint32_t cap, cp_unit *text_out, uint32_t text_cap, uint32_t *text_len); -// cp_editor_frame over lines [first_line, last_line] clamped to the document, with no first and last in the -// header. entry_revisions[i] is the cached revision of line first_line + i. -CP_API uint32_t cp_editor_frame_range(const cp_editor *editor, const cp_snapshot *snapshot, int32_t first_line, - int32_t last_line, int32_t applied_revision, int32_t use_changed, - const int32_t *entry_revisions, int32_t *out, uint32_t cap, cp_unit *text_out, - uint32_t text_cap, uint32_t *text_len); // A line's triples after an edit inside it replaced removed units at start with inserted units. CP_API uint32_t cp_shift_spans(const int32_t *spans, uint32_t count, int32_t start, int32_t removed, int32_t inserted, int32_t *out, uint32_t cap); #ifdef CODEPAD_TEST_HOOKS +// cp_editor_frame over lines [first_line, last_line] clamped to the document, with no first and last in the +// header. entry_revisions[i] is the cached revision of line first_line + i. +CP_API uint32_t cp_test_frame_range(const cp_editor *editor, const cp_snapshot *snapshot, int32_t first_line, + int32_t last_line, int32_t applied_revision, int32_t use_changed, + const int32_t *entry_revisions, int32_t *out, uint32_t cap, cp_unit *text_out, + uint32_t text_cap, uint32_t *text_len); // Parses source with the language, runs query over the whole tree and returns how many matches pass their // predicates, or -1 with a message in error when the query does not compile. CP_API int32_t cp_test_predicate(const cp_language *language, const char *query, uint32_t query_len, diff --git a/cpp/core/src/capi_layout.cpp b/cpp/core/src/capi_layout.cpp index c14a9e23..25bd8e58 100644 --- a/cpp/core/src/capi_layout.cpp +++ b/cpp/core/src/capi_layout.cpp @@ -33,9 +33,12 @@ int32_t cp_layout_configure(cp_layout *layout, const cp_layout_config *config) { void cp_layout_geometry(const cp_layout *layout, cp_geometry *out) { fill(*layout->layout, out); } int32_t cp_layout_scroll_to(cp_layout *layout, int32_t x, int32_t y, cp_geometry *out) { - bool moved = layout->layout->scroll_to(x, y); - fill(*layout->layout, out); - return moved ? 1 : 0; + Layout &l = *layout->layout; + int32_t old_x = l.scroll_x(); + int32_t old_y = l.scroll_y(); + l.scroll_to(x, y); + fill(l, out); + return (l.scroll_x() != old_x ? 1 : 0) | (l.scroll_y() != old_y ? 2 : 0); } int32_t cp_layout_reveal(cp_layout *layout, int32_t left, int32_t top, int32_t right, int32_t bottom, diff --git a/cpp/core/src/frame.cpp b/cpp/core/src/frame.cpp index 82bf6caa..fd942913 100644 --- a/cpp/core/src/frame.cpp +++ b/cpp/core/src/frame.cpp @@ -180,23 +180,6 @@ static uint32_t build_frame(const cp_editor *editor, const cp_snapshot *snapshot return size; } -extern "C" uint32_t cp_editor_frame_range(const cp_editor *editor, const cp_snapshot *snapshot, int32_t first_line, - int32_t last_line, int32_t applied_revision, int32_t use_changed, - const int32_t *entry_revisions, int32_t *out, uint32_t cap, - cp_unit *text_out, uint32_t text_cap, uint32_t *text_len) { - int32_t line_count = editor->doc.line_count(); - int32_t first = std::clamp(first_line, 0, line_count - 1); - int32_t last = std::clamp(last_line, first, line_count - 1); - std::vector entries(static_cast(last - first + 1)); - for (int32_t line = first; line <= last; line++) { - bool requested = line >= first_line && line <= last_line; - entries[static_cast(line - first)] = requested ? entry_revisions[line - first_line] : CP_NO_ENTRY; - } - std::vector ints = frame_header(editor); - return build_frame(editor, snapshot, first, last, entries, applied_revision, use_changed, ints, out, cap, text_out, - text_cap, text_len); -} - extern "C" uint32_t cp_editor_frame(const cp_editor *editor, const cp_layout *layout, const cp_snapshot *snapshot, int32_t applied_revision, int32_t use_changed, const int32_t *entries, uint32_t entry_count, int32_t *out, uint32_t cap, cp_unit *text_out, @@ -223,6 +206,23 @@ extern "C" uint32_t cp_shift_spans(const int32_t *spans, uint32_t count, int32_t } #ifdef CODEPAD_TEST_HOOKS +extern "C" uint32_t cp_test_frame_range(const cp_editor *editor, const cp_snapshot *snapshot, int32_t first_line, + int32_t last_line, int32_t applied_revision, int32_t use_changed, + const int32_t *entry_revisions, int32_t *out, uint32_t cap, cp_unit *text_out, + uint32_t text_cap, uint32_t *text_len) { + int32_t line_count = editor->doc.line_count(); + int32_t first = std::clamp(first_line, 0, line_count - 1); + int32_t last = std::clamp(last_line, first, line_count - 1); + std::vector entries(static_cast(last - first + 1)); + for (int32_t line = first; line <= last; line++) { + bool requested = line >= first_line && line <= last_line; + entries[static_cast(line - first)] = requested ? entry_revisions[line - first_line] : CP_NO_ENTRY; + } + std::vector ints = frame_header(editor); + return build_frame(editor, snapshot, first, last, entries, applied_revision, use_changed, ints, out, cap, text_out, + text_cap, text_len); +} + extern "C" uint32_t cp_test_dirty_runs(const cp_unit *text, uint32_t length, uint32_t first_line_start, int32_t first_line, int32_t last_line, int32_t revision, int32_t applied, const int32_t *changed, int32_t changed_len, const int32_t *entry_revisions, diff --git a/example/android/app/src/androidTest/java/codepad/example/ContentSizeTest.kt b/example/android/app/src/androidTest/java/codepad/example/ContentSizeTest.kt index bac78064..7353253f 100644 --- a/example/android/app/src/androidTest/java/codepad/example/ContentSizeTest.kt +++ b/example/android/app/src/androidTest/java/codepad/example/ContentSizeTest.kt @@ -31,6 +31,34 @@ class ContentSizeTest { } } + // setInitialText swaps the editor under the same layout: the size and wrap stay, the rows start over and the + // scroll goes back to the top. + @Test + fun setInitialTextWhileScrolledKeepsTheMetrics() { + launch().use { s -> + val editor = s.editor() + onMain { + val sizes = ArrayList>() + editor.onContentSizeListener = { w, h -> sizes.add(w to h) } + editor.setContentInsets(0f, 24f, 0f, 0f) + editor.setSoftWrap(true) + editor.setInitialText(List(1000) { "line $it" }.joinToString("\n")) + layout(editor) + draw(editor) + editor.scrollToLine(500, false) + draw(editor) + assertTrue("scrolled, at ${editor.frame.scrollY}", editor.frame.scrollY > 0f) + val row = (sizes[0].second - 24f) / 1000 + editor.setInitialText((listOf("word ".repeat(60)) + List(9) { "line $it" }).joinToString("\n")) + draw(editor) + val density = editor.resources.displayMetrics.density + assertEquals(0f, editor.frame.scrollY, 0f) + assertEquals("still wrapping", 600 / density, sizes.last().first, 0.5f) + assertTrue("the long line wraps, ${sizes.last().second}", sizes.last().second > 11 * row + 24f) + } + } + } + @Test fun listenerReportsTheSizeWithInsetsOncePerChange() { launch().use { s -> diff --git a/example/android/app/src/androidTest/java/codepad/example/DecorationPaintTest.kt b/example/android/app/src/androidTest/java/codepad/example/DecorationPaintTest.kt index cfd2e02d..b51792d5 100644 --- a/example/android/app/src/androidTest/java/codepad/example/DecorationPaintTest.kt +++ b/example/android/app/src/androidTest/java/codepad/example/DecorationPaintTest.kt @@ -38,6 +38,26 @@ class DecorationPaintTest { ) } + // A checker marks lines all over a file. Each one below the window would cost a layout call per draw, and the + // debug switch the suite runs with throws past eight of them. + @Test + fun decorationsBelowTheWindowCostNoLayoutCall() { + launch().use { s -> + val editor = s.editor() + onMain { + editor.setInitialText(List(200) { "line $it" }.joinToString("\n")) + layout(editor) + draw(editor) + val doc = editor.core.document + val items = (100 until 106).flatMap { line -> + listOf(Underline(doc.lineStart(line), doc.lineStart(line) + 4, red, UnderlineStyle.Solid, 2f, 4f), LineBackground(line, tint)) + } + editor.setDecorations(items, -1) + draw(editor) + } + } + } + @Test fun solidUnderlineSitsOffsetBelowTheBaseline() { launch().use { s -> diff --git a/example/android/app/src/androidTest/java/codepad/example/InputConnectionTest.kt b/example/android/app/src/androidTest/java/codepad/example/InputConnectionTest.kt index f4e5edd7..8024180e 100644 --- a/example/android/app/src/androidTest/java/codepad/example/InputConnectionTest.kt +++ b/example/android/app/src/androidTest/java/codepad/example/InputConnectionTest.kt @@ -110,6 +110,27 @@ class InputConnectionTest { } } + // The layout lives as long as the core. A dropped view still in the window relays out on a keyboard edit that + // widens the gutter, and draws, until it leaves. + @Test + fun aDroppedViewStillDrawsUntilItLeavesTheWindow() { + launch().use { s -> + val editor = s.editor() + onMain { + editor.setInitialText("abc") + layout(editor) + draw(editor) + editor.requestFocus() + val connection = checkNotNull(editor.onCreateInputConnection(EditorInfo())) + editor.close() + assertTrue(connection.commitText("\n".repeat(9), 1)) + draw(editor) + (editor.parent as ViewGroup).removeView(editor) + assertFalse(connection.commitText("x", 1)) + } + } + } + // A keyboard call queued before the dropped view left the window runs after its core was freed. @Test fun aKeyboardCallAfterTheCoreIsFreedDoesNothing() { diff --git a/ios/Codepad/core/EditorFrame.swift b/ios/Codepad/core/EditorFrame.swift index eeb62072..c1f282ad 100644 --- a/ios/Codepad/core/EditorFrame.swift +++ b/ios/Codepad/core/EditorFrame.swift @@ -60,84 +60,46 @@ final class FrameReader { self.units = [UInt16](repeating: 0, count: max(units, 1)) } - /// The draw's frame: the layout picks the lines, `pairs` holds (line, revision) for each cached line. - func read( - core: EditorCore, layout: Viewport, snapshot: Snapshot?, applied: Int, useChanged: Bool, pairs: [Int32] - ) -> EditorFrame { - while true { - var textLength: UInt32 = 0 - let needed = callLayout(core, layout, snapshot, applied, useChanged, pairs, &textLength) - let fits = Int(needed) <= ints.count && Int(textLength) <= units.count - if fits { return decode(nil) } - if Int(needed) > ints.count { ints = [Int32](repeating: 0, count: Int(needed)) } - if Int(textLength) > units.count { units = [UInt16](repeating: 0, count: Int(textLength)) } - } - } + /// One frame call's buffers: the ints, their capacity, the text units, their capacity and the text length out. + typealias Call = ( + UnsafeMutablePointer?, UInt32, UnsafeMutablePointer?, UInt32, UnsafeMutablePointer + ) -> UInt32 - /// A frame of lines [first, last], with one entry per line. + /// The draw's frame: the layout picks the lines, `pairs` holds (line, revision) for each cached line in any order. func read( - core: EditorCore, snapshot: Snapshot?, first: Int, last: Int, applied: Int, useChanged: Bool, entries: [Int32] + core: EditorCore, layout: Viewport, snapshot: Snapshot?, applied: Int, useChanged: Bool, pairs: [Int32] ) -> EditorFrame { - while true { - var textLength: UInt32 = 0 - let needed = call(core, snapshot, first, last, applied, useChanged, entries, &textLength) - let fits = Int(needed) <= ints.count && Int(textLength) <= units.count - if fits { return decode((first, last)) } - if Int(needed) > ints.count { ints = [Int32](repeating: 0, count: Int(needed)) } - if Int(textLength) > units.count { units = [UInt16](repeating: 0, count: Int(textLength)) } - } - } - - private func callLayout( - _ core: EditorCore, _ layout: Viewport, _ snapshot: Snapshot?, _ applied: Int, _ useChanged: Bool, - _ pairs: [Int32], _ textLength: inout UInt32 - ) -> UInt32 { let handle: OpaquePointer = core.document.handle let layoutHandle: OpaquePointer = layout.handle let snap: OpaquePointer? = snapshot?.pointer let appliedRevision = Int32(clamping: applied) let changed: Int32 = useChanged ? 1 : 0 let pairCount = UInt32(pairs.count / 2) - var length: UInt32 = 0 - let needed: UInt32 = pairs.withUnsafeBufferPointer { p in - ints.withUnsafeMutableBufferPointer { o in - units.withUnsafeMutableBufferPointer { t in - let intCap = UInt32(o.count) - let textCap = UInt32(t.count) - return cp_editor_frame( - handle, layoutHandle, snap, appliedRevision, changed, p.baseAddress, pairCount, o.baseAddress, intCap, - t.baseAddress, textCap, &length) - } + return read(window: nil) { out, cap, text, textCap, length in + pairs.withUnsafeBufferPointer { p in + cp_editor_frame( + handle, layoutHandle, snap, appliedRevision, changed, p.baseAddress, pairCount, out, cap, text, textCap, + length) } } - textLength = length - return needed } - private func call( - _ core: EditorCore, _ snapshot: Snapshot?, _ first: Int, _ last: Int, _ applied: Int, _ useChanged: Bool, - _ entries: [Int32], _ textLength: inout UInt32 - ) -> UInt32 { - let handle: OpaquePointer = core.document.handle - let snap: OpaquePointer? = snapshot?.pointer - let firstLine = Int32(clamping: first) - let lastLine = Int32(clamping: last) - let appliedRevision = Int32(clamping: applied) - let changed: Int32 = useChanged ? 1 : 0 - var length: UInt32 = 0 - let needed: UInt32 = entries.withUnsafeBufferPointer { e in - ints.withUnsafeMutableBufferPointer { o in + /// Makes `call` until both buffers fit, then decodes. `window` is the range a range call asked for. + func read(window: (Int, Int)?, _ call: Call) -> EditorFrame { + while true { + var textLength: UInt32 = 0 + let needed: UInt32 = ints.withUnsafeMutableBufferPointer { o in units.withUnsafeMutableBufferPointer { t in let intCap = UInt32(o.count) let textCap = UInt32(t.count) - return cp_editor_frame_range( - handle, snap, firstLine, lastLine, appliedRevision, changed, e.baseAddress, o.baseAddress, intCap, - t.baseAddress, textCap, &length) + return call(o.baseAddress, intCap, t.baseAddress, textCap, &textLength) } } + let fits = Int(needed) <= ints.count && Int(textLength) <= units.count + if fits { return decode(window) } + if Int(needed) > ints.count { ints = [Int32](repeating: 0, count: Int(needed)) } + if Int(textLength) > units.count { units = [UInt16](repeating: 0, count: Int(textLength)) } } - textLength = length - return needed } /// `window` is the range a range call asked for. The layout's call writes its own after the header. diff --git a/tests/swift/CoreLayoutTests.swift b/tests/swift/CoreLayoutTests.swift index db52c848..bef486c5 100644 --- a/tests/swift/CoreLayoutTests.swift +++ b/tests/swift/CoreLayoutTests.swift @@ -56,6 +56,20 @@ final class CoreLayoutTests: XCTestCase { XCTAssertEqual(Array(out[6...10]), [1, 1, 1, 1, 1]) } + // A fling frame makes one scroll call and learns from it which edge it reached, for the edge glow. + func testScrollToReportsEachAxisThatMoved() { + let core = EditorCore((0..<20).map { _ in String(repeating: "x", count: 30) }.joined(separator: "\n")) + let viewport = Viewport() + viewport.attach(core) + viewport.rowHeight = 10 + viewport.resize(width: 100, height: 50) + viewport.widestLine = 300 + XCTAssertEqual(cp_layout_scroll_to(viewport.handle, 0, 0, nil), 0) + XCTAssertEqual(cp_layout_scroll_to(viewport.handle, 40, 0, nil), 1) + XCTAssertEqual(cp_layout_scroll_to(viewport.handle, 40, 30, nil), 2) + XCTAssertEqual(cp_layout_scroll_to(viewport.handle, 0, 0, nil), 3) + } + // onGapLayout publishes every gap on each draw, the ones off screen too, so the measure call carries them all. func testMeasureWritesEveryGapAfterTheRows() { let core = EditorCore((0..<20).map { _ in "x" }.joined(separator: "\n")) diff --git a/tests/swift/FrameTests.swift b/tests/swift/FrameTests.swift index 15d25896..5a3a30c2 100644 --- a/tests/swift/FrameTests.swift +++ b/tests/swift/FrameTests.swift @@ -4,6 +4,26 @@ import XCTest @testable import Codepad +extension FrameReader { + /// A frame of lines [first, last] with one entry per line, through the test hook. + func read( + core: EditorCore, snapshot: Snapshot?, first: Int, last: Int, applied: Int, useChanged: Bool, entries: [Int32] + ) -> EditorFrame { + let handle: OpaquePointer = core.document.handle + let snap: OpaquePointer? = snapshot?.pointer + let firstLine = Int32(clamping: first) + let lastLine = Int32(clamping: last) + let appliedRevision = Int32(clamping: applied) + let changed: Int32 = useChanged ? 1 : 0 + return read(window: (first, last)) { out, cap, text, textCap, length in + entries.withUnsafeBufferPointer { e in + cp_test_frame_range( + handle, snap, firstLine, lastLine, appliedRevision, changed, e.baseAddress, out, cap, text, textCap, length) + } + } + } +} + final class FrameTests: XCTestCase { private struct SplitMix: RandomNumberGenerator { var state: UInt64 From 1bb2c7ff8c5ce8588d6fff759900d54041492dd7 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 14:54:06 +0100 Subject: [PATCH 08/21] docs: describe the layout in the core and the two calls per draw --- website/docs/internals/architecture.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/website/docs/internals/architecture.md b/website/docs/internals/architecture.md index 2b183957..98115b5e 100644 --- a/website/docs/internals/architecture.md +++ b/website/docs/internals/architecture.md @@ -4,7 +4,7 @@ description: The shared C++ core, the platform layers and threads, the tree-sitt sidebar_position: 1 --- -The editor engine is one C++ core under `cpp/core`, shared by Android and iOS. It holds the document, the selection, undo, the editing commands, decorations, search and the tree-sitter parsing, behind a C API that Kotlin calls through JNI and Swift calls directly. Each platform keeps its own view, layout, input and drawing, in Kotlin and in Swift, with the same layers and the same names, and it is bound to React Native through Nitro Views. The TypeScript wrapper, the core, the tree-sitter runtime, the grammars and the test vectors are shared. +The editor engine is one C++ core under `cpp/core`, shared by Android and iOS. It holds the document, the selection, undo, the editing commands, decorations, search, the tree-sitter parsing and the rows and scroll of the layout, behind a C API that Kotlin calls through JNI and Swift calls directly. Each platform keeps its own view, line layout, input and drawing, in Kotlin and in Swift, with the same layers and the same names, and it is bound to React Native through Nitro Views. The TypeScript wrapper, the core, the tree-sitter runtime, the grammars and the test vectors are shared. ## Why an own engine @@ -19,7 +19,7 @@ Under `me.sectiontn.codepad` in `android/src/main/java`: | `core` | `EditorCore`, `Document`, `UndoManager`, `DecorationSet`, `TextMovement`, `Searcher` and `EditorFrame`, thin Kotlin facades over the C++ core. | `CoreNative` | | `input` | `ImeSession`, the keyboard protocol, and `KeyCommands`, the hardware key table. | core | | `syntax` | `SyntaxEngine` and its thread, `CoreNative`, the JNI binding to the C++ core, `LanguageRegistry`, `Highlighter`, the per line span cache. | core | -| `layout` | `LineLayout` over `StaticLayout`, `HeightMap`, `LayoutCache`, `Viewport`, `CaretMover`, `GutterMetrics`. | core, syntax | +| `layout` | `LineLayout` over `StaticLayout`, `LayoutCache`, `Viewport` (the facade over the core's layout), `CaretMover`, `GutterMetrics`. | core, syntax | | `view` | `CodeEditorView`: drawing, gestures, scrolling, the input connection, handles, the edit menu, the keyboard inset tracker. | every layer before it | | `com.margelo.nitro.codepad` | `HybridCodeEditorView` and `HybridCodepad`, the Nitro layer. | view | @@ -27,7 +27,7 @@ The core runs `tests/vectors/*.json` on the JVM and under `swift test`. The keyb ### `core` -The document is immutable UTF-16 text in shared chunks, plus a table of line starts. An edit builds a new text that shares every chunk outside the edited range. A parse or a reader on another thread goes on reading the version it started with, and an edit copies only the chunks it changes. `\r\n` and a `\r` on its own become `\n` on load. One replacement is the only mutation. The main thread prepares it outside the lock and commits it under the exclusive lock. A draw reads everything it needs in one call, `cp_editor_frame`: the selection, the visible lines' starts, and the lines to lay out with their spans and text. Undo groups hold the inverse changes plus the selection before and after. Single character typing merges into the previous group when it is adjacent, within a second and not a newline. API edits never merge with typing. +The document is immutable UTF-16 text in shared chunks, plus a table of line starts. An edit builds a new text that shares every chunk outside the edited range. A parse or a reader on another thread goes on reading the version it started with, and an edit copies only the chunks it changes. `\r\n` and a `\r` on its own become `\n` on load. One replacement is the only mutation. The main thread prepares it outside the lock and commits it under the exclusive lock. A draw reads the document in one call, `cp_editor_frame`: the core's layout picks the visible lines, and the call returns the selection, their starts, and the lines to lay out with their spans and text. Undo groups hold the inverse changes plus the selection before and after. Single character typing merges into the previous group when it is adjacent, within a second and not a newline. API edits never merge with typing. ### `syntax` @@ -37,7 +37,7 @@ The main thread queries the published snapshot for the visible lines only and ca ### `layout` -`LineLayout` turns a line into a `StaticLayout` at the wrap width. The row height is uniform, `round(fontSize * lineHeight)`, so a fallback font for emoji or CJK never changes it. `HeightMap` stores a row count per line, with unmeasured lines counting as one. `LayoutCache` is an LRU around the viewport. Only a wrap width change drops it, and the scroll is then re-anchored to the top visible line. +`LineLayout` turns a line into a `StaticLayout` at the wrap width. The row height is uniform, `round(fontSize * lineHeight)`, so a fallback font for emoji or CJK never changes it. The core's layout stores a row count per line, with unmeasured lines counting as one, the gap rows under decorated lines, and the scroll. Edits update the rows inside the core before the change callback runs. `Viewport` is the facade over it. Once the view has laid out the frame's lines, one more call, `cp_layout_measure`, records their row counts and the widest line. It returns the view top of each visible line, their rows and every gap, and the painters read that copy until the draw ends. A draw makes these two core calls, and a fling frame makes one scroll call. `LayoutCache` is an LRU around the viewport. Only a wrap width change drops it, and the scroll is then re-anchored to the top visible line. ### `view` From d1e9d452b0ed2b2ef511eb3eb7a89f7e32a76164 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 15:25:16 +0100 Subject: [PATCH 09/21] fix: read no top of the last draw before the measure call The sentinel for a draw without tops still let its first line read the previous draw's top, so a reveal before the measure call placed the caret row off by the scroll since then. --- .../me/sectiontn/codepad/layout/Viewport.kt | 4 +++- .../sectiontn/codepad/layout/ViewportTest.kt | 22 +++++++++++++++++++ ios/Codepad/layout/Viewport.swift | 2 +- tests/swift/CoreLayoutTests.swift | 16 ++++++++++++++ 4 files changed, 42 insertions(+), 2 deletions(-) diff --git a/android/src/main/java/me/sectiontn/codepad/layout/Viewport.kt b/android/src/main/java/me/sectiontn/codepad/layout/Viewport.kt index ae9f76c2..710b2a46 100644 --- a/android/src/main/java/me/sectiontn/codepad/layout/Viewport.kt +++ b/android/src/main/java/me/sectiontn/codepad/layout/Viewport.kt @@ -332,7 +332,9 @@ class Viewport { configKnown = true } - private fun drawnTop(line: Int): Int? = if (cached && line >= first && line <= last + 1) buffer[line - first] else null + // last < first means this draw has no tops yet, or lost them to a scroll move. + private fun drawnTop(line: Int): Int? = + if (cached && last >= first && line >= first && line <= last + 1) buffer[line - first] else null private fun field(i: Int): Int { if (!cached) geometry() diff --git a/android/src/test/java/me/sectiontn/codepad/layout/ViewportTest.kt b/android/src/test/java/me/sectiontn/codepad/layout/ViewportTest.kt index 73da7388..0559a5db 100644 --- a/android/src/test/java/me/sectiontn/codepad/layout/ViewportTest.kt +++ b/android/src/test/java/me/sectiontn/codepad/layout/ViewportTest.kt @@ -64,6 +64,28 @@ class ViewportTest { } } + // A draw reveals the caret before its measure call, when its copy has no tops yet. Reading the last draw's top there + // puts the caret row off by the scroll since then, and the reveal jumps or misses. + @Test + fun aReadBeforeTheMeasureCallIgnoresTheLastDrawsTops() { + lines(100).use { core -> + val v = Viewport() + v.attach(core) + v.rowHeight = 10 + v.resize(100, 50) + v.scrollTo(0, 100) + v.beginDraw(checksCalls = false) + v.measure(IntArray(0), 0, -1, 10, 16) + v.endDraw() + v.scrollTo(0, 300) + v.beginDraw(checksCalls = false) + v.measured(10, 1) + assertEquals(10, v.rowStart(10)) + v.endDraw() + v.close() + } + } + // With the debug switch on, a ninth single layout call in one draw throws: a per-line crossing crept into the draw. @Test fun aNinthCallInsideADrawThrowsInDebug() { diff --git a/ios/Codepad/layout/Viewport.swift b/ios/Codepad/layout/Viewport.swift index 38826a80..48aa8d6d 100644 --- a/ios/Codepad/layout/Viewport.swift +++ b/ios/Codepad/layout/Viewport.swift @@ -314,7 +314,7 @@ final class Viewport { } private func drawnTop(_ line: Int) -> Int? { - cached && line >= first && line <= last + 1 ? Int(buffer[line - first]) : nil + cached && last >= first && line >= first && line <= last + 1 ? Int(buffer[line - first]) : nil } private static func parseGaps(_ ints: ArraySlice, from start: Int) -> [Gap] { diff --git a/tests/swift/CoreLayoutTests.swift b/tests/swift/CoreLayoutTests.swift index bef486c5..94dffe5b 100644 --- a/tests/swift/CoreLayoutTests.swift +++ b/tests/swift/CoreLayoutTests.swift @@ -70,6 +70,22 @@ final class CoreLayoutTests: XCTestCase { XCTAssertEqual(cp_layout_scroll_to(viewport.handle, 0, 0, nil), 3) } + // A draw reveals the caret before its measure call, when its copy has no tops yet. Reading the last draw's top there + // puts the caret row off by the scroll since then, and the reveal jumps or misses. + func testAReadBeforeTheMeasureCallIgnoresTheLastDrawsTops() { + let core = EditorCore((0..<100).map { "line \($0)" }.joined(separator: "\n")) + let viewport = Viewport() + viewport.attach(core) + viewport.rowHeight = 10 + viewport.resize(width: 100, height: 50) + viewport.beginDraw(scrollX: 0, scrollY: 100) + viewport.measure(pairs: [], widest: -1, first: 10, last: 16) + viewport.endDraw() + viewport.beginDraw(scrollX: 0, scrollY: 300) + XCTAssertEqual(viewport.rowStart(10), 10) + viewport.endDraw() + } + // onGapLayout publishes every gap on each draw, the ones off screen too, so the measure call carries them all. func testMeasureWritesEveryGapAfterTheRows() { let core = EditorCore((0..<20).map { _ in "x" }.joined(separator: "\n")) From f9f9c82acb83f58c3cafb62720434da417c2aef1 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 18:28:30 +0100 Subject: [PATCH 10/21] fix(core): clamp the scroll when a measured visible line shrinks A visible line that lost rows at the end of the content left the scroll past the new end, so the view showed blank space until the next scroll. Only lines above the viewport shift the scroll, every row change now clamps it. --- cpp/core/src/layout.cpp | 7 ++++--- tests/vectors/layout.json | 1 + 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/cpp/core/src/layout.cpp b/cpp/core/src/layout.cpp index 401f9f64..b121bc7c 100644 --- a/cpp/core/src/layout.cpp +++ b/cpp/core/src/layout.cpp @@ -222,9 +222,10 @@ void Layout::restore(Anchor anchor) { void Layout::measured(int32_t line, int32_t rows) { int32_t first = first_visible_line(); int32_t old = set_rows(line, rows); - if (old != rows && line < first) { - scroll_y_ = std::clamp(scroll_y_ + (rows - old) * config_.row_height, 0, max_scroll_y()); - } + if (old == rows) return; + if (line < first) scroll_y_ += (rows - old) * config_.row_height; + // A visible line that shrinks can lower the end of the content below the scroll. + scroll_y_ = std::clamp(scroll_y_, 0, max_scroll_y()); } void Layout::geometry(cp_geometry &out) const { diff --git a/tests/vectors/layout.json b/tests/vectors/layout.json index 6c1e4eb5..b5831af9 100644 --- a/tests/vectors/layout.json +++ b/tests/vectors/layout.json @@ -4,6 +4,7 @@ { "name": "unmeasured lines count one row each", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }], "expect": { "widthChanged": true, "totalRows": 20, "rowStart": { "10": 10, "20": 20 }, "content": [100, 200], "maxScroll": [0, 150], "visible": [0, 4] } }, { "name": "a line measured below the viewport leaves the scroll", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "scrollTo", "x": 0, "y": 30, "expect": { "result": true, "scroll": [0, 30], "visible": [3, 7] } }, { "op": "measure", "pairs": [[10, 3]] }], "expect": { "scroll": [0, 30], "totalRows": 22, "rowStart": { "11": 13 }, "content": [100, 220] } }, { "name": "a line measured above the viewport keeps the visible text in place", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "scrollTo", "x": 0, "y": 50, "expect": { "visible": [5, 9], "lineTop": { "5": 0 } } }, { "op": "measure", "pairs": [[2, 3]] }], "expect": { "scroll": [0, 70], "visible": [5, 9], "lineTop": { "5": 0 }, "maxScroll": [0, 170] } }, + { "name": "a visible line that shrinks at the end of the content clamps the scroll", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": true }, { "op": "measure", "pairs": [[19, 10]] }, { "op": "scrollTo", "x": 0, "y": 1000, "expect": { "scroll": [0, 240], "maxScroll": [0, 240] } }, { "op": "measure", "pairs": [[19, 1]] }], "expect": { "scroll": [0, 150], "maxScroll": [0, 150], "totalRows": 20 } }, { "name": "a batch with a growth above and a shrink at the first visible line keeps that line in place", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "measure", "pairs": [[5, 3]] }, { "op": "scrollTo", "x": 0, "y": 50, "expect": { "visible": [5, 7], "lineTop": { "5": 0 } } }, { "op": "measure", "pairs": [[2, 2], [5, 1]] }], "expect": { "scroll": [0, 60], "lineTop": { "5": 0 }, "totalRows": 21, "content": [100, 210], "maxScroll": [0, 160] } }, { "name": "gap rows sit beside wrap rows", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": true }, { "op": "decorate", "items": [{ "kind": "gap", "line": 3, "rows": 2 }] }, { "op": "measure", "pairs": [[3, 2]] }], "expect": { "rowStart": { "3": 3, "4": 7 }, "isGapRow": { "3": false, "4": false, "5": true, "6": true, "7": false }, "totalRows": 23 } }, { "name": "a new decoration set replaces the gaps", "text": "x\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx", "ops": [{ "op": "layout", "rowHeight": 10, "width": 100, "height": 50, "insets": [0, 0, 0, 0], "gutter": 0, "padding": 0, "wrap": false }, { "op": "decorate", "items": [{ "kind": "gap", "line": 2, "rows": 2 }], "expect": { "totalRows": 22 } }, { "op": "decorate", "items": [{ "kind": "gap", "line": 5, "rows": 1 }] }], "expect": { "totalRows": 21, "rowStart": { "3": 3, "6": 7 }, "isGapRow": { "3": false, "6": true } } }, From 7d4f7f8e91e8be8a9e2bc16afed5ae3b282d412f Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 18:28:31 +0100 Subject: [PATCH 11/21] fix: keep the frame's cached layouts through a draw's inserts Each run line laid out in a draw evicts the oldest layout. Since the frame call stopped reading the cache line by line, the frame's own lines were not refreshed first, so after a jump back to the old end of the cache a frame line could be evicted before the draw reached it and stay blank for that draw. --- .../sectiontn/codepad/view/CodeEditorView.kt | 2 ++ example/ios/CodepadTests/ScrollTests.swift | 25 +++++++++++++++++++ ios/Codepad/view/CodeEditorView.swift | 6 +++-- 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt index ef0f2c70..4070b265 100644 --- a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt +++ b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt @@ -1355,6 +1355,8 @@ class CodeEditorView(context: Context) : View(context) { var count = 0 var widest = -1 var r = 0 + // A run line's insert evicts the oldest layout, which must not be a frame line the loop has not reached yet. + for (line in frame.first..frame.last) cache[line] // The spans and text of the run lines arrive in line order, one entry per line. var next = 0 for (line in frame.first..frame.last) { diff --git a/example/ios/CodepadTests/ScrollTests.swift b/example/ios/CodepadTests/ScrollTests.swift index 3a1f5a24..4dd4b9b1 100644 --- a/example/ios/CodepadTests/ScrollTests.swift +++ b/example/ios/CodepadTests/ScrollTests.swift @@ -19,4 +19,29 @@ final class ScrollTests: XCTestCase { draw(editor) XCTAssertEqual(editor.latestFrame.scrollX, before, accuracy: 0.5, "scrollX after the inset change") } + + // A draw that lays out new lines evicts the oldest layouts. After a jump back to the old end of the cache, the + // frame's own cached lines must not be evicted before the draw reaches them, or they stay blank. + func testAJumpBackKeepsTheFramesCachedLines() { + let editor = launch() + editor.setInitialText((0..<3000).map { "line \($0)" }.joined(separator: "\n")) + layout(editor) + draw(editor) + let rowHeight = CGFloat(editor.viewport.rowHeight) + let span = editor.viewport.lastVisibleLine() - editor.viewport.firstVisibleLine() + var top = 0 + while top < 3 * editor.cache.capacity { + top += span + editor.contentOffset.y = CGFloat(top) * rowHeight + draw(editor) + } + var oldest = Int.max + editor.cache.forEachEntry { line, _ in oldest = min(oldest, line) } + editor.contentOffset.y = CGFloat(oldest - span / 2) * rowHeight + draw(editor) + var cached = Set() + editor.cache.forEachEntry { line, _ in cached.insert(line) } + let frame = editor.viewport.firstVisibleLine()...editor.viewport.lastVisibleLine() + XCTAssertEqual(frame.filter { !cached.contains($0) }, [], "frame \(frame), oldest cached before the jump \(oldest)") + } } diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index 31e0b74c..675a4359 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -7,7 +7,7 @@ import os @MainActor final class CodeEditorView: UIScrollView { /// revision is the snapshot the spans came from, -1 when the line was laid out plain. - private final class Entry { + final class Entry { let id: Int let layout: LineLayout let spans: [Int]? @@ -109,7 +109,7 @@ final class CodeEditorView: UIScrollView { // Set from the frame call to the end of publish. private var drawFrame: EditorFrame? let viewport = Viewport() - private let cache = LayoutCache(capacity: 64) + let cache = LayoutCache(capacity: 64) private var nextEntryId = 0 private var brackets: BracketHighlight private lazy var geometry = ContentGeometry(self) @@ -1008,6 +1008,8 @@ final class CodeEditorView: UIScrollView { widest = max(widest, offeredWidth(layout)) } var r = 0 + // A run line's insert evicts the oldest layout, which must not be a frame line the loop has not reached yet. + for line in frame.first...frame.last { _ = cache[line] } // The spans and text of the run lines arrive in line order, one entry per line. var next = 0 for line in frame.first...frame.last { From df39dea4ef3458fd2941272d7a1749c8d763cd81 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 18:59:10 +0100 Subject: [PATCH 12/21] fix: lay out the lines a clamp in the measure call shows When a visible line lost rows at the end of the content, the measure call clamped the scroll and lines above the frame came into view with no layout. Android drew them blank until the next invalidate. The draw now takes the frame again in that case, on both platforms. --- .../sectiontn/codepad/view/CodeEditorView.kt | 9 ++++++++- example/ios/CodepadTests/ScrollTests.swift | 18 ++++++++++++++++++ ios/Codepad/view/CodeEditorView.swift | 12 ++++++++++-- 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt index 4070b265..e923c63c 100644 --- a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt +++ b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt @@ -1269,10 +1269,17 @@ class CodeEditorView(context: Context) : View(context) { revealSelection() } // One core call for the document. Until publish returns, every document read comes from it. - val f = readFrame() + var f = readFrame() drawFrame = f if (debugSwitch()) core.document.drawingThread = Thread.currentThread() prepare(f, m) + // A measure call that clamps the scroll (a visible line lost rows at the end) shows lines above the frame. They + // are laid out in this draw too, so none of them shows blank. + if (viewport.firstVisibleLine() < f.first) { + f = readFrame() + drawFrame = f + prepare(f, m) + } val firstLine = f.first val lastBound = f.last val caretLine = f.caretLine diff --git a/example/ios/CodepadTests/ScrollTests.swift b/example/ios/CodepadTests/ScrollTests.swift index 4dd4b9b1..edf4e3eb 100644 --- a/example/ios/CodepadTests/ScrollTests.swift +++ b/example/ios/CodepadTests/ScrollTests.swift @@ -44,4 +44,22 @@ final class ScrollTests: XCTestCase { let frame = editor.viewport.firstVisibleLine()...editor.viewport.lastVisibleLine() XCTAssertEqual(frame.filter { !cached.contains($0) }, [], "frame \(frame), oldest cached before the jump \(oldest)") } + + // A measure call that lowers the end of the content clamps the scroll and shows lines above the draw's frame. The + // same draw lays them out, so none of them shows blank. + func testAClampInTheMeasureCallLaysOutTheLinesItShows() { + let editor = launch() + editor.setInitialText((0..<100).map { "line \($0)" }.joined(separator: "\n")) + layout(editor) + draw(editor) + // The core holds 30 rows for the last line, its layout will have one. + editor.viewport.measured(99, 30) + editor.contentOffset.y = CGFloat(editor.viewport.maxScrollY) + editor.setNeedsLayout() + editor.layoutIfNeeded() + var cached = Set() + editor.cache.forEachEntry { line, _ in cached.insert(line) } + let frame = editor.viewport.firstVisibleLine()...editor.viewport.lastVisibleLine() + XCTAssertEqual(frame.filter { !cached.contains($0) }, [], "frame \(frame)") + } } diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index 675a4359..f4cfd24e 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -662,12 +662,20 @@ final class CodeEditorView: UIScrollView { revealPending = false revealSelection() } - let frame = readFrame() + var frame = readFrame() drawFrame = frame core.document.drawing = true + var moved = prepare(frame, m) + // A measure call that clamps the scroll (a visible line lost rows at the end) shows lines above the frame. They + // are laid out in this draw too, so none of them shows blank. + if viewport.firstVisibleLine() < frame.first { + frame = readFrame() + drawFrame = frame + if prepare(frame, m) { moved = true } + } let first = frame.first let lastBound = frame.last - if prepare(frame, m) { pushScroll() } else { updateContentSize() } + if moved { pushScroll() } else { updateContentSize() } let caretLine = frame.caretLine let lastLine = placeLayers(first, lastBound, m) placeGutter(first, lastLine, caretLine) From a293bfeac37995749b24b1dcb756d553f201888b Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 19:00:29 +0100 Subject: [PATCH 13/21] fix(ios): move the scroll view when an edit clamps the core scroll An edit that shortened the content under the offset clamped the core scroll but left contentOffset where it was. The next draw's clamp then saw no move, so the layers and UIKit used different offsets. --- example/ios/CodepadTests/ScrollTests.swift | 15 +++++++++++++++ ios/Codepad/view/CodeEditorView.swift | 8 +++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/example/ios/CodepadTests/ScrollTests.swift b/example/ios/CodepadTests/ScrollTests.swift index edf4e3eb..831c6cea 100644 --- a/example/ios/CodepadTests/ScrollTests.swift +++ b/example/ios/CodepadTests/ScrollTests.swift @@ -62,4 +62,19 @@ final class ScrollTests: XCTestCase { let frame = editor.viewport.firstVisibleLine()...editor.viewport.lastVisibleLine() XCTAssertEqual(frame.filter { !cached.contains($0) }, [], "frame \(frame)") } + + // An API edit that removes the lines under the offset clamps the core scroll. The scroll view must take it, or the + // layers paint at one offset while UIKit scrolls at another. + func testAnEditThatShortensTheContentUnderTheOffsetMovesIt() { + let editor = launch() + editor.setInitialText((0..<200).map { "line \($0)" }.joined(separator: "\n")) + layout(editor) + draw(editor) + editor.contentOffset.y = CGFloat(editor.viewport.maxScrollY) + draw(editor) + _ = editor.core.replace(editor.core.document.lineStart(20), editor.core.document.length, "") + draw(editor) + XCTAssertEqual(editor.contentOffset.y, CGFloat(editor.viewport.scrollY)) + XCTAssertLessThanOrEqual(editor.viewport.scrollY, editor.viewport.maxScrollY) + } } diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index f4cfd24e..d3e4155b 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -764,7 +764,13 @@ final class CodeEditorView: UIScrollView { textInput.cursorView.resetBlinkAnimation() textInput.menu.hide() selectionViewsDirty = true - updateContentSize() + // An edit that shortens the content under the offset clamped the core scroll. The scroll view takes it here, + // since the next draw's clamp would see no move. + if contentOffset.y > CGFloat(viewport.maxScrollY) || contentOffset.x > CGFloat(viewport.maxScrollX) { + pushScroll() + } else { + updateContentSize() + } setNeedsLayout() onChange?(change, origin) onChangeText?(doc.text()) From d360beeebba49d165c0a00596a3eda3a226ed1ba Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 19:00:30 +0100 Subject: [PATCH 14/21] docs(core): note that the caller clamps after a config or widest change --- cpp/core/include/codepad.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cpp/core/include/codepad.h b/cpp/core/include/codepad.h index 62bc0103..006efd3b 100644 --- a/cpp/core/include/codepad.h +++ b/cpp/core/include/codepad.h @@ -211,7 +211,8 @@ CP_API void cp_layout_free(cp_layout *layout); // Resets the rows to the editor's lines and takes its gaps. Every later edit and gap change of the editor updates // the rows before the change callback runs. NULL detaches. CP_API void cp_editor_attach_layout(cp_editor *editor, cp_layout *layout); -// Returns 1 when the text area width changed, which is when line layouts must be rebuilt. +// Returns 1 when the text area width changed, which is when line layouts must be rebuilt. The scroll is left as it +// is: follow with cp_layout_scroll_to or cp_layout_restore, which clamp it and say whether it moved. CP_API int32_t cp_layout_configure(cp_layout *layout, const cp_layout_config *config); CP_API void cp_layout_geometry(const cp_layout *layout, cp_geometry *out); // Clamps and applies. Returns 1 when x moved, 2 when y moved, 3 when both did. out may be NULL. @@ -226,6 +227,7 @@ CP_API int32_t cp_layout_reveal(cp_layout *layout, int32_t left, int32_t top, in CP_API uint32_t cp_layout_measure(cp_layout *layout, const int32_t *pairs, uint32_t pair_count, int32_t widest, int32_t first_line, int32_t last_line, cp_geometry *out, int32_t *tops_rows, uint32_t cap); +// Leaves the scroll as it is, like cp_layout_configure. CP_API void cp_layout_set_widest(cp_layout *layout, int32_t widest); // Rows of a line outside the layout are 0. CP_API int32_t cp_layout_rows(const cp_layout *layout, int32_t line); @@ -242,7 +244,7 @@ CP_API int32_t cp_layout_row_at(const cp_layout *layout, int32_t y); CP_API void cp_layout_anchor(const cp_layout *layout, int32_t *line, int32_t *offset); // Returns 1 when the scroll moved. CP_API int32_t cp_layout_restore(cp_layout *layout, int32_t line, int32_t offset); -// Every line back to one row. Gaps stay. +// Every line back to one row. Gaps stay. The scroll is left as it is, for cp_layout_restore. CP_API void cp_layout_reset_rows(cp_layout *layout); // Search, a PCRE2 regex or plain text, in Unicode mode with any newline ending a line. Empty matches are skipped. From 066d8101ec34c24e32c1709de6869be4f2203470 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 19:00:30 +0100 Subject: [PATCH 15/21] test: measure a batch with a growth above and a shrink at the top --- tests/swift/CoreLayoutTests.swift | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/swift/CoreLayoutTests.swift b/tests/swift/CoreLayoutTests.swift index 94dffe5b..837b5081 100644 --- a/tests/swift/CoreLayoutTests.swift +++ b/tests/swift/CoreLayoutTests.swift @@ -56,6 +56,22 @@ final class CoreLayoutTests: XCTestCase { XCTAssertEqual(Array(out[6...10]), [1, 1, 1, 1, 1]) } + // The draw measures through the batch entry point, the vectors one pair at a time. A growth above and a shrink at + // the first visible line in one batch keep that line in place. + func testABatchWithAGrowthAboveAndAShrinkAtTheTopKeepsTheTopLine() { + let core = EditorCore((0..<20).map { _ in "x" }.joined(separator: "\n")) + let viewport = Viewport() + viewport.attach(core) + viewport.rowHeight = 10 + viewport.resize(width: 100, height: 50) + viewport.measured(5, 3) + viewport.beginDraw(scrollX: 0, scrollY: 50) + XCTAssertTrue(viewport.measure(pairs: [2, 2, 5, 1], widest: -1, first: 5, last: 9)) + XCTAssertEqual(viewport.scrollY, 60) + XCTAssertEqual(viewport.lineTop(5), 0) + viewport.endDraw() + } + // A fling frame makes one scroll call and learns from it which edge it reached, for the edge glow. func testScrollToReportsEachAxisThatMoved() { let core = EditorCore((0..<20).map { _ in String(repeating: "x", count: 30) }.joined(separator: "\n")) From 2d05742e007ec730f74f3844ac4764487baf207e Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 19:19:14 +0100 Subject: [PATCH 16/21] fix: keep taking the frame until it reaches the first visible line The lines a clamp in the measure call shows get their own measure call, and when one of them had stale rows that call clamps again. A single extra frame read then left the lines it showed blank. --- .../main/java/me/sectiontn/codepad/view/CodeEditorView.kt | 6 +++--- example/ios/CodepadTests/ScrollTests.swift | 7 ++++--- ios/Codepad/view/CodeEditorView.swift | 6 +++--- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt index e923c63c..b7690d60 100644 --- a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt +++ b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt @@ -1273,9 +1273,9 @@ class CodeEditorView(context: Context) : View(context) { drawFrame = f if (debugSwitch()) core.document.drawingThread = Thread.currentThread() prepare(f, m) - // A measure call that clamps the scroll (a visible line lost rows at the end) shows lines above the frame. They - // are laid out in this draw too, so none of them shows blank. - if (viewport.firstVisibleLine() < f.first) { + // A measure call that clamps the scroll (a visible line lost rows at the end) shows lines above the frame, and + // their own measure call can clamp again. They are laid out in this draw, so none of them shows blank. + while (viewport.firstVisibleLine() < f.first) { f = readFrame() drawFrame = f prepare(f, m) diff --git a/example/ios/CodepadTests/ScrollTests.swift b/example/ios/CodepadTests/ScrollTests.swift index 831c6cea..3573203a 100644 --- a/example/ios/CodepadTests/ScrollTests.swift +++ b/example/ios/CodepadTests/ScrollTests.swift @@ -45,14 +45,15 @@ final class ScrollTests: XCTestCase { XCTAssertEqual(frame.filter { !cached.contains($0) }, [], "frame \(frame), oldest cached before the jump \(oldest)") } - // A measure call that lowers the end of the content clamps the scroll and shows lines above the draw's frame. The - // same draw lays them out, so none of them shows blank. + // A measure call that lowers the end of the content clamps the scroll and shows lines above the draw's frame, and + // their measure call can clamp again. The same draw lays them all out, so none of them shows blank. func testAClampInTheMeasureCallLaysOutTheLinesItShows() { let editor = launch() editor.setInitialText((0..<100).map { "line \($0)" }.joined(separator: "\n")) layout(editor) draw(editor) - // The core holds 30 rows for the last line, its layout will have one. + // The core holds 30 rows for each of the last two lines, their layouts will have one. + editor.viewport.measured(98, 30) editor.viewport.measured(99, 30) editor.contentOffset.y = CGFloat(editor.viewport.maxScrollY) editor.setNeedsLayout() diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index d3e4155b..436e91c6 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -666,9 +666,9 @@ final class CodeEditorView: UIScrollView { drawFrame = frame core.document.drawing = true var moved = prepare(frame, m) - // A measure call that clamps the scroll (a visible line lost rows at the end) shows lines above the frame. They - // are laid out in this draw too, so none of them shows blank. - if viewport.firstVisibleLine() < frame.first { + // A measure call that clamps the scroll (a visible line lost rows at the end) shows lines above the frame, and + // their own measure call can clamp again. They are laid out in this draw, so none of them shows blank. + while viewport.firstVisibleLine() < frame.first { frame = readFrame() drawFrame = frame if prepare(frame, m) { moved = true } From cb2dd0174b71239c8a95567014cccde1ffd074a0 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 19:19:15 +0100 Subject: [PATCH 17/21] fix: tell scroll listeners when an edit clamps the scroll An edit that shortened the content under the scroll clamped it in the core, but no scroll event went out, so a host kept the old offset. --- .../sectiontn/codepad/view/CodeEditorView.kt | 2 ++ .../java/codepad/example/ScrollTest.kt | 25 +++++++++++++++++++ example/ios/CodepadTests/ScrollTests.swift | 7 ++++-- ios/Codepad/view/CodeEditorView.swift | 5 ++-- 4 files changed, 35 insertions(+), 4 deletions(-) diff --git a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt index b7690d60..14f762e4 100644 --- a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt +++ b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt @@ -566,6 +566,8 @@ class CodeEditorView(context: Context) : View(context) { cache.shift(first, oldCount, newCount) search?.onChange(change) if (updateGutter()) relayout() + // A clamp the edit made reaches the scroll listener like any other move. + if (viewport.scrollX / density != frame.scrollX || viewport.scrollY / density != frame.scrollY) onScrolled() hideInsertionHandle() menu.hide() restartBlink() diff --git a/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt b/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt index c059c21c..c659adce 100644 --- a/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt +++ b/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt @@ -30,4 +30,29 @@ class ScrollTest { } } } + + // An API edit that removes the lines under the scroll clamps it in the core. The scroll listener must hear of it, + // or the host keeps the old offset. + @Test + fun anEditThatClampsTheScrollReachesTheScrollListener() { + launch().use { s -> + val editor = s.editor() + onMain { + editor.setInitialText((0 until 200).joinToString("\n") { "line $it" }) + layout(editor) + draw(editor) + editor.scrollToLine(199, false) + draw(editor) + val before = editor.frame.scrollY + assertTrue("scrolled to the end, scrollY $before", before > 0f) + var heard = -1f + editor.onScrollListener = { heard = it.scrollY } + val doc = editor.core.document + editor.core.replace(doc.lineStart(20), doc.length, "") + draw(editor) + assertTrue("the edit clamped the scroll, scrollY ${editor.frame.scrollY}", editor.frame.scrollY < before) + assertEquals(editor.frame.scrollY, heard, 0.01f) + } + } + } } diff --git a/example/ios/CodepadTests/ScrollTests.swift b/example/ios/CodepadTests/ScrollTests.swift index 3573203a..4e573cf8 100644 --- a/example/ios/CodepadTests/ScrollTests.swift +++ b/example/ios/CodepadTests/ScrollTests.swift @@ -64,8 +64,8 @@ final class ScrollTests: XCTestCase { XCTAssertEqual(frame.filter { !cached.contains($0) }, [], "frame \(frame)") } - // An API edit that removes the lines under the offset clamps the core scroll. The scroll view must take it, or the - // layers paint at one offset while UIKit scrolls at another. + // An API edit that removes the lines under the offset clamps the core scroll. The scroll view and the scroll + // listener must take it, or the layers paint at one offset while UIKit and the host keep another. func testAnEditThatShortensTheContentUnderTheOffsetMovesIt() { let editor = launch() editor.setInitialText((0..<200).map { "line \($0)" }.joined(separator: "\n")) @@ -73,9 +73,12 @@ final class ScrollTests: XCTestCase { draw(editor) editor.contentOffset.y = CGFloat(editor.viewport.maxScrollY) draw(editor) + var heard: CGFloat? + editor.onScroll = { heard = $0.scrollY } _ = editor.core.replace(editor.core.document.lineStart(20), editor.core.document.length, "") draw(editor) XCTAssertEqual(editor.contentOffset.y, CGFloat(editor.viewport.scrollY)) XCTAssertLessThanOrEqual(editor.viewport.scrollY, editor.viewport.maxScrollY) + XCTAssertEqual(heard, CGFloat(editor.viewport.scrollY)) } } diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index 436e91c6..4dc4181b 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -764,10 +764,11 @@ final class CodeEditorView: UIScrollView { textInput.cursorView.resetBlinkAnimation() textInput.menu.hide() selectionViewsDirty = true - // An edit that shortens the content under the offset clamped the core scroll. The scroll view takes it here, - // since the next draw's clamp would see no move. + // An edit that shortens the content under the offset clamped the core scroll. The scroll view and the scroll + // listener take it here, since the next draw's clamp would see no move. if contentOffset.y > CGFloat(viewport.maxScrollY) || contentOffset.x > CGFloat(viewport.maxScrollX) { pushScroll() + onScrolled() } else { updateContentSize() } From b981d4c785f59b4f8f8c02eac253cb9e98ee5514 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 20:45:15 +0100 Subject: [PATCH 18/21] test(ios): make the scroll tests fail without their fixes The jump test read the cache after a render, whose second layout pass laid the evicted lines out, and it took line 0, which holds the caret, as the oldest entry. The edit test only shortened the content across a gutter change. --- example/ios/CodepadTests/ScrollTests.swift | 25 ++++++++++++++-------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/example/ios/CodepadTests/ScrollTests.swift b/example/ios/CodepadTests/ScrollTests.swift index 4e573cf8..538f279f 100644 --- a/example/ios/CodepadTests/ScrollTests.swift +++ b/example/ios/CodepadTests/ScrollTests.swift @@ -35,10 +35,13 @@ final class ScrollTests: XCTestCase { editor.contentOffset.y = CGFloat(top) * rowHeight draw(editor) } + // Line 0 holds the caret, which every draw lays out, so it stays the newest entry. var oldest = Int.max - editor.cache.forEachEntry { line, _ in oldest = min(oldest, line) } + editor.cache.forEachEntry { line, _ in if line > 0 { oldest = min(oldest, line) } } editor.contentOffset.y = CGFloat(oldest - span / 2) * rowHeight - draw(editor) + // One layout pass: a render can run a second one, which lays the evicted lines out and hides the miss. + editor.setNeedsLayout() + editor.layoutIfNeeded() var cached = Set() editor.cache.forEachEntry { line, _ in cached.insert(line) } let frame = editor.viewport.firstVisibleLine()...editor.viewport.lastVisibleLine() @@ -71,14 +74,18 @@ final class ScrollTests: XCTestCase { editor.setInitialText((0..<200).map { "line \($0)" }.joined(separator: "\n")) layout(editor) draw(editor) - editor.contentOffset.y = CGFloat(editor.viewport.maxScrollY) - draw(editor) var heard: CGFloat? editor.onScroll = { heard = $0.scrollY } - _ = editor.core.replace(editor.core.document.lineStart(20), editor.core.document.length, "") - draw(editor) - XCTAssertEqual(editor.contentOffset.y, CGFloat(editor.viewport.scrollY)) - XCTAssertLessThanOrEqual(editor.viewport.scrollY, editor.viewport.maxScrollY) - XCTAssertEqual(heard, CGFloat(editor.viewport.scrollY)) + // Keeping 110 lines keeps the gutter, keeping 20 shrinks it and relays out. Both clamp the scroll. + for keep in [110, 20] { + editor.contentOffset.y = CGFloat(editor.viewport.maxScrollY) + draw(editor) + heard = nil + _ = editor.core.replace(editor.core.document.lineStart(keep), editor.core.document.length, "") + draw(editor) + XCTAssertEqual(editor.contentOffset.y, CGFloat(editor.viewport.scrollY), "keeping \(keep) lines") + XCTAssertLessThanOrEqual(editor.viewport.scrollY, editor.viewport.maxScrollY) + XCTAssertEqual(heard, CGFloat(editor.viewport.scrollY), "keeping \(keep) lines") + } } } From 87d1dd8ba620204277f81bf96480a141f7c3af7a Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 20:45:16 +0100 Subject: [PATCH 19/21] fix(ios): send the scroll event when an edit moves the scroll A clamp followed by a relayout (the gutter shrank) synced contentOffset before the check ran, so no scroll event went out. The check now compares the core scroll with the last published frame, like Android. UIKit brings contentOffset back into shorter content itself, so the push from a293bfe goes. --- ios/Codepad/view/CodeEditorView.swift | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index 4dc4181b..2d6002cd 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -764,13 +764,11 @@ final class CodeEditorView: UIScrollView { textInput.cursorView.resetBlinkAnimation() textInput.menu.hide() selectionViewsDirty = true - // An edit that shortens the content under the offset clamped the core scroll. The scroll view and the scroll - // listener take it here, since the next draw's clamp would see no move. - if contentOffset.y > CGFloat(viewport.maxScrollY) || contentOffset.x > CGFloat(viewport.maxScrollX) { - pushScroll() + updateContentSize() + // A move the edit made, through the core's clamp or a relayout, reaches the scroll listener like any other. + // UIKit brings contentOffset back into the shorter content itself. + if CGFloat(viewport.scrollX) != latestFrame.scrollX || CGFloat(viewport.scrollY) != latestFrame.scrollY { onScrolled() - } else { - updateContentSize() } setNeedsLayout() onChange?(change, origin) From 8ea2ba90a2739993f9a424e3f58ae4513c21f7ac Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 21:12:14 +0100 Subject: [PATCH 20/21] fix(ios): bring back the push and send the scroll event after a relayout Comparing the core scroll to the last frame instead of pushing it left a stale caret view in a later test of the suite, so the push into the scroll view comes back. An edit that shrinks the gutter relays out and moves the offset before that check, so the relayout now sends the scroll event itself. --- ios/Codepad/view/CodeEditorView.swift | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index 2d6002cd..33abfe2e 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -752,7 +752,12 @@ final class CodeEditorView: UIScrollView { cache.shift(first: first, oldCount: oldCount, newCount: newCount) search?.onChange(change) // The core already moved the rows and gaps with the edit and clamped the scroll. - if updateGutter() { relayout() } + if updateGutter() { + // A relayout that moved the offset is a scroll the listener hears of, like the clamp below. + let before = contentOffset + relayout() + if contentOffset != before { onScrolled() } + } if origin != .api { revealPending = true } // A change the keyboard did not make: it ends a composition it touched and the keyboard hears of it. let session = textInput.session @@ -764,11 +769,13 @@ final class CodeEditorView: UIScrollView { textInput.cursorView.resetBlinkAnimation() textInput.menu.hide() selectionViewsDirty = true - updateContentSize() - // A move the edit made, through the core's clamp or a relayout, reaches the scroll listener like any other. - // UIKit brings contentOffset back into the shorter content itself. - if CGFloat(viewport.scrollX) != latestFrame.scrollX || CGFloat(viewport.scrollY) != latestFrame.scrollY { + // An edit that shortens the content under the offset clamped the core scroll. The scroll view and the scroll + // listener take it here, since the next draw's clamp would see no move. + if contentOffset.y > CGFloat(viewport.maxScrollY) || contentOffset.x > CGFloat(viewport.maxScrollX) { + pushScroll() onScrolled() + } else { + updateContentSize() } setNeedsLayout() onChange?(change, origin) From 5a4aa269c6a1eb740e6380e28903d2c90d4262c3 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 13 Nov 2026 21:45:19 +0100 Subject: [PATCH 21/21] fix: tell scroll listeners when the draw's measure call moves the scroll A measure call that clamped the scroll moved it in a draw where nothing else scrolled, and the scroll listener never heard of it. iOS pushed the new offset without marking the scroll, Android did not mark it at all. The Android measure call now reports the move like the Swift one. --- .../me/sectiontn/codepad/layout/Viewport.kt | 6 +++-- .../sectiontn/codepad/view/CodeEditorView.kt | 15 +++++++---- .../sectiontn/codepad/layout/ViewportTest.kt | 24 +++++++++++++++++ .../java/codepad/example/ScrollTest.kt | 26 +++++++++++++++++++ example/ios/CodepadTests/ScrollTests.swift | 19 ++++++++++++++ ios/Codepad/view/CodeEditorView.swift | 8 +++++- 6 files changed, 90 insertions(+), 8 deletions(-) diff --git a/android/src/main/java/me/sectiontn/codepad/layout/Viewport.kt b/android/src/main/java/me/sectiontn/codepad/layout/Viewport.kt index 710b2a46..5ffe5bbe 100644 --- a/android/src/main/java/me/sectiontn/codepad/layout/Viewport.kt +++ b/android/src/main/java/me/sectiontn/codepad/layout/Viewport.kt @@ -140,12 +140,14 @@ class Viewport { /** * The draw's measure call: the first [pairCount] (line, rows) pairs and the widest line, then the tops and rows of - * [first]..[last] and every gap. + * [first]..[last] and every gap. Returns true when it moved the scroll from the last position this viewport read. */ - fun measure(pairs: IntArray, pairCount: Int, widest: Int, first: Int, last: Int) { + fun measure(pairs: IntArray, pairCount: Int, widest: Int, first: Int, last: Int): Boolean { + val before = known[SCROLL_Y] this.first = first this.last = last fill(pairs, pairCount, widest) + return known[SCROLL_Y] != before } fun endDraw() { diff --git a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt index 14f762e4..2bed0528 100644 --- a/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt +++ b/android/src/main/java/me/sectiontn/codepad/view/CodeEditorView.kt @@ -1274,14 +1274,16 @@ class CodeEditorView(context: Context) : View(context) { var f = readFrame() drawFrame = f if (debugSwitch()) core.document.drawingThread = Thread.currentThread() - prepare(f, m) + var moved = prepare(f, m) // A measure call that clamps the scroll (a visible line lost rows at the end) shows lines above the frame, and // their own measure call can clamp again. They are laid out in this draw, so none of them shows blank. while (viewport.firstVisibleLine() < f.first) { f = readFrame() drawFrame = f - prepare(f, m) + if (prepare(f, m)) moved = true } + // A move the measure call made reaches the scroll listener at the end of this draw. + if (moved) scrollDirty = true val firstLine = f.first val lastBound = f.last val caretLine = f.caretLine @@ -1354,8 +1356,11 @@ class CodeEditorView(context: Context) : View(context) { return frameReader.read(core, viewport, usable?.pointer ?: 0L, appliedRevision, incremental, framePairs, n) } - /** Ends with the draw's measure call, which takes the rows of every line laid out here and the widest one. */ - private fun prepare(frame: EditorFrame, m: RowMetrics) { + /** + * Ends with the draw's measure call, which takes the rows of every line laid out here and the widest one. Returns + * true when that call moved the scroll. + */ + private fun prepare(frame: EditorFrame, m: RowMetrics): Boolean { // The core paints from the snapshot only when it is at the frame's revision. Otherwise its runs are the lines // with no layout, and those take the spans keepSpans kept. val consistent = highlighter != null && snapshot?.revision == frame.revision @@ -1402,7 +1407,7 @@ class CodeEditorView(context: Context) : View(context) { pendingSpans = null pendingTail = null } - viewport.measure(measurePairs, count, widest, frame.first, frame.last) + return viewport.measure(measurePairs, count, widest, frame.first, frame.last) } /** The spans [keepSpans] kept for a line of [revision], the current one, or null. */ diff --git a/android/src/test/java/me/sectiontn/codepad/layout/ViewportTest.kt b/android/src/test/java/me/sectiontn/codepad/layout/ViewportTest.kt index 0559a5db..0078b554 100644 --- a/android/src/test/java/me/sectiontn/codepad/layout/ViewportTest.kt +++ b/android/src/test/java/me/sectiontn/codepad/layout/ViewportTest.kt @@ -86,6 +86,30 @@ class ViewportTest { } } + // A measure call that lowers the end of the content under the scroll clamps it. The view tells the scroll listener + // only when the call reports the move. + @Test + fun aMeasureCallReportsTheScrollItMoved() { + lines(100).use { core -> + val v = Viewport() + v.attach(core) + v.rowHeight = 10 + v.resize(100, 50) + v.measured(98, 30) + v.measured(99, 30) + v.scrollTo(0, v.maxScrollY) + val before = v.scrollY + v.beginDraw(checksCalls = false) + assertTrue(v.measure(intArrayOf(98, 1, 99, 1), 2, -1, 90, 99)) + v.endDraw() + assertTrue("clamped from $before to ${v.scrollY}", v.scrollY < before) + v.beginDraw(checksCalls = false) + assertFalse(v.measure(IntArray(0), 0, -1, 90, 99)) + v.endDraw() + v.close() + } + } + // With the debug switch on, a ninth single layout call in one draw throws: a per-line crossing crept into the draw. @Test fun aNinthCallInsideADrawThrowsInDebug() { diff --git a/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt b/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt index c659adce..b82aaa27 100644 --- a/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt +++ b/example/android/app/src/androidTest/java/codepad/example/ScrollTest.kt @@ -3,6 +3,8 @@ package codepad.example import android.os.SystemClock import android.view.KeyEvent import androidx.test.ext.junit.runners.AndroidJUnit4 +import me.sectiontn.codepad.layout.Viewport +import me.sectiontn.codepad.view.CodeEditorView import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test @@ -31,6 +33,30 @@ class ScrollTest { } } + // A measure call that clamps the scroll moves it in a draw where nothing else scrolled. The listener hears of it. + @Test + fun aClampInTheMeasureCallReachesTheScrollListener() { + launch().use { s -> + val editor = s.editor() + onMain { + editor.setInitialText((0 until 100).joinToString("\n") { "line $it" }) + layout(editor) + draw(editor) + val viewport = CodeEditorView::class.java.getDeclaredField("viewport").apply { isAccessible = true } + .get(editor) as Viewport + viewport.measured(98, 30) + viewport.measured(99, 30) + viewport.scrollTo(0, viewport.maxScrollY) + val before = viewport.scrollY + var heard = -1f + editor.onScrollListener = { heard = it.scrollY } + draw(editor) + assertTrue("the measure call clamped the scroll, scrollY ${viewport.scrollY}", viewport.scrollY < before) + assertEquals(editor.frame.scrollY, heard, 0.01f) + } + } + } + // An API edit that removes the lines under the scroll clamps it in the core. The scroll listener must hear of it, // or the host keeps the old offset. @Test diff --git a/example/ios/CodepadTests/ScrollTests.swift b/example/ios/CodepadTests/ScrollTests.swift index 538f279f..4f9931ce 100644 --- a/example/ios/CodepadTests/ScrollTests.swift +++ b/example/ios/CodepadTests/ScrollTests.swift @@ -67,6 +67,25 @@ final class ScrollTests: XCTestCase { XCTAssertEqual(frame.filter { !cached.contains($0) }, [], "frame \(frame)") } + // A measure call that clamps the scroll moves it in a draw where nothing else scrolled. The listener hears of it. + func testAClampInTheMeasureCallReachesTheScrollListener() { + let editor = launch() + editor.setInitialText((0..<100).map { "line \($0)" }.joined(separator: "\n")) + layout(editor) + draw(editor) + editor.viewport.measured(98, 30) + editor.viewport.measured(99, 30) + _ = editor.viewport.scrollTo(0, editor.viewport.maxScrollY) + editor.contentOffset.y = CGFloat(editor.viewport.scrollY) + let before = editor.viewport.scrollY + var heard: CGFloat? + editor.onScroll = { heard = $0.scrollY } + editor.setNeedsLayout() + editor.layoutIfNeeded() + XCTAssertLessThan(editor.viewport.scrollY, before, "the measure call clamped the scroll") + XCTAssertEqual(heard, CGFloat(editor.viewport.scrollY)) + } + // An API edit that removes the lines under the offset clamps the core scroll. The scroll view and the scroll // listener must take it, or the layers paint at one offset while UIKit and the host keep another. func testAnEditThatShortensTheContentUnderTheOffsetMovesIt() { diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index 33abfe2e..3c233b93 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -675,7 +675,13 @@ final class CodeEditorView: UIScrollView { } let first = frame.first let lastBound = frame.last - if moved { pushScroll() } else { updateContentSize() } + if moved { + // A move the measure call made reaches the scroll listener at the end of this draw. + scrollDirty = true + pushScroll() + } else { + updateContentSize() + } let caretLine = frame.caretLine let lastLine = placeLayers(first, lastBound, m) placeGutter(first, lastLine, caretLine)