From 0784c581ac82228f32bdcb06b7154893c54e4fb8 Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:07:10 +0900 Subject: [PATCH 1/8] Docs: CodeEditor caret and position rectangles (FR-38 criterion 19, #553) Leader-approved provisional SPEC (darkpyonix leader, 2026-11-13; owner delegated mockup-matching toolkit SPEC). --- docs/SPEC.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/SPEC.md b/docs/SPEC.md index 253e0ddcf..6d338fe6c 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -2675,6 +2675,9 @@ Notification::new("세션이 끝났습니다") 4. 줄 높이 보고가 실제 그린 줄 높이와 같습니다(fr38_editor_reports_line_height). 5. 두 편집기 중 하나를 스크롤하면 `CodeScrolled`가 오고, 그 값으로 다른 편집기에 `SetScrollOffset`을 주면 같은 픽셀 위치에 섭니다(fr38_editor_scroll_offset_round_trips). 6. 와이어([leader, provisional] (darkpyonix leader, 2026-11-13; owner delegated mockup-matching toolkit SPEC)). 속성 `LineNumbers` 178(bool, 없으면 true), `GutterMinWidthDp` 179(여백을 포함한 줄 번호 열의 최소 폭), `GutterPaddingDp` 180, `TextInsetDp` 181(각 f32, dp), `CodeEditorColors` 182(색 레코드의 블롭), `OnCodeMetrics` 183, `OnCodeScrolled` 184(핸들러 id). 색 레코드는 12바이트입니다: `container`, `gutter`, `lineNumber`, `currentLineNumber`, `currentLine`(각 `u16` `ColorRole`, 0이면 디자인 시스템의 색), 예약 `u16`. 모르는 역할이나 길이가 맞지 않는 레코드는 `ProtocolError`를 보내고 디자인 시스템의 색으로 그립니다. 이벤트 `CodeMetrics`(54)와 `CodeScrolled`(55)는 24바이트로, 공통 머리 16바이트 뒤에 `f64` 하나(물리 픽셀)가 오며 `ValueChanged`의 페이로드 모양을 씁니다. 듣는 핸들러가 없으면 보내지 않고, 나중에 붙으면 그때의 값을 한 번 보냅니다. 스크롤 위치가 0인 편집기는 `CodeScrolled`를 보내지 않습니다. 명령 `SetScrollOffset`(30)은 16바이트입니다: 머리 4, `node_id: u32`, `offset_px: f64`(물리 픽셀). 0보다 작으면 맨 위, 문서 끝을 넘으면 끝에 맞추고, 숫자가 아닌 값은 그 명령만 버리고 `ProtocolError`를 보냅니다. 편집기가 아직 크기를 받지 못했으면 첫 배치 뒤에 적용합니다. 편집기는 글자 속성 중 `TypeRole`, `FontSize`, `LineHeight`, `Font`만 받습니다. `Font` 목록을 보내면 역할과 관계없이 그 목록으로 그립니다. `LineNumbers`가 false이면 줄 번호 열과 구분선이 없고, 거터 장식, 접기 표시, 변경 표시 막대의 열은 있을 때만 남습니다. +19. 캐럿과 위치 사각형(이슈 #553, [leader, provisional] (darkpyonix leader, 2026-11-13; owner delegated mockup-matching toolkit SPEC)). 편집기가 캐럿 사각형을 이벤트 `CaretRect`(이벤트 태그 64: `line`, `column`, `x`, `y`, `width`, `height`, 창 dp, 스크롤과 확대 반영)로 캐럿이 움직이거나 스크롤될 때 프레임당 최대 한 번 보냅니다. 핸들러 속성 `OnCaretRect`(속성 태그 195)가 있을 때만 보냅니다. Host는 편집기 핸들의 위치 질의(명령 `QueryPositionRect`, 명령 태그 39: `request`, `line`, `column`)를 보내고 이벤트 `PositionRect`(이벤트 태그 65: `request`, 사각형 또는 "없음")로 답을 받습니다. 보이지 않는 위치는 "없음"입니다. 제안 목록, 매개변수 힌트, 이름 바꾸기 상자, 호버를 캐럿이나 위치에 붙이는 데 씁니다. + 1. 3번째 줄 5번째 열에 캐럿을 두면 캐럿 사각형이 그 글자의 그려진 위치와 1dp 안에서 같고, 스크롤하면 새 위치가 한 번 옵니다(fr38_editor_reports_the_caret_rect). + 2. 위치 질의는 보이는 위치에 사각형을, 보이지 않는 위치에 "없음"을 한 번 답합니다(fr38_editor_answers_position_rects). #### 38.9 추가 기능의 와이어 (소유자 승인 2026-10-25, 이슈 #30) From aa03c95bd1124d2d40b655c636b5158902224ce7 Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:07:11 +0900 Subject: [PATCH 2/8] Docs: CodeEditor key preview the Host can consume (FR-38 criterion 20, #554) Leader-approved provisional SPEC (darkpyonix leader, 2026-11-13; owner delegated mockup-matching toolkit SPEC). --- docs/SPEC.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/SPEC.md b/docs/SPEC.md index 6d338fe6c..a47816673 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -2678,6 +2678,9 @@ Notification::new("세션이 끝났습니다") 19. 캐럿과 위치 사각형(이슈 #553, [leader, provisional] (darkpyonix leader, 2026-11-13; owner delegated mockup-matching toolkit SPEC)). 편집기가 캐럿 사각형을 이벤트 `CaretRect`(이벤트 태그 64: `line`, `column`, `x`, `y`, `width`, `height`, 창 dp, 스크롤과 확대 반영)로 캐럿이 움직이거나 스크롤될 때 프레임당 최대 한 번 보냅니다. 핸들러 속성 `OnCaretRect`(속성 태그 195)가 있을 때만 보냅니다. Host는 편집기 핸들의 위치 질의(명령 `QueryPositionRect`, 명령 태그 39: `request`, `line`, `column`)를 보내고 이벤트 `PositionRect`(이벤트 태그 65: `request`, 사각형 또는 "없음")로 답을 받습니다. 보이지 않는 위치는 "없음"입니다. 제안 목록, 매개변수 힌트, 이름 바꾸기 상자, 호버를 캐럿이나 위치에 붙이는 데 씁니다. 1. 3번째 줄 5번째 열에 캐럿을 두면 캐럿 사각형이 그 글자의 그려진 위치와 1dp 안에서 같고, 스크롤하면 새 위치가 한 번 옵니다(fr38_editor_reports_the_caret_rect). 2. 위치 질의는 보이는 위치에 사각형을, 보이지 않는 위치에 "없음"을 한 번 답합니다(fr38_editor_answers_position_rects). +20. 키 미리보기(이슈 #554, [leader, provisional] (darkpyonix leader, 2026-11-13; owner delegated mockup-matching toolkit SPEC)). 편집기에 `on_key_preview`(핸들러 속성 `OnKeyPreview`, 속성 태그 196)가 있습니다. 편집기가 키를 처리하기 전에 `KeyDown`(12.1과 같은 레코드: code, text, 수정자, repeat)이 Host로 가고, 핸들러가 소비하면(FR-12의 동기 반환값) 편집기는 그 키를 처리하지 않습니다. IME 조합 중에는 보내지 않습니다(12.1의 규칙). 제안 목록이 열린 동안 위, 아래, Enter, Tab, Escape와 F12, F2, Ctrl+Space, Ctrl/Cmd+. 같은 명령 키를 Host가 가져가는 데 씁니다. + 1. 미리보기 핸들러가 Down을 소비하면 캐럿이 움직이지 않고, 소비하지 않으면 지금처럼 움직입니다(fr38_editor_key_preview_consumes_keys). + 2. IME 조합 중에는 미리보기가 가지 않습니다(fr38_editor_key_preview_skips_composition). #### 38.9 추가 기능의 와이어 (소유자 승인 2026-10-25, 이슈 #30) From 2041ca580e042b079accedefaa81cb08cd8ff8de Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:07:11 +0900 Subject: [PATCH 3/8] Docs: CodeEditor pointer with modifiers and text position (FR-38 criterion 21, #555) Leader-approved provisional SPEC (darkpyonix leader, 2026-11-13; owner delegated mockup-matching toolkit SPEC). --- docs/SPEC.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/SPEC.md b/docs/SPEC.md index a47816673..0f814641c 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -2681,6 +2681,8 @@ Notification::new("세션이 끝났습니다") 20. 키 미리보기(이슈 #554, [leader, provisional] (darkpyonix leader, 2026-11-13; owner delegated mockup-matching toolkit SPEC)). 편집기에 `on_key_preview`(핸들러 속성 `OnKeyPreview`, 속성 태그 196)가 있습니다. 편집기가 키를 처리하기 전에 `KeyDown`(12.1과 같은 레코드: code, text, 수정자, repeat)이 Host로 가고, 핸들러가 소비하면(FR-12의 동기 반환값) 편집기는 그 키를 처리하지 않습니다. IME 조합 중에는 보내지 않습니다(12.1의 규칙). 제안 목록이 열린 동안 위, 아래, Enter, Tab, Escape와 F12, F2, Ctrl+Space, Ctrl/Cmd+. 같은 명령 키를 Host가 가져가는 데 씁니다. 1. 미리보기 핸들러가 Down을 소비하면 캐럿이 움직이지 않고, 소비하지 않으면 지금처럼 움직입니다(fr38_editor_key_preview_consumes_keys). 2. IME 조합 중에는 미리보기가 가지 않습니다(fr38_editor_key_preview_skips_composition). +21. 수정자와 글자 위치를 가진 포인터(이슈 #555, [leader, provisional] (darkpyonix leader, 2026-11-13; owner delegated mockup-matching toolkit SPEC)). 편집기에 `on_code_pointer`(핸들러 속성 `OnCodePointer`, 속성 태그 197, FR-46과 같은 종류 마스크)가 있고, FR-46의 포인터 레코드에 그 지점의 글자 위치(`line`, `column`, 글자 위가 아니면 "없음")를 덧붙인 이벤트 `CodePointer`(이벤트 태그 66)를 보냅니다. 버튼, 수정자, 클릭 수, 소비 규칙은 FR-46과 같고, 소비한 Down은 캐럿을 옮기지 않습니다. Cmd/Ctrl+클릭으로 정의로 가고 Cmd/Ctrl+호버로 낱말에 밑줄을 긋는 데 씁니다. + 1. Cmd+클릭이 그 글자의 줄과 열, 수정자 `meta`를 싣고 한 번 오고, 핸들러가 소비하면 캐럿이 그대로입니다(fr38_editor_pointer_reports_text_position). #### 38.9 추가 기능의 와이어 (소유자 승인 2026-10-25, 이슈 #30) From 2f405d80af9db6ee687c8505b900c7801316f346 Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:07:11 +0900 Subject: [PATCH 4/8] Docs: CodeEditor line and range background decorations (FR-38 criterion 22, #542) Leader-approved provisional SPEC (darkpyonix leader, 2026-11-13; owner delegated mockup-matching toolkit SPEC). --- docs/SPEC.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/SPEC.md b/docs/SPEC.md index 0f814641c..8f99f9f2a 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -2683,6 +2683,9 @@ Notification::new("세션이 끝났습니다") 2. IME 조합 중에는 미리보기가 가지 않습니다(fr38_editor_key_preview_skips_composition). 21. 수정자와 글자 위치를 가진 포인터(이슈 #555, [leader, provisional] (darkpyonix leader, 2026-11-13; owner delegated mockup-matching toolkit SPEC)). 편집기에 `on_code_pointer`(핸들러 속성 `OnCodePointer`, 속성 태그 197, FR-46과 같은 종류 마스크)가 있고, FR-46의 포인터 레코드에 그 지점의 글자 위치(`line`, `column`, 글자 위가 아니면 "없음")를 덧붙인 이벤트 `CodePointer`(이벤트 태그 66)를 보냅니다. 버튼, 수정자, 클릭 수, 소비 규칙은 FR-46과 같고, 소비한 Down은 캐럿을 옮기지 않습니다. Cmd/Ctrl+클릭으로 정의로 가고 Cmd/Ctrl+호버로 낱말에 밑줄을 긋는 데 씁니다. 1. Cmd+클릭이 그 글자의 줄과 열, 수정자 `meta`를 싣고 한 번 오고, 핸들러가 소비하면 캐럿이 그대로입니다(fr38_editor_pointer_reports_text_position). +22. 줄 배경과 범위 배경 장식(이슈 #542, [leader, provisional] (darkpyonix leader, 2026-11-13; owner delegated mockup-matching toolkit SPEC)). 장식에 `LineBackground { line_start, line_end, color: ColorRole }`와 `RangeBackground { range, color: ColorRole }`가 더해집니다(장식 종류 값은 추가 전용으로 뒤에 붙입니다). 줄 배경은 편집기 폭 전체(줄 끝 너머 포함)를 칠하고, 범위 배경은 그 안의 바뀐 글자들을 더 진하게 칠합니다. 색은 `DiffAdded`, `DiffRemoved`, `DiffModified` 같은 역할만 받습니다. 다른 장식과 같이 편집을 따라 움직입니다(기준 4의 규칙). + 1. `DiffAdded` 줄 배경이 그 줄의 편집기 폭 전체를 칠하고(줄 끝 너머 픽셀 포함) 앞에 줄을 끼우면 아래로 따라갑니다(fr38_line_background_spans_the_width_and_follows_edits). + 2. 범위 배경이 그 글자들만 칠합니다(fr38_range_background_paints_its_characters). #### 38.9 추가 기능의 와이어 (소유자 승인 2026-10-25, 이슈 #30) From dd3b8c6b450aa6360906274326de1154a1aec969 Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:28:53 +0900 Subject: [PATCH 5/8] Feat: Report the code editor's caret rectangle and answer position queries (FR-38, #553) Covers FR-38 criterion 19. Wire: the OnCaretRect handler property (195), the CaretRect event (64: line, column, x, y, width, height) and the QueryPositionRect command (39: node, request, line, column) answered by the PositionRect event (65: request, a found word, the rectangle). Both events are 40 bytes, the command 20. Rectangles are in the window's dp, so the editor's scroll and the window's zoom are in them. Rust: CodeRect, CaretRect, Batch::query_position_rect and code::position_query, whose callback the Host calls once when the answer arrives. The vectors gain the command and both events (events.bin is 1519 bytes). Renderer: the field path and the drawn path find the caret after layout, from the draw pass and the layout callbacks, and the model reports it at most once a frame and only when it moved. A query is answered at once where the editor is drawn and after its first draw otherwise; a position that is scrolled away, folded or not in the document, a node that is not an editor, and an editor removed before it was drawn are answered with nothing, so every query has exactly one answer. Tests: fr38_editor_reports_the_caret_rect (19.1) and fr38_editor_answers_position_rects (19.2) on both paths, plus fr38_editor_answers_position_rects_through_the_interpreter and fr38_on_caret_rect_is_a_property_of_an_editor in CodeEditorAnchorTest; fr38_caret_and_position_rects_keep_their_assigned_tags, fr38_editor_reports_the_caret_rect_on_the_wire and fr38_editor_answers_position_rects_on_the_wire in code_editor.rs; the vector offsets in ProtocolVectorsTest. --- CHANGELOG.md | 4 + .../android-kotlin/shared/CodeEditorModel.kt | 95 ++++++ .../shared/CodeEditorSurface.kt | 120 ++++++++ .../android-kotlin/shared/HostCodeEditor.kt | 35 ++- .../android-kotlin/shared/NodeTable.kt | 26 +- .../android-kotlin/shared/Protocol.gen.kt | 50 +++- compose-rust/schema-hash.txt | 2 +- compose-rust/src/boundary.rs | 32 ++ compose-rust/src/code.rs | 125 ++++++++ compose-rust/src/codegen.rs | 94 +++++- compose-rust/src/lib.rs | 7 +- compose-rust/src/protocol.rs | 110 ++++++- compose-rust/src/runtime/seam.rs | 18 ++ compose-rust/src/schema.rs | 43 ++- compose-rust/tests/code_editor.rs | 196 +++++++++++- compose-rust/tests/vectors/events.bin | Bin 1439 -> 1519 bytes compose-rust/tests/vectors/mutations.bin | Bin 6051 -> 6071 bytes compose-rust/tests/vectors/vectors.json | 10 +- renderer/desktop/src/protocol/Protocol.gen.kt | 50 +++- .../desktop/src/renderer/CodeEditorModel.kt | 95 ++++++ .../desktop/src/renderer/CodeEditorSurface.kt | 120 ++++++++ .../desktop/src/renderer/DrawnCodeEditor.kt | 74 ++++- .../desktop/src/renderer/HostCodeEditor.kt | 35 ++- renderer/desktop/src/renderer/NodeTable.kt | 26 +- renderer/desktop/test/CodeEditorAnchorTest.kt | 282 ++++++++++++++++++ renderer/desktop/test/ProtocolVectorsTest.kt | 10 +- 26 files changed, 1627 insertions(+), 32 deletions(-) create mode 100644 renderer/desktop/test/CodeEditorAnchorTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index d165a8c8f..f555d67cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Where the code editor's caret is, and where any position is + +A `CodeEditor` with the new `OnCaretRect` handler property (tag 195) reports where it draws its caret in a `CaretRect` event (tag 64): the line, the column and a rectangle in the window's dp, with the editor's scroll and the window's zoom already in it. It is sent when the caret moves or the view scrolls, at most once a frame. `Batch::query_position_rect(node, request, position)` asks where a caret at any other position would be drawn, in a `QueryPositionRect` command (tag 39), and `compose_rust::code::position_query(callback)` gives the request its number. Every query gets exactly one `PositionRect` event (tag 65) back: the rectangle, or `None` where the position is not on screen, is not in the document, or the editor is gone. A suggestion list, a parameter hint, a rename box or a hover card is placed with them ([#553](https://github.com/DarkPyonix/compose-rust/issues/553)). + ### Long tokens break inside under `KeepAll`, and fields take a word break `Text::overflow_wrap(OverflowWrap::Anywhere)` lets a token too long for its line, such as a path or a URL, break between its letters even under `WordBreak::KeepAll`, while the tokens that fit keep their breaks. Such a text is as narrow as its widest letter when a weighted `Row` asks, so a 40 letter path in a narrow column wraps instead of widening the text past the column. `TextField::word_break` and `TextField::overflow_wrap` apply the same rules to the typed text and the placeholder: a `KeepAll` field breaks a Korean hint only at its spaces. The field's value, and what the Host is told, stays exactly what was typed. Each sends the existing `WordBreak` (111) or `OverflowWrap` (112) property, and only when it is called ([#443](https://github.com/DarkPyonix/compose-rust/issues/443), [#444](https://github.com/DarkPyonix/compose-rust/issues/444)). diff --git a/compose-rust/android-kotlin/shared/CodeEditorModel.kt b/compose-rust/android-kotlin/shared/CodeEditorModel.kt index 2e58fd878..5566728f2 100644 --- a/compose-rust/android-kotlin/shared/CodeEditorModel.kt +++ b/compose-rust/android-kotlin/shared/CodeEditorModel.kt @@ -90,6 +90,15 @@ class RevealRequest(val start: CodePosition, val end: CodePosition, val align: R */ class ScrollRequest(val offsetPx: Int) +/** + * A rectangle on screen in the dp of the window's content: the editor's scroll and the + * window's zoom are already in it. + */ +data class CodeRectDp(val x: Float, val y: Float, val width: Float, val height: Float) + +/** Where the caret is drawn: the place it stands at and its rectangle. */ +data class CaretReport(val position: CodePosition, val rect: CodeRectDp) + /** One colour run of the syntax as it stands in the current version of the document. */ class LiveSpan(var start: CodePosition, var end: CodePosition, val paint: Paint) @@ -128,6 +137,12 @@ sealed interface EditorOutput { /** How far the view is scrolled, in pixels. Steps between two reports are one report. */ class Scrolled(val offsetPx: Int) : EditorOutput + /** Where the caret is drawn. Moves between two reports are one report. */ + class Caret(val report: CaretReport) : EditorOutput + + /** The answer to the Host's position query [request]: a rectangle, or null where none is on screen. */ + class PositionAnswer(val request: Int, val rect: CodeRectDp?) : EditorOutput + /** The reader folded or unfolded the stretch that starts on [startLine]. */ class FoldToggled(val startLine: Int, val collapsed: Boolean) : EditorOutput @@ -216,6 +231,27 @@ class CodeEditorModel( var hearsLineHeight = false var hearsScroll = false + /** + * Where the caret is drawn, as the surface last said and as the Host was last told, and + * whether the Host listens. Like the row height, what nobody listens for is not counted + * as told. + */ + private var pendingCaret: CaretReport? = null + private var reportedCaret: CaretReport? = null + var hearsCaretRect = false + + /** + * How the surface that draws the editor finds a position on screen, or null before it + * has been drawn. It answers null for a position that is not on screen. + */ + var locator: ((CodePosition) -> CodeRectDp?)? = null + + /** The Host's position queries that arrived before the editor was drawn, in order. */ + private val waitingQueries = ArrayList>() + + /** Whether a query is waiting for the surface to be drawn. */ + val hasWaitingQueries: Boolean get() = waitingQueries.isNotEmpty() + private var focused = false private var composing = false @@ -573,6 +609,65 @@ class CodeEditorModel( reportedScroll = pendingScroll output += EditorOutput.Scrolled(pendingScroll) } + val caret = pendingCaret + if (hearsCaretRect && caret != null && caret != reportedCaret) { + reportedCaret = caret + output += EditorOutput.Caret(caret) + } + } + + /** + * The surface says where it draws the caret. Said whenever it draws, reported only when + * it is not what the Host was last told, and at most once per drain. + */ + fun reportCaretRect(report: CaretReport) { + pendingCaret = report + } + + /** Whether the caret has moved since the Host was told, and the Host listens. */ + val caretUntold: Boolean get() = hearsCaretRect && pendingCaret != null && pendingCaret != reportedCaret + + /** + * The Host asks where a caret at a position would be drawn. Answered at once where the + * editor has been drawn, and as soon as it is otherwise. A place that is not in the + * document is not on screen. + */ + fun hostQueryPosition(request: Int, line: Int, column: Int) { + val position = CodePosition(line, column) + if (line < 0 || column < 0 || !document.isValid(position)) { + output += EditorOutput.PositionAnswer(request, null) + return + } + val find = locator + if (find == null) { + waitingQueries += request to position + return + } + output += EditorOutput.PositionAnswer(request, find(position)) + } + + /** Answers the queries that waited for the surface, now that it can find a position. */ + fun answerWaitingQueries() { + val find = locator ?: return + if (waitingQueries.isEmpty()) return + for ((request, position) in waitingQueries.toList()) { + output += EditorOutput.PositionAnswer( + request, + if (document.isValid(position)) find(position) else null, + ) + } + waitingQueries.clear() + } + + /** + * The requests of every query still waiting, which the editor will never answer now + * because it is going away, and none waiting any more. + */ + fun abandonQueries(): List { + if (waitingQueries.isEmpty()) return emptyList() + val requests = waitingQueries.map { it.first } + waitingQueries.clear() + return requests } /** A position moved to the nearest place the document has, never between a pair's halves. */ diff --git a/compose-rust/android-kotlin/shared/CodeEditorSurface.kt b/compose-rust/android-kotlin/shared/CodeEditorSurface.kt index 08e4030cc..1206cc9a6 100644 --- a/compose-rust/android-kotlin/shared/CodeEditorSurface.kt +++ b/compose-rust/android-kotlin/shared/CodeEditorSurface.kt @@ -26,6 +26,7 @@ import androidx.compose.foundation.text.selection.LocalTextSelectionColors import androidx.compose.foundation.text.selection.TextSelectionColors import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue @@ -33,6 +34,7 @@ import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds @@ -41,6 +43,7 @@ import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path @@ -62,7 +65,9 @@ import androidx.compose.ui.input.key.type import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.layout +import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.semantics.semantics @@ -88,6 +93,7 @@ import dev.darkpyonix.composerust.protocol.GutterDecorationKind import dev.darkpyonix.composerust.protocol.Paint import dev.darkpyonix.composerust.protocol.RevealAlign import kotlinx.coroutines.delay +import kotlinx.coroutines.launch import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt @@ -891,6 +897,91 @@ internal fun rowHeightPx(style: TextStyle, density: Density): Int = with(density max(1, lineHeight.toPx().roundToInt()) } +/** A rectangle in root pixels as dp of the window's content, at [density] pixels a dp. */ +internal fun Rect.toDp(density: Float): CodeRectDp = + CodeRectDp(left / density, top / density, width / density, height / density) + +/** + * Whether a caret rectangle in root pixels can be seen in an editor whose view is + * [viewport], with its text starting [textLeft] pixels in: some of the row is inside the + * view, and the caret is right of the gutter and not past the right edge. + */ +internal fun caretOnScreen(rect: Rect, viewport: LayoutCoordinates?, textLeft: Float): Boolean { + val view = viewport?.takeIf { it.isAttached } ?: return false + val origin = view.localToRoot(Offset.Zero) + val top = origin.y + val bottom = origin.y + view.size.height + val left = origin.x + textLeft + val right = origin.x + view.size.width + // Half a pixel either way, for a caret that stands exactly on the gutter's edge. + return rect.bottom > top && rect.top < bottom && rect.left >= left - 0.5f && rect.left <= right + 0.5f +} + +/** + * Where a field surface draws a document position, for the caret report and the Host's + * position queries. + * + * Its fields are refreshed on every composition and read after layout, from the draw pass + * and from the layout callbacks, where the field's text layout and its place on screen are + * the ones the reader sees. + */ +internal class FieldPlaces(private val window: FieldWindow) { + /** The field itself, where its text layout's coordinates start. */ + var field: LayoutCoordinates? = null + + /** The editor's view: everything the reader can see of it. */ + var viewport: LayoutCoordinates? = null + var layout: (() -> TextLayoutResult?)? = null + var textLeftPx = 0f + var density = 1f + + /** The width the field draws its caret at. */ + var caretWidthPx = 2f + + /** The function the model finds positions with, the same one for as long as this lives. */ + val locate: (CodePosition) -> CodeRectDp? = { position -> + caretInRoot(position)?.takeIf { caretOnScreen(it, viewport, textLeftPx) }?.toDp(density) + } + + /** + * Where a caret at [position] is drawn, in root pixels, or null where the field does + * not hold the position: a line outside its window, or one a fold hides. + */ + fun caretInRoot(position: CodePosition): Rect? { + val model = window.model + if (!model.document.isValid(position) || model.isHidden(position.line)) return null + val offset = window.toField(position) ?: return null + val result = layout?.invoke() ?: return null + val coordinates = field?.takeIf { it.isAttached } ?: return null + var shown = window.toShown(offset, asEnd = false) + // A suggestion shows after the caret that stands where it starts. + val ghost = model.ghostText + if (ghost != null && ghost.start == position && ghost.text.isNotEmpty()) shown -= ghost.text.length + val cursor = result.getCursorRect(shown.coerceIn(0, result.layoutInput.text.length)) + return Rect(coordinates.localToRoot(Offset(cursor.left, cursor.top)), Size(caretWidthPx, cursor.height)) + } + + /** + * Tells the model how to find positions and where the caret is, and answers the queries + * that waited for the editor to be drawn. Answers whether the Host has something to hear. + */ + fun report(): Boolean { + // Before the field and the view have both been placed, nothing found here would be + // where the reader sees it, and a waiting query would be answered with nothing. + val ready = field?.isAttached == true && viewport?.isAttached == true && layout?.invoke() != null + if (!ready) return false + val model = window.model + model.locator = locate + if (!window.caretOutside) { + val caret = model.selection.caret + caretInRoot(caret)?.let { model.reportCaretRect(CaretReport(caret, it.toDp(density))) } + } + val answered = model.hasWaitingQueries + if (answered) model.answerWaitingQueries() + return answered || model.caretUntold + } +} + /** * The two field paths. [whole] holds every line; otherwise the field holds the lines around * the screen and is refilled as the view scrolls. @@ -992,6 +1083,21 @@ private fun FieldSurface( val textInsetPx = with(density) { look.textInset.roundToPx() } + // Where the caret is drawn and where a position is, read after layout. What they find + // is sent from a coroutine rather than from inside the pass that found it. + val places = remember(window) { FieldPlaces(window).also { it.layout = { layoutHolder[0]?.invoke() } } } + places.textLeftPx = (gutterWidthPx + textInsetPx).toFloat() + places.density = density.density + places.caretWidthPx = with(density) { 2.dp.toPx() } + val scope = rememberCoroutineScope() + val currentCallbacks by rememberUpdatedState(callbacks) + val reportPlaces: () -> Unit = remember(places, scope) { + { if (places.report()) scope.launch { currentCallbacks.onOutput() } } + } + DisposableEffect(model, places) { + onDispose { if (model.locator === places.locate) model.locator = null } + } + CompositionLocalProvider( LocalTextSelectionColors provides TextSelectionColors(look.cursor, look.selection), ) { @@ -1004,6 +1110,10 @@ private fun FieldSurface( .onSizeChanged { size -> viewportHeight = size.height viewportWidth = size.width + } + .onGloballyPositioned { coordinates -> + places.viewport = coordinates + reportPlaces() }, ) { // The extent the offset may run to. A number, never a measured height. @@ -1017,6 +1127,12 @@ private fun FieldSurface( translate(top = -vertical.offset.toFloat()) { drawCurrentLine(window, rows, rowPx, look) } + // Read so that typing, a move of the caret and a scroll along the + // lines all draw this again, and the caret is reported from here. + window.state.text + window.state.selection + horizontal.value + reportPlaces() }, ) { Box( @@ -1084,6 +1200,10 @@ private fun FieldSurface( placeable.place(textInsetPx, rows.rowTop(window.start) * rowPx - vertical.offset) } } + .onGloballyPositioned { coordinates -> + places.field = coordinates + reportPlaces() + } .onFocusChanged { focusState -> overlayFocusStack.noteFocused(focus, focusState.hasFocus) model.focusChanged(focusState.hasFocus) diff --git a/compose-rust/android-kotlin/shared/HostCodeEditor.kt b/compose-rust/android-kotlin/shared/HostCodeEditor.kt index 1803e59e5..7352d698b 100644 --- a/compose-rust/android-kotlin/shared/HostCodeEditor.kt +++ b/compose-rust/android-kotlin/shared/HostCodeEditor.kt @@ -114,8 +114,9 @@ internal fun HostCodeEditor( // sent now. val hearsMetrics = node.handler(PropertyKind.OnCodeMetrics) != null val hearsScroll = node.handler(PropertyKind.OnCodeScrolled) != null - LaunchedEffect(model, hearsMetrics, hearsScroll) { - if (hearsMetrics || hearsScroll) callbacks.onOutput() + val hearsCaret = node.handler(PropertyKind.OnCaretRect) != null + LaunchedEffect(model, hearsMetrics, hearsScroll, hearsCaret) { + if (hearsMetrics || hearsScroll || hearsCaret) callbacks.onOutput() } val focusRequest = node.focusRequestRevision CodeEditorSurface(model, look, callbacks, modifier, focusRequest = focusRequest) { scrolling -> @@ -294,6 +295,36 @@ internal fun Node.codeEvents(outputs: List, onError: (String) -> U val handler = handler(PropertyKind.OnCodeScrolled) ?: continue events += HostEvent.CodeScrolled(id, handler, output.offsetPx.toDouble()) } + // In the window's dp, the scroll and the zoom already in them. + is EditorOutput.Caret -> { + val handler = handler(PropertyKind.OnCaretRect) ?: continue + val (position, rect) = output.report + events += HostEvent.CaretRect( + id, + handler, + position.line, + position.column, + rect.x, + rect.y, + rect.width, + rect.height, + ) + } + // An answer goes to the query and names no handler: the Host asked, so it is + // waiting for it whether or not anything on the editor listens. + is EditorOutput.PositionAnswer -> { + val rect = output.rect + events += HostEvent.PositionRect( + id, + 0L, + output.request, + rect != null, + rect?.x ?: 0f, + rect?.y ?: 0f, + rect?.width ?: 0f, + rect?.height ?: 0f, + ) + } is EditorOutput.Composing -> { val handler = handler(PropertyKind.OnCompositionChange) ?: continue events += HostEvent.CompositionChanged(id, handler, output.composing) diff --git a/compose-rust/android-kotlin/shared/NodeTable.kt b/compose-rust/android-kotlin/shared/NodeTable.kt index ea66252ca..317cec569 100644 --- a/compose-rust/android-kotlin/shared/NodeTable.kt +++ b/compose-rust/android-kotlin/shared/NodeTable.kt @@ -499,6 +499,18 @@ class NodeTable { code.hostScrollTo(mutation.offsetPx) collectCode(node) } + // A question, answered exactly once: by the editor where it can find the + // position, and here, with nothing on screen, where there is no editor to ask. + is Mutation.QueryPositionRect -> { + val found = codeNode(mutation.nodeId, "QueryPositionRect") + if (found == null) { + outbox += HostEvent.PositionRect(mutation.nodeId, 0L, mutation.request, false, 0f, 0f, 0f, 0f) + } else { + val (node, code) = found + code.hostQueryPosition(mutation.request, mutation.line, mutation.column) + collectCode(node) + } + } // Requests too: the scroll position is this side's. Each is checked here and // waits on the node for the container, which keeps it in range, may animate it, @@ -783,6 +795,10 @@ class NodeTable { code.hearsScroll = value is PropertyValue.Integer return } + PropertyKind.OnCaretRect -> { + code.hearsCaretRect = value is PropertyValue.Integer + return + } else -> return } collectCode(node) @@ -951,7 +967,13 @@ class NodeTable { private fun removeSubtree(nodeId: Int) { val node = nodes.remove(nodeId) ?: return - codeNodes.remove(nodeId) + if (codeNodes.remove(nodeId) != null) { + // A query the editor had not answered yet is answered now, with nothing on + // screen: it never will be otherwise. + for (request in node.code?.abandonQueries().orEmpty()) { + outbox += HostEvent.PositionRect(nodeId, 0L, request, false, 0f, 0f, 0f, 0f) + } + } node.scroll?.let(scrolls::forget) if (node.widget == WidgetKind.Window) { windowThemes.remove(nodeId) @@ -1416,6 +1438,8 @@ class NodeTable { PropertyKind.CodeEditorColors, PropertyKind.OnCodeMetrics, PropertyKind.OnCodeScrolled, + // The handler told where the caret is drawn. + PropertyKind.OnCaretRect, -> widget == WidgetKind.CodeEditor PropertyKind.OnCompositionChange -> diff --git a/compose-rust/android-kotlin/shared/Protocol.gen.kt b/compose-rust/android-kotlin/shared/Protocol.gen.kt index 6392d253c..cfc8caa07 100644 --- a/compose-rust/android-kotlin/shared/Protocol.gen.kt +++ b/compose-rust/android-kotlin/shared/Protocol.gen.kt @@ -8,7 +8,7 @@ import java.nio.charset.StandardCharsets enum class WidgetKind { Column, Row, Box, Text, TextField, Button, Spacer, LazyColumn, ScrollColumn, Image, Icon, Checkbox, RadioButton, Switch, Slider, ProgressIndicator, Divider, Card, Surface, Dialog, Menu, Tabs, TopAppBar, LazyRow, Tooltip, Canvas, DatePicker, TimePicker, Dropdown, Navigation, NavigationItem, Sheet, Scaffold, ScaffoldSlot, LazyGrid, FileDropTarget, ScrollRow, Chip, FloatingAction, Badge, SelectionContainer, SplitPane, CodeEditor, AbsoluteBox, Window, FlowRow, Popover, LinearProgressIndicator } -enum class PropertyKind { Text, Placeholder, Enabled, Multiline, OnClick, OnValueChange, OnSubmit, OnFocusLost, OnKeyDown, ItemCount, ItemKey, OnRangeRequested, TypeRole, FontSize, FontWeight, LineHeight, LetterSpacing, Color, TextAlign, MaxLines, Overflow, Arrangement, Spacing, SpaceRole, Alignment, Variant, Asset, Checked, Steps, Determinate, Circular, Vertical, Open, OnDismiss, SelectedIndex, Commands, Value, Min, Max, Icon, Slot, Columns, MinColumnWidth, Spans, OnFilesEntered, OnFilesDropped, Section, Count, Collapsible, ButtonKind, Decorations, SyntaxSpans, TabWidth, OnEditRejected, OnHover, OnSave, OnDecorationClick, Folds, GutterDecorations, OnSelectionChange, Font, WordBreak, OverflowWrap, TabSize, AbsoluteSize, SoftWrap, SpanFonts, OnVisibleRangeChange, OnEditorFocusChange, OnFoldChange, OnCompositionChange, OnPointer, PointerKinds, Cursor, UserSelect, IslandZoom, WindowTitle, WindowSize, WindowMinSize, WindowResizable, WindowChrome, WindowTitleBar, WindowIcon, WindowPosition, WindowRestoreKey, WindowZoomLevel, DragFromPointer, OnWindowCloseRequested, OnWindowFocusChanged, OnWindowMoved, OnWindowDrag, OnWindowUnavailable, OnWindowClosed, OnWindowDragOver, TearOffKey, OnFocusGained, OnKeyUp, AccessibleName, TrackColor, ThumbColor, ActiveTrackColor, ContainerColor, CheckColor, ControlSize, ReportSize, Scrim, Bare, HorizontalSpacing, VerticalSpacing, HorizontalAlignment, VerticalAlignment, MaxItemsInEachRow, Placement, Align, OffsetDp, LineNumbers, GutterMinWidthDp, GutterPaddingDp, TextInsetDp, CodeEditorColors, OnCodeMetrics, OnCodeScrolled, CompactNavigation, OnScrollChanged, Snap, MaxHeightFraction, Progress } +enum class PropertyKind { Text, Placeholder, Enabled, Multiline, OnClick, OnValueChange, OnSubmit, OnFocusLost, OnKeyDown, ItemCount, ItemKey, OnRangeRequested, TypeRole, FontSize, FontWeight, LineHeight, LetterSpacing, Color, TextAlign, MaxLines, Overflow, Arrangement, Spacing, SpaceRole, Alignment, Variant, Asset, Checked, Steps, Determinate, Circular, Vertical, Open, OnDismiss, SelectedIndex, Commands, Value, Min, Max, Icon, Slot, Columns, MinColumnWidth, Spans, OnFilesEntered, OnFilesDropped, Section, Count, Collapsible, ButtonKind, Decorations, SyntaxSpans, TabWidth, OnEditRejected, OnHover, OnSave, OnDecorationClick, Folds, GutterDecorations, OnSelectionChange, Font, WordBreak, OverflowWrap, TabSize, AbsoluteSize, SoftWrap, SpanFonts, OnVisibleRangeChange, OnEditorFocusChange, OnFoldChange, OnCompositionChange, OnPointer, PointerKinds, Cursor, UserSelect, IslandZoom, WindowTitle, WindowSize, WindowMinSize, WindowResizable, WindowChrome, WindowTitleBar, WindowIcon, WindowPosition, WindowRestoreKey, WindowZoomLevel, DragFromPointer, OnWindowCloseRequested, OnWindowFocusChanged, OnWindowMoved, OnWindowDrag, OnWindowUnavailable, OnWindowClosed, OnWindowDragOver, TearOffKey, OnFocusGained, OnKeyUp, AccessibleName, TrackColor, ThumbColor, ActiveTrackColor, ContainerColor, CheckColor, ControlSize, ReportSize, Scrim, Bare, HorizontalSpacing, VerticalSpacing, HorizontalAlignment, VerticalAlignment, MaxItemsInEachRow, Placement, Align, OffsetDp, LineNumbers, GutterMinWidthDp, GutterPaddingDp, TextInsetDp, CodeEditorColors, OnCodeMetrics, OnCodeScrolled, CompactNavigation, OnScrollChanged, Snap, MaxHeightFraction, OnCaretRect, Progress } enum class Key { Enter, Other, Escape, Tab, Backspace, Delete, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Home, End, PageUp, PageDown } @@ -1494,6 +1494,17 @@ sealed interface Mutation { val rectWidthPx: Double, val rectHeightPx: Double, ) : Mutation + + /** + * Asks the code editor [nodeId] where a caret at [line] and [column] would be drawn. + * Answered once by a `PositionRect` event carrying [request]. + */ + data class QueryPositionRect( + val nodeId: Int, + val request: Int, + val line: Int, + val column: Int, + ) : Mutation } /** The words of the scroll records: flag bits, target kinds and alignments. */ @@ -1587,13 +1598,15 @@ sealed interface HostEvent { data class ScrollChanged(override val nodeId: Int, override val handlerId: Long, val item: Int, val flags: Int, val xPx: Double, val yPx: Double, val maxXPx: Double, val maxYPx: Double, val viewportWidthPx: Double, val viewportHeightPx: Double) : HostEvent data class CodeMetrics(override val nodeId: Int, override val handlerId: Long, val value: Double) : HostEvent data class CodeScrolled(override val nodeId: Int, override val handlerId: Long, val value: Double) : HostEvent + data class CaretRect(override val nodeId: Int, override val handlerId: Long, val line: Int, val column: Int, val x: kotlin.Float, val y: kotlin.Float, val width: kotlin.Float, val height: kotlin.Float) : HostEvent + data class PositionRect(override val nodeId: Int, override val handlerId: Long, val request: Int, val found: Boolean, val x: kotlin.Float, val y: kotlin.Float, val width: kotlin.Float, val height: kotlin.Float) : HostEvent } class ProtocolException(message: String, val offset: Int) : IllegalArgumentException("$message at byte offset $offset") object Protocol { - const val SCHEMA_HASH: Long = -5141307034944019668L + const val SCHEMA_HASH: Long = 6073216674444015188L const val PROTOCOL_VERSION: Int = 1 private const val TAG_ENVELOPE = 0 @@ -1632,6 +1645,7 @@ object Protocol { private const val TAG_RELEASE_FILE_HANDLE = 34 private const val TAG_SCROLL_TO = 35 private const val TAG_SCROLL_INTO_VIEW = 36 + private const val TAG_QUERY_POSITION_RECT = 39 private const val ENVELOPE_LENGTH = 12 private const val ANIMATION_HEADER_LENGTH = 52 private const val KEYFRAME_HEAD_LENGTH = 24 @@ -1879,6 +1893,15 @@ object Protocol { rectHeightPx = Double.fromBits(readU64(batch, base, available, offset + 44)), ) } + TAG_QUERY_POSITION_RECT -> { + requireRecordLength(length, 20, offset) + Mutation.QueryPositionRect( + nodeId = readU32(batch, base, available, offset + 4).toInt(), + request = readU32(batch, base, available, offset + 8).toInt(), + line = readU32(batch, base, available, offset + 12).toInt(), + column = readU32(batch, base, available, offset + 16).toInt(), + ) + } TAG_SET_WINDOW -> { requireRecordLength(length, 32, offset) // Bit 0 is `resizable`, bit 1 asks for every whole-dp size change; the @@ -2171,6 +2194,8 @@ object Protocol { is HostEvent.ScrollChanged -> null is HostEvent.CodeMetrics -> null is HostEvent.CodeScrolled -> null + is HostEvent.CaretRect -> null + is HostEvent.PositionRect -> null } val recordLength = when (event) { is HostEvent.Clicked -> 16 @@ -2223,6 +2248,8 @@ object Protocol { is HostEvent.ScrollChanged -> 72 is HostEvent.CodeMetrics -> 24 is HostEvent.CodeScrolled -> 24 + is HostEvent.CaretRect -> 40 + is HostEvent.PositionRect -> 40 } val totalLength = recordLength.toLong() + (text?.size ?: 0) if (totalLength > Int.MAX_VALUE || totalLength > out.remaining().toLong()) { @@ -2279,6 +2306,8 @@ object Protocol { is HostEvent.ScrollChanged -> 60 is HostEvent.CodeMetrics -> 54 is HostEvent.CodeScrolled -> 55 + is HostEvent.CaretRect -> 64 + is HostEvent.PositionRect -> 65 } out.putShort(tag.toShort()) out.putShort(recordLength.toShort()) @@ -2503,6 +2532,22 @@ object Protocol { } is HostEvent.CodeMetrics -> out.putDouble(event.value) is HostEvent.CodeScrolled -> out.putDouble(event.value) + is HostEvent.CaretRect -> { + out.putInt(event.line) + out.putInt(event.column) + out.putFloat(event.x) + out.putFloat(event.y) + out.putFloat(event.width) + out.putFloat(event.height) + } + is HostEvent.PositionRect -> { + out.putInt(event.request) + out.putInt(if (event.found) 1 else 0) + out.putFloat(if (event.found) event.x else 0f) + out.putFloat(if (event.found) event.y else 0f) + out.putFloat(if (event.found) event.width else 0f) + out.putFloat(if (event.found) event.height else 0f) + } } if (text != null) out.put(text) return out.position() - start @@ -2719,6 +2764,7 @@ object Protocol { 186 -> PropertyKind.OnScrollChanged 188 -> PropertyKind.Snap 189 -> PropertyKind.MaxHeightFraction + 195 -> PropertyKind.OnCaretRect 27 -> PropertyKind.Progress else -> throw ProtocolException("unknown property tag $tag", offset) } diff --git a/compose-rust/schema-hash.txt b/compose-rust/schema-hash.txt index 4fa2733c9..dc898c697 100644 --- a/compose-rust/schema-hash.txt +++ b/compose-rust/schema-hash.txt @@ -1 +1 @@ -0xb8a6687dd4f1e32c +0x544866635c36f654 diff --git a/compose-rust/src/boundary.rs b/compose-rust/src/boundary.rs index dec4e095d..9ee76e3a4 100644 --- a/compose-rust/src/boundary.rs +++ b/compose-rust/src/boundary.rs @@ -353,6 +353,8 @@ impl Host { crate::message::reset_messages(); // A clipboard write is the same: it belongs to the Host that asked for it. crate::clipboard::reset_clipboard(); + // A question about where a position is on screen was asked of the old Renderer. + crate::code::reset_position_queries(); // The Renderer reports its zoom again at start, and a level the last Host asked for // and never sent is that Host's business. crate::zoom::reset_zoom(); @@ -618,6 +620,27 @@ impl Host { self.render_and_finish(0) } + /// Hands where a position of a code editor is to the query that asked. The callback + /// runs like a handler, and what it changes is in the batch this call returns. An + /// answer nobody is waiting for any more is dropped. + fn position_rect( + &mut self, + request: u32, + rect: Option, + ) -> Result<(&[u8], i64), ProtocolError> { + let mut delivered = false; + { + let _dispatch_guard = EventDispatchGuard::enter(); + self.runtime.run_in_context(&mut || { + delivered = crate::code::deliver_position_rect(request, rect) + }); + } + if !delivered { + return self.empty_batch(); + } + self.render_and_finish(0) + } + /// Hands the Renderer's answer to whoever asked for it: an operation on a file picked on /// the web when the request number has its top bit set, a storage operation otherwise. /// @@ -855,6 +878,15 @@ impl Host { kinds, ); } + // Where a position of a code editor is on screen: the answer to a query an + // application asked, found by request number. It names the editor it is about + // and no handler. + EventPayload::PositionRect { request, rect } => { + if event.handler_id != 0 { + return Err(ProtocolError::InvalidValueKind(0)); + } + return self.position_rect(request, rect); + } // Where Android keeps the application's files. Operations that were waiting for // it go to the storage thread, which wakes them when they finish. EventPayload::StorageLocation(path) => { diff --git a/compose-rust/src/code.rs b/compose-rust/src/code.rs index cf7ca9ceb..d11ae8f3f 100644 --- a/compose-rust/src/code.rs +++ b/compose-rust/src/code.rs @@ -1122,3 +1122,128 @@ pub struct CodeScroll { /// `Batch::set_scroll_offset` takes. pub offset_px: f64, } + +/// A rectangle on screen, in the dp the window lays its content out in. +/// +/// The editor's own scroll is already in it, and so is the window's zoom, because the zoom +/// is part of what a dp is there. The origin is the top left corner of the window's +/// content, which is where an overlay the application opens over the editor is placed +/// from, so a suggestion list or a hover card can be put at `x`, `y + height` as it is. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct CodeRect { + pub x: f32, + pub y: f32, + pub width: f32, + pub height: f32, +} + +impl CodeRect { + pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self { + Self { + x, + y, + width, + height, + } + } + + /// The bottom edge, which is where a list that opens under the caret starts. + pub fn bottom(&self) -> f32 { + self.y + self.height + } + + /// The right edge. + pub fn right(&self) -> f32 { + self.x + self.width + } +} + +/// Where an editor draws its caret, as the Renderer reported it. +/// +/// Sent when the caret moves or the view scrolls, at most once a frame, and only to an +/// editor whose application listens for it. The rectangle is the caret itself: as tall as +/// a row and as wide as the caret is drawn. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CaretRect { + /// The place in the document the caret stands at. + pub position: Position, + pub rect: CodeRect, +} + +impl CaretRect { + /// The caret's place and rectangle out of a `CaretRect` event, or None for any other. + pub fn from_payload(payload: &crate::schema::EventPayload<'_>) -> Option { + match *payload { + crate::schema::EventPayload::CaretRect { line, column, rect } => Some(Self { + position: Position::new(line, column), + rect, + }), + _ => None, + } + } +} + +/// What a position query is answered with: the rectangle a caret at that position would be +/// drawn in, or None where the position is not on screen. +pub type PositionAnswer = Option; + +type PositionCallback = Box; + +thread_local! { + /// Callbacks waiting for their answer, by request number. + static POSITION_QUERIES: std::cell::RefCell> = + const { std::cell::RefCell::new(Vec::new()) }; + /// The next request number. 0 is skipped so a zeroed record never looks like a query. + static NEXT_POSITION_QUERY: std::cell::Cell = const { std::cell::Cell::new(1) }; +} + +/// Numbers one question about where a position of an editor is on screen, and keeps +/// `on_answer` until the answer arrives. +/// +/// The number goes into the command that asks it, `Batch::query_position_rect`, written by +/// whatever holds the editor's node. The Renderer answers every query exactly once, with +/// the rectangle a caret at that position would be drawn in, or with None where the +/// position is not on screen: scrolled away, folded, outside the document, or in an editor +/// that is gone. `on_answer` then runs on the UI thread, inside the call that carried the +/// answer, and anything it changes is in the batch that call returns. +/// +/// It is how a hover card, a rename box or a parameter hint is put next to a word that is +/// not where the caret is. +pub fn position_query(on_answer: impl FnOnce(PositionAnswer) + 'static) -> u32 { + let request = NEXT_POSITION_QUERY.with(|next| { + let mut id = next.get(); + if id == 0 { + id = 1; + } + next.set(id.wrapping_add(1)); + id + }); + POSITION_QUERIES.with_borrow_mut(|waiting| waiting.push((request, Box::new(on_answer)))); + request +} + +/// Hands an answer to the callback that asked for it. Returns whether there was one; an +/// answer nobody is waiting for any more is ignored. +pub(crate) fn deliver_position_rect(request: u32, answer: PositionAnswer) -> bool { + // Taken out before it runs: the callback may ask again, which edits the list. + let callback = POSITION_QUERIES.with_borrow_mut(|waiting| { + waiting + .iter() + .position(|(id, _)| *id == request) + .map(|at| waiting.remove(at).1) + }); + match callback { + Some(callback) => { + callback(answer); + true + } + None => false, + } +} + +/// Forgets every query still waiting. Used when a new `Host` takes over the thread: the +/// Renderer it talks to has never heard of them. +#[doc(hidden)] +pub fn reset_position_queries() { + POSITION_QUERIES.with_borrow_mut(Vec::clear); +} diff --git a/compose-rust/src/codegen.rs b/compose-rust/src/codegen.rs index 597d2376d..c02af44b4 100644 --- a/compose-rust/src/codegen.rs +++ b/compose-rust/src/codegen.rs @@ -641,6 +641,17 @@ sealed interface Mutation { val rectWidthPx: Double, val rectHeightPx: Double, ) : Mutation + + /** + * Asks the code editor [nodeId] where a caret at [line] and [column] would be drawn. + * Answered once by a `PositionRect` event carrying [request]. + */ + data class QueryPositionRect( + val nodeId: Int, + val request: Int, + val line: Int, + val column: Int, + ) : Mutation } /** The words of the scroll records: flag bits, target kinds and alignments. */ @@ -769,6 +780,15 @@ object ScrollWire { EventPayloadType::ScrollChanged => output.push_str( ", val item: Int, val flags: Int, val xPx: Double, val yPx: Double, val maxXPx: Double, val maxYPx: Double, val viewportWidthPx: Double, val viewportHeightPx: Double", ), + // In the window's dp, the scroll and the zoom already in them. + EventPayloadType::CodeCaretRect => output.push_str( + ", val line: Int, val column: Int, val x: kotlin.Float, val y: kotlin.Float, val width: kotlin.Float, val height: kotlin.Float", + ), + // `found` is false where the position is not on screen, and the rectangle is then + // all zero. + EventPayloadType::CodePositionRect => output.push_str( + ", val request: Int, val found: Boolean, val x: kotlin.Float, val y: kotlin.Float, val width: kotlin.Float, val height: kotlin.Float", + ), } if event.payload == EventPayloadType::IoAnswer { writeln!( @@ -845,6 +865,7 @@ object Protocol { private const val TAG_RELEASE_FILE_HANDLE = 34 private const val TAG_SCROLL_TO = 35 private const val TAG_SCROLL_INTO_VIEW = 36 + private const val TAG_QUERY_POSITION_RECT = 39 private const val ENVELOPE_LENGTH = 12 private const val ANIMATION_HEADER_LENGTH = 52 private const val KEYFRAME_HEAD_LENGTH = 24 @@ -1092,6 +1113,15 @@ object Protocol { rectHeightPx = Double.fromBits(readU64(batch, base, available, offset + 44)), ) } + TAG_QUERY_POSITION_RECT -> { + requireRecordLength(length, 20, offset) + Mutation.QueryPositionRect( + nodeId = readU32(batch, base, available, offset + 4).toInt(), + request = readU32(batch, base, available, offset + 8).toInt(), + line = readU32(batch, base, available, offset + 12).toInt(), + column = readU32(batch, base, available, offset + 16).toInt(), + ) + } TAG_SET_WINDOW -> { requireRecordLength(length, 32, offset) // Bit 0 is `resizable`, bit 1 asks for every whole-dp size change; the @@ -1395,7 +1425,10 @@ object Protocol { ) .unwrap(); } - EventPayloadType::None | EventPayloadType::ScrollChanged => { + EventPayloadType::None + | EventPayloadType::ScrollChanged + | EventPayloadType::CodeCaretRect + | EventPayloadType::CodePositionRect => { writeln!( output, " is HostEvent.{} -> null", @@ -1495,6 +1528,8 @@ object Protocol { EventPayloadType::FileHandles => 52, // The item and the flags, then six doubles. EventPayloadType::ScrollChanged => 72, + // Two words and four floats. + EventPayloadType::CodeCaretRect | EventPayloadType::CodePositionRect => 40, }; writeln!( output, @@ -1826,6 +1861,28 @@ object Protocol { output.push_str(" out.putDouble(event.viewportHeightPx)\n"); output.push_str(" }\n"); } + EventPayloadType::CodeCaretRect => { + writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap(); + output.push_str(" out.putInt(event.line)\n"); + output.push_str(" out.putInt(event.column)\n"); + for field in ["x", "y", "width", "height"] { + writeln!(output, " out.putFloat(event.{field})").unwrap(); + } + output.push_str(" }\n"); + } + EventPayloadType::CodePositionRect => { + writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap(); + output.push_str(" out.putInt(event.request)\n"); + output.push_str(" out.putInt(if (event.found) 1 else 0)\n"); + for field in ["x", "y", "width", "height"] { + writeln!( + output, + " out.putFloat(if (event.found) event.{field} else 0f)" + ) + .unwrap(); + } + output.push_str(" }\n"); + } EventPayloadType::FileHandles => { writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap(); output.push_str(" out.putInt(event.request)\n"); @@ -3629,6 +3686,14 @@ pub fn generate_mutation_vector() -> Result, ProtocolError> { node_id: 12, offset_px: 1234.5, }, + // A question about where a place on the editor's second line is, after its scroll + // command. + Mutation::QueryPositionRect { + node_id: 12, + request: 17, + line: 1, + column: 8, + }, // The overlay tokens with every field set to its own value, the transient // message's two at the end of the record, before the record that stays last. Mutation::SetOverlayTokens( @@ -4036,6 +4101,25 @@ pub fn generate_event_vector() -> Result, ProtocolError> { handler_id: 29, payload: EventPayload::CodeScrolled { offset_px: 1234.5 }, }, + // The caret's rectangle and the answer to the position query in the mutation + // vector, each with fractions a reader of the wrong width cannot pass. + HostEvent { + node_id: 12, + handler_id: 30, + payload: EventPayload::CaretRect { + line: 1, + column: 8, + rect: crate::code::CodeRect::new(120.5, 64.25, 2.0, 20.0), + }, + }, + HostEvent { + node_id: 12, + handler_id: 0, + payload: EventPayload::PositionRect { + request: 17, + rect: Some(crate::code::CodeRect::new(88.75, 64.25, 2.0, 20.0)), + }, + }, ]; let mut output = Vec::new(); let mut encoded = Vec::new(); @@ -4055,7 +4139,7 @@ pub fn generate_vector_description() -> String { "mutations": {{ "file": "mutations.bin", "description": "One batch covering every record, property value, modifier layout, drawing command, asset, message, notification command, palette entry, text run, split pane property, the HTML and CSS drawing elements, the animations the Renderer plays and code editor record", - "recordCount": 121, + "recordCount": 122, "palette": [ {{ "role": "Primary", "scheme": "Light", "argb": "ffe8590c" }}, {{ "role": "Primary", "scheme": "Dark", "argb": "ffff8a4c" }}, @@ -4077,7 +4161,7 @@ pub fn generate_vector_description() -> String { }}, "events": {{ "file": "events.bin", - "description": "Forty-two independently decodable event records concatenated in schema order", + "description": "Forty-four independently decodable event records concatenated in schema order", "records": [ {{ "type": "Clicked", "offset": 0, "length": 16, "nodeId": 7, "handlerId": 11 }}, {{ "type": "TextChanged", "offset": 16, "length": 30, "nodeId": 8, "handlerId": 12, "text": "한글" }}, @@ -4120,7 +4204,9 @@ pub fn generate_vector_description() -> String { {{ "type": "StorageLocation", "offset": 1237, "length": 82, "nodeId": 0, "handlerId": 0, "text": "/data/user/0/dev.darkpyonix.composerust.samples.todo/files" }}, {{ "type": "ScrollChanged", "offset": 1319, "length": 72, "nodeId": 10, "handlerId": 21, "item": 3, "flags": 3, "xPx": 0.0, "yPx": 700.5, "maxXPx": 0.0, "maxYPx": -1.0, "viewportWidthPx": 320.0, "viewportHeightPx": 300.0 }}, {{ "type": "CodeMetrics", "offset": 1391, "length": 24, "nodeId": 12, "handlerId": 28, "value": 40.0 }}, - {{ "type": "CodeScrolled", "offset": 1415, "length": 24, "nodeId": 12, "handlerId": 29, "value": 1234.5 }} + {{ "type": "CodeScrolled", "offset": 1415, "length": 24, "nodeId": 12, "handlerId": 29, "value": 1234.5 }}, + {{ "type": "CaretRect", "offset": 1439, "length": 40, "nodeId": 12, "handlerId": 30, "line": 1, "column": 8, "x": 120.5, "y": 64.25, "width": 2.0, "height": 20.0 }}, + {{ "type": "PositionRect", "offset": 1479, "length": 40, "nodeId": 12, "handlerId": 0, "request": 17, "found": true, "x": 88.75, "y": 64.25, "width": 2.0, "height": 20.0 }} ] }} }} diff --git a/compose-rust/src/lib.rs b/compose-rust/src/lib.rs index 1b22f2138..3a057f567 100644 --- a/compose-rust/src/lib.rs +++ b/compose-rust/src/lib.rs @@ -70,9 +70,10 @@ pub use boundary::{ }; pub use brush::{Brush, Stop, brush, release_brush}; pub use code::{ - CodeChange, CodeEditorColors, CodeHover, CodeMetrics, CodeRange, CodeScroll, Decoration, - Decorations, EditRejected, Fold, FoldChange, Folds, GutterDecoration, GutterDecorations, - Position, SaveRequest, SelectionChange, SyntaxSpan, SyntaxSpans, VisibleRange, + CaretRect, CodeChange, CodeEditorColors, CodeHover, CodeMetrics, CodeRange, CodeRect, + CodeScroll, Decoration, Decorations, EditRejected, Fold, FoldChange, Folds, GutterDecoration, + GutterDecorations, Position, SaveRequest, SelectionChange, SyntaxSpan, SyntaxSpans, + VisibleRange, }; #[doc(hidden)] pub use compose_rust_macros::__compose_call_check; diff --git a/compose-rust/src/protocol.rs b/compose-rust/src/protocol.rs index edf89cd09..0fa6f5b90 100644 --- a/compose-rust/src/protocol.rs +++ b/compose-rust/src/protocol.rs @@ -73,6 +73,12 @@ const TAG_RELEASE_FILE_HANDLE: u16 = 34; // the Renderer owns the position and reports what it did in `ScrollChanged`. const TAG_SCROLL_TO: u16 = 35; const TAG_SCROLL_INTO_VIEW: u16 = 36; +// 37 and 38 are held by commands on other branches. 39 asks a code editor where a position +// is on screen, answered by one `PositionRect` event carrying the same request number. +const TAG_QUERY_POSITION_RECT: u16 = 39; +/// `QueryPositionRect` in full: the 4 byte head, the node, the request, the line and the +/// column. +const QUERY_POSITION_RECT_LEN: usize = 20; /// `ScrollTo` in full: the 4 byte head, the node, the item, the flags and two `f64`. const SCROLL_TO_LEN: usize = 32; /// `ScrollIntoView` in full: the 4 byte head, the node, the target, four `u16` and four `f64`. @@ -377,6 +383,15 @@ pub enum Mutation<'a> { flags: u16, rect: crate::schema::Rect, }, + /// Asks the code editor `node_id` where a caret at `line` and `column` would be drawn. + /// Answered exactly once, by a `PositionRect` event carrying `request`: a rectangle in + /// the window's dp, or none where the position is not on screen. + QueryPositionRect { + node_id: u32, + request: u32, + line: u32, + column: u32, + }, } #[derive(Clone, Debug, Eq, PartialEq)] @@ -488,6 +503,12 @@ const EVENT_STORAGE_LOCATION: u16 = 59; const EVENT_SCROLL_CHANGED: u16 = 60; /// `ScrollChanged` in full: the 16 byte header, the item, the flags and six `f64`. const SCROLL_CHANGED_LEN: usize = 72; +// 61 to 63 are held by events on other branches. 64 is where a code editor's caret is +// drawn and 65 the answer to a position query, both with a rectangle of four `f32`. +const EVENT_CARET_RECT: u16 = 64; +const EVENT_POSITION_RECT: u16 = 65; +/// `CaretRect` and `PositionRect` in full: the 16 byte header, two words and four `f32`. +const CODE_RECT_EVENT_LEN: usize = 40; /// Where `SetWindow` keeps the mode and the last window policy: in the bits of the /// `resizable` word above the flag. @@ -943,6 +964,32 @@ pub fn decode_event(bytes: &[u8]) -> Result, ProtocolError> { } } EVENT_SCROLL_CHANGED => return Err(ProtocolError::InvalidRecordLength), + EVENT_CARET_RECT if record_len == CODE_RECT_EVENT_LEN => { + crate::schema::EventPayload::CaretRect { + line: read_u32(bytes, 16)?, + column: read_u32(bytes, 20)?, + rect: read_code_rect(bytes, 24)?, + } + } + EVENT_POSITION_RECT if record_len == CODE_RECT_EVENT_LEN => { + let found = read_u32(bytes, 20)?; + let rect = read_code_rect(bytes, 24)?; + crate::schema::EventPayload::PositionRect { + request: read_u32(bytes, 16)?, + rect: match found { + 0 => None, + 1 => Some(rect), + other => { + return Err(ProtocolError::InvalidValueKind( + other.min(u32::from(u16::MAX)) as u16, + )); + } + }, + } + } + EVENT_CARET_RECT | EVENT_POSITION_RECT => { + return Err(ProtocolError::InvalidRecordLength); + } EVENT_WINDOW_CLOSE_REQUESTED..=EVENT_APPLICATION_REOPEN => { return Err(ProtocolError::InvalidRecordLength); } @@ -981,6 +1028,22 @@ pub fn decode_event(bytes: &[u8]) -> Result, ProtocolError> { }) } +/// The four `f32` of a code editor rectangle, starting at `offset`. +fn read_code_rect(bytes: &[u8], offset: usize) -> Result { + Ok(crate::code::CodeRect { + x: f32::from_bits(read_u32(bytes, offset)?), + y: f32::from_bits(read_u32(bytes, offset + 4)?), + width: f32::from_bits(read_u32(bytes, offset + 8)?), + height: f32::from_bits(read_u32(bytes, offset + 12)?), + }) +} + +fn put_code_rect(output: &mut Vec, rect: crate::code::CodeRect) { + for value in [rect.x, rect.y, rect.width, rect.height] { + output.extend_from_slice(&value.to_bits().to_le_bytes()); + } +} + /// Test/mock helper for constructing a Renderer-to-Host event. pub fn encode_event(event: &HostEvent<'_>, output: &mut Vec) -> Result<(), ProtocolError> { output.clear(); @@ -1464,6 +1527,25 @@ pub fn encode_event(event: &HostEvent<'_>, output: &mut Vec) -> Result<(), P } return Ok(()); } + if let crate::schema::EventPayload::CaretRect { line, column, rect } = event.payload { + put_event_header(output, EVENT_CARET_RECT, CODE_RECT_EVENT_LEN as u16, event); + output.extend_from_slice(&line.to_le_bytes()); + output.extend_from_slice(&column.to_le_bytes()); + put_code_rect(output, rect); + return Ok(()); + } + if let crate::schema::EventPayload::PositionRect { request, rect } = event.payload { + put_event_header( + output, + EVENT_POSITION_RECT, + CODE_RECT_EVENT_LEN as u16, + event, + ); + output.extend_from_slice(&request.to_le_bytes()); + output.extend_from_slice(&u32::from(rect.is_some()).to_le_bytes()); + put_code_rect(output, rect.unwrap_or_default()); + return Ok(()); + } if let crate::schema::EventPayload::ZoomChanged { k, os, level } = event.payload { output.extend_from_slice(&EVENT_ZOOM_CHANGED.to_le_bytes()); output.extend_from_slice(&28_u16.to_le_bytes()); @@ -1551,7 +1633,9 @@ pub fn encode_event(event: &HostEvent<'_>, output: &mut Vec) -> Result<(), P | crate::schema::EventPayload::ClipboardText { .. } | crate::schema::EventPayload::IoAnswer { .. } | crate::schema::EventPayload::FileHandles { .. } - | crate::schema::EventPayload::ScrollChanged { .. } => unreachable!(), + | crate::schema::EventPayload::ScrollChanged { .. } + | crate::schema::EventPayload::CaretRect { .. } + | crate::schema::EventPayload::PositionRect { .. } => unreachable!(), crate::schema::EventPayload::AnimationEvent { .. } | crate::schema::EventPayload::Pointer { .. } | crate::schema::EventPayload::ReducedMotionChanged(_) @@ -1946,6 +2030,21 @@ impl BatchEncoder { self.put_u64(x_px.to_bits()); self.put_u64(y_px.to_bits()); } + Mutation::QueryPositionRect { + node_id, + request, + line, + column, + } => { + self.begin_record( + TAG_QUERY_POSITION_RECT, + (QUERY_POSITION_RECT_LEN - 4) as u16, + ); + self.put_u32(*node_id); + self.put_u32(*request); + self.put_u32(*line); + self.put_u32(*column); + } Mutation::ScrollIntoView { node_id, target, @@ -2684,6 +2783,15 @@ pub fn decode_batch(bytes: &[u8]) -> Result>, ProtocolError> { offset_px: f64::from_bits(read_u64(bytes, payload + 4)?), }, TAG_SET_SCROLL_OFFSET => return Err(ProtocolError::InvalidRecordLength), + TAG_QUERY_POSITION_RECT if len == QUERY_POSITION_RECT_LEN => { + Mutation::QueryPositionRect { + node_id: read_u32(bytes, payload)?, + request: read_u32(bytes, payload + 4)?, + line: read_u32(bytes, payload + 8)?, + column: read_u32(bytes, payload + 12)?, + } + } + TAG_QUERY_POSITION_RECT => return Err(ProtocolError::InvalidRecordLength), TAG_CREATE..=TAG_EDIT_CODE | TAG_START_ANIMATION | TAG_CONTROL_ANIMATION diff --git a/compose-rust/src/runtime/seam.rs b/compose-rust/src/runtime/seam.rs index a2bd57cee..fad187709 100644 --- a/compose-rust/src/runtime/seam.rs +++ b/compose-rust/src/runtime/seam.rs @@ -374,6 +374,24 @@ impl Batch { self.write(Mutation::SetScrollOffset { node_id, offset_px }); } + /// Writes one question to a code editor: where would a caret at `position` be drawn. + /// `request` is the number [`crate::code::position_query`] gave the callback that waits + /// for the answer. The Renderer answers it exactly once, with a rectangle in the + /// window's dp, or with none where the position is not on screen. + pub fn query_position_rect( + &mut self, + node_id: u32, + request: u32, + position: crate::code::Position, + ) { + self.write(Mutation::QueryPositionRect { + node_id, + request, + line: position.line, + column: position.column, + }); + } + /// Appends the streamed tail to a Text node without resending its whole value. pub fn append_text_node(&mut self, node_id: u32, text: &str) { self.write(Mutation::AppendText { node_id, text }); diff --git a/compose-rust/src/schema.rs b/compose-rust/src/schema.rs index f1ca41a1f..31dd7b5f4 100644 --- a/compose-rust/src/schema.rs +++ b/compose-rust/src/schema.rs @@ -207,6 +207,13 @@ pub enum EventPayloadType { /// physical pixels (offset, furthest offset and viewport, x before y). A fixed 72-byte /// record. ScrollChanged, + /// Where a code editor's caret is drawn: the line and the column it stands at, then + /// `x`, `y`, `width` and `height` as `f32` in the window's dp. A fixed 40-byte record. + CodeCaretRect, + /// The answer to one position query: the request number, a word that is 1 when the + /// position is on screen and 0 when it is not, then the rectangle as in + /// `CodeCaretRect`, all zero when there is none. A fixed 40-byte record. + CodePositionRect, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -220,13 +227,13 @@ pub struct EventSchema { pub const SCHEMA_DESCRIPTOR: &str = concat!( "compose-rust/v1;", "widgets=Column,Row,Box,Text,TextField,Button,Spacer,LazyColumn,ScrollColumn,Image,Icon,Checkbox,RadioButton,Switch,Slider,ProgressIndicator,Divider,Card,Surface,Dialog,Menu,Tabs,TopAppBar,LazyRow,Tooltip,Canvas,DatePicker,TimePicker,Dropdown,Navigation,NavigationItem,Sheet,Scaffold,ScaffoldSlot,LazyGrid,FileDropTarget,ScrollRow,Chip,FloatingAction,Badge,SelectionContainer,SplitPane,CodeEditor,AbsoluteBox,Window,FlowRow,Popover;", - "properties=text,placeholder,enabled,multiline,on_click,on_value_change,on_submit,on_focus_lost,on_key_down,item_count,item_key,on_range_requested,type_role,font_size,font_weight,line_height,letter_spacing,color,text_align,max_lines,overflow,arrangement,spacing,space_role,alignment,variant,asset,checked,steps,determinate,circular,vertical,open,on_dismiss,selected_index,commands,value,min,max,icon,slot,columns,min_column_width,spans,on_files_entered,on_files_dropped,section,count,collapsible,button_kind,decorations,syntax_spans,tab_width,on_edit_rejected,on_hover,on_save,on_decoration_click,folds,gutter_decorations,on_selection_change,font,word_break,overflow_wrap,tab_size,absolute_size,soft_wrap,span_fonts,on_visible_range_change,on_editor_focus_change,on_fold_change,on_composition_change,on_pointer,pointer_kinds,cursor,user_select,island_zoom,window_title,window_size,window_min_size,window_resizable,window_chrome,window_title_bar,window_icon,window_position,window_restore_key,window_zoom_level,drag_from_pointer,on_window_close_requested,on_window_focus_changed,on_window_moved,on_window_drag,on_window_unavailable,on_window_closed,on_window_drag_over,tear_off_key,on_focus_gained,on_key_up,accessible_name,track_color,thumb_color,active_track_color,container_color,check_color,control_size,report_size,scrim,bare,horizontal_spacing,vertical_spacing,horizontal_alignment,vertical_alignment,max_items_in_each_row,placement,align,offset_dp,line_numbers,gutter_min_width_dp,gutter_padding_dp,text_inset_dp,code_editor_colors,on_code_metrics,on_code_scrolled,compact_navigation,on_scroll_changed,snap,max_height_fraction;", + "properties=text,placeholder,enabled,multiline,on_click,on_value_change,on_submit,on_focus_lost,on_key_down,item_count,item_key,on_range_requested,type_role,font_size,font_weight,line_height,letter_spacing,color,text_align,max_lines,overflow,arrangement,spacing,space_role,alignment,variant,asset,checked,steps,determinate,circular,vertical,open,on_dismiss,selected_index,commands,value,min,max,icon,slot,columns,min_column_width,spans,on_files_entered,on_files_dropped,section,count,collapsible,button_kind,decorations,syntax_spans,tab_width,on_edit_rejected,on_hover,on_save,on_decoration_click,folds,gutter_decorations,on_selection_change,font,word_break,overflow_wrap,tab_size,absolute_size,soft_wrap,span_fonts,on_visible_range_change,on_editor_focus_change,on_fold_change,on_composition_change,on_pointer,pointer_kinds,cursor,user_select,island_zoom,window_title,window_size,window_min_size,window_resizable,window_chrome,window_title_bar,window_icon,window_position,window_restore_key,window_zoom_level,drag_from_pointer,on_window_close_requested,on_window_focus_changed,on_window_moved,on_window_drag,on_window_unavailable,on_window_closed,on_window_drag_over,tear_off_key,on_focus_gained,on_key_up,accessible_name,track_color,thumb_color,active_track_color,container_color,check_color,control_size,report_size,scrim,bare,horizontal_spacing,vertical_spacing,horizontal_alignment,vertical_alignment,max_items_in_each_row,placement,align,offset_dp,line_numbers,gutter_min_width_dp,gutter_padding_dp,text_inset_dp,code_editor_colors,on_code_metrics,on_code_scrolled,compact_navigation,on_scroll_changed,snap,max_height_fraction,on_caret_rect;", "modifiers=Empty,Padding,FillMaxWidth,FillMaxHeight,Width,Height,Size,Background,Clickable,PaddingRole,PaddingEach,Weight,Shape,ShapeRole,Border,Elevation,ObserveSize,Motion,Material,Offset,RequiredSize,BorderEach,CornerEach,Shadow,Clip,Alpha,Transform,Transform3D,MatchParentSize,WindowDrag,PressFeedback,Semantics,CornerCurve;", "keys=Enter,Other;", - "events=Clicked,TextChanged,TextSubmitted,FocusLost,ProtocolError,KeyDown,RangeRequested,ValueChanged,WindowSizeChanged,DesignSystemResolved,FilesEntered,FilesDropped,NotificationActivated,NotificationPermissionChanged,CodeChanged,CodeEditRejected,CodeHovered,CodeSaveRequested,DecorationActivated,AnimationEvent,ReducedMotionChanged,Pointer,ZoomChanged,SelectionChanged,VisibleRangeChanged,EditorFocusChanged,FoldChanged,CompositionChanged,WindowCloseRequested,WindowFocusChanged,WindowMoved,WindowDrag,WindowDragOver,WindowUnavailable,WindowClosed,WindowRequested,ApplicationReopen,FocusGained,KeyUp,FileDialogResult,ClipboardText,CodeMetrics,CodeScrolled,IoAnswer,FileHandles,StorageLocation,ScrollChanged;", + "events=Clicked,TextChanged,TextSubmitted,FocusLost,ProtocolError,KeyDown,RangeRequested,ValueChanged,WindowSizeChanged,DesignSystemResolved,FilesEntered,FilesDropped,NotificationActivated,NotificationPermissionChanged,CodeChanged,CodeEditRejected,CodeHovered,CodeSaveRequested,DecorationActivated,AnimationEvent,ReducedMotionChanged,Pointer,ZoomChanged,SelectionChanged,VisibleRangeChanged,EditorFocusChanged,FoldChanged,CompositionChanged,WindowCloseRequested,WindowFocusChanged,WindowMoved,WindowDrag,WindowDragOver,WindowUnavailable,WindowClosed,WindowRequested,ApplicationReopen,FocusGained,KeyUp,FileDialogResult,ClipboardText,CodeMetrics,CodeScrolled,IoAnswer,FileHandles,StorageLocation,ScrollChanged,CaretRect,PositionRect;", "windowsizeclasses=Compact,Medium,Expanded;", "windowheightclasses=Compact,Medium,Expanded;", - "commands=Create,SetProp,SetModifier,Insert,Move,Remove,SetText,AppendText,SetTheme,SetWindow,RegisterAsset,ReleaseAsset,ShowMessage,PostNotification,WithdrawNotification,RequestNotificationPermission,EditCode,StartAnimation,ControlAnimation,SetSelection,RevealRange,SetFolded,SetWindowTheme,FocusWindow,RequestFocus,ShowFileDialog,SetOverlayTokens,SetClipboardText,ReadClipboard,SetScrollOffset,StorageCall,FileCall,ReleaseFileHandle,ScrollTo,ScrollIntoView;", + "commands=Create,SetProp,SetModifier,Insert,Move,Remove,SetText,AppendText,SetTheme,SetWindow,RegisterAsset,ReleaseAsset,ShowMessage,PostNotification,WithdrawNotification,RequestNotificationPermission,EditCode,StartAnimation,ControlAnimation,SetSelection,RevealRange,SetFolded,SetWindowTheme,FocusWindow,RequestFocus,ShowFileDialog,SetOverlayTokens,SetClipboardText,ReadClipboard,SetScrollOffset,StorageCall,FileCall,ReleaseFileHandle,ScrollTo,ScrollIntoView,QueryPositionRect;", // The fields of the overlay tokens record in wire order. A field is only appended, and // appending one changes the record's length, so it is part of what the hash covers. "overlaytokens=sheet_corner_radius,dialog_corner_radius,popup_corner_radius,sheet_elevation,popup_elevation,dialog_elevation,sheet_padding,dialog_padding,popup_padding,scrim,toast_elevation,toast_corner_radius" @@ -398,6 +405,8 @@ const fn schema_hash() -> u64 { EventPayloadType::IoAnswer => 31, EventPayloadType::FileHandles => 32, EventPayloadType::ScrollChanged => 33, + EventPayloadType::CodeCaretRect => 34, + EventPayloadType::CodePositionRect => 35, }], ); index += 1; @@ -3583,6 +3592,9 @@ crate::extensions::define_property_schema_with_extensions!(define_wire_enum; PRO // Absent leaves the height to the design system. 187 is held by a property on another // branch. MaxHeightFraction = 189, + // The handler a code editor tells where its caret is drawn. 190 to 194 are held by + // properties on other branches. + OnCaretRect = 195, }); #[derive(Clone, Debug, PartialEq)] @@ -3923,6 +3935,19 @@ pub enum EventPayload<'a> { viewport_width_px: f64, viewport_height_px: f64, }, + /// Where a code editor draws its caret, in the window's dp with the scroll and the zoom + /// already in it. At most once a frame, when the caret or the view moves. + CaretRect { + line: u32, + column: u32, + rect: crate::code::CodeRect, + }, + /// The answer to one `QueryPositionRect`, carrying the request number the Host gave + /// it. `None` where the position is not on screen. + PositionRect { + request: u32, + rect: Option, + }, } /// A rectangle in physical pixels, for [`ScrollTarget`]. @@ -4302,6 +4327,18 @@ pub const EVENT_SCHEMA: &[EventSchema] = &[ tag: 55, payload: EventPayloadType::Double, }, + // 61 to 63 are held by events on other branches. Where a code editor's caret is drawn, + // and the answer to a question about where a position is. + EventSchema { + name: "CaretRect", + tag: 64, + payload: EventPayloadType::CodeCaretRect, + }, + EventSchema { + name: "PositionRect", + tag: 65, + payload: EventPayloadType::CodePositionRect, + }, ]; /// One argument of a boundary operation. diff --git a/compose-rust/tests/code_editor.rs b/compose-rust/tests/code_editor.rs index 56909c75c..bd5ddd1c9 100644 --- a/compose-rust/tests/code_editor.rs +++ b/compose-rust/tests/code_editor.rs @@ -3,10 +3,11 @@ //! and back here; what a Dioxus component sends is tested in the adapter. use compose_rust::code::{ - CODE_EDITOR_COLORS_LEN, CODE_EDITOR_COLORS_RECORD, CodeChange, CodeEditorColors, CodeRange, - DECORATION_LEN, DECORATION_RECORD, Decoration, Decorations, FOLD_LEN, FOLD_RECORD, Fold, Folds, - GUTTER_DECORATION_LEN, GUTTER_DECORATION_RECORD, GutterDecoration, GutterDecorations, Position, - RecordFieldType, SYNTAX_SPAN_LEN, SYNTAX_SPAN_RECORD, SyntaxSpan, SyntaxSpans, byte_offset, + CODE_EDITOR_COLORS_LEN, CODE_EDITOR_COLORS_RECORD, CaretRect, CodeChange, CodeEditorColors, + CodeRange, CodeRect, DECORATION_LEN, DECORATION_RECORD, Decoration, Decorations, FOLD_LEN, + FOLD_RECORD, Fold, Folds, GUTTER_DECORATION_LEN, GUTTER_DECORATION_RECORD, GutterDecoration, + GutterDecorations, Position, PositionAnswer, RecordFieldType, SYNTAX_SPAN_LEN, + SYNTAX_SPAN_RECORD, SyntaxSpan, SyntaxSpans, byte_offset, position_query, }; use compose_rust::protocol::{ BatchEncoder, HostEvent, Mutation, PropertyValue, ProtocolError, decode_batch, decode_event, @@ -51,6 +52,11 @@ enum Record { node_id: u32, offset_px: f64, }, + QueryPositionRect { + node_id: u32, + request: u32, + position: Position, + }, Other, } @@ -141,6 +147,16 @@ fn records(batch: &[u8]) -> Vec { Mutation::SetScrollOffset { node_id, offset_px } => { Record::SetScrollOffset { node_id, offset_px } } + Mutation::QueryPositionRect { + node_id, + request, + line, + column, + } => Record::QueryPositionRect { + node_id, + request, + position: Position::new(line, column), + }, _ => Record::Other, }) .collect() @@ -1027,3 +1043,175 @@ fn fr38_editor_scroll_offset_round_trips_on_the_wire() { short[14] = 12; assert!(decode_batch(&short).is_err()); } + +/// The caret report, the position query and its answer keep the tags the wire table gives +/// them, past the numbers other requirements hold. +#[test] +fn fr38_caret_and_position_rects_keep_their_assigned_tags() { + assert_eq!(PropertyKind::OnCaretRect as u16, 195); + assert_eq!(event_tag("CaretRect"), 64); + assert_eq!(event_tag("PositionRect"), 65); + assert_eq!( + PropertyKind::from_name("on_caret_rect"), + Ok(PropertyKind::OnCaretRect) + ); +} + +/// The caret comes back as two words and four floats in a 40 byte record, read into the +/// place and the rectangle. A record of another length under the same tag is refused. +#[test] +fn fr38_editor_reports_the_caret_rect_on_the_wire() { + let rect = CodeRect::new(120.5, 64.25, 2.0, 20.0); + let (length, decoded) = round_trip(EventPayload::CaretRect { + line: 2, + column: 4, + rect, + }); + assert_eq!(length, 40); + assert_eq!( + CaretRect::from_payload(&decoded.payload), + Some(CaretRect { + position: Position::new(2, 4), + rect, + }) + ); + assert_eq!(rect.bottom(), 84.25); + assert_eq!(rect.right(), 122.5); + assert_eq!( + CaretRect::from_payload(&EventPayload::CodeSaveRequested { version: 1 }), + None + ); + + let mut wire = Vec::new(); + encode_event( + &HostEvent { + node_id: 3, + handler_id: 9, + payload: EventPayload::CaretRect { + line: 0, + column: 0, + rect, + }, + }, + &mut wire, + ) + .unwrap(); + assert_eq!(&wire[0..4], &[64, 0, 40, 0]); + wire[2] = 36; + assert_eq!( + decode_event(&wire[..36]), + Err(ProtocolError::InvalidRecordLength) + ); +} + +thread_local! { + static ANSWERS: std::cell::RefCell> = + const { std::cell::RefCell::new(Vec::new()) }; +} + +#[compose_rust::runtime::Composable] +fn Nothing() { + compose_rust::ui::Text("editor"); +} + +/// The query is a 20 byte command written with the request number a callback was given, +/// the answer a 40 byte event with a word that says whether the position is on screen, and +/// through a Host the answer reaches its own callback once. +#[test] +fn fr38_editor_answers_position_rects_on_the_wire() { + ANSWERS.with_borrow_mut(Vec::clear); + let near = position_query(|answer| ANSWERS.with_borrow_mut(|all| all.push(("near", answer)))); + let far = position_query(|answer| ANSWERS.with_borrow_mut(|all| all.push(("far", answer)))); + assert_ne!(near, 0, "0 is never a request number"); + assert_ne!(near, far); + + let mut batch = compose_rust::Batch::new(); + batch.begin(); + batch.query_position_rect(4, near, Position::new(1, 8)); + let bytes = batch.finish().unwrap().to_vec(); + assert_eq!(&bytes[12..16], &[39, 0, 20, 0]); + assert_eq!( + records(&bytes), + vec![Record::QueryPositionRect { + node_id: 4, + request: near, + position: Position::new(1, 8), + }] + ); + let mut short = bytes.clone(); + short[14] = 16; + assert!(decode_batch(&short).is_err()); + + let rect = CodeRect::new(88.75, 64.25, 2.0, 20.0); + let (length, _) = round_trip(EventPayload::PositionRect { + request: near, + rect: Some(rect), + }); + assert_eq!(length, 40); + let (length, decoded) = round_trip(EventPayload::PositionRect { + request: far, + rect: None, + }); + assert_eq!(length, 40); + assert_eq!( + decoded.payload, + EventPayload::PositionRect { + request: far, + rect: None + } + ); + // The word is 0 or 1, and anything else is a record the two sides disagree on. + let mut wire = Vec::new(); + encode_event( + &HostEvent { + node_id: 4, + handler_id: 0, + payload: EventPayload::PositionRect { + request: far, + rect: Some(rect), + }, + }, + &mut wire, + ) + .unwrap(); + assert_eq!(&wire[20..24], &[1, 0, 0, 0]); + wire[20] = 2; + assert_eq!(decode_event(&wire), Err(ProtocolError::InvalidValueKind(2))); + + // Through a Host: each answer goes to the callback that asked, once. + let mut host = compose_rust::ComposeHost::with_theme( + Nothing, + compose_rust::schema::Theme::unified(compose_rust::schema::DesignSystem::Material3), + ); + host.rebuild().expect("the first batch encodes"); + // Made after the Host, which forgets every query a Host before it left waiting. + let near = position_query(|answer| ANSWERS.with_borrow_mut(|all| all.push(("near", answer)))); + let far = position_query(|answer| ANSWERS.with_borrow_mut(|all| all.push(("far", answer)))); + let answer = |request: u32, rect: Option| HostEvent { + node_id: 4, + handler_id: 0, + payload: EventPayload::PositionRect { request, rect }, + }; + host.dispatch(answer(far, None)) + .expect("the answer dispatches"); + host.dispatch(answer(near, Some(rect))) + .expect("the answer dispatches"); + host.dispatch(answer(near, None)) + .expect("an answer nobody waits for is ignored"); + assert_eq!( + ANSWERS.with_borrow(Clone::clone), + vec![("far", None), ("near", Some(rect))] + ); + // An answer is addressed to no handler. + assert!( + host.dispatch(HostEvent { + node_id: 4, + handler_id: 7, + payload: EventPayload::PositionRect { + request: far, + rect: None + }, + }) + .is_err() + ); +} diff --git a/compose-rust/tests/vectors/events.bin b/compose-rust/tests/vectors/events.bin index 690717d0471903456097ff8808be7cce0f7b5bdc..b0cd0bfcdf61795a205cb5d71d5f76361eb6d405 100644 GIT binary patch delta 88 zcmbQw{hoWneAWO51`P%t1_lN>AO-zr$6G&qbgN21?qolDA5ex&0 zf>p2(6qO)B!GFO*tgLMW#l~PG;@c#Ga~!|jH*aU>=ITK+h!91o*A#*wm7CsvCUaMDRy~Q&xk!P>x+WZ2YCfl*4)JgDLrxj1;<^=Md| zG(lI`<2t$peee;K;42sgKe}vzDl|M6Dz|vmkm9GYW7H!e&!eXFmlH&H9T!XkFcB@G zkzp>HBZ)$Pr@6mO1(_0`m{L^v#;k}ZPForO8Lr-cHPo$#aK3QSlH!fmtab6p?^u6x z$PP43^0@t=nUcfKwB}0AJ2P1qA7JBP22@Q1U<{lDQ{WKP0$(_T3uP!dDEpwA!V#!W yq~UXjs%lC)-c#r*6xD=P9@DHEB-;Bk=qB_g`|&R?M_#)MDj-kz8$=D;W#booi$%Zy delta 455 zcmYk2F-QVo6vyAYJ0nZ)Jk7ff2^Euq2%#WaY6vO^8zO3RtD&sHAtVrzprBD6QA17A z7!eXdP&740OAxf=7D25+i~YYe=zSc&@B6?1_r7=UDpSk&i2{_15S6R`QO;E-;=Fv3 zKi7Cog1XB^N$YVg$+Vv0Em_qUcw27t*^QkZB7=y!sgrzQfD$wZs@Ov=3?8*T8uliQ z(=pC?j!r=jyaiqG3G4u0+H8O-G%O318&Wh}ey{HvH9wEYu<3eBQKIXX3#ML}h*r=@ zNb=@TH0!jQ`^yxN$;pZ7^157_1-_G{mGbW4>iSnhy?O}eqvS1@pJmf3@vD4b|0cdr zM*DPREcBp#JJMlKYE4IG?5T7UMMAh};YU;xF)#=Yf(ft>YF5td*!&`t0VriqO<@;Q oH { + requireRecordLength(length, 20, offset) + Mutation.QueryPositionRect( + nodeId = readU32(batch, base, available, offset + 4).toInt(), + request = readU32(batch, base, available, offset + 8).toInt(), + line = readU32(batch, base, available, offset + 12).toInt(), + column = readU32(batch, base, available, offset + 16).toInt(), + ) + } TAG_SET_WINDOW -> { requireRecordLength(length, 32, offset) // Bit 0 is `resizable`, bit 1 asks for every whole-dp size change; the @@ -2171,6 +2194,8 @@ object Protocol { is HostEvent.ScrollChanged -> null is HostEvent.CodeMetrics -> null is HostEvent.CodeScrolled -> null + is HostEvent.CaretRect -> null + is HostEvent.PositionRect -> null } val recordLength = when (event) { is HostEvent.Clicked -> 16 @@ -2223,6 +2248,8 @@ object Protocol { is HostEvent.ScrollChanged -> 72 is HostEvent.CodeMetrics -> 24 is HostEvent.CodeScrolled -> 24 + is HostEvent.CaretRect -> 40 + is HostEvent.PositionRect -> 40 } val totalLength = recordLength.toLong() + (text?.size ?: 0) if (totalLength > Int.MAX_VALUE || totalLength > out.remaining().toLong()) { @@ -2279,6 +2306,8 @@ object Protocol { is HostEvent.ScrollChanged -> 60 is HostEvent.CodeMetrics -> 54 is HostEvent.CodeScrolled -> 55 + is HostEvent.CaretRect -> 64 + is HostEvent.PositionRect -> 65 } out.putShort(tag.toShort()) out.putShort(recordLength.toShort()) @@ -2503,6 +2532,22 @@ object Protocol { } is HostEvent.CodeMetrics -> out.putDouble(event.value) is HostEvent.CodeScrolled -> out.putDouble(event.value) + is HostEvent.CaretRect -> { + out.putInt(event.line) + out.putInt(event.column) + out.putFloat(event.x) + out.putFloat(event.y) + out.putFloat(event.width) + out.putFloat(event.height) + } + is HostEvent.PositionRect -> { + out.putInt(event.request) + out.putInt(if (event.found) 1 else 0) + out.putFloat(if (event.found) event.x else 0f) + out.putFloat(if (event.found) event.y else 0f) + out.putFloat(if (event.found) event.width else 0f) + out.putFloat(if (event.found) event.height else 0f) + } } if (text != null) out.put(text) return out.position() - start @@ -2719,6 +2764,7 @@ object Protocol { 186 -> PropertyKind.OnScrollChanged 188 -> PropertyKind.Snap 189 -> PropertyKind.MaxHeightFraction + 195 -> PropertyKind.OnCaretRect 27 -> PropertyKind.Progress else -> throw ProtocolException("unknown property tag $tag", offset) } diff --git a/renderer/desktop/src/renderer/CodeEditorModel.kt b/renderer/desktop/src/renderer/CodeEditorModel.kt index 2e58fd878..5566728f2 100644 --- a/renderer/desktop/src/renderer/CodeEditorModel.kt +++ b/renderer/desktop/src/renderer/CodeEditorModel.kt @@ -90,6 +90,15 @@ class RevealRequest(val start: CodePosition, val end: CodePosition, val align: R */ class ScrollRequest(val offsetPx: Int) +/** + * A rectangle on screen in the dp of the window's content: the editor's scroll and the + * window's zoom are already in it. + */ +data class CodeRectDp(val x: Float, val y: Float, val width: Float, val height: Float) + +/** Where the caret is drawn: the place it stands at and its rectangle. */ +data class CaretReport(val position: CodePosition, val rect: CodeRectDp) + /** One colour run of the syntax as it stands in the current version of the document. */ class LiveSpan(var start: CodePosition, var end: CodePosition, val paint: Paint) @@ -128,6 +137,12 @@ sealed interface EditorOutput { /** How far the view is scrolled, in pixels. Steps between two reports are one report. */ class Scrolled(val offsetPx: Int) : EditorOutput + /** Where the caret is drawn. Moves between two reports are one report. */ + class Caret(val report: CaretReport) : EditorOutput + + /** The answer to the Host's position query [request]: a rectangle, or null where none is on screen. */ + class PositionAnswer(val request: Int, val rect: CodeRectDp?) : EditorOutput + /** The reader folded or unfolded the stretch that starts on [startLine]. */ class FoldToggled(val startLine: Int, val collapsed: Boolean) : EditorOutput @@ -216,6 +231,27 @@ class CodeEditorModel( var hearsLineHeight = false var hearsScroll = false + /** + * Where the caret is drawn, as the surface last said and as the Host was last told, and + * whether the Host listens. Like the row height, what nobody listens for is not counted + * as told. + */ + private var pendingCaret: CaretReport? = null + private var reportedCaret: CaretReport? = null + var hearsCaretRect = false + + /** + * How the surface that draws the editor finds a position on screen, or null before it + * has been drawn. It answers null for a position that is not on screen. + */ + var locator: ((CodePosition) -> CodeRectDp?)? = null + + /** The Host's position queries that arrived before the editor was drawn, in order. */ + private val waitingQueries = ArrayList>() + + /** Whether a query is waiting for the surface to be drawn. */ + val hasWaitingQueries: Boolean get() = waitingQueries.isNotEmpty() + private var focused = false private var composing = false @@ -573,6 +609,65 @@ class CodeEditorModel( reportedScroll = pendingScroll output += EditorOutput.Scrolled(pendingScroll) } + val caret = pendingCaret + if (hearsCaretRect && caret != null && caret != reportedCaret) { + reportedCaret = caret + output += EditorOutput.Caret(caret) + } + } + + /** + * The surface says where it draws the caret. Said whenever it draws, reported only when + * it is not what the Host was last told, and at most once per drain. + */ + fun reportCaretRect(report: CaretReport) { + pendingCaret = report + } + + /** Whether the caret has moved since the Host was told, and the Host listens. */ + val caretUntold: Boolean get() = hearsCaretRect && pendingCaret != null && pendingCaret != reportedCaret + + /** + * The Host asks where a caret at a position would be drawn. Answered at once where the + * editor has been drawn, and as soon as it is otherwise. A place that is not in the + * document is not on screen. + */ + fun hostQueryPosition(request: Int, line: Int, column: Int) { + val position = CodePosition(line, column) + if (line < 0 || column < 0 || !document.isValid(position)) { + output += EditorOutput.PositionAnswer(request, null) + return + } + val find = locator + if (find == null) { + waitingQueries += request to position + return + } + output += EditorOutput.PositionAnswer(request, find(position)) + } + + /** Answers the queries that waited for the surface, now that it can find a position. */ + fun answerWaitingQueries() { + val find = locator ?: return + if (waitingQueries.isEmpty()) return + for ((request, position) in waitingQueries.toList()) { + output += EditorOutput.PositionAnswer( + request, + if (document.isValid(position)) find(position) else null, + ) + } + waitingQueries.clear() + } + + /** + * The requests of every query still waiting, which the editor will never answer now + * because it is going away, and none waiting any more. + */ + fun abandonQueries(): List { + if (waitingQueries.isEmpty()) return emptyList() + val requests = waitingQueries.map { it.first } + waitingQueries.clear() + return requests } /** A position moved to the nearest place the document has, never between a pair's halves. */ diff --git a/renderer/desktop/src/renderer/CodeEditorSurface.kt b/renderer/desktop/src/renderer/CodeEditorSurface.kt index 08e4030cc..1206cc9a6 100644 --- a/renderer/desktop/src/renderer/CodeEditorSurface.kt +++ b/renderer/desktop/src/renderer/CodeEditorSurface.kt @@ -26,6 +26,7 @@ import androidx.compose.foundation.text.selection.LocalTextSelectionColors import androidx.compose.foundation.text.selection.TextSelectionColors import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue @@ -33,6 +34,7 @@ import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds @@ -41,6 +43,7 @@ import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path @@ -62,7 +65,9 @@ import androidx.compose.ui.input.key.type import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.layout +import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.semantics.semantics @@ -88,6 +93,7 @@ import dev.darkpyonix.composerust.protocol.GutterDecorationKind import dev.darkpyonix.composerust.protocol.Paint import dev.darkpyonix.composerust.protocol.RevealAlign import kotlinx.coroutines.delay +import kotlinx.coroutines.launch import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt @@ -891,6 +897,91 @@ internal fun rowHeightPx(style: TextStyle, density: Density): Int = with(density max(1, lineHeight.toPx().roundToInt()) } +/** A rectangle in root pixels as dp of the window's content, at [density] pixels a dp. */ +internal fun Rect.toDp(density: Float): CodeRectDp = + CodeRectDp(left / density, top / density, width / density, height / density) + +/** + * Whether a caret rectangle in root pixels can be seen in an editor whose view is + * [viewport], with its text starting [textLeft] pixels in: some of the row is inside the + * view, and the caret is right of the gutter and not past the right edge. + */ +internal fun caretOnScreen(rect: Rect, viewport: LayoutCoordinates?, textLeft: Float): Boolean { + val view = viewport?.takeIf { it.isAttached } ?: return false + val origin = view.localToRoot(Offset.Zero) + val top = origin.y + val bottom = origin.y + view.size.height + val left = origin.x + textLeft + val right = origin.x + view.size.width + // Half a pixel either way, for a caret that stands exactly on the gutter's edge. + return rect.bottom > top && rect.top < bottom && rect.left >= left - 0.5f && rect.left <= right + 0.5f +} + +/** + * Where a field surface draws a document position, for the caret report and the Host's + * position queries. + * + * Its fields are refreshed on every composition and read after layout, from the draw pass + * and from the layout callbacks, where the field's text layout and its place on screen are + * the ones the reader sees. + */ +internal class FieldPlaces(private val window: FieldWindow) { + /** The field itself, where its text layout's coordinates start. */ + var field: LayoutCoordinates? = null + + /** The editor's view: everything the reader can see of it. */ + var viewport: LayoutCoordinates? = null + var layout: (() -> TextLayoutResult?)? = null + var textLeftPx = 0f + var density = 1f + + /** The width the field draws its caret at. */ + var caretWidthPx = 2f + + /** The function the model finds positions with, the same one for as long as this lives. */ + val locate: (CodePosition) -> CodeRectDp? = { position -> + caretInRoot(position)?.takeIf { caretOnScreen(it, viewport, textLeftPx) }?.toDp(density) + } + + /** + * Where a caret at [position] is drawn, in root pixels, or null where the field does + * not hold the position: a line outside its window, or one a fold hides. + */ + fun caretInRoot(position: CodePosition): Rect? { + val model = window.model + if (!model.document.isValid(position) || model.isHidden(position.line)) return null + val offset = window.toField(position) ?: return null + val result = layout?.invoke() ?: return null + val coordinates = field?.takeIf { it.isAttached } ?: return null + var shown = window.toShown(offset, asEnd = false) + // A suggestion shows after the caret that stands where it starts. + val ghost = model.ghostText + if (ghost != null && ghost.start == position && ghost.text.isNotEmpty()) shown -= ghost.text.length + val cursor = result.getCursorRect(shown.coerceIn(0, result.layoutInput.text.length)) + return Rect(coordinates.localToRoot(Offset(cursor.left, cursor.top)), Size(caretWidthPx, cursor.height)) + } + + /** + * Tells the model how to find positions and where the caret is, and answers the queries + * that waited for the editor to be drawn. Answers whether the Host has something to hear. + */ + fun report(): Boolean { + // Before the field and the view have both been placed, nothing found here would be + // where the reader sees it, and a waiting query would be answered with nothing. + val ready = field?.isAttached == true && viewport?.isAttached == true && layout?.invoke() != null + if (!ready) return false + val model = window.model + model.locator = locate + if (!window.caretOutside) { + val caret = model.selection.caret + caretInRoot(caret)?.let { model.reportCaretRect(CaretReport(caret, it.toDp(density))) } + } + val answered = model.hasWaitingQueries + if (answered) model.answerWaitingQueries() + return answered || model.caretUntold + } +} + /** * The two field paths. [whole] holds every line; otherwise the field holds the lines around * the screen and is refilled as the view scrolls. @@ -992,6 +1083,21 @@ private fun FieldSurface( val textInsetPx = with(density) { look.textInset.roundToPx() } + // Where the caret is drawn and where a position is, read after layout. What they find + // is sent from a coroutine rather than from inside the pass that found it. + val places = remember(window) { FieldPlaces(window).also { it.layout = { layoutHolder[0]?.invoke() } } } + places.textLeftPx = (gutterWidthPx + textInsetPx).toFloat() + places.density = density.density + places.caretWidthPx = with(density) { 2.dp.toPx() } + val scope = rememberCoroutineScope() + val currentCallbacks by rememberUpdatedState(callbacks) + val reportPlaces: () -> Unit = remember(places, scope) { + { if (places.report()) scope.launch { currentCallbacks.onOutput() } } + } + DisposableEffect(model, places) { + onDispose { if (model.locator === places.locate) model.locator = null } + } + CompositionLocalProvider( LocalTextSelectionColors provides TextSelectionColors(look.cursor, look.selection), ) { @@ -1004,6 +1110,10 @@ private fun FieldSurface( .onSizeChanged { size -> viewportHeight = size.height viewportWidth = size.width + } + .onGloballyPositioned { coordinates -> + places.viewport = coordinates + reportPlaces() }, ) { // The extent the offset may run to. A number, never a measured height. @@ -1017,6 +1127,12 @@ private fun FieldSurface( translate(top = -vertical.offset.toFloat()) { drawCurrentLine(window, rows, rowPx, look) } + // Read so that typing, a move of the caret and a scroll along the + // lines all draw this again, and the caret is reported from here. + window.state.text + window.state.selection + horizontal.value + reportPlaces() }, ) { Box( @@ -1084,6 +1200,10 @@ private fun FieldSurface( placeable.place(textInsetPx, rows.rowTop(window.start) * rowPx - vertical.offset) } } + .onGloballyPositioned { coordinates -> + places.field = coordinates + reportPlaces() + } .onFocusChanged { focusState -> overlayFocusStack.noteFocused(focus, focusState.hasFocus) model.focusChanged(focusState.hasFocus) diff --git a/renderer/desktop/src/renderer/DrawnCodeEditor.kt b/renderer/desktop/src/renderer/DrawnCodeEditor.kt index 391d5e166..8201beb0a 100644 --- a/renderer/desktop/src/renderer/DrawnCodeEditor.kt +++ b/renderer/desktop/src/renderer/DrawnCodeEditor.kt @@ -11,6 +11,7 @@ import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.scrollable import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue @@ -18,6 +19,7 @@ import androidx.compose.runtime.snapshotFlow import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds @@ -59,6 +61,7 @@ import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.dp import dev.darkpyonix.composerust.protocol.DecorationKind +import kotlinx.coroutines.launch import kotlin.math.max import kotlin.math.min @@ -123,6 +126,11 @@ private class DrawnState( var coordinates: LayoutCoordinates? = null var rows: RowMap = RowMap.of(model) var scroll: EditorScroll? = null + + /** Where the text area starts, after the gutter, and how many pixels make a dp. */ + var gutterWidth = 0f + var density = 1f + var caretWidthPx = 1.5f private val views = HashMap() private var viewsRevision = -1 @@ -270,6 +278,54 @@ private class DrawnState( callbacks.onOutput() } + /** + * Where a caret at [position] is drawn, in this editor's own pixels. [composed] puts it + * after what an input method is composing there, which is where the caret is drawn. + */ + private fun caretLocal(position: CodePosition, composed: Boolean): Rect { + val view = view(position.line) + val column = position.column.coerceIn(0, view.caretAt.size - 1) + val shown = view.caretAt[column] + if (composed) composing.length else 0 + val x = textLeft + view.layout.getHorizontalPosition(shown, true) + val y = rows.textRow(position.line) * rowPx.toFloat() - (scroll?.offset ?: 0) + return Rect(Offset(x, y), Size(caretWidthPx, rowPx.toFloat())) + } + + private fun Rect.inRoot(): Rect { + val coordinates = coordinates?.takeIf { it.isAttached } ?: return this + return Rect(coordinates.localToRoot(topLeft), size) + } + + /** The function the model finds positions with, the same one for as long as this lives. */ + val locate: (CodePosition) -> CodeRectDp? = { position -> + if (!model.document.isValid(position) || model.isHidden(position.line)) { + null + } else { + val local = caretLocal(position, composed = false) + val size = coordinates?.size + val onScreen = size != null && + local.bottom > 0f && local.top < size.height && + local.left >= gutterWidth - 0.5f && local.left <= size.width + 0.5f + if (onScreen) local.inRoot().toDp(density) else null + } + } + + /** + * Tells the model how to find positions and where the caret is, and answers the queries + * that waited for the editor to be drawn. Answers whether the Host has something to hear. + */ + fun report(): Boolean { + if (coordinates?.isAttached != true || measurer == null) return false + model.locator = locate + val caret = model.selection.caret + if (model.document.isValid(caret)) { + model.reportCaretRect(CaretReport(caret, caretLocal(caret, composed = true).inRoot().toDp(density))) + } + val answered = model.hasWaitingQueries + if (answered) model.answerWaitingQueries() + return answered || model.caretUntold + } + fun positionAt(point: Offset): Pair { val row = ((point.y + (scroll?.offset ?: 0)) / rowPx).toInt().coerceAtLeast(0) val line = rows.lineAtRow(row).coerceIn(0, model.document.lineCount - 1) @@ -326,6 +382,18 @@ private fun DrawnSurface( markColumn + foldColumn + density.changeColumnPx(model, look) ).toFloat() state.textLeft = gutterWidth + with(density) { look.textInset.toPx() } + state.gutterWidth = gutterWidth + state.density = density.density + state.caretWidthPx = with(density) { 1.5.dp.toPx() } + // What the caret report and the waiting queries found is sent from a coroutine rather + // than from inside the draw pass that found it. + val scope = rememberCoroutineScope() + val reportPlaces: () -> Unit = remember(state, scope) { + { if (state.report()) scope.launch { state.callbacks.onOutput() } } + } + DisposableEffect(model, state) { + onDispose { if (model.locator === state.locate) model.locator = null } + } // What the reader's edits queued is sent from here as well, on the composition thread. SideEffect { callbacks.onOutput() } @@ -376,7 +444,10 @@ private fun DrawnSurface( // their rows less the offset, and the extent is only a number. .fillMaxSize() .scrollable(vertical.scrollable, Orientation.Vertical) - .onGloballyPositioned { state.coordinates = it } + .onGloballyPositioned { + state.coordinates = it + reportPlaces() + } .drawnTextInput(state) .focusRequester(focus) .onFocusChanged { @@ -447,6 +518,7 @@ private fun DrawnSurface( translate(top = -scroll.toFloat()) { drawLines(state, rows, scroll, viewportHeight, gutterWidth, markColumn, foldColumn, focused) } + reportPlaces() }, ) } diff --git a/renderer/desktop/src/renderer/HostCodeEditor.kt b/renderer/desktop/src/renderer/HostCodeEditor.kt index 1803e59e5..7352d698b 100644 --- a/renderer/desktop/src/renderer/HostCodeEditor.kt +++ b/renderer/desktop/src/renderer/HostCodeEditor.kt @@ -114,8 +114,9 @@ internal fun HostCodeEditor( // sent now. val hearsMetrics = node.handler(PropertyKind.OnCodeMetrics) != null val hearsScroll = node.handler(PropertyKind.OnCodeScrolled) != null - LaunchedEffect(model, hearsMetrics, hearsScroll) { - if (hearsMetrics || hearsScroll) callbacks.onOutput() + val hearsCaret = node.handler(PropertyKind.OnCaretRect) != null + LaunchedEffect(model, hearsMetrics, hearsScroll, hearsCaret) { + if (hearsMetrics || hearsScroll || hearsCaret) callbacks.onOutput() } val focusRequest = node.focusRequestRevision CodeEditorSurface(model, look, callbacks, modifier, focusRequest = focusRequest) { scrolling -> @@ -294,6 +295,36 @@ internal fun Node.codeEvents(outputs: List, onError: (String) -> U val handler = handler(PropertyKind.OnCodeScrolled) ?: continue events += HostEvent.CodeScrolled(id, handler, output.offsetPx.toDouble()) } + // In the window's dp, the scroll and the zoom already in them. + is EditorOutput.Caret -> { + val handler = handler(PropertyKind.OnCaretRect) ?: continue + val (position, rect) = output.report + events += HostEvent.CaretRect( + id, + handler, + position.line, + position.column, + rect.x, + rect.y, + rect.width, + rect.height, + ) + } + // An answer goes to the query and names no handler: the Host asked, so it is + // waiting for it whether or not anything on the editor listens. + is EditorOutput.PositionAnswer -> { + val rect = output.rect + events += HostEvent.PositionRect( + id, + 0L, + output.request, + rect != null, + rect?.x ?: 0f, + rect?.y ?: 0f, + rect?.width ?: 0f, + rect?.height ?: 0f, + ) + } is EditorOutput.Composing -> { val handler = handler(PropertyKind.OnCompositionChange) ?: continue events += HostEvent.CompositionChanged(id, handler, output.composing) diff --git a/renderer/desktop/src/renderer/NodeTable.kt b/renderer/desktop/src/renderer/NodeTable.kt index ea66252ca..317cec569 100644 --- a/renderer/desktop/src/renderer/NodeTable.kt +++ b/renderer/desktop/src/renderer/NodeTable.kt @@ -499,6 +499,18 @@ class NodeTable { code.hostScrollTo(mutation.offsetPx) collectCode(node) } + // A question, answered exactly once: by the editor where it can find the + // position, and here, with nothing on screen, where there is no editor to ask. + is Mutation.QueryPositionRect -> { + val found = codeNode(mutation.nodeId, "QueryPositionRect") + if (found == null) { + outbox += HostEvent.PositionRect(mutation.nodeId, 0L, mutation.request, false, 0f, 0f, 0f, 0f) + } else { + val (node, code) = found + code.hostQueryPosition(mutation.request, mutation.line, mutation.column) + collectCode(node) + } + } // Requests too: the scroll position is this side's. Each is checked here and // waits on the node for the container, which keeps it in range, may animate it, @@ -783,6 +795,10 @@ class NodeTable { code.hearsScroll = value is PropertyValue.Integer return } + PropertyKind.OnCaretRect -> { + code.hearsCaretRect = value is PropertyValue.Integer + return + } else -> return } collectCode(node) @@ -951,7 +967,13 @@ class NodeTable { private fun removeSubtree(nodeId: Int) { val node = nodes.remove(nodeId) ?: return - codeNodes.remove(nodeId) + if (codeNodes.remove(nodeId) != null) { + // A query the editor had not answered yet is answered now, with nothing on + // screen: it never will be otherwise. + for (request in node.code?.abandonQueries().orEmpty()) { + outbox += HostEvent.PositionRect(nodeId, 0L, request, false, 0f, 0f, 0f, 0f) + } + } node.scroll?.let(scrolls::forget) if (node.widget == WidgetKind.Window) { windowThemes.remove(nodeId) @@ -1416,6 +1438,8 @@ class NodeTable { PropertyKind.CodeEditorColors, PropertyKind.OnCodeMetrics, PropertyKind.OnCodeScrolled, + // The handler told where the caret is drawn. + PropertyKind.OnCaretRect, -> widget == WidgetKind.CodeEditor PropertyKind.OnCompositionChange -> diff --git a/renderer/desktop/test/CodeEditorAnchorTest.kt b/renderer/desktop/test/CodeEditorAnchorTest.kt new file mode 100644 index 000000000..37fea4a92 --- /dev/null +++ b/renderer/desktop/test/CodeEditorAnchorTest.kt @@ -0,0 +1,282 @@ +package dev.darkpyonix.composerust.test + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.runComposeUiTest +import androidx.compose.ui.unit.Density +import dev.darkpyonix.composerust.foundation.code.CODE_EDITOR_FIELD_TAG +import dev.darkpyonix.composerust.foundation.code.CodeEditorPath +import dev.darkpyonix.composerust.foundation.code.defaultCodeEditorPath +import dev.darkpyonix.composerust.foundation.code.installDrawnCodeEditor +import dev.darkpyonix.composerust.protocol.ColorScheme +import dev.darkpyonix.composerust.protocol.DesignSystem +import dev.darkpyonix.composerust.protocol.HostEvent +import dev.darkpyonix.composerust.protocol.Modifier as ProtocolModifier +import dev.darkpyonix.composerust.protocol.Mutation +import dev.darkpyonix.composerust.protocol.Protocol +import dev.darkpyonix.composerust.protocol.PropertyKind +import dev.darkpyonix.composerust.protocol.PropertyValue +import dev.darkpyonix.composerust.protocol.Theme +import dev.darkpyonix.composerust.protocol.WidgetKind +import dev.darkpyonix.composerust.runtime.ComposeRustContent +import dev.darkpyonix.composerust.runtime.ComposeRustHost +import dev.darkpyonix.composerust.runtime.rememberComposeRustHost +import dev.darkpyonix.composerust.tooling.FakeHostConnection +import dev.darkpyonix.composerust.ui.node.NodeTable +import dev.darkpyonix.composerust.ui.node.TableError +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.abs +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +private const val EDITOR = 2 +private const val BOX = 3 +private const val ON_CARET = 71L + +/** Sixty lines, `let value_0 = 0;` and on, so the view has somewhere to scroll to. */ +private val LINES = (0 until 60).map { "let value_$it = $it;" } +private val TEXT = LINES.joinToString("\n") + +/** Where a document position is in the field's text, which holds the whole window from line 0. */ +private fun fieldOffset(line: Int, column: Int): Int = LINES.take(line).sumOf { it.length + 1 } + column + +/** An editor alone on the page, 300 by 200 dp, with the records the test adds after it. */ +private fun page(vararg extra: Mutation): List = buildList { + add(Mutation.SetTheme(Theme(DesignSystem.Material3, DesignSystem.Material3, ColorScheme.Light, false))) + add(Mutation.Create(EDITOR, WidgetKind.CodeEditor)) + add(Mutation.SetModifier(EDITOR, 0, ProtocolModifier.Size(300f, 200f))) + add(Mutation.SetProp(EDITOR, PropertyKind.Text, PropertyValue.Text(TEXT))) + addAll(extra) +} + +private fun close(expected: Float, actual: Float, within: Float, what: String) = + assertTrue(abs(expected - actual) <= within, "$what: expected $expected, was $actual") + +/** + * Criterion 19 of the code editor: the editor says where it draws its caret, and answers + * the Host's questions about where a position is, both in the window's dp with the scroll + * and the zoom already in them. Each runs on the field path and on the drawn path. + */ +@OptIn(ExperimentalTestApi::class) +class CodeEditorAnchorTest { + @AfterTest + fun windowedPath() { + defaultCodeEditorPath = CodeEditorPath.Windowed + } + + private fun ComposeUiTest.show(connection: FakeHostConnection): () -> ComposeRustHost { + lateinit var host: ComposeRustHost + setContent { + CompositionLocalProvider(LocalDensity provides Density(2f)) { + host = rememberComposeRustHost(connection) + ComposeRustContent(host) + } + } + waitForIdle() + return { host } + } + + /** + * Where the field draws the character at a position, in the window's dp: the left and + * top of its box in the field's own layout, moved by where the field is. + */ + private fun ComposeUiTest.drawnAt(line: Int, column: Int): Offset { + val layout = drawnLayout(EDITOR) + val box = layout.getBoundingBox(fieldOffset(line, column)) + val field = onNodeWithTag(CODE_EDITOR_FIELD_TAG, useUnmergedTree = true).fetchSemanticsNode().positionInRoot + return Offset((field.x + box.left) / 2f, (field.y + box.top) / 2f) + } + + /** + * Criterion 19.1. A caret the Host puts on the third line at the fifth column is + * reported where that character is drawn, within a dp, and a scroll of 20dp reports the + * new place once, 20dp higher. + */ + @Test + fun fr38_editor_reports_the_caret_rect() { + installDrawnCodeEditor() + var fieldCaret: HostEvent.CaretRect? = null + for (path in listOf(CodeEditorPath.Windowed, CodeEditorPath.Drawn)) { + defaultCodeEditorPath = path + runComposeUiTest { + val connection = FakeHostConnection( + page( + Mutation.SetProp(EDITOR, PropertyKind.OnCaretRect, PropertyValue.Integer(ON_CARET)), + Mutation.SetSelection(EDITOR, 0, 2, 4, 2, 4), + ), + ) + val host = show(connection) + assertEquals(emptyList(), connection.events.filterIsInstance(), "$path") + fun reported() = connection.nodeEvents.filterIsInstance() + val caret = reported().last() + assertEquals(EDITOR, caret.nodeId) + assertEquals(ON_CARET, caret.handlerId) + assertEquals(2 to 4, caret.line to caret.column, "$path") + assertTrue(caret.height > 10f && caret.width > 0f, "$path: the caret is $caret") + if (path == CodeEditorPath.Windowed) { + val drawn = drawnAt(2, 4) + close(drawn.x, caret.x, 1f, "$path x") + close(drawn.y, caret.y, 1f, "$path y") + val layout = drawnLayout(EDITOR) + close((layout.getLineBottom(2) - layout.getLineTop(2)) / 2f, caret.height, 1f, "$path height") + fieldCaret = caret + } else { + // The same face, the same gutter and the same rows: the drawn path puts the + // character where the field does. + val field = fieldCaret!! + close(field.x, caret.x, 1f, "$path x") + close(field.y, caret.y, 1f, "$path y") + close(field.height, caret.height, 1f, "$path height") + } + + // The view scrolls 40 pixels, 20dp: one report, 20dp higher, nothing else moved. + val before = reported().size + connection.scheduleFrame(listOf(Mutation.SetScrollOffset(EDITOR, 40.0))) + host().renderFrame(0L) + waitForIdle() + assertEquals(before + 1, reported().size, "$path: a scroll reports the caret once") + val scrolled = reported().last() + assertEquals(2 to 4, scrolled.line to scrolled.column) + close(caret.y - 20f, scrolled.y, 0.5f, "$path scrolled y") + close(caret.x, scrolled.x, 0.5f, "$path scrolled x") + + // A frame in which nothing moved says nothing. + connection.scheduleFrame(listOf(Mutation.SetProp(EDITOR, PropertyKind.TabWidth, PropertyValue.Integer(4)))) + host().renderFrame(0L) + waitForIdle() + assertEquals(before + 1, reported().size, "$path: a still caret is not reported again") + + // The event is the header, two words and four floats. + val buffer = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN) + assertEquals(40, Protocol.encodeEvent(scrolled, buffer)) + } + } + } + + /** + * Criterion 19.2. A position on screen is answered with where a caret there is drawn, + * one that is scrolled away or not in the document with nothing, and each query once. A + * query sent with the editor waits for it to be drawn. + */ + @Test + fun fr38_editor_answers_position_rects() { + installDrawnCodeEditor() + for (path in listOf(CodeEditorPath.Windowed, CodeEditorPath.Drawn)) { + defaultCodeEditorPath = path + runComposeUiTest { + val connection = FakeHostConnection(page(Mutation.QueryPositionRect(EDITOR, 4, 0, 0))) + val host = show(connection) + fun answers(request: Int) = + connection.nodeEvents.filterIsInstance().filter { it.request == request } + + // Asked before the editor had a size, answered once it was drawn. + val first = answers(4).single() + assertEquals(EDITOR, first.nodeId) + assertEquals(0L, first.handlerId) + assertTrue(first.found, "$path: the start of the document is on screen") + + connection.scheduleFrame( + listOf( + Mutation.QueryPositionRect(EDITOR, 5, 1, 4), + Mutation.QueryPositionRect(EDITOR, 6, 55, 0), + Mutation.QueryPositionRect(EDITOR, 7, 1, 400), + Mutation.QueryPositionRect(EDITOR, 8, 999, 0), + ), + ) + host().renderFrame(0L) + waitForIdle() + val visible = answers(5).single() + assertTrue(visible.found, "$path: line 1 is on screen") + if (path == CodeEditorPath.Windowed) { + val drawn = drawnAt(1, 4) + close(drawn.x, visible.x, 1f, "$path x") + close(drawn.y, visible.y, 1f, "$path y") + } + assertTrue(visible.y > first.y, "$path: line 1 is below line 0") + // Fifty-five lines down is past the bottom of a view 200dp tall. + assertFalse(answers(6).single().found, "$path: line 55 is not on screen") + assertEquals(0f, answers(6).single().x) + // Places that are not in the document are on no screen. + assertFalse(answers(7).single().found) + assertFalse(answers(8).single().found) + + // Once the view has scrolled down to it, line 55 is on screen. + connection.scheduleFrame(listOf(Mutation.SetScrollOffset(EDITOR, 1.0e9))) + host().renderFrame(0L) + waitForIdle() + connection.scheduleFrame(listOf(Mutation.QueryPositionRect(EDITOR, 9, 55, 0))) + host().renderFrame(0L) + waitForIdle() + assertTrue(answers(9).single().found, "$path: line 55 after the scroll") + // And no query was answered twice. + assertEquals(listOf(4, 5, 6, 7, 8, 9), connection.nodeEvents.filterIsInstance().map { it.request }) + assertEquals(emptyList(), connection.events.filterIsInstance(), "$path") + } + } + } + + /** + * The query through the interpreter: a node that is not an editor, or none at all, is a + * protocol error and still an answer, and an editor removed before it was drawn answers + * what waited. The record is 20 bytes on the wire. + */ + @Test + fun fr38_editor_answers_position_rects_through_the_interpreter() { + val table = NodeTable() + table.apply(Mutation.Create(EDITOR, WidgetKind.CodeEditor)) + table.apply(Mutation.SetProp(EDITOR, PropertyKind.Text, PropertyValue.Text("a\nb"))) + table.apply(Mutation.Create(BOX, WidgetKind.Box)) + table.drainEvents() + table.drainErrors() + + table.apply(Mutation.QueryPositionRect(BOX, 1, 0, 0)) + table.apply(Mutation.QueryPositionRect(99, 2, 0, 0)) + assertEquals( + listOf(TableError.UNSUPPORTED_PROPERTY, TableError.UNKNOWN_NODE), + table.drainErrors().map { it.code }, + ) + assertEquals( + listOf( + HostEvent.PositionRect(BOX, 0L, 1, false, 0f, 0f, 0f, 0f), + HostEvent.PositionRect(99, 0L, 2, false, 0f, 0f, 0f, 0f), + ), + table.drainEvents(), + ) + + // Never drawn, so the query waits; the editor goes, so it is answered with nothing. + table.apply(Mutation.QueryPositionRect(EDITOR, 3, 1, 0)) + assertEquals(emptyList(), table.drainEvents()) + table.apply(Mutation.Remove(EDITOR)) + assertEquals(listOf(HostEvent.PositionRect(EDITOR, 0L, 3, false, 0f, 0f, 0f, 0f)), table.drainEvents()) + assertEquals(emptyList(), table.drainErrors()) + + // The bytes the Rust encoder writes: tag 39, 20 bytes, the node, the request, the line + // and the column. + val batch = ByteBuffer.allocate(12 + 20).order(ByteOrder.LITTLE_ENDIAN) + batch.putShort(0).putShort(12).putInt(12 + 20).putInt(1) + batch.putShort(39).putShort(20).putInt(EDITOR).putInt(17).putInt(1).putInt(8) + batch.flip() + val decoded = mutableListOf() + Protocol.decode(batch, decoded::add) + assertEquals(listOf(Mutation.QueryPositionRect(EDITOR, 17, 1, 8)), decoded) + // The answer is the header, two words and four floats. + val out = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN) + assertEquals(40, Protocol.encodeEvent(HostEvent.PositionRect(EDITOR, 0L, 17, true, 1f, 2f, 3f, 4f), out)) + } + + /** The handler the caret is reported to is an editor's own property. */ + @Test + fun fr38_on_caret_rect_is_a_property_of_an_editor() { + assertTrue(NodeTable.supportsProperty(WidgetKind.CodeEditor, PropertyKind.OnCaretRect)) + assertFalse(NodeTable.supportsProperty(WidgetKind.TextField, PropertyKind.OnCaretRect)) + assertFalse(NodeTable.supportsProperty(WidgetKind.Text, PropertyKind.OnCaretRect)) + } +} diff --git a/renderer/desktop/test/ProtocolVectorsTest.kt b/renderer/desktop/test/ProtocolVectorsTest.kt index 0874b27de..c77b427ce 100644 --- a/renderer/desktop/test/ProtocolVectorsTest.kt +++ b/renderer/desktop/test/ProtocolVectorsTest.kt @@ -142,6 +142,7 @@ class ProtocolVectorsTest { is Mutation.RevealRange -> mutation.nodeId !in created is Mutation.SetFolded -> mutation.nodeId !in created is Mutation.SetScrollOffset -> mutation.nodeId !in created + is Mutation.QueryPositionRect -> mutation.nodeId !in created // An animation is played on a node, so one that names a node the vector // never created is reported once the batch is in. is Mutation.StartAnimation -> mutation.animation.nodeId !in created @@ -947,6 +948,9 @@ class ProtocolVectorsTest { // The row height and the scroll offset, after everything that was here before. 1391 to HostEvent.CodeMetrics(12, 28L, 40.0), 1415 to HostEvent.CodeScrolled(12, 29L, 1234.5), + // Where the caret is drawn and the answer to the position query, after them. + 1439 to HostEvent.CaretRect(12, 30L, 1, 8, 120.5f, 64.25f, 2f, 20f), + 1479 to HostEvent.PositionRect(12, 0L, 17, true, 88.75f, 64.25f, 2f, 20f), ) for ((offset, event) in expected) { val wire = encoded(event) @@ -955,7 +959,7 @@ class ProtocolVectorsTest { "$event at $offset", ) } - assertEquals(1439, bytes.size) + assertEquals(1519, bytes.size) } /** @@ -977,6 +981,10 @@ class ProtocolVectorsTest { listOf(Mutation.SetFolded(12, 0, true)), mutations.filterIsInstance(), ) + assertEquals( + listOf(Mutation.QueryPositionRect(12, 17, 1, 8)), + mutations.filterIsInstance(), + ) assertEquals( listOf(Mutation.SetScrollOffset(12, 1234.5)), mutations.filterIsInstance(), From 11be5c80115dd5413f46fd1efbad8636dd4cf1a6 Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:32:20 +0900 Subject: [PATCH 6/8] Feat: Offer the code editor's keys to the Host before the editor handles them (FR-38, #554) Covers FR-38 criterion 20. Wire: the OnKeyPreview handler property (196). What it hears is the existing KeyDown record of FR-12.1 (code, text, modifiers, repeat), and the synchronous result says whether the Host took the key. Renderer: the field path asks from its preview key handler and the drawn path at the top of its key handling, so a key the Host consumes never reaches the editor. Nothing is offered while an input method composes, a release is never offered, and every event passes the held-key tracker so a repeat is marked as one. Tests: fr38_editor_key_preview_consumes_keys (20.1, both paths) and fr38_editor_key_preview_skips_composition (20.2) in CodeEditorInputHooksTest; fr38_editor_key_preview_keeps_its_tag_and_the_key_down_record in code_editor.rs. --- CHANGELOG.md | 4 + .../shared/CodeEditorSurface.kt | 12 +- .../android-kotlin/shared/HostCodeEditor.kt | 25 +++ .../android-kotlin/shared/NodeTable.kt | 4 +- .../android-kotlin/shared/Protocol.gen.kt | 5 +- compose-rust/schema-hash.txt | 2 +- compose-rust/src/schema.rs | 6 +- compose-rust/tests/code_editor.rs | 33 ++++ compose-rust/tests/vectors/vectors.json | 2 +- renderer/desktop/src/protocol/Protocol.gen.kt | 5 +- .../desktop/src/renderer/CodeEditorSurface.kt | 12 +- .../desktop/src/renderer/DrawnCodeEditor.kt | 2 + .../desktop/src/renderer/HostCodeEditor.kt | 25 +++ renderer/desktop/src/renderer/NodeTable.kt | 4 +- .../desktop/test/CodeEditorInputHooksTest.kt | 186 ++++++++++++++++++ 15 files changed, 316 insertions(+), 11 deletions(-) create mode 100644 renderer/desktop/test/CodeEditorInputHooksTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index f555d67cb..e47cd7ec3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### The Host hears the code editor's keys first + +A `CodeEditor` with the new `OnKeyPreview` handler property (tag 196) offers every key press to the Host before it handles the key itself, as the `KeyDown` record a key handler hears. A press the handler consumes, through the same synchronous result as any key handler, is not the editor's: Down does not move the caret and Enter inserts no line. Nothing is offered while an input method is composing. A suggestion list takes Up, Down, Enter, Tab and Escape this way while it is open, and an application takes its own commands such as F12, F2, Ctrl+Space or Ctrl/Cmd+. ([#554](https://github.com/DarkPyonix/compose-rust/issues/554)). + ### Where the code editor's caret is, and where any position is A `CodeEditor` with the new `OnCaretRect` handler property (tag 195) reports where it draws its caret in a `CaretRect` event (tag 64): the line, the column and a rectangle in the window's dp, with the editor's scroll and the window's zoom already in it. It is sent when the caret moves or the view scrolls, at most once a frame. `Batch::query_position_rect(node, request, position)` asks where a caret at any other position would be drawn, in a `QueryPositionRect` command (tag 39), and `compose_rust::code::position_query(callback)` gives the request its number. Every query gets exactly one `PositionRect` event (tag 65) back: the rectangle, or `None` where the position is not on screen, is not in the document, or the editor is gone. A suggestion list, a parameter hint, a rename box or a hover card is placed with them ([#553](https://github.com/DarkPyonix/compose-rust/issues/553)). diff --git a/compose-rust/android-kotlin/shared/CodeEditorSurface.kt b/compose-rust/android-kotlin/shared/CodeEditorSurface.kt index 1206cc9a6..71eafdf59 100644 --- a/compose-rust/android-kotlin/shared/CodeEditorSurface.kt +++ b/compose-rust/android-kotlin/shared/CodeEditorSurface.kt @@ -283,6 +283,13 @@ class CodeEditorCallbacks( * or zero. */ val onHover: (decoration: Long, position: CodePosition, rest: Boolean) -> Unit, + /** + * A key event, offered before the editor does anything with it. True means the Host + * took the key and the editor leaves it alone. [composing] says an input method is + * composing, which the Host is never offered a key during. Every event comes through + * here, releases too, so a held key's repeats can be told from its first press. + */ + val onKeyPreview: (event: KeyEvent, composing: Boolean) -> Boolean = { _, _ -> false }, ) /** Test tag of the field a field surface types into. */ @@ -1212,7 +1219,10 @@ private fun FieldSurface( .focusRequester(focus) .testTag(CODE_EDITOR_FIELD_TAG) .onPreviewKeyEvent { event -> - handleKey(event, window, look, callbacks) + // The Host hears the key first, and a key it takes is + // not the editor's. + callbacks.onKeyPreview(event, window.state.composition != null) || + handleKey(event, window, look, callbacks) } .pointerInput(window, look) { awaitPointerEventScope { diff --git a/compose-rust/android-kotlin/shared/HostCodeEditor.kt b/compose-rust/android-kotlin/shared/HostCodeEditor.kt index 7352d698b..22dee7862 100644 --- a/compose-rust/android-kotlin/shared/HostCodeEditor.kt +++ b/compose-rust/android-kotlin/shared/HostCodeEditor.kt @@ -6,6 +6,9 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier +import androidx.compose.ui.input.key.KeyEvent +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.type import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import dev.darkpyonix.composerust.design.HostPlatform @@ -81,6 +84,7 @@ internal fun HostCodeEditor( node.bytes(PropertyKind.CodeEditorColors), ) { codeEditorLook(node, theme, tabWidth, fontChain) } val currentDispatcher by rememberUpdatedState(dispatcher) + val keyPreview = remember(node) { codeEditorKeyPreview(node, { currentDispatcher }) } val callbacks = remember(node, model) { CodeEditorCallbacks( onOutput = { node.sendCodeOutput(model.drainOutput(includeReports = true), currentDispatcher) }, @@ -107,6 +111,7 @@ internal fun HostCodeEditor( ) } }, + onKeyPreview = keyPreview, ) } // A listener attached after the editor was drawn has the row height and the offset @@ -147,6 +152,26 @@ private fun EditorScroll.axis(viewport: () -> Int): ScrollAxis = ScrollAxis( jump = { target -> scrollTo(target) }, ) +/** + * What an editor offers the Host before it handles a key: the `KeyDown` record a key handler + * hears, sent to the node's `OnKeyPreview` handler, whose answer says whether the Host took + * the key. Nothing is sent while an input method composes, for a release, or where nothing + * listens. Every event passes through [held], so a repeat is marked as one. + */ +internal fun codeEditorKeyPreview( + node: Node, + dispatcher: () -> EventDispatcher, + held: HeldKeys = HeldKeys(), +): (KeyEvent, Boolean) -> Boolean = { event, composing -> + val handler = node.handler(PropertyKind.OnKeyPreview) + if (handler == null) { + held.observe(event.type, event.key) + false + } else { + dispatchKeyDown(node.id, handler, event, composing, dispatcher(), held) + } +} + /** The colours the application gave this editor, or null where it gave none that can be read. */ internal fun Node.codeEditorColors(): CodeEditorColorsRecord? = bytes(PropertyKind.CodeEditorColors)?.let { bytes -> diff --git a/compose-rust/android-kotlin/shared/NodeTable.kt b/compose-rust/android-kotlin/shared/NodeTable.kt index 317cec569..3a3145824 100644 --- a/compose-rust/android-kotlin/shared/NodeTable.kt +++ b/compose-rust/android-kotlin/shared/NodeTable.kt @@ -1438,8 +1438,10 @@ class NodeTable { PropertyKind.CodeEditorColors, PropertyKind.OnCodeMetrics, PropertyKind.OnCodeScrolled, - // The handler told where the caret is drawn. + // The handler told where the caret is drawn, and the one offered keys + // before the editor handles them. PropertyKind.OnCaretRect, + PropertyKind.OnKeyPreview, -> widget == WidgetKind.CodeEditor PropertyKind.OnCompositionChange -> diff --git a/compose-rust/android-kotlin/shared/Protocol.gen.kt b/compose-rust/android-kotlin/shared/Protocol.gen.kt index cfc8caa07..b8e2a8a2c 100644 --- a/compose-rust/android-kotlin/shared/Protocol.gen.kt +++ b/compose-rust/android-kotlin/shared/Protocol.gen.kt @@ -8,7 +8,7 @@ import java.nio.charset.StandardCharsets enum class WidgetKind { Column, Row, Box, Text, TextField, Button, Spacer, LazyColumn, ScrollColumn, Image, Icon, Checkbox, RadioButton, Switch, Slider, ProgressIndicator, Divider, Card, Surface, Dialog, Menu, Tabs, TopAppBar, LazyRow, Tooltip, Canvas, DatePicker, TimePicker, Dropdown, Navigation, NavigationItem, Sheet, Scaffold, ScaffoldSlot, LazyGrid, FileDropTarget, ScrollRow, Chip, FloatingAction, Badge, SelectionContainer, SplitPane, CodeEditor, AbsoluteBox, Window, FlowRow, Popover, LinearProgressIndicator } -enum class PropertyKind { Text, Placeholder, Enabled, Multiline, OnClick, OnValueChange, OnSubmit, OnFocusLost, OnKeyDown, ItemCount, ItemKey, OnRangeRequested, TypeRole, FontSize, FontWeight, LineHeight, LetterSpacing, Color, TextAlign, MaxLines, Overflow, Arrangement, Spacing, SpaceRole, Alignment, Variant, Asset, Checked, Steps, Determinate, Circular, Vertical, Open, OnDismiss, SelectedIndex, Commands, Value, Min, Max, Icon, Slot, Columns, MinColumnWidth, Spans, OnFilesEntered, OnFilesDropped, Section, Count, Collapsible, ButtonKind, Decorations, SyntaxSpans, TabWidth, OnEditRejected, OnHover, OnSave, OnDecorationClick, Folds, GutterDecorations, OnSelectionChange, Font, WordBreak, OverflowWrap, TabSize, AbsoluteSize, SoftWrap, SpanFonts, OnVisibleRangeChange, OnEditorFocusChange, OnFoldChange, OnCompositionChange, OnPointer, PointerKinds, Cursor, UserSelect, IslandZoom, WindowTitle, WindowSize, WindowMinSize, WindowResizable, WindowChrome, WindowTitleBar, WindowIcon, WindowPosition, WindowRestoreKey, WindowZoomLevel, DragFromPointer, OnWindowCloseRequested, OnWindowFocusChanged, OnWindowMoved, OnWindowDrag, OnWindowUnavailable, OnWindowClosed, OnWindowDragOver, TearOffKey, OnFocusGained, OnKeyUp, AccessibleName, TrackColor, ThumbColor, ActiveTrackColor, ContainerColor, CheckColor, ControlSize, ReportSize, Scrim, Bare, HorizontalSpacing, VerticalSpacing, HorizontalAlignment, VerticalAlignment, MaxItemsInEachRow, Placement, Align, OffsetDp, LineNumbers, GutterMinWidthDp, GutterPaddingDp, TextInsetDp, CodeEditorColors, OnCodeMetrics, OnCodeScrolled, CompactNavigation, OnScrollChanged, Snap, MaxHeightFraction, OnCaretRect, Progress } +enum class PropertyKind { Text, Placeholder, Enabled, Multiline, OnClick, OnValueChange, OnSubmit, OnFocusLost, OnKeyDown, ItemCount, ItemKey, OnRangeRequested, TypeRole, FontSize, FontWeight, LineHeight, LetterSpacing, Color, TextAlign, MaxLines, Overflow, Arrangement, Spacing, SpaceRole, Alignment, Variant, Asset, Checked, Steps, Determinate, Circular, Vertical, Open, OnDismiss, SelectedIndex, Commands, Value, Min, Max, Icon, Slot, Columns, MinColumnWidth, Spans, OnFilesEntered, OnFilesDropped, Section, Count, Collapsible, ButtonKind, Decorations, SyntaxSpans, TabWidth, OnEditRejected, OnHover, OnSave, OnDecorationClick, Folds, GutterDecorations, OnSelectionChange, Font, WordBreak, OverflowWrap, TabSize, AbsoluteSize, SoftWrap, SpanFonts, OnVisibleRangeChange, OnEditorFocusChange, OnFoldChange, OnCompositionChange, OnPointer, PointerKinds, Cursor, UserSelect, IslandZoom, WindowTitle, WindowSize, WindowMinSize, WindowResizable, WindowChrome, WindowTitleBar, WindowIcon, WindowPosition, WindowRestoreKey, WindowZoomLevel, DragFromPointer, OnWindowCloseRequested, OnWindowFocusChanged, OnWindowMoved, OnWindowDrag, OnWindowUnavailable, OnWindowClosed, OnWindowDragOver, TearOffKey, OnFocusGained, OnKeyUp, AccessibleName, TrackColor, ThumbColor, ActiveTrackColor, ContainerColor, CheckColor, ControlSize, ReportSize, Scrim, Bare, HorizontalSpacing, VerticalSpacing, HorizontalAlignment, VerticalAlignment, MaxItemsInEachRow, Placement, Align, OffsetDp, LineNumbers, GutterMinWidthDp, GutterPaddingDp, TextInsetDp, CodeEditorColors, OnCodeMetrics, OnCodeScrolled, CompactNavigation, OnScrollChanged, Snap, MaxHeightFraction, OnCaretRect, OnKeyPreview, Progress } enum class Key { Enter, Other, Escape, Tab, Backspace, Delete, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Home, End, PageUp, PageDown } @@ -1606,7 +1606,7 @@ class ProtocolException(message: String, val offset: Int) : IllegalArgumentException("$message at byte offset $offset") object Protocol { - const val SCHEMA_HASH: Long = 6073216674444015188L + const val SCHEMA_HASH: Long = -487432507980895884L const val PROTOCOL_VERSION: Int = 1 private const val TAG_ENVELOPE = 0 @@ -2765,6 +2765,7 @@ object Protocol { 188 -> PropertyKind.Snap 189 -> PropertyKind.MaxHeightFraction 195 -> PropertyKind.OnCaretRect + 196 -> PropertyKind.OnKeyPreview 27 -> PropertyKind.Progress else -> throw ProtocolException("unknown property tag $tag", offset) } diff --git a/compose-rust/schema-hash.txt b/compose-rust/schema-hash.txt index dc898c697..0a3d57532 100644 --- a/compose-rust/schema-hash.txt +++ b/compose-rust/schema-hash.txt @@ -1 +1 @@ -0x544866635c36f654 +0xf93c4ab76dd22974 diff --git a/compose-rust/src/schema.rs b/compose-rust/src/schema.rs index 31dd7b5f4..102c25d22 100644 --- a/compose-rust/src/schema.rs +++ b/compose-rust/src/schema.rs @@ -227,7 +227,7 @@ pub struct EventSchema { pub const SCHEMA_DESCRIPTOR: &str = concat!( "compose-rust/v1;", "widgets=Column,Row,Box,Text,TextField,Button,Spacer,LazyColumn,ScrollColumn,Image,Icon,Checkbox,RadioButton,Switch,Slider,ProgressIndicator,Divider,Card,Surface,Dialog,Menu,Tabs,TopAppBar,LazyRow,Tooltip,Canvas,DatePicker,TimePicker,Dropdown,Navigation,NavigationItem,Sheet,Scaffold,ScaffoldSlot,LazyGrid,FileDropTarget,ScrollRow,Chip,FloatingAction,Badge,SelectionContainer,SplitPane,CodeEditor,AbsoluteBox,Window,FlowRow,Popover;", - "properties=text,placeholder,enabled,multiline,on_click,on_value_change,on_submit,on_focus_lost,on_key_down,item_count,item_key,on_range_requested,type_role,font_size,font_weight,line_height,letter_spacing,color,text_align,max_lines,overflow,arrangement,spacing,space_role,alignment,variant,asset,checked,steps,determinate,circular,vertical,open,on_dismiss,selected_index,commands,value,min,max,icon,slot,columns,min_column_width,spans,on_files_entered,on_files_dropped,section,count,collapsible,button_kind,decorations,syntax_spans,tab_width,on_edit_rejected,on_hover,on_save,on_decoration_click,folds,gutter_decorations,on_selection_change,font,word_break,overflow_wrap,tab_size,absolute_size,soft_wrap,span_fonts,on_visible_range_change,on_editor_focus_change,on_fold_change,on_composition_change,on_pointer,pointer_kinds,cursor,user_select,island_zoom,window_title,window_size,window_min_size,window_resizable,window_chrome,window_title_bar,window_icon,window_position,window_restore_key,window_zoom_level,drag_from_pointer,on_window_close_requested,on_window_focus_changed,on_window_moved,on_window_drag,on_window_unavailable,on_window_closed,on_window_drag_over,tear_off_key,on_focus_gained,on_key_up,accessible_name,track_color,thumb_color,active_track_color,container_color,check_color,control_size,report_size,scrim,bare,horizontal_spacing,vertical_spacing,horizontal_alignment,vertical_alignment,max_items_in_each_row,placement,align,offset_dp,line_numbers,gutter_min_width_dp,gutter_padding_dp,text_inset_dp,code_editor_colors,on_code_metrics,on_code_scrolled,compact_navigation,on_scroll_changed,snap,max_height_fraction,on_caret_rect;", + "properties=text,placeholder,enabled,multiline,on_click,on_value_change,on_submit,on_focus_lost,on_key_down,item_count,item_key,on_range_requested,type_role,font_size,font_weight,line_height,letter_spacing,color,text_align,max_lines,overflow,arrangement,spacing,space_role,alignment,variant,asset,checked,steps,determinate,circular,vertical,open,on_dismiss,selected_index,commands,value,min,max,icon,slot,columns,min_column_width,spans,on_files_entered,on_files_dropped,section,count,collapsible,button_kind,decorations,syntax_spans,tab_width,on_edit_rejected,on_hover,on_save,on_decoration_click,folds,gutter_decorations,on_selection_change,font,word_break,overflow_wrap,tab_size,absolute_size,soft_wrap,span_fonts,on_visible_range_change,on_editor_focus_change,on_fold_change,on_composition_change,on_pointer,pointer_kinds,cursor,user_select,island_zoom,window_title,window_size,window_min_size,window_resizable,window_chrome,window_title_bar,window_icon,window_position,window_restore_key,window_zoom_level,drag_from_pointer,on_window_close_requested,on_window_focus_changed,on_window_moved,on_window_drag,on_window_unavailable,on_window_closed,on_window_drag_over,tear_off_key,on_focus_gained,on_key_up,accessible_name,track_color,thumb_color,active_track_color,container_color,check_color,control_size,report_size,scrim,bare,horizontal_spacing,vertical_spacing,horizontal_alignment,vertical_alignment,max_items_in_each_row,placement,align,offset_dp,line_numbers,gutter_min_width_dp,gutter_padding_dp,text_inset_dp,code_editor_colors,on_code_metrics,on_code_scrolled,compact_navigation,on_scroll_changed,snap,max_height_fraction,on_caret_rect,on_key_preview;", "modifiers=Empty,Padding,FillMaxWidth,FillMaxHeight,Width,Height,Size,Background,Clickable,PaddingRole,PaddingEach,Weight,Shape,ShapeRole,Border,Elevation,ObserveSize,Motion,Material,Offset,RequiredSize,BorderEach,CornerEach,Shadow,Clip,Alpha,Transform,Transform3D,MatchParentSize,WindowDrag,PressFeedback,Semantics,CornerCurve;", "keys=Enter,Other;", "events=Clicked,TextChanged,TextSubmitted,FocusLost,ProtocolError,KeyDown,RangeRequested,ValueChanged,WindowSizeChanged,DesignSystemResolved,FilesEntered,FilesDropped,NotificationActivated,NotificationPermissionChanged,CodeChanged,CodeEditRejected,CodeHovered,CodeSaveRequested,DecorationActivated,AnimationEvent,ReducedMotionChanged,Pointer,ZoomChanged,SelectionChanged,VisibleRangeChanged,EditorFocusChanged,FoldChanged,CompositionChanged,WindowCloseRequested,WindowFocusChanged,WindowMoved,WindowDrag,WindowDragOver,WindowUnavailable,WindowClosed,WindowRequested,ApplicationReopen,FocusGained,KeyUp,FileDialogResult,ClipboardText,CodeMetrics,CodeScrolled,IoAnswer,FileHandles,StorageLocation,ScrollChanged,CaretRect,PositionRect;", @@ -3595,6 +3595,10 @@ crate::extensions::define_property_schema_with_extensions!(define_wire_enum; PRO // The handler a code editor tells where its caret is drawn. 190 to 194 are held by // properties on other branches. OnCaretRect = 195, + // The handler a code editor offers each key press to before it handles the key itself. + // It hears the `KeyDown` record a key handler does, and a press it consumes is not the + // editor's. Never while an input method is composing. + OnKeyPreview = 196, }); #[derive(Clone, Debug, PartialEq)] diff --git a/compose-rust/tests/code_editor.rs b/compose-rust/tests/code_editor.rs index bd5ddd1c9..61f70e1f7 100644 --- a/compose-rust/tests/code_editor.rs +++ b/compose-rust/tests/code_editor.rs @@ -1215,3 +1215,36 @@ fn fr38_editor_answers_position_rects_on_the_wire() { .is_err() ); } + +/// The key preview is the editor's own handler property, past the caret's, and what it +/// hears is the `KeyDown` record a key handler hears: the same 32 bytes and tag, so a Host +/// reads a previewed key the way it reads any other and answers it with the same result. +#[test] +fn fr38_editor_key_preview_keeps_its_tag_and_the_key_down_record() { + assert_eq!(PropertyKind::OnKeyPreview as u16, 196); + assert_eq!( + PropertyKind::from_name("on_key_preview"), + Ok(PropertyKind::OnKeyPreview) + ); + let (length, decoded) = round_trip(EventPayload::KeyDown { + key: compose_rust::Key::ArrowDown, + shift_key: false, + ctrl_key: true, + alt_key: false, + meta_key: false, + repeat: true, + code: 0x51, + text: "ArrowDown", + }); + assert_eq!(length, 32 + "ArrowDown".len()); + assert!(matches!( + decoded.payload, + EventPayload::KeyDown { + key: compose_rust::Key::ArrowDown, + ctrl_key: true, + repeat: true, + code: 0x51, + .. + } + )); +} diff --git a/compose-rust/tests/vectors/vectors.json b/compose-rust/tests/vectors/vectors.json index 81f9d4602..685b4b74c 100644 --- a/compose-rust/tests/vectors/vectors.json +++ b/compose-rust/tests/vectors/vectors.json @@ -1,6 +1,6 @@ { "format": "compose-rust protocol vectors v1", - "schemaHashUnsigned": "6073216674444015188", + "schemaHashUnsigned": "17959311565728655732", "byteOrder": "little-endian", "mutations": { "file": "mutations.bin", diff --git a/renderer/desktop/src/protocol/Protocol.gen.kt b/renderer/desktop/src/protocol/Protocol.gen.kt index cfc8caa07..b8e2a8a2c 100644 --- a/renderer/desktop/src/protocol/Protocol.gen.kt +++ b/renderer/desktop/src/protocol/Protocol.gen.kt @@ -8,7 +8,7 @@ import java.nio.charset.StandardCharsets enum class WidgetKind { Column, Row, Box, Text, TextField, Button, Spacer, LazyColumn, ScrollColumn, Image, Icon, Checkbox, RadioButton, Switch, Slider, ProgressIndicator, Divider, Card, Surface, Dialog, Menu, Tabs, TopAppBar, LazyRow, Tooltip, Canvas, DatePicker, TimePicker, Dropdown, Navigation, NavigationItem, Sheet, Scaffold, ScaffoldSlot, LazyGrid, FileDropTarget, ScrollRow, Chip, FloatingAction, Badge, SelectionContainer, SplitPane, CodeEditor, AbsoluteBox, Window, FlowRow, Popover, LinearProgressIndicator } -enum class PropertyKind { Text, Placeholder, Enabled, Multiline, OnClick, OnValueChange, OnSubmit, OnFocusLost, OnKeyDown, ItemCount, ItemKey, OnRangeRequested, TypeRole, FontSize, FontWeight, LineHeight, LetterSpacing, Color, TextAlign, MaxLines, Overflow, Arrangement, Spacing, SpaceRole, Alignment, Variant, Asset, Checked, Steps, Determinate, Circular, Vertical, Open, OnDismiss, SelectedIndex, Commands, Value, Min, Max, Icon, Slot, Columns, MinColumnWidth, Spans, OnFilesEntered, OnFilesDropped, Section, Count, Collapsible, ButtonKind, Decorations, SyntaxSpans, TabWidth, OnEditRejected, OnHover, OnSave, OnDecorationClick, Folds, GutterDecorations, OnSelectionChange, Font, WordBreak, OverflowWrap, TabSize, AbsoluteSize, SoftWrap, SpanFonts, OnVisibleRangeChange, OnEditorFocusChange, OnFoldChange, OnCompositionChange, OnPointer, PointerKinds, Cursor, UserSelect, IslandZoom, WindowTitle, WindowSize, WindowMinSize, WindowResizable, WindowChrome, WindowTitleBar, WindowIcon, WindowPosition, WindowRestoreKey, WindowZoomLevel, DragFromPointer, OnWindowCloseRequested, OnWindowFocusChanged, OnWindowMoved, OnWindowDrag, OnWindowUnavailable, OnWindowClosed, OnWindowDragOver, TearOffKey, OnFocusGained, OnKeyUp, AccessibleName, TrackColor, ThumbColor, ActiveTrackColor, ContainerColor, CheckColor, ControlSize, ReportSize, Scrim, Bare, HorizontalSpacing, VerticalSpacing, HorizontalAlignment, VerticalAlignment, MaxItemsInEachRow, Placement, Align, OffsetDp, LineNumbers, GutterMinWidthDp, GutterPaddingDp, TextInsetDp, CodeEditorColors, OnCodeMetrics, OnCodeScrolled, CompactNavigation, OnScrollChanged, Snap, MaxHeightFraction, OnCaretRect, Progress } +enum class PropertyKind { Text, Placeholder, Enabled, Multiline, OnClick, OnValueChange, OnSubmit, OnFocusLost, OnKeyDown, ItemCount, ItemKey, OnRangeRequested, TypeRole, FontSize, FontWeight, LineHeight, LetterSpacing, Color, TextAlign, MaxLines, Overflow, Arrangement, Spacing, SpaceRole, Alignment, Variant, Asset, Checked, Steps, Determinate, Circular, Vertical, Open, OnDismiss, SelectedIndex, Commands, Value, Min, Max, Icon, Slot, Columns, MinColumnWidth, Spans, OnFilesEntered, OnFilesDropped, Section, Count, Collapsible, ButtonKind, Decorations, SyntaxSpans, TabWidth, OnEditRejected, OnHover, OnSave, OnDecorationClick, Folds, GutterDecorations, OnSelectionChange, Font, WordBreak, OverflowWrap, TabSize, AbsoluteSize, SoftWrap, SpanFonts, OnVisibleRangeChange, OnEditorFocusChange, OnFoldChange, OnCompositionChange, OnPointer, PointerKinds, Cursor, UserSelect, IslandZoom, WindowTitle, WindowSize, WindowMinSize, WindowResizable, WindowChrome, WindowTitleBar, WindowIcon, WindowPosition, WindowRestoreKey, WindowZoomLevel, DragFromPointer, OnWindowCloseRequested, OnWindowFocusChanged, OnWindowMoved, OnWindowDrag, OnWindowUnavailable, OnWindowClosed, OnWindowDragOver, TearOffKey, OnFocusGained, OnKeyUp, AccessibleName, TrackColor, ThumbColor, ActiveTrackColor, ContainerColor, CheckColor, ControlSize, ReportSize, Scrim, Bare, HorizontalSpacing, VerticalSpacing, HorizontalAlignment, VerticalAlignment, MaxItemsInEachRow, Placement, Align, OffsetDp, LineNumbers, GutterMinWidthDp, GutterPaddingDp, TextInsetDp, CodeEditorColors, OnCodeMetrics, OnCodeScrolled, CompactNavigation, OnScrollChanged, Snap, MaxHeightFraction, OnCaretRect, OnKeyPreview, Progress } enum class Key { Enter, Other, Escape, Tab, Backspace, Delete, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Home, End, PageUp, PageDown } @@ -1606,7 +1606,7 @@ class ProtocolException(message: String, val offset: Int) : IllegalArgumentException("$message at byte offset $offset") object Protocol { - const val SCHEMA_HASH: Long = 6073216674444015188L + const val SCHEMA_HASH: Long = -487432507980895884L const val PROTOCOL_VERSION: Int = 1 private const val TAG_ENVELOPE = 0 @@ -2765,6 +2765,7 @@ object Protocol { 188 -> PropertyKind.Snap 189 -> PropertyKind.MaxHeightFraction 195 -> PropertyKind.OnCaretRect + 196 -> PropertyKind.OnKeyPreview 27 -> PropertyKind.Progress else -> throw ProtocolException("unknown property tag $tag", offset) } diff --git a/renderer/desktop/src/renderer/CodeEditorSurface.kt b/renderer/desktop/src/renderer/CodeEditorSurface.kt index 1206cc9a6..71eafdf59 100644 --- a/renderer/desktop/src/renderer/CodeEditorSurface.kt +++ b/renderer/desktop/src/renderer/CodeEditorSurface.kt @@ -283,6 +283,13 @@ class CodeEditorCallbacks( * or zero. */ val onHover: (decoration: Long, position: CodePosition, rest: Boolean) -> Unit, + /** + * A key event, offered before the editor does anything with it. True means the Host + * took the key and the editor leaves it alone. [composing] says an input method is + * composing, which the Host is never offered a key during. Every event comes through + * here, releases too, so a held key's repeats can be told from its first press. + */ + val onKeyPreview: (event: KeyEvent, composing: Boolean) -> Boolean = { _, _ -> false }, ) /** Test tag of the field a field surface types into. */ @@ -1212,7 +1219,10 @@ private fun FieldSurface( .focusRequester(focus) .testTag(CODE_EDITOR_FIELD_TAG) .onPreviewKeyEvent { event -> - handleKey(event, window, look, callbacks) + // The Host hears the key first, and a key it takes is + // not the editor's. + callbacks.onKeyPreview(event, window.state.composition != null) || + handleKey(event, window, look, callbacks) } .pointerInput(window, look) { awaitPointerEventScope { diff --git a/renderer/desktop/src/renderer/DrawnCodeEditor.kt b/renderer/desktop/src/renderer/DrawnCodeEditor.kt index 8201beb0a..82c5bb40a 100644 --- a/renderer/desktop/src/renderer/DrawnCodeEditor.kt +++ b/renderer/desktop/src/renderer/DrawnCodeEditor.kt @@ -608,6 +608,8 @@ private fun DrawScope.drawLines( /** The keys the drawn editor answers. Typed characters arrive here the way they reach a text field on the desktop. */ private fun drawnKey(event: KeyEvent, state: DrawnState): Boolean { + // The Host hears the key first, and a key it takes is not the editor's. + if (state.callbacks.onKeyPreview(event, state.composing.isNotEmpty())) return true // While an input method composes, its keys are its own. if (state.composing.isNotEmpty()) return false val model = state.model diff --git a/renderer/desktop/src/renderer/HostCodeEditor.kt b/renderer/desktop/src/renderer/HostCodeEditor.kt index 7352d698b..22dee7862 100644 --- a/renderer/desktop/src/renderer/HostCodeEditor.kt +++ b/renderer/desktop/src/renderer/HostCodeEditor.kt @@ -6,6 +6,9 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier +import androidx.compose.ui.input.key.KeyEvent +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.type import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import dev.darkpyonix.composerust.design.HostPlatform @@ -81,6 +84,7 @@ internal fun HostCodeEditor( node.bytes(PropertyKind.CodeEditorColors), ) { codeEditorLook(node, theme, tabWidth, fontChain) } val currentDispatcher by rememberUpdatedState(dispatcher) + val keyPreview = remember(node) { codeEditorKeyPreview(node, { currentDispatcher }) } val callbacks = remember(node, model) { CodeEditorCallbacks( onOutput = { node.sendCodeOutput(model.drainOutput(includeReports = true), currentDispatcher) }, @@ -107,6 +111,7 @@ internal fun HostCodeEditor( ) } }, + onKeyPreview = keyPreview, ) } // A listener attached after the editor was drawn has the row height and the offset @@ -147,6 +152,26 @@ private fun EditorScroll.axis(viewport: () -> Int): ScrollAxis = ScrollAxis( jump = { target -> scrollTo(target) }, ) +/** + * What an editor offers the Host before it handles a key: the `KeyDown` record a key handler + * hears, sent to the node's `OnKeyPreview` handler, whose answer says whether the Host took + * the key. Nothing is sent while an input method composes, for a release, or where nothing + * listens. Every event passes through [held], so a repeat is marked as one. + */ +internal fun codeEditorKeyPreview( + node: Node, + dispatcher: () -> EventDispatcher, + held: HeldKeys = HeldKeys(), +): (KeyEvent, Boolean) -> Boolean = { event, composing -> + val handler = node.handler(PropertyKind.OnKeyPreview) + if (handler == null) { + held.observe(event.type, event.key) + false + } else { + dispatchKeyDown(node.id, handler, event, composing, dispatcher(), held) + } +} + /** The colours the application gave this editor, or null where it gave none that can be read. */ internal fun Node.codeEditorColors(): CodeEditorColorsRecord? = bytes(PropertyKind.CodeEditorColors)?.let { bytes -> diff --git a/renderer/desktop/src/renderer/NodeTable.kt b/renderer/desktop/src/renderer/NodeTable.kt index 317cec569..3a3145824 100644 --- a/renderer/desktop/src/renderer/NodeTable.kt +++ b/renderer/desktop/src/renderer/NodeTable.kt @@ -1438,8 +1438,10 @@ class NodeTable { PropertyKind.CodeEditorColors, PropertyKind.OnCodeMetrics, PropertyKind.OnCodeScrolled, - // The handler told where the caret is drawn. + // The handler told where the caret is drawn, and the one offered keys + // before the editor handles them. PropertyKind.OnCaretRect, + PropertyKind.OnKeyPreview, -> widget == WidgetKind.CodeEditor PropertyKind.OnCompositionChange -> diff --git a/renderer/desktop/test/CodeEditorInputHooksTest.kt b/renderer/desktop/test/CodeEditorInputHooksTest.kt new file mode 100644 index 000000000..774eb6862 --- /dev/null +++ b/renderer/desktop/test/CodeEditorInputHooksTest.kt @@ -0,0 +1,186 @@ +package dev.darkpyonix.composerust.test + +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.InternalComposeUiApi +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEvent +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.click +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.performMouseInput +import androidx.compose.ui.test.pressKey +import androidx.compose.ui.test.requestFocus +import androidx.compose.ui.test.runComposeUiTest +import dev.darkpyonix.composerust.design.HostPlatform +import dev.darkpyonix.composerust.foundation.code.CODE_EDITOR_FIELD_TAG +import dev.darkpyonix.composerust.foundation.code.CodeEditorPath +import dev.darkpyonix.composerust.foundation.code.CodePosition +import dev.darkpyonix.composerust.foundation.code.defaultCodeEditorPath +import dev.darkpyonix.composerust.foundation.code.installDrawnCodeEditor +import dev.darkpyonix.composerust.foundation.codeEditorKeyPreview +import dev.darkpyonix.composerust.protocol.ColorScheme +import dev.darkpyonix.composerust.protocol.DesignSystem +import dev.darkpyonix.composerust.protocol.HostEvent +import dev.darkpyonix.composerust.protocol.Key as ProtocolKey +import dev.darkpyonix.composerust.protocol.Modifier as ProtocolModifier +import dev.darkpyonix.composerust.protocol.Mutation +import dev.darkpyonix.composerust.protocol.PropertyKind +import dev.darkpyonix.composerust.protocol.PropertyValue +import dev.darkpyonix.composerust.protocol.Theme +import dev.darkpyonix.composerust.protocol.WidgetKind +import dev.darkpyonix.composerust.runtime.ComposeRustContent +import dev.darkpyonix.composerust.runtime.ComposeRustHost +import dev.darkpyonix.composerust.runtime.EventDispatcher +import dev.darkpyonix.composerust.runtime.hostPlatformOverride +import dev.darkpyonix.composerust.runtime.rememberComposeRustHost +import dev.darkpyonix.composerust.tooling.FakeHostConnection +import dev.darkpyonix.composerust.tooling.HostResponse +import dev.darkpyonix.composerust.ui.node.NodeTable +import dev.darkpyonix.composerust.ui.node.nodeTestTag +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +private const val EDITOR = 2 +private const val ON_PREVIEW = 81L + +/** An editor alone on the page, 300 by 160 dp, with the records the test adds after it. */ +private fun page(text: String, vararg extra: Mutation): List = buildList { + add(Mutation.SetTheme(Theme(DesignSystem.Material3, DesignSystem.Material3, ColorScheme.Light, false))) + add(Mutation.Create(EDITOR, WidgetKind.CodeEditor)) + add(Mutation.SetModifier(EDITOR, 0, ProtocolModifier.Size(300f, 160f))) + add(Mutation.SetProp(EDITOR, PropertyKind.Text, PropertyValue.Text(text))) + addAll(extra) +} + +/** + * Criteria 20 and 21 of the code editor: the Host hears a key before the editor does and + * can take it, and hears the pointer over the editor with the place in the text under it. + */ +@OptIn(ExperimentalTestApi::class) +class CodeEditorInputHooksTest { + @BeforeTest + fun windowsShortcuts() { + hostPlatformOverride = HostPlatform.Windows + } + + @AfterTest + fun clearPlatform() { + hostPlatformOverride = null + defaultCodeEditorPath = CodeEditorPath.Windowed + } + + private fun ComposeUiTest.show(connection: FakeHostConnection): () -> ComposeRustHost { + lateinit var host: ComposeRustHost + setContent { + host = rememberComposeRustHost(connection) + ComposeRustContent(host) + } + waitForIdle() + return { host } + } + + /** + * Criterion 20.1. The Host takes Down while a list is open: the caret stays where it + * was. It lets Down go: the caret moves a line, as it does with nobody listening. Both + * presses reach the Host first, as the `KeyDown` record a key handler hears. + */ + @Test + fun fr38_editor_key_preview_consumes_keys() { + installDrawnCodeEditor() + for (path in listOf(CodeEditorPath.Windowed, CodeEditorPath.Drawn)) { + defaultCodeEditorPath = path + runComposeUiTest { + var take = true + val connection = FakeHostConnection( + page("first\nsecond\nthird", Mutation.SetProp(EDITOR, PropertyKind.OnKeyPreview, PropertyValue.Integer(ON_PREVIEW))), + ) + connection.respondWith { event -> + if (event is HostEvent.KeyDown && event.handlerId == ON_PREVIEW && take) HostResponse(result = 1) else HostResponse() + } + val host = show(connection) + fun caret() = host().table.node(EDITOR)!!.code!!.selection.caret + val target = if (path == CodeEditorPath.Drawn) { + // The drawn editor takes the focus when it is pressed, here past the + // end of the first line. + val editor = onNodeWithTag(nodeTestTag(EDITOR)) + editor.performMouseInput { click(Offset(width - 4f, 4f)) } + editor + } else { + onNodeWithTag(CODE_EDITOR_FIELD_TAG, useUnmergedTree = true).also { it.requestFocus() } + } + waitForIdle() + val start = caret() + assertEquals(0, start.line, "$path") + + target.performKeyInput { pressKey(Key.DirectionDown) } + waitForIdle() + assertEquals(start, caret(), "$path: a key the Host took moved the caret") + + take = false + target.performKeyInput { pressKey(Key.DirectionDown) } + waitForIdle() + assertEquals(1, caret().line, "$path: a key the Host let go did not move the caret") + + val previews = connection.nodeEvents.filterIsInstance() + assertEquals(2, previews.size, "$path: each press is offered once: $previews") + for (preview in previews) { + assertEquals(EDITOR, preview.nodeId) + assertEquals(ON_PREVIEW, preview.handlerId) + assertEquals(ProtocolKey.ArrowDown, preview.key) + assertEquals(0x51, preview.code) + assertEquals("ArrowDown", preview.text) + assertFalse(preview.repeat) + } + } + } + assertTrue(NodeTable.supportsProperty(WidgetKind.CodeEditor, PropertyKind.OnKeyPreview)) + assertFalse(NodeTable.supportsProperty(WidgetKind.TextField, PropertyKind.OnKeyPreview)) + } + + /** + * Criterion 20.2. While an input method composes nothing is offered to the Host, so a + * Down that picks a candidate stays the input method's. Releases are never offered, and + * outside a composition the press is, with the Host's answer as the editor's. + */ + @OptIn(InternalComposeUiApi::class, ExperimentalComposeUiApi::class) + @Test + fun fr38_editor_key_preview_skips_composition() { + val table = NodeTable() + table.apply(Mutation.Create(EDITOR, WidgetKind.CodeEditor)) + table.apply(Mutation.SetProp(EDITOR, PropertyKind.OnKeyPreview, PropertyValue.Integer(ON_PREVIEW))) + val node = table.node(EDITOR)!! + val sent = mutableListOf() + var answer = true + val preview = codeEditorKeyPreview(node, { EventDispatcher { sent += it; answer } }) + val down = KeyEvent(Key.DirectionDown, KeyEventType.KeyDown) + val up = KeyEvent(Key.DirectionDown, KeyEventType.KeyUp) + + assertFalse(preview(down, true), "a key during a composition was taken from the input method") + assertFalse(preview(up, true)) + assertEquals(emptyList(), sent, "a key during a composition reached the Host") + + assertTrue(preview(down, false), "the Host's answer is the editor's") + assertFalse(preview(up, false), "a release is not offered") + answer = false + assertFalse(preview(down, false)) + assertEquals(2, sent.size) + assertTrue(sent.all { it is HostEvent.KeyDown && it.handlerId == ON_PREVIEW && it.nodeId == EDITOR }) + + // Held down, the second press is a repeat. + preview(down, false) + assertTrue((sent.last() as HostEvent.KeyDown).repeat) + + // Nobody listening: nothing is sent and the key stays the editor's. + table.apply(Mutation.SetProp(EDITOR, PropertyKind.OnKeyPreview, PropertyValue.None)) + assertFalse(preview(down, false)) + assertEquals(3, sent.size) + } +} From 23dc7491d48b6f06727c84b627b2c67853a635a5 Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:40:01 +0900 Subject: [PATCH 7/8] Feat: Send the code editor's pointer events with the text position under them (FR-38, #555) Covers FR-38 criterion 21. Wire: the OnCodePointer handler property (197), with the kinds taken from the node's PointerKinds mask, which an editor now accepts. The CodePointer event (66) is the 72 byte Pointer record followed by the line and the column under the pointer, both u32::MAX over no character: 80 bytes. Rust: code::CodePointer, a PointerEvent and the position. The event vector gains one (events.bin is 1599 bytes). Renderer: the editor's view carries the same pointer node a subscribed node does, on the same router, so the kinds, the buttons, the modifiers, the click count, capture, the menu and a move a frame are FR-46's own. It routes in the first pass rather than the main one, so a Down the Host consumes is consumed before the field's selection gesture or the drawn editor's press sees it, and the caret stays. The field path finds the character through the field's layout and the drawn path through its rows; the gutter, past a line's end, a lens row and below the last line are over no character. Tests: fr38_editor_pointer_reports_text_position (21.1, both paths) in CodeEditorInputHooksTest; fr38_editor_pointer_reports_text_position_on_the_wire in code_editor.rs; the vector offset in ProtocolVectorsTest. PointerEventsTest still passes on the shared router. --- CHANGELOG.md | 4 + .../shared/CodeEditorSurface.kt | 32 +++- .../android-kotlin/shared/HostCodeEditor.kt | 10 ++ .../android-kotlin/shared/NodeTable.kt | 7 +- .../android-kotlin/shared/PointerEvents.kt | 114 +++++++++++++++ .../android-kotlin/shared/Protocol.gen.kt | 26 +++- compose-rust/schema-hash.txt | 2 +- compose-rust/src/code.rs | 57 ++++++++ compose-rust/src/codegen.rs | 42 +++++- compose-rust/src/lib.rs | 8 +- compose-rust/src/protocol.rs | 104 ++++++++++++- compose-rust/src/schema.rs | 38 ++++- compose-rust/tests/code_editor.rs | 138 +++++++++++++++++- compose-rust/tests/vectors/events.bin | Bin 1519 -> 1599 bytes compose-rust/tests/vectors/vectors.json | 7 +- renderer/desktop/src/protocol/Protocol.gen.kt | 26 +++- .../desktop/src/renderer/CodeEditorSurface.kt | 32 +++- .../desktop/src/renderer/DrawnCodeEditor.kt | 23 ++- .../desktop/src/renderer/HostCodeEditor.kt | 10 ++ renderer/desktop/src/renderer/NodeTable.kt | 7 +- .../desktop/src/renderer/PointerEvents.kt | 114 +++++++++++++++ .../desktop/test/CodeEditorInputHooksTest.kt | 103 ++++++++++++- renderer/desktop/test/ProtocolVectorsTest.kt | 8 +- 23 files changed, 879 insertions(+), 33 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e47cd7ec3..ba5f5120c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Code editor pointer events with the text under them + +A `CodeEditor` with the new `OnCodePointer` handler property (tag 197) and a `PointerKinds` mask sends its pointer events in a `CodePointer` event (tag 66): the 72 byte `Pointer` record of a node's pointer event, then the line and the column of the character under the pointer, or none over the gutter, past the end of a line or below the last one. The kinds, the buttons, the modifiers, the click count, the capture, a move a frame and the consumption rules are a node's pointer event's, and a `Down` the handler consumes does not move the caret. Cmd or Ctrl and a click goes to a definition this way, and Cmd or Ctrl and a hover underlines a word ([#555](https://github.com/DarkPyonix/compose-rust/issues/555)). + ### The Host hears the code editor's keys first A `CodeEditor` with the new `OnKeyPreview` handler property (tag 196) offers every key press to the Host before it handles the key itself, as the `KeyDown` record a key handler hears. A press the handler consumes, through the same synchronous result as any key handler, is not the editor's: Down does not move the caret and Enter inserts no line. Nothing is offered while an input method is composing. A suggestion list takes Up, Down, Enter, Tab and Escape this way while it is open, and an application takes its own commands such as F12, F2, Ctrl+Space or Ctrl/Cmd+. ([#554](https://github.com/DarkPyonix/compose-rust/issues/554)). diff --git a/compose-rust/android-kotlin/shared/CodeEditorSurface.kt b/compose-rust/android-kotlin/shared/CodeEditorSurface.kt index 71eafdf59..e398abcbf 100644 --- a/compose-rust/android-kotlin/shared/CodeEditorSurface.kt +++ b/compose-rust/android-kotlin/shared/CodeEditorSurface.kt @@ -87,6 +87,7 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import dev.darkpyonix.composerust.foundation.CodePointerTarget import dev.darkpyonix.composerust.protocol.ColorRole import dev.darkpyonix.composerust.protocol.DecorationKind import dev.darkpyonix.composerust.protocol.GutterDecorationKind @@ -290,6 +291,11 @@ class CodeEditorCallbacks( * here, releases too, so a held key's repeats can be told from its first press. */ val onKeyPreview: (event: KeyEvent, composing: Boolean) -> Boolean = { _, _ -> false }, + /** + * What the editor's view carries for the Host's pointer events over it, given what is + * under a point of the view. Nothing where the Host does not listen. + */ + val codePointer: @Composable (CodePointerTarget) -> Modifier = { Modifier }, ) /** Test tag of the field a field surface types into. */ @@ -932,13 +938,14 @@ internal fun caretOnScreen(rect: Rect, viewport: LayoutCoordinates?, textLeft: F * and from the layout callbacks, where the field's text layout and its place on screen are * the ones the reader sees. */ -internal class FieldPlaces(private val window: FieldWindow) { +internal class FieldPlaces(private val window: FieldWindow) : CodePointerTarget { /** The field itself, where its text layout's coordinates start. */ var field: LayoutCoordinates? = null /** The editor's view: everything the reader can see of it. */ var viewport: LayoutCoordinates? = null var layout: (() -> TextLayoutResult?)? = null + var gutterWidthPx = 0f var textLeftPx = 0f var density = 1f @@ -968,6 +975,22 @@ internal class FieldPlaces(private val window: FieldWindow) { return Rect(coordinates.localToRoot(Offset(cursor.left, cursor.top)), Size(caretWidthPx, cursor.height)) } + override fun positionAt(x: Float, y: Float): CodePosition? { + if (x < gutterWidthPx) return null + val view = viewport?.takeIf { it.isAttached } ?: return null + val coordinates = field?.takeIf { it.isAttached } ?: return null + val result = layout?.invoke() ?: return null + val point = coordinates.localPositionOf(view, Offset(x, y)) + if (point.x < 0f || point.y < 0f || point.y >= result.size.height) return null + // Past the end of the line it is on, the pointer is over no character. + val line = result.getLineForVerticalPosition(point.y) + if (point.x > result.getLineRight(line)) return null + val (offset, insertion) = window.toFieldOffset(result.getOffsetForPosition(point)) + // A lens row and a suggestion are shown, not the document's text. + if (insertion != null) return null + return window.toDoc(offset) + } + /** * Tells the model how to find positions and where the caret is, and answers the queries * that waited for the editor to be drawn. Answers whether the Host has something to hear. @@ -1093,6 +1116,7 @@ private fun FieldSurface( // Where the caret is drawn and where a position is, read after layout. What they find // is sent from a coroutine rather than from inside the pass that found it. val places = remember(window) { FieldPlaces(window).also { it.layout = { layoutHolder[0]?.invoke() } } } + places.gutterWidthPx = gutterWidthPx.toFloat() places.textLeftPx = (gutterWidthPx + textInsetPx).toFloat() places.density = density.density places.caretWidthPx = with(density) { 2.dp.toPx() } @@ -1111,6 +1135,9 @@ private fun FieldSurface( Box( modifier .boundedHeight(DEFAULT_EDITOR_HEIGHT) + // Outside the field, so the Host hears a press before the field moves the + // caret for it, and over the gutter as well as the text. + .then(callbacks.codePointer(places)) .changeSemantics(model, look) .background(look.container) .clipToBounds() @@ -1231,7 +1258,8 @@ private fun FieldSurface( val change = event.changes.firstOrNull() ?: continue val result = layoutHolder[0]?.invoke() when (event.type) { - PointerEventType.Press -> { + // A press the Host took is not the editor's. + PointerEventType.Press -> if (!change.isConsumed) { val lens = result?.let { lensAt(window, it, change.position) } diff --git a/compose-rust/android-kotlin/shared/HostCodeEditor.kt b/compose-rust/android-kotlin/shared/HostCodeEditor.kt index 22dee7862..9567c510a 100644 --- a/compose-rust/android-kotlin/shared/HostCodeEditor.kt +++ b/compose-rust/android-kotlin/shared/HostCodeEditor.kt @@ -112,6 +112,16 @@ internal fun HostCodeEditor( } }, onKeyPreview = keyPreview, + // The Host's pointer events over the editor go through the same router as every + // other node's, so a press the editor does not consume goes on to the nearest + // subscribed node around it. + codePointer = { target -> + if (node.subscribesToCodePointer()) { + codePointerEvents(node, table.pointers, currentDispatcher, target) + } else { + Modifier + } + }, ) } // A listener attached after the editor was drawn has the row height and the offset diff --git a/compose-rust/android-kotlin/shared/NodeTable.kt b/compose-rust/android-kotlin/shared/NodeTable.kt index 3a3145824..94c16801d 100644 --- a/compose-rust/android-kotlin/shared/NodeTable.kt +++ b/compose-rust/android-kotlin/shared/NodeTable.kt @@ -1133,7 +1133,9 @@ class NodeTable { widget == WidgetKind.ScrollRow || widget == WidgetKind.SelectionContainer || widget == WidgetKind.Spacer || - widget == WidgetKind.AbsoluteBox + widget == WidgetKind.AbsoluteBox || + // An editor's own pointer events take the same mask of kinds. + (widget == WidgetKind.CodeEditor && property == PropertyKind.PointerKinds) // A Tooltip's text is the explanation it shows, and its description in the // accessibility tree. A destination's is its label. @@ -1442,6 +1444,9 @@ class NodeTable { // before the editor handles them. PropertyKind.OnCaretRect, PropertyKind.OnKeyPreview, + // The handler of its pointer events with the text under them. The kinds it + // hears are the node's `PointerKinds`, below. + PropertyKind.OnCodePointer, -> widget == WidgetKind.CodeEditor PropertyKind.OnCompositionChange -> diff --git a/compose-rust/android-kotlin/shared/PointerEvents.kt b/compose-rust/android-kotlin/shared/PointerEvents.kt index a64a6bb80..9cc32481d 100644 --- a/compose-rust/android-kotlin/shared/PointerEvents.kt +++ b/compose-rust/android-kotlin/shared/PointerEvents.kt @@ -30,6 +30,7 @@ import androidx.compose.ui.platform.LocalViewConfiguration import androidx.compose.ui.unit.IntSize import dev.darkpyonix.composerust.design.HostPlatform import dev.darkpyonix.composerust.design.detectHostPlatform +import dev.darkpyonix.composerust.foundation.code.CodePosition import dev.darkpyonix.composerust.protocol.HostEvent import dev.darkpyonix.composerust.protocol.PointerKind import dev.darkpyonix.composerust.protocol.PointerType @@ -120,6 +121,29 @@ internal fun HostNode.pointerKinds(): Int = internal fun HostNode.subscribesToPointer(): Boolean = handler(PropertyKind.OnPointer) != null && pointerKinds() != 0 +/** + * Whether a code editor has both halves of its own subscription: the handler that hears its + * pointer with the text under it, and at least one kind in the same mask a node's has. + */ +internal fun HostNode.subscribesToCodePointer(): Boolean = + handler(PropertyKind.OnCodePointer) != null && pointerKinds() != 0 + +/** + * A code editor's surface, as the pointer events over it see it: what is under a point. + * + * The editor's pointer node routes in the first pass rather than the main one. The text + * the editor draws handles a press in the main pass, so a press the Host consumed has to be + * consumed before then, or the caret would move under a Cmd-click that was the Host's. + */ +interface CodePointerTarget { + /** + * The character under a point of the editor's view, in its pixels, or null where there + * is none: the gutter, past the end of a line, below the last line, or a row the editor + * shows that is not the document's. + */ + fun positionAt(x: Float, y: Float): CodePosition? +} + /** * The modifier of a subscribed node. Call it only for a node that subscribes. * @@ -156,6 +180,38 @@ internal fun hostPointerEvents( ) } +/** + * The modifier of a code editor's view whose node subscribes to [PropertyKind.OnCodePointer]. + * The records are the ones [hostPointerEvents] sends with the character under the pointer + * after them, and every rule is the same: the kinds, the capture, a move a frame, the click + * count, the menu, and a consumed press consumed for Compose too. + */ +@Composable +internal fun codePointerEvents( + node: HostNode, + router: PointerRouter, + dispatcher: EventDispatcher, + target: CodePointerTarget, +): Modifier { + val outer = LocalDensity.current + val view = LocalViewConfiguration.current + val controlClickIsMenu = remember { + (hostPlatformOverride ?: detectHostPlatform()) == HostPlatform.MacOs + } + return HostPointerElement( + node, + router, + dispatcher, + outer.density, + view.doubleTapTimeoutMillis, + view.longPressTimeoutMillis, + view.touchSlop, + controlClickIsMenu, + hostWheelDeltaMode, + target, + ) +} + private data class HostPointerElement( val node: HostNode, val router: PointerRouter, @@ -166,6 +222,8 @@ private data class HostPointerElement( val slop: Float, val controlClickIsMenu: Boolean, val wheelMode: WheelDeltaMode, + /** A code editor's view, for the editor's own events. Null for a node's [PropertyKind.OnPointer]. */ + val code: CodePointerTarget? = null, ) : ModifierNodeElement() { override fun create(): HostPointerNode = HostPointerNode(node, router, dispatcher).also(::configure) @@ -193,6 +251,7 @@ private data class HostPointerElement( node.slop = slop node.controlClickIsMenu = controlClickIsMenu node.wheelMode = wheelMode + node.code = code } } @@ -213,6 +272,9 @@ internal class HostPointerNode( var controlClickIsMenu = false var wheelMode = WheelDeltaMode.Line + /** The code editor this node is the view of, which makes its records `CodePointer` ones. */ + var code: CodePointerTarget? = null + /** The event being dispatched, as this node sees it: its positions are this node's own. */ var current: PointerEvent? = null @@ -281,6 +343,20 @@ internal class HostPointerNode( } override fun onPointerEvent(pointerEvent: PointerEvent, pass: PointerEventPass, bounds: IntSize) { + if (code != null) { + // Routed on the way down, before the editor's text sees the event: the nodes of + // the chain further out are already on the stack, and the editor is the + // innermost subscriber there is. + if (pass != PointerEventPass.Initial) return + current = pointerEvent + router.begin(this) + if (pointerEvent.type == PointerEventType.Scroll && wheelTaken && wants(PointerKind.Wheel)) { + val changes = pointerEvent.changes + for (index in changes.indices) changes[index].consume() + } + router.finish(this, pointerEvent) + return + } when (pass) { // On the way down every subscriber in the path says it is there. The deepest // one is the first to see the main pass, and by then the whole path is known. @@ -351,6 +427,8 @@ internal class HostPointerNode( deltaY: Float = 0f, deltaMode: WheelDeltaMode = WheelDeltaMode.Pixel, ): Boolean { + val editor = code + if (editor != null) return sendCode(editor, kind, button, clickCount, deltaX, deltaY, deltaMode) val handler = host.handler(PropertyKind.OnPointer) ?: return false if (!router.alive(host.id)) return false return dispatcher.dispatch( @@ -374,6 +452,42 @@ internal class HostPointerNode( ) } + /** [send] for a code editor's view: the same record, and the character under the pointer. */ + private fun sendCode( + editor: CodePointerTarget, + kind: PointerKind, + button: Int, + clickCount: Int, + deltaX: Float, + deltaY: Float, + deltaMode: WheelDeltaMode, + ): Boolean { + val handler = host.handler(PropertyKind.OnCodePointer) ?: return false + if (!router.alive(host.id)) return false + val position = editor.positionAt(lastX, lastY) + return dispatcher.dispatch( + HostEvent.CodePointer( + nodeId = host.id, + handlerId = handler, + kind = kind, + pointerId = lastPointerId, + pointerType = lastPointerType, + x = lastX / pxPerUnit, + y = lastY / pxPerUnit, + buttons = lastButtons, + button = button, + modifiers = lastModifiers, + clickCount = clickCount, + deltaX = deltaX, + deltaY = deltaY, + deltaMode = deltaMode, + timestampNanos = lastUptimeMillis * 1_000_000L, + line = position?.line ?: -1, + column = position?.column ?: -1, + ), + ) + } + fun armLongPress() { cancelLongPress() if (!isAttached) return diff --git a/compose-rust/android-kotlin/shared/Protocol.gen.kt b/compose-rust/android-kotlin/shared/Protocol.gen.kt index b8e2a8a2c..abd9815ef 100644 --- a/compose-rust/android-kotlin/shared/Protocol.gen.kt +++ b/compose-rust/android-kotlin/shared/Protocol.gen.kt @@ -8,7 +8,7 @@ import java.nio.charset.StandardCharsets enum class WidgetKind { Column, Row, Box, Text, TextField, Button, Spacer, LazyColumn, ScrollColumn, Image, Icon, Checkbox, RadioButton, Switch, Slider, ProgressIndicator, Divider, Card, Surface, Dialog, Menu, Tabs, TopAppBar, LazyRow, Tooltip, Canvas, DatePicker, TimePicker, Dropdown, Navigation, NavigationItem, Sheet, Scaffold, ScaffoldSlot, LazyGrid, FileDropTarget, ScrollRow, Chip, FloatingAction, Badge, SelectionContainer, SplitPane, CodeEditor, AbsoluteBox, Window, FlowRow, Popover, LinearProgressIndicator } -enum class PropertyKind { Text, Placeholder, Enabled, Multiline, OnClick, OnValueChange, OnSubmit, OnFocusLost, OnKeyDown, ItemCount, ItemKey, OnRangeRequested, TypeRole, FontSize, FontWeight, LineHeight, LetterSpacing, Color, TextAlign, MaxLines, Overflow, Arrangement, Spacing, SpaceRole, Alignment, Variant, Asset, Checked, Steps, Determinate, Circular, Vertical, Open, OnDismiss, SelectedIndex, Commands, Value, Min, Max, Icon, Slot, Columns, MinColumnWidth, Spans, OnFilesEntered, OnFilesDropped, Section, Count, Collapsible, ButtonKind, Decorations, SyntaxSpans, TabWidth, OnEditRejected, OnHover, OnSave, OnDecorationClick, Folds, GutterDecorations, OnSelectionChange, Font, WordBreak, OverflowWrap, TabSize, AbsoluteSize, SoftWrap, SpanFonts, OnVisibleRangeChange, OnEditorFocusChange, OnFoldChange, OnCompositionChange, OnPointer, PointerKinds, Cursor, UserSelect, IslandZoom, WindowTitle, WindowSize, WindowMinSize, WindowResizable, WindowChrome, WindowTitleBar, WindowIcon, WindowPosition, WindowRestoreKey, WindowZoomLevel, DragFromPointer, OnWindowCloseRequested, OnWindowFocusChanged, OnWindowMoved, OnWindowDrag, OnWindowUnavailable, OnWindowClosed, OnWindowDragOver, TearOffKey, OnFocusGained, OnKeyUp, AccessibleName, TrackColor, ThumbColor, ActiveTrackColor, ContainerColor, CheckColor, ControlSize, ReportSize, Scrim, Bare, HorizontalSpacing, VerticalSpacing, HorizontalAlignment, VerticalAlignment, MaxItemsInEachRow, Placement, Align, OffsetDp, LineNumbers, GutterMinWidthDp, GutterPaddingDp, TextInsetDp, CodeEditorColors, OnCodeMetrics, OnCodeScrolled, CompactNavigation, OnScrollChanged, Snap, MaxHeightFraction, OnCaretRect, OnKeyPreview, Progress } +enum class PropertyKind { Text, Placeholder, Enabled, Multiline, OnClick, OnValueChange, OnSubmit, OnFocusLost, OnKeyDown, ItemCount, ItemKey, OnRangeRequested, TypeRole, FontSize, FontWeight, LineHeight, LetterSpacing, Color, TextAlign, MaxLines, Overflow, Arrangement, Spacing, SpaceRole, Alignment, Variant, Asset, Checked, Steps, Determinate, Circular, Vertical, Open, OnDismiss, SelectedIndex, Commands, Value, Min, Max, Icon, Slot, Columns, MinColumnWidth, Spans, OnFilesEntered, OnFilesDropped, Section, Count, Collapsible, ButtonKind, Decorations, SyntaxSpans, TabWidth, OnEditRejected, OnHover, OnSave, OnDecorationClick, Folds, GutterDecorations, OnSelectionChange, Font, WordBreak, OverflowWrap, TabSize, AbsoluteSize, SoftWrap, SpanFonts, OnVisibleRangeChange, OnEditorFocusChange, OnFoldChange, OnCompositionChange, OnPointer, PointerKinds, Cursor, UserSelect, IslandZoom, WindowTitle, WindowSize, WindowMinSize, WindowResizable, WindowChrome, WindowTitleBar, WindowIcon, WindowPosition, WindowRestoreKey, WindowZoomLevel, DragFromPointer, OnWindowCloseRequested, OnWindowFocusChanged, OnWindowMoved, OnWindowDrag, OnWindowUnavailable, OnWindowClosed, OnWindowDragOver, TearOffKey, OnFocusGained, OnKeyUp, AccessibleName, TrackColor, ThumbColor, ActiveTrackColor, ContainerColor, CheckColor, ControlSize, ReportSize, Scrim, Bare, HorizontalSpacing, VerticalSpacing, HorizontalAlignment, VerticalAlignment, MaxItemsInEachRow, Placement, Align, OffsetDp, LineNumbers, GutterMinWidthDp, GutterPaddingDp, TextInsetDp, CodeEditorColors, OnCodeMetrics, OnCodeScrolled, CompactNavigation, OnScrollChanged, Snap, MaxHeightFraction, OnCaretRect, OnKeyPreview, OnCodePointer, Progress } enum class Key { Enter, Other, Escape, Tab, Backspace, Delete, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Home, End, PageUp, PageDown } @@ -1600,13 +1600,14 @@ sealed interface HostEvent { data class CodeScrolled(override val nodeId: Int, override val handlerId: Long, val value: Double) : HostEvent data class CaretRect(override val nodeId: Int, override val handlerId: Long, val line: Int, val column: Int, val x: kotlin.Float, val y: kotlin.Float, val width: kotlin.Float, val height: kotlin.Float) : HostEvent data class PositionRect(override val nodeId: Int, override val handlerId: Long, val request: Int, val found: Boolean, val x: kotlin.Float, val y: kotlin.Float, val width: kotlin.Float, val height: kotlin.Float) : HostEvent + data class CodePointer(override val nodeId: Int, override val handlerId: Long, val kind: PointerKind, val pointerId: Int, val pointerType: PointerType, val x: kotlin.Float, val y: kotlin.Float, val buttons: Int, val button: Int, val modifiers: Int, val clickCount: Int, val deltaX: kotlin.Float, val deltaY: kotlin.Float, val deltaMode: WheelDeltaMode, val timestampNanos: Long, val line: Int, val column: Int) : HostEvent } class ProtocolException(message: String, val offset: Int) : IllegalArgumentException("$message at byte offset $offset") object Protocol { - const val SCHEMA_HASH: Long = -487432507980895884L + const val SCHEMA_HASH: Long = -8415703039461350493L const val PROTOCOL_VERSION: Int = 1 private const val TAG_ENVELOPE = 0 @@ -2196,6 +2197,7 @@ object Protocol { is HostEvent.CodeScrolled -> null is HostEvent.CaretRect -> null is HostEvent.PositionRect -> null + is HostEvent.CodePointer -> null } val recordLength = when (event) { is HostEvent.Clicked -> 16 @@ -2250,6 +2252,7 @@ object Protocol { is HostEvent.CodeScrolled -> 24 is HostEvent.CaretRect -> 40 is HostEvent.PositionRect -> 40 + is HostEvent.CodePointer -> 80 } val totalLength = recordLength.toLong() + (text?.size ?: 0) if (totalLength > Int.MAX_VALUE || totalLength > out.remaining().toLong()) { @@ -2308,6 +2311,7 @@ object Protocol { is HostEvent.CodeScrolled -> 55 is HostEvent.CaretRect -> 64 is HostEvent.PositionRect -> 65 + is HostEvent.CodePointer -> 66 } out.putShort(tag.toShort()) out.putShort(recordLength.toShort()) @@ -2548,6 +2552,23 @@ object Protocol { out.putFloat(if (event.found) event.width else 0f) out.putFloat(if (event.found) event.height else 0f) } + is HostEvent.CodePointer -> { + out.putInt(pointerKindTag(event.kind)) + out.putInt(event.pointerId) + out.putInt(pointerTypeTag(event.pointerType)) + out.putFloat(event.x) + out.putFloat(event.y) + out.putInt(event.buttons) + out.putInt(event.button) + out.putInt(event.modifiers) + out.putInt(event.clickCount) + out.putFloat(event.deltaX) + out.putFloat(event.deltaY) + out.putInt(wheelDeltaModeTag(event.deltaMode)) + out.putLong(event.timestampNanos) + out.putInt(event.line) + out.putInt(event.column) + } } if (text != null) out.put(text) return out.position() - start @@ -2766,6 +2787,7 @@ object Protocol { 189 -> PropertyKind.MaxHeightFraction 195 -> PropertyKind.OnCaretRect 196 -> PropertyKind.OnKeyPreview + 197 -> PropertyKind.OnCodePointer 27 -> PropertyKind.Progress else -> throw ProtocolException("unknown property tag $tag", offset) } diff --git a/compose-rust/schema-hash.txt b/compose-rust/schema-hash.txt index 0a3d57532..140590c02 100644 --- a/compose-rust/schema-hash.txt +++ b/compose-rust/schema-hash.txt @@ -1 +1 @@ -0xf93c4ab76dd22974 +0x8b356aac85bb23a3 diff --git a/compose-rust/src/code.rs b/compose-rust/src/code.rs index d11ae8f3f..1b33b050d 100644 --- a/compose-rust/src/code.rs +++ b/compose-rust/src/code.rs @@ -1247,3 +1247,60 @@ pub(crate) fn deliver_position_rect(request: u32, answer: PositionAnswer) -> boo pub fn reset_position_queries() { POSITION_QUERIES.with_borrow_mut(Vec::clear); } + +/// A pointer event over a code editor, with the place in the text under the pointer. +/// +/// Everything a node's pointer event says, under the same rules: the kinds the editor +/// subscribes to with `PointerKinds`, the buttons, the modifiers, the click count, a `Move` +/// at most once a frame, and a press held by the editor until it is released. Consuming a +/// `Down` keeps the caret where it was, which is what Cmd or Ctrl and a click needs to go to +/// a definition without moving the reader's caret. +#[derive(Clone, Debug)] +pub struct CodePointer { + pub event: crate::PointerEvent, + /// The character under the pointer, or None where it is over none: the gutter, past the + /// end of a line, or below the last one. + pub position: Option, +} + +impl CodePointer { + /// The event out of a `CodePointer` payload, or None for any other. + pub fn from_payload(payload: &crate::schema::EventPayload<'_>) -> Option { + match *payload { + crate::schema::EventPayload::CodePointer { + kind, + pointer_id, + pointer_type, + x, + y, + buttons, + button, + modifiers, + click_count, + delta_x, + delta_y, + delta_mode, + timestamp_nanos, + position, + } => Some(Self { + event: crate::PointerEvent::new( + kind, + pointer_id, + pointer_type, + x, + y, + buttons, + button, + modifiers, + click_count, + delta_x, + delta_y, + delta_mode, + timestamp_nanos, + ), + position, + }), + _ => None, + } + } +} diff --git a/compose-rust/src/codegen.rs b/compose-rust/src/codegen.rs index c02af44b4..f3f6cf553 100644 --- a/compose-rust/src/codegen.rs +++ b/compose-rust/src/codegen.rs @@ -789,6 +789,11 @@ object ScrollWire { EventPayloadType::CodePositionRect => output.push_str( ", val request: Int, val found: Boolean, val x: kotlin.Float, val y: kotlin.Float, val width: kotlin.Float, val height: kotlin.Float", ), + // The pointer's fields, then the character under it: -1 and -1 where it is over + // none. + EventPayloadType::CodePointer => output.push_str( + ", val kind: PointerKind, val pointerId: Int, val pointerType: PointerType, val x: kotlin.Float, val y: kotlin.Float, val buttons: Int, val button: Int, val modifiers: Int, val clickCount: Int, val deltaX: kotlin.Float, val deltaY: kotlin.Float, val deltaMode: WheelDeltaMode, val timestampNanos: Long, val line: Int, val column: Int", + ), } if event.payload == EventPayloadType::IoAnswer { writeln!( @@ -1428,7 +1433,8 @@ object Protocol { EventPayloadType::None | EventPayloadType::ScrollChanged | EventPayloadType::CodeCaretRect - | EventPayloadType::CodePositionRect => { + | EventPayloadType::CodePositionRect + | EventPayloadType::CodePointer => { writeln!( output, " is HostEvent.{} -> null", @@ -1530,6 +1536,8 @@ object Protocol { EventPayloadType::ScrollChanged => 72, // Two words and four floats. EventPayloadType::CodeCaretRect | EventPayloadType::CodePositionRect => 40, + // The pointer record and two words. + EventPayloadType::CodePointer => 80, }; writeln!( output, @@ -1716,7 +1724,7 @@ object Protocol { output.push_str(" out.putInt(reducedMotionTag(event.state))\n"); output.push_str(" }\n"); } - EventPayloadType::Pointer => { + EventPayloadType::Pointer | EventPayloadType::CodePointer => { writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap(); output.push_str(" out.putInt(pointerKindTag(event.kind))\n"); output.push_str(" out.putInt(event.pointerId)\n"); @@ -1735,6 +1743,10 @@ object Protocol { " out.putInt(wheelDeltaModeTag(event.deltaMode))\n", ); output.push_str(" out.putLong(event.timestampNanos)\n"); + if event.payload == EventPayloadType::CodePointer { + output.push_str(" out.putInt(event.line)\n"); + output.push_str(" out.putInt(event.column)\n"); + } output.push_str(" }\n"); } EventPayloadType::CodeSelection => { @@ -4120,6 +4132,27 @@ pub fn generate_event_vector() -> Result, ProtocolError> { rect: Some(crate::code::CodeRect::new(88.75, 64.25, 2.0, 20.0)), }, }, + // A Cmd-click over the emoji's column on the editor's second line. + HostEvent { + node_id: 12, + handler_id: 31, + payload: EventPayload::CodePointer { + kind: crate::schema::PointerKind::Down, + pointer_id: 1, + pointer_type: crate::schema::PointerType::Mouse, + x: 96.5, + y: 30.25, + buttons: 1, + button: 1, + modifiers: 8, + click_count: 1, + delta_x: 0.0, + delta_y: 0.0, + delta_mode: crate::schema::WheelDeltaMode::Pixel, + timestamp_nanos: 123_456_789_000, + position: Some(crate::code::Position::new(1, 13)), + }, + }, ]; let mut output = Vec::new(); let mut encoded = Vec::new(); @@ -4161,7 +4194,7 @@ pub fn generate_vector_description() -> String { }}, "events": {{ "file": "events.bin", - "description": "Forty-four independently decodable event records concatenated in schema order", + "description": "Forty-five independently decodable event records concatenated in schema order", "records": [ {{ "type": "Clicked", "offset": 0, "length": 16, "nodeId": 7, "handlerId": 11 }}, {{ "type": "TextChanged", "offset": 16, "length": 30, "nodeId": 8, "handlerId": 12, "text": "한글" }}, @@ -4206,7 +4239,8 @@ pub fn generate_vector_description() -> String { {{ "type": "CodeMetrics", "offset": 1391, "length": 24, "nodeId": 12, "handlerId": 28, "value": 40.0 }}, {{ "type": "CodeScrolled", "offset": 1415, "length": 24, "nodeId": 12, "handlerId": 29, "value": 1234.5 }}, {{ "type": "CaretRect", "offset": 1439, "length": 40, "nodeId": 12, "handlerId": 30, "line": 1, "column": 8, "x": 120.5, "y": 64.25, "width": 2.0, "height": 20.0 }}, - {{ "type": "PositionRect", "offset": 1479, "length": 40, "nodeId": 12, "handlerId": 0, "request": 17, "found": true, "x": 88.75, "y": 64.25, "width": 2.0, "height": 20.0 }} + {{ "type": "PositionRect", "offset": 1479, "length": 40, "nodeId": 12, "handlerId": 0, "request": 17, "found": true, "x": 88.75, "y": 64.25, "width": 2.0, "height": 20.0 }}, + {{ "type": "CodePointer", "offset": 1519, "length": 80, "nodeId": 12, "handlerId": 31, "kind": "Down", "pointerId": 1, "pointerType": "Mouse", "x": 96.5, "y": 30.25, "buttons": 1, "button": 1, "modifiers": 8, "clickCount": 1, "deltaX": 0.0, "deltaY": 0.0, "deltaMode": "Pixel", "timestampNanos": 123456789000, "line": 1, "column": 13 }} ] }} }} diff --git a/compose-rust/src/lib.rs b/compose-rust/src/lib.rs index 3a057f567..a4688b173 100644 --- a/compose-rust/src/lib.rs +++ b/compose-rust/src/lib.rs @@ -70,10 +70,10 @@ pub use boundary::{ }; pub use brush::{Brush, Stop, brush, release_brush}; pub use code::{ - CaretRect, CodeChange, CodeEditorColors, CodeHover, CodeMetrics, CodeRange, CodeRect, - CodeScroll, Decoration, Decorations, EditRejected, Fold, FoldChange, Folds, GutterDecoration, - GutterDecorations, Position, SaveRequest, SelectionChange, SyntaxSpan, SyntaxSpans, - VisibleRange, + CaretRect, CodeChange, CodeEditorColors, CodeHover, CodeMetrics, CodePointer, CodeRange, + CodeRect, CodeScroll, Decoration, Decorations, EditRejected, Fold, FoldChange, Folds, + GutterDecoration, GutterDecorations, Position, SaveRequest, SelectionChange, SyntaxSpan, + SyntaxSpans, VisibleRange, }; #[doc(hidden)] pub use compose_rust_macros::__compose_call_check; diff --git a/compose-rust/src/protocol.rs b/compose-rust/src/protocol.rs index 0fa6f5b90..7a72caa10 100644 --- a/compose-rust/src/protocol.rs +++ b/compose-rust/src/protocol.rs @@ -509,6 +509,11 @@ const EVENT_CARET_RECT: u16 = 64; const EVENT_POSITION_RECT: u16 = 65; /// `CaretRect` and `PositionRect` in full: the 16 byte header, two words and four `f32`. const CODE_RECT_EVENT_LEN: usize = 40; +// 66 is a pointer over a code editor: the pointer record and the place in the text under it. +const EVENT_CODE_POINTER: u16 = 66; +const CODE_POINTER_LEN: usize = POINTER_RECORD_LEN + 8; +/// The line and the column of a pointer that is over no character. +const NO_CODE_POSITION: u32 = u32::MAX; /// Where `SetWindow` keeps the mode and the last window policy: in the bits of the /// `resizable` word above the flag. @@ -990,6 +995,53 @@ pub fn decode_event(bytes: &[u8]) -> Result, ProtocolError> { EVENT_CARET_RECT | EVENT_POSITION_RECT => { return Err(ProtocolError::InvalidRecordLength); } + EVENT_CODE_POINTER if record_len == CODE_POINTER_LEN => { + let crate::schema::EventPayload::Pointer { + kind, + pointer_id, + pointer_type, + x, + y, + buttons, + button, + modifiers, + click_count, + delta_x, + delta_y, + delta_mode, + timestamp_nanos, + } = decode_pointer(bytes)? + else { + unreachable!("decode_pointer reads a pointer record"); + }; + let line = read_u32(bytes, POINTER_RECORD_LEN)?; + let column = read_u32(bytes, POINTER_RECORD_LEN + 4)?; + let position = match (line, column) { + (NO_CODE_POSITION, NO_CODE_POSITION) => None, + // One half of "nowhere" is a record the two sides disagree on. + (NO_CODE_POSITION, _) | (_, NO_CODE_POSITION) => { + return Err(ProtocolError::InvalidValueKind(u16::MAX)); + } + (line, column) => Some(crate::code::Position::new(line, column)), + }; + crate::schema::EventPayload::CodePointer { + kind, + pointer_id, + pointer_type, + x, + y, + buttons, + button, + modifiers, + click_count, + delta_x, + delta_y, + delta_mode, + timestamp_nanos, + position, + } + } + EVENT_CODE_POINTER => return Err(ProtocolError::InvalidRecordLength), EVENT_WINDOW_CLOSE_REQUESTED..=EVENT_APPLICATION_REOPEN => { return Err(ProtocolError::InvalidRecordLength); } @@ -1213,6 +1265,55 @@ pub fn encode_event(event: &HostEvent<'_>, output: &mut Vec) -> Result<(), P output.extend_from_slice(×tamp_nanos.to_le_bytes()); return Ok(()); } + if let crate::schema::EventPayload::CodePointer { + kind, + pointer_id, + pointer_type, + x, + y, + buttons, + button, + modifiers, + click_count, + delta_x, + delta_y, + delta_mode, + timestamp_nanos, + position, + } = event.payload + { + // The pointer record as a `Pointer` event writes it, under this tag and length. + encode_event( + &HostEvent { + node_id: event.node_id, + handler_id: event.handler_id, + payload: crate::schema::EventPayload::Pointer { + kind, + pointer_id, + pointer_type, + x, + y, + buttons, + button, + modifiers, + click_count, + delta_x, + delta_y, + delta_mode, + timestamp_nanos, + }, + }, + output, + )?; + output[0..2].copy_from_slice(&EVENT_CODE_POINTER.to_le_bytes()); + output[2..4].copy_from_slice(&(CODE_POINTER_LEN as u16).to_le_bytes()); + let (line, column) = position.map_or((NO_CODE_POSITION, NO_CODE_POSITION), |at| { + (at.line, at.column) + }); + output.extend_from_slice(&line.to_le_bytes()); + output.extend_from_slice(&column.to_le_bytes()); + return Ok(()); + } if let crate::schema::EventPayload::ReducedMotionChanged(state) = event.payload { output.extend_from_slice(&EVENT_REDUCED_MOTION_CHANGED.to_le_bytes()); output.extend_from_slice(&20_u16.to_le_bytes()); @@ -1635,7 +1736,8 @@ pub fn encode_event(event: &HostEvent<'_>, output: &mut Vec) -> Result<(), P | crate::schema::EventPayload::FileHandles { .. } | crate::schema::EventPayload::ScrollChanged { .. } | crate::schema::EventPayload::CaretRect { .. } - | crate::schema::EventPayload::PositionRect { .. } => unreachable!(), + | crate::schema::EventPayload::PositionRect { .. } + | crate::schema::EventPayload::CodePointer { .. } => unreachable!(), crate::schema::EventPayload::AnimationEvent { .. } | crate::schema::EventPayload::Pointer { .. } | crate::schema::EventPayload::ReducedMotionChanged(_) diff --git a/compose-rust/src/schema.rs b/compose-rust/src/schema.rs index 102c25d22..a8ef5e5fc 100644 --- a/compose-rust/src/schema.rs +++ b/compose-rust/src/schema.rs @@ -214,6 +214,10 @@ pub enum EventPayloadType { /// position is on screen and 0 when it is not, then the rectangle as in /// `CodeCaretRect`, all zero when there is none. A fixed 40-byte record. CodePositionRect, + /// A pointer event over a code editor: the 72-byte `Pointer` record, then the line and + /// the column of the text under the pointer, both `u32::MAX` where it is over none. A + /// fixed 80-byte record. + CodePointer, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -227,10 +231,10 @@ pub struct EventSchema { pub const SCHEMA_DESCRIPTOR: &str = concat!( "compose-rust/v1;", "widgets=Column,Row,Box,Text,TextField,Button,Spacer,LazyColumn,ScrollColumn,Image,Icon,Checkbox,RadioButton,Switch,Slider,ProgressIndicator,Divider,Card,Surface,Dialog,Menu,Tabs,TopAppBar,LazyRow,Tooltip,Canvas,DatePicker,TimePicker,Dropdown,Navigation,NavigationItem,Sheet,Scaffold,ScaffoldSlot,LazyGrid,FileDropTarget,ScrollRow,Chip,FloatingAction,Badge,SelectionContainer,SplitPane,CodeEditor,AbsoluteBox,Window,FlowRow,Popover;", - "properties=text,placeholder,enabled,multiline,on_click,on_value_change,on_submit,on_focus_lost,on_key_down,item_count,item_key,on_range_requested,type_role,font_size,font_weight,line_height,letter_spacing,color,text_align,max_lines,overflow,arrangement,spacing,space_role,alignment,variant,asset,checked,steps,determinate,circular,vertical,open,on_dismiss,selected_index,commands,value,min,max,icon,slot,columns,min_column_width,spans,on_files_entered,on_files_dropped,section,count,collapsible,button_kind,decorations,syntax_spans,tab_width,on_edit_rejected,on_hover,on_save,on_decoration_click,folds,gutter_decorations,on_selection_change,font,word_break,overflow_wrap,tab_size,absolute_size,soft_wrap,span_fonts,on_visible_range_change,on_editor_focus_change,on_fold_change,on_composition_change,on_pointer,pointer_kinds,cursor,user_select,island_zoom,window_title,window_size,window_min_size,window_resizable,window_chrome,window_title_bar,window_icon,window_position,window_restore_key,window_zoom_level,drag_from_pointer,on_window_close_requested,on_window_focus_changed,on_window_moved,on_window_drag,on_window_unavailable,on_window_closed,on_window_drag_over,tear_off_key,on_focus_gained,on_key_up,accessible_name,track_color,thumb_color,active_track_color,container_color,check_color,control_size,report_size,scrim,bare,horizontal_spacing,vertical_spacing,horizontal_alignment,vertical_alignment,max_items_in_each_row,placement,align,offset_dp,line_numbers,gutter_min_width_dp,gutter_padding_dp,text_inset_dp,code_editor_colors,on_code_metrics,on_code_scrolled,compact_navigation,on_scroll_changed,snap,max_height_fraction,on_caret_rect,on_key_preview;", + "properties=text,placeholder,enabled,multiline,on_click,on_value_change,on_submit,on_focus_lost,on_key_down,item_count,item_key,on_range_requested,type_role,font_size,font_weight,line_height,letter_spacing,color,text_align,max_lines,overflow,arrangement,spacing,space_role,alignment,variant,asset,checked,steps,determinate,circular,vertical,open,on_dismiss,selected_index,commands,value,min,max,icon,slot,columns,min_column_width,spans,on_files_entered,on_files_dropped,section,count,collapsible,button_kind,decorations,syntax_spans,tab_width,on_edit_rejected,on_hover,on_save,on_decoration_click,folds,gutter_decorations,on_selection_change,font,word_break,overflow_wrap,tab_size,absolute_size,soft_wrap,span_fonts,on_visible_range_change,on_editor_focus_change,on_fold_change,on_composition_change,on_pointer,pointer_kinds,cursor,user_select,island_zoom,window_title,window_size,window_min_size,window_resizable,window_chrome,window_title_bar,window_icon,window_position,window_restore_key,window_zoom_level,drag_from_pointer,on_window_close_requested,on_window_focus_changed,on_window_moved,on_window_drag,on_window_unavailable,on_window_closed,on_window_drag_over,tear_off_key,on_focus_gained,on_key_up,accessible_name,track_color,thumb_color,active_track_color,container_color,check_color,control_size,report_size,scrim,bare,horizontal_spacing,vertical_spacing,horizontal_alignment,vertical_alignment,max_items_in_each_row,placement,align,offset_dp,line_numbers,gutter_min_width_dp,gutter_padding_dp,text_inset_dp,code_editor_colors,on_code_metrics,on_code_scrolled,compact_navigation,on_scroll_changed,snap,max_height_fraction,on_caret_rect,on_key_preview,on_code_pointer;", "modifiers=Empty,Padding,FillMaxWidth,FillMaxHeight,Width,Height,Size,Background,Clickable,PaddingRole,PaddingEach,Weight,Shape,ShapeRole,Border,Elevation,ObserveSize,Motion,Material,Offset,RequiredSize,BorderEach,CornerEach,Shadow,Clip,Alpha,Transform,Transform3D,MatchParentSize,WindowDrag,PressFeedback,Semantics,CornerCurve;", "keys=Enter,Other;", - "events=Clicked,TextChanged,TextSubmitted,FocusLost,ProtocolError,KeyDown,RangeRequested,ValueChanged,WindowSizeChanged,DesignSystemResolved,FilesEntered,FilesDropped,NotificationActivated,NotificationPermissionChanged,CodeChanged,CodeEditRejected,CodeHovered,CodeSaveRequested,DecorationActivated,AnimationEvent,ReducedMotionChanged,Pointer,ZoomChanged,SelectionChanged,VisibleRangeChanged,EditorFocusChanged,FoldChanged,CompositionChanged,WindowCloseRequested,WindowFocusChanged,WindowMoved,WindowDrag,WindowDragOver,WindowUnavailable,WindowClosed,WindowRequested,ApplicationReopen,FocusGained,KeyUp,FileDialogResult,ClipboardText,CodeMetrics,CodeScrolled,IoAnswer,FileHandles,StorageLocation,ScrollChanged,CaretRect,PositionRect;", + "events=Clicked,TextChanged,TextSubmitted,FocusLost,ProtocolError,KeyDown,RangeRequested,ValueChanged,WindowSizeChanged,DesignSystemResolved,FilesEntered,FilesDropped,NotificationActivated,NotificationPermissionChanged,CodeChanged,CodeEditRejected,CodeHovered,CodeSaveRequested,DecorationActivated,AnimationEvent,ReducedMotionChanged,Pointer,ZoomChanged,SelectionChanged,VisibleRangeChanged,EditorFocusChanged,FoldChanged,CompositionChanged,WindowCloseRequested,WindowFocusChanged,WindowMoved,WindowDrag,WindowDragOver,WindowUnavailable,WindowClosed,WindowRequested,ApplicationReopen,FocusGained,KeyUp,FileDialogResult,ClipboardText,CodeMetrics,CodeScrolled,IoAnswer,FileHandles,StorageLocation,ScrollChanged,CaretRect,PositionRect,CodePointer;", "windowsizeclasses=Compact,Medium,Expanded;", "windowheightclasses=Compact,Medium,Expanded;", "commands=Create,SetProp,SetModifier,Insert,Move,Remove,SetText,AppendText,SetTheme,SetWindow,RegisterAsset,ReleaseAsset,ShowMessage,PostNotification,WithdrawNotification,RequestNotificationPermission,EditCode,StartAnimation,ControlAnimation,SetSelection,RevealRange,SetFolded,SetWindowTheme,FocusWindow,RequestFocus,ShowFileDialog,SetOverlayTokens,SetClipboardText,ReadClipboard,SetScrollOffset,StorageCall,FileCall,ReleaseFileHandle,ScrollTo,ScrollIntoView,QueryPositionRect;", @@ -407,6 +411,7 @@ const fn schema_hash() -> u64 { EventPayloadType::ScrollChanged => 33, EventPayloadType::CodeCaretRect => 34, EventPayloadType::CodePositionRect => 35, + EventPayloadType::CodePointer => 36, }], ); index += 1; @@ -3599,6 +3604,9 @@ crate::extensions::define_property_schema_with_extensions!(define_wire_enum; PRO // It hears the `KeyDown` record a key handler does, and a press it consumes is not the // editor's. Never while an input method is composing. OnKeyPreview = 196, + // The handler a code editor sends its pointer events to, each with the place in the + // text under the pointer. The kinds it hears are the `PointerKinds` mask's. + OnCodePointer = 197, }); #[derive(Clone, Debug, PartialEq)] @@ -3952,6 +3960,26 @@ pub enum EventPayload<'a> { request: u32, rect: Option, }, + /// A pointer event over a code editor: every field a `Pointer` event has, with the same + /// meaning and the same rules, and the place in the text under the pointer. `position` + /// is `None` where the pointer is not over a character: over the gutter, past the end + /// of a line or below the last one. + CodePointer { + kind: PointerKind, + pointer_id: u32, + pointer_type: PointerType, + x: f32, + y: f32, + buttons: u32, + button: u32, + modifiers: u32, + click_count: u32, + delta_x: f32, + delta_y: f32, + delta_mode: WheelDeltaMode, + timestamp_nanos: u64, + position: Option, + }, } /// A rectangle in physical pixels, for [`ScrollTarget`]. @@ -4343,6 +4371,12 @@ pub const EVENT_SCHEMA: &[EventSchema] = &[ tag: 65, payload: EventPayloadType::CodePositionRect, }, + // A pointer over a code editor, with the place in the text under it. + EventSchema { + name: "CodePointer", + tag: 66, + payload: EventPayloadType::CodePointer, + }, ]; /// One argument of a boundary operation. diff --git a/compose-rust/tests/code_editor.rs b/compose-rust/tests/code_editor.rs index 61f70e1f7..9d8a7aeec 100644 --- a/compose-rust/tests/code_editor.rs +++ b/compose-rust/tests/code_editor.rs @@ -4,10 +4,10 @@ use compose_rust::code::{ CODE_EDITOR_COLORS_LEN, CODE_EDITOR_COLORS_RECORD, CaretRect, CodeChange, CodeEditorColors, - CodeRange, CodeRect, DECORATION_LEN, DECORATION_RECORD, Decoration, Decorations, FOLD_LEN, - FOLD_RECORD, Fold, Folds, GUTTER_DECORATION_LEN, GUTTER_DECORATION_RECORD, GutterDecoration, - GutterDecorations, Position, PositionAnswer, RecordFieldType, SYNTAX_SPAN_LEN, - SYNTAX_SPAN_RECORD, SyntaxSpan, SyntaxSpans, byte_offset, position_query, + CodePointer, CodeRange, CodeRect, DECORATION_LEN, DECORATION_RECORD, Decoration, Decorations, + FOLD_LEN, FOLD_RECORD, Fold, Folds, GUTTER_DECORATION_LEN, GUTTER_DECORATION_RECORD, + GutterDecoration, GutterDecorations, Position, PositionAnswer, RecordFieldType, + SYNTAX_SPAN_LEN, SYNTAX_SPAN_RECORD, SyntaxSpan, SyntaxSpans, byte_offset, position_query, }; use compose_rust::protocol::{ BatchEncoder, HostEvent, Mutation, PropertyValue, ProtocolError, decode_batch, decode_event, @@ -1248,3 +1248,133 @@ fn fr38_editor_key_preview_keeps_its_tag_and_the_key_down_record() { } )); } + +fn code_pointer( + kind: compose_rust::PointerKind, + position: Option, +) -> EventPayload<'static> { + EventPayload::CodePointer { + kind, + pointer_id: 1, + pointer_type: compose_rust::PointerType::Mouse, + x: 96.5, + y: 30.25, + buttons: 1, + button: 1, + modifiers: 8, + click_count: 1, + delta_x: 0.0, + delta_y: 0.0, + delta_mode: compose_rust::WheelDeltaMode::Pixel, + timestamp_nanos: 123_456_789_000, + position, + } +} + +/// A pointer over the editor is the 72 byte pointer record and the line and the column +/// under it, 80 bytes under its own tag, and both halves of the place are `u32::MAX` where +/// it is over no character. Read back, it is a pointer event with the place beside it. +#[test] +fn fr38_editor_pointer_reports_text_position_on_the_wire() { + assert_eq!(PropertyKind::OnCodePointer as u16, 197); + assert_eq!(event_tag("CodePointer"), 66); + assert_eq!( + PropertyKind::from_name("on_code_pointer"), + Ok(PropertyKind::OnCodePointer) + ); + + let over = code_pointer(compose_rust::PointerKind::Down, Some(Position::new(1, 13))); + let (length, decoded) = round_trip(over.clone()); + assert_eq!(length, 80); + let read = CodePointer::from_payload(&decoded.payload).expect("a code pointer"); + assert_eq!(read.position, Some(Position::new(1, 13))); + assert_eq!(read.event.kind(), compose_rust::PointerKind::Down); + assert!(read.event.meta_key()); + assert!(!read.event.ctrl_key()); + assert_eq!(read.event.click_count(), 1); + assert_eq!(read.event.x(), 96.5); + assert!(CodePointer::from_payload(&EventPayload::CodeSaveRequested { version: 0 }).is_none()); + + // The first 72 bytes are what a pointer event of the same fields writes. + let mut wire = Vec::new(); + encode_event( + &HostEvent { + node_id: 3, + handler_id: 9, + payload: over, + }, + &mut wire, + ) + .unwrap(); + let mut pointer = Vec::new(); + encode_event( + &HostEvent { + node_id: 3, + handler_id: 9, + payload: EventPayload::Pointer { + kind: compose_rust::PointerKind::Down, + pointer_id: 1, + pointer_type: compose_rust::PointerType::Mouse, + x: 96.5, + y: 30.25, + buttons: 1, + button: 1, + modifiers: 8, + click_count: 1, + delta_x: 0.0, + delta_y: 0.0, + delta_mode: compose_rust::WheelDeltaMode::Pixel, + timestamp_nanos: 123_456_789_000, + }, + }, + &mut pointer, + ) + .unwrap(); + assert_eq!(&wire[0..4], &[66, 0, 80, 0]); + assert_eq!(&wire[4..72], &pointer[4..72]); + assert_eq!(&wire[72..80], &[1, 0, 0, 0, 13, 0, 0, 0]); + + // Over no character. + let (length, decoded) = round_trip(code_pointer(compose_rust::PointerKind::Move, None)); + assert_eq!(length, 80); + assert_eq!( + CodePointer::from_payload(&decoded.payload) + .unwrap() + .position, + None + ); + let mut nowhere = Vec::new(); + encode_event( + &HostEvent { + node_id: 3, + handler_id: 9, + payload: code_pointer(compose_rust::PointerKind::Move, None), + }, + &mut nowhere, + ) + .unwrap(); + assert_eq!(&nowhere[72..80], &[0xff; 8]); + // Half of nowhere is a record the two sides disagree on, and a short one is refused. + nowhere[72..76].copy_from_slice(&0_u32.to_le_bytes()); + assert!(decode_event(&nowhere).is_err()); + wire[2] = 72; + assert_eq!( + decode_event(&wire[..72]), + Err(ProtocolError::InvalidRecordLength) + ); + + // The vector both sides test against holds it after the position answer. + let vectors = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/vectors"); + let events = std::fs::read(format!("{vectors}/events.bin")).unwrap(); + let mut expected = Vec::new(); + encode_event( + &HostEvent { + node_id: 12, + handler_id: 31, + payload: code_pointer(compose_rust::PointerKind::Down, Some(Position::new(1, 13))), + }, + &mut expected, + ) + .unwrap(); + assert_eq!(&events[1519..1599], expected.as_slice()); +} diff --git a/compose-rust/tests/vectors/events.bin b/compose-rust/tests/vectors/events.bin index b0cd0bfcdf61795a205cb5d71d5f76361eb6d405..df4ccf41eb7de842c89e7f55b71f7d05665d8ca8 100644 GIT binary patch delta 88 zcmaFQy`N{pd)5Fah5!a01_lOsAO-;zAZCPO28M%93=E$fVSEm_IFJDa98xp)$pG0P IHM~F!0QbBIVE_OC delta 7 Ocmdnb^PYRddsYArQUhuL diff --git a/compose-rust/tests/vectors/vectors.json b/compose-rust/tests/vectors/vectors.json index 685b4b74c..66526af3e 100644 --- a/compose-rust/tests/vectors/vectors.json +++ b/compose-rust/tests/vectors/vectors.json @@ -1,6 +1,6 @@ { "format": "compose-rust protocol vectors v1", - "schemaHashUnsigned": "17959311565728655732", + "schemaHashUnsigned": "10031041034248201123", "byteOrder": "little-endian", "mutations": { "file": "mutations.bin", @@ -27,7 +27,7 @@ }, "events": { "file": "events.bin", - "description": "Forty-four independently decodable event records concatenated in schema order", + "description": "Forty-five independently decodable event records concatenated in schema order", "records": [ { "type": "Clicked", "offset": 0, "length": 16, "nodeId": 7, "handlerId": 11 }, { "type": "TextChanged", "offset": 16, "length": 30, "nodeId": 8, "handlerId": 12, "text": "한글" }, @@ -72,7 +72,8 @@ { "type": "CodeMetrics", "offset": 1391, "length": 24, "nodeId": 12, "handlerId": 28, "value": 40.0 }, { "type": "CodeScrolled", "offset": 1415, "length": 24, "nodeId": 12, "handlerId": 29, "value": 1234.5 }, { "type": "CaretRect", "offset": 1439, "length": 40, "nodeId": 12, "handlerId": 30, "line": 1, "column": 8, "x": 120.5, "y": 64.25, "width": 2.0, "height": 20.0 }, - { "type": "PositionRect", "offset": 1479, "length": 40, "nodeId": 12, "handlerId": 0, "request": 17, "found": true, "x": 88.75, "y": 64.25, "width": 2.0, "height": 20.0 } + { "type": "PositionRect", "offset": 1479, "length": 40, "nodeId": 12, "handlerId": 0, "request": 17, "found": true, "x": 88.75, "y": 64.25, "width": 2.0, "height": 20.0 }, + { "type": "CodePointer", "offset": 1519, "length": 80, "nodeId": 12, "handlerId": 31, "kind": "Down", "pointerId": 1, "pointerType": "Mouse", "x": 96.5, "y": 30.25, "buttons": 1, "button": 1, "modifiers": 8, "clickCount": 1, "deltaX": 0.0, "deltaY": 0.0, "deltaMode": "Pixel", "timestampNanos": 123456789000, "line": 1, "column": 13 } ] } } diff --git a/renderer/desktop/src/protocol/Protocol.gen.kt b/renderer/desktop/src/protocol/Protocol.gen.kt index b8e2a8a2c..abd9815ef 100644 --- a/renderer/desktop/src/protocol/Protocol.gen.kt +++ b/renderer/desktop/src/protocol/Protocol.gen.kt @@ -8,7 +8,7 @@ import java.nio.charset.StandardCharsets enum class WidgetKind { Column, Row, Box, Text, TextField, Button, Spacer, LazyColumn, ScrollColumn, Image, Icon, Checkbox, RadioButton, Switch, Slider, ProgressIndicator, Divider, Card, Surface, Dialog, Menu, Tabs, TopAppBar, LazyRow, Tooltip, Canvas, DatePicker, TimePicker, Dropdown, Navigation, NavigationItem, Sheet, Scaffold, ScaffoldSlot, LazyGrid, FileDropTarget, ScrollRow, Chip, FloatingAction, Badge, SelectionContainer, SplitPane, CodeEditor, AbsoluteBox, Window, FlowRow, Popover, LinearProgressIndicator } -enum class PropertyKind { Text, Placeholder, Enabled, Multiline, OnClick, OnValueChange, OnSubmit, OnFocusLost, OnKeyDown, ItemCount, ItemKey, OnRangeRequested, TypeRole, FontSize, FontWeight, LineHeight, LetterSpacing, Color, TextAlign, MaxLines, Overflow, Arrangement, Spacing, SpaceRole, Alignment, Variant, Asset, Checked, Steps, Determinate, Circular, Vertical, Open, OnDismiss, SelectedIndex, Commands, Value, Min, Max, Icon, Slot, Columns, MinColumnWidth, Spans, OnFilesEntered, OnFilesDropped, Section, Count, Collapsible, ButtonKind, Decorations, SyntaxSpans, TabWidth, OnEditRejected, OnHover, OnSave, OnDecorationClick, Folds, GutterDecorations, OnSelectionChange, Font, WordBreak, OverflowWrap, TabSize, AbsoluteSize, SoftWrap, SpanFonts, OnVisibleRangeChange, OnEditorFocusChange, OnFoldChange, OnCompositionChange, OnPointer, PointerKinds, Cursor, UserSelect, IslandZoom, WindowTitle, WindowSize, WindowMinSize, WindowResizable, WindowChrome, WindowTitleBar, WindowIcon, WindowPosition, WindowRestoreKey, WindowZoomLevel, DragFromPointer, OnWindowCloseRequested, OnWindowFocusChanged, OnWindowMoved, OnWindowDrag, OnWindowUnavailable, OnWindowClosed, OnWindowDragOver, TearOffKey, OnFocusGained, OnKeyUp, AccessibleName, TrackColor, ThumbColor, ActiveTrackColor, ContainerColor, CheckColor, ControlSize, ReportSize, Scrim, Bare, HorizontalSpacing, VerticalSpacing, HorizontalAlignment, VerticalAlignment, MaxItemsInEachRow, Placement, Align, OffsetDp, LineNumbers, GutterMinWidthDp, GutterPaddingDp, TextInsetDp, CodeEditorColors, OnCodeMetrics, OnCodeScrolled, CompactNavigation, OnScrollChanged, Snap, MaxHeightFraction, OnCaretRect, OnKeyPreview, Progress } +enum class PropertyKind { Text, Placeholder, Enabled, Multiline, OnClick, OnValueChange, OnSubmit, OnFocusLost, OnKeyDown, ItemCount, ItemKey, OnRangeRequested, TypeRole, FontSize, FontWeight, LineHeight, LetterSpacing, Color, TextAlign, MaxLines, Overflow, Arrangement, Spacing, SpaceRole, Alignment, Variant, Asset, Checked, Steps, Determinate, Circular, Vertical, Open, OnDismiss, SelectedIndex, Commands, Value, Min, Max, Icon, Slot, Columns, MinColumnWidth, Spans, OnFilesEntered, OnFilesDropped, Section, Count, Collapsible, ButtonKind, Decorations, SyntaxSpans, TabWidth, OnEditRejected, OnHover, OnSave, OnDecorationClick, Folds, GutterDecorations, OnSelectionChange, Font, WordBreak, OverflowWrap, TabSize, AbsoluteSize, SoftWrap, SpanFonts, OnVisibleRangeChange, OnEditorFocusChange, OnFoldChange, OnCompositionChange, OnPointer, PointerKinds, Cursor, UserSelect, IslandZoom, WindowTitle, WindowSize, WindowMinSize, WindowResizable, WindowChrome, WindowTitleBar, WindowIcon, WindowPosition, WindowRestoreKey, WindowZoomLevel, DragFromPointer, OnWindowCloseRequested, OnWindowFocusChanged, OnWindowMoved, OnWindowDrag, OnWindowUnavailable, OnWindowClosed, OnWindowDragOver, TearOffKey, OnFocusGained, OnKeyUp, AccessibleName, TrackColor, ThumbColor, ActiveTrackColor, ContainerColor, CheckColor, ControlSize, ReportSize, Scrim, Bare, HorizontalSpacing, VerticalSpacing, HorizontalAlignment, VerticalAlignment, MaxItemsInEachRow, Placement, Align, OffsetDp, LineNumbers, GutterMinWidthDp, GutterPaddingDp, TextInsetDp, CodeEditorColors, OnCodeMetrics, OnCodeScrolled, CompactNavigation, OnScrollChanged, Snap, MaxHeightFraction, OnCaretRect, OnKeyPreview, OnCodePointer, Progress } enum class Key { Enter, Other, Escape, Tab, Backspace, Delete, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Home, End, PageUp, PageDown } @@ -1600,13 +1600,14 @@ sealed interface HostEvent { data class CodeScrolled(override val nodeId: Int, override val handlerId: Long, val value: Double) : HostEvent data class CaretRect(override val nodeId: Int, override val handlerId: Long, val line: Int, val column: Int, val x: kotlin.Float, val y: kotlin.Float, val width: kotlin.Float, val height: kotlin.Float) : HostEvent data class PositionRect(override val nodeId: Int, override val handlerId: Long, val request: Int, val found: Boolean, val x: kotlin.Float, val y: kotlin.Float, val width: kotlin.Float, val height: kotlin.Float) : HostEvent + data class CodePointer(override val nodeId: Int, override val handlerId: Long, val kind: PointerKind, val pointerId: Int, val pointerType: PointerType, val x: kotlin.Float, val y: kotlin.Float, val buttons: Int, val button: Int, val modifiers: Int, val clickCount: Int, val deltaX: kotlin.Float, val deltaY: kotlin.Float, val deltaMode: WheelDeltaMode, val timestampNanos: Long, val line: Int, val column: Int) : HostEvent } class ProtocolException(message: String, val offset: Int) : IllegalArgumentException("$message at byte offset $offset") object Protocol { - const val SCHEMA_HASH: Long = -487432507980895884L + const val SCHEMA_HASH: Long = -8415703039461350493L const val PROTOCOL_VERSION: Int = 1 private const val TAG_ENVELOPE = 0 @@ -2196,6 +2197,7 @@ object Protocol { is HostEvent.CodeScrolled -> null is HostEvent.CaretRect -> null is HostEvent.PositionRect -> null + is HostEvent.CodePointer -> null } val recordLength = when (event) { is HostEvent.Clicked -> 16 @@ -2250,6 +2252,7 @@ object Protocol { is HostEvent.CodeScrolled -> 24 is HostEvent.CaretRect -> 40 is HostEvent.PositionRect -> 40 + is HostEvent.CodePointer -> 80 } val totalLength = recordLength.toLong() + (text?.size ?: 0) if (totalLength > Int.MAX_VALUE || totalLength > out.remaining().toLong()) { @@ -2308,6 +2311,7 @@ object Protocol { is HostEvent.CodeScrolled -> 55 is HostEvent.CaretRect -> 64 is HostEvent.PositionRect -> 65 + is HostEvent.CodePointer -> 66 } out.putShort(tag.toShort()) out.putShort(recordLength.toShort()) @@ -2548,6 +2552,23 @@ object Protocol { out.putFloat(if (event.found) event.width else 0f) out.putFloat(if (event.found) event.height else 0f) } + is HostEvent.CodePointer -> { + out.putInt(pointerKindTag(event.kind)) + out.putInt(event.pointerId) + out.putInt(pointerTypeTag(event.pointerType)) + out.putFloat(event.x) + out.putFloat(event.y) + out.putInt(event.buttons) + out.putInt(event.button) + out.putInt(event.modifiers) + out.putInt(event.clickCount) + out.putFloat(event.deltaX) + out.putFloat(event.deltaY) + out.putInt(wheelDeltaModeTag(event.deltaMode)) + out.putLong(event.timestampNanos) + out.putInt(event.line) + out.putInt(event.column) + } } if (text != null) out.put(text) return out.position() - start @@ -2766,6 +2787,7 @@ object Protocol { 189 -> PropertyKind.MaxHeightFraction 195 -> PropertyKind.OnCaretRect 196 -> PropertyKind.OnKeyPreview + 197 -> PropertyKind.OnCodePointer 27 -> PropertyKind.Progress else -> throw ProtocolException("unknown property tag $tag", offset) } diff --git a/renderer/desktop/src/renderer/CodeEditorSurface.kt b/renderer/desktop/src/renderer/CodeEditorSurface.kt index 71eafdf59..e398abcbf 100644 --- a/renderer/desktop/src/renderer/CodeEditorSurface.kt +++ b/renderer/desktop/src/renderer/CodeEditorSurface.kt @@ -87,6 +87,7 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import dev.darkpyonix.composerust.foundation.CodePointerTarget import dev.darkpyonix.composerust.protocol.ColorRole import dev.darkpyonix.composerust.protocol.DecorationKind import dev.darkpyonix.composerust.protocol.GutterDecorationKind @@ -290,6 +291,11 @@ class CodeEditorCallbacks( * here, releases too, so a held key's repeats can be told from its first press. */ val onKeyPreview: (event: KeyEvent, composing: Boolean) -> Boolean = { _, _ -> false }, + /** + * What the editor's view carries for the Host's pointer events over it, given what is + * under a point of the view. Nothing where the Host does not listen. + */ + val codePointer: @Composable (CodePointerTarget) -> Modifier = { Modifier }, ) /** Test tag of the field a field surface types into. */ @@ -932,13 +938,14 @@ internal fun caretOnScreen(rect: Rect, viewport: LayoutCoordinates?, textLeft: F * and from the layout callbacks, where the field's text layout and its place on screen are * the ones the reader sees. */ -internal class FieldPlaces(private val window: FieldWindow) { +internal class FieldPlaces(private val window: FieldWindow) : CodePointerTarget { /** The field itself, where its text layout's coordinates start. */ var field: LayoutCoordinates? = null /** The editor's view: everything the reader can see of it. */ var viewport: LayoutCoordinates? = null var layout: (() -> TextLayoutResult?)? = null + var gutterWidthPx = 0f var textLeftPx = 0f var density = 1f @@ -968,6 +975,22 @@ internal class FieldPlaces(private val window: FieldWindow) { return Rect(coordinates.localToRoot(Offset(cursor.left, cursor.top)), Size(caretWidthPx, cursor.height)) } + override fun positionAt(x: Float, y: Float): CodePosition? { + if (x < gutterWidthPx) return null + val view = viewport?.takeIf { it.isAttached } ?: return null + val coordinates = field?.takeIf { it.isAttached } ?: return null + val result = layout?.invoke() ?: return null + val point = coordinates.localPositionOf(view, Offset(x, y)) + if (point.x < 0f || point.y < 0f || point.y >= result.size.height) return null + // Past the end of the line it is on, the pointer is over no character. + val line = result.getLineForVerticalPosition(point.y) + if (point.x > result.getLineRight(line)) return null + val (offset, insertion) = window.toFieldOffset(result.getOffsetForPosition(point)) + // A lens row and a suggestion are shown, not the document's text. + if (insertion != null) return null + return window.toDoc(offset) + } + /** * Tells the model how to find positions and where the caret is, and answers the queries * that waited for the editor to be drawn. Answers whether the Host has something to hear. @@ -1093,6 +1116,7 @@ private fun FieldSurface( // Where the caret is drawn and where a position is, read after layout. What they find // is sent from a coroutine rather than from inside the pass that found it. val places = remember(window) { FieldPlaces(window).also { it.layout = { layoutHolder[0]?.invoke() } } } + places.gutterWidthPx = gutterWidthPx.toFloat() places.textLeftPx = (gutterWidthPx + textInsetPx).toFloat() places.density = density.density places.caretWidthPx = with(density) { 2.dp.toPx() } @@ -1111,6 +1135,9 @@ private fun FieldSurface( Box( modifier .boundedHeight(DEFAULT_EDITOR_HEIGHT) + // Outside the field, so the Host hears a press before the field moves the + // caret for it, and over the gutter as well as the text. + .then(callbacks.codePointer(places)) .changeSemantics(model, look) .background(look.container) .clipToBounds() @@ -1231,7 +1258,8 @@ private fun FieldSurface( val change = event.changes.firstOrNull() ?: continue val result = layoutHolder[0]?.invoke() when (event.type) { - PointerEventType.Press -> { + // A press the Host took is not the editor's. + PointerEventType.Press -> if (!change.isConsumed) { val lens = result?.let { lensAt(window, it, change.position) } diff --git a/renderer/desktop/src/renderer/DrawnCodeEditor.kt b/renderer/desktop/src/renderer/DrawnCodeEditor.kt index 82c5bb40a..77070fb3f 100644 --- a/renderer/desktop/src/renderer/DrawnCodeEditor.kt +++ b/renderer/desktop/src/renderer/DrawnCodeEditor.kt @@ -60,6 +60,7 @@ import androidx.compose.ui.text.drawText import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.dp +import dev.darkpyonix.composerust.foundation.CodePointerTarget import dev.darkpyonix.composerust.protocol.DecorationKind import kotlinx.coroutines.launch import kotlin.math.max @@ -109,7 +110,7 @@ private class DrawnState( val model: CodeEditorModel, var look: CodeEditorLook, var callbacks: CodeEditorCallbacks, -) : DrawnInputTarget { +) : DrawnInputTarget, CodePointerTarget { /** The platform clipboard, set on every composition. */ lateinit var clipboard: ClipboardManager @@ -326,6 +327,21 @@ private class DrawnState( return answered || model.caretUntold } + override fun positionAt(x: Float, y: Float): CodePosition? { + if (x < textLeft) return null + val row = ((y + (scroll?.offset ?: 0)) / rowPx).toInt() + if (y + (scroll?.offset ?: 0) < 0f || row >= rows.totalRows) return null + val line = rows.lineAtRow(row) + // A lens above the line, and the rows a suggestion of several lines adds below it, + // are not the document's text. + if (row != rows.textRow(line)) return null + val view = view(line) + val local = x - textLeft + // Past the end of the line, the pointer is over no character. + if (local > view.layout.size.width) return null + return CodePosition(line, view.column(local)) + } + fun positionAt(point: Offset): Pair { val row = ((point.y + (scroll?.offset ?: 0)) / rowPx).toInt().coerceAtLeast(0) val line = rows.lineAtRow(row).coerceIn(0, model.document.lineCount - 1) @@ -433,6 +449,9 @@ private fun DrawnSurface( Box( modifier .boundedHeight(DEFAULT_EDITOR_HEIGHT) + // Outside the box that takes presses, so the Host hears a press before the + // caret moves for it. + .then(callbacks.codePointer(state)) .changeSemantics(model, look) .background(look.container) .clipToBounds() @@ -466,6 +485,8 @@ private fun DrawnSurface( when (event.type) { PointerEventType.Press -> { focus.requestFocus() + // A press the Host took is not the editor's: the caret stays. + if (change.isConsumed) continue val (position, onLens) = state.positionAt(change.position) if (change.position.x < gutterWidth) { pressGutter( diff --git a/renderer/desktop/src/renderer/HostCodeEditor.kt b/renderer/desktop/src/renderer/HostCodeEditor.kt index 22dee7862..9567c510a 100644 --- a/renderer/desktop/src/renderer/HostCodeEditor.kt +++ b/renderer/desktop/src/renderer/HostCodeEditor.kt @@ -112,6 +112,16 @@ internal fun HostCodeEditor( } }, onKeyPreview = keyPreview, + // The Host's pointer events over the editor go through the same router as every + // other node's, so a press the editor does not consume goes on to the nearest + // subscribed node around it. + codePointer = { target -> + if (node.subscribesToCodePointer()) { + codePointerEvents(node, table.pointers, currentDispatcher, target) + } else { + Modifier + } + }, ) } // A listener attached after the editor was drawn has the row height and the offset diff --git a/renderer/desktop/src/renderer/NodeTable.kt b/renderer/desktop/src/renderer/NodeTable.kt index 3a3145824..94c16801d 100644 --- a/renderer/desktop/src/renderer/NodeTable.kt +++ b/renderer/desktop/src/renderer/NodeTable.kt @@ -1133,7 +1133,9 @@ class NodeTable { widget == WidgetKind.ScrollRow || widget == WidgetKind.SelectionContainer || widget == WidgetKind.Spacer || - widget == WidgetKind.AbsoluteBox + widget == WidgetKind.AbsoluteBox || + // An editor's own pointer events take the same mask of kinds. + (widget == WidgetKind.CodeEditor && property == PropertyKind.PointerKinds) // A Tooltip's text is the explanation it shows, and its description in the // accessibility tree. A destination's is its label. @@ -1442,6 +1444,9 @@ class NodeTable { // before the editor handles them. PropertyKind.OnCaretRect, PropertyKind.OnKeyPreview, + // The handler of its pointer events with the text under them. The kinds it + // hears are the node's `PointerKinds`, below. + PropertyKind.OnCodePointer, -> widget == WidgetKind.CodeEditor PropertyKind.OnCompositionChange -> diff --git a/renderer/desktop/src/renderer/PointerEvents.kt b/renderer/desktop/src/renderer/PointerEvents.kt index a64a6bb80..9cc32481d 100644 --- a/renderer/desktop/src/renderer/PointerEvents.kt +++ b/renderer/desktop/src/renderer/PointerEvents.kt @@ -30,6 +30,7 @@ import androidx.compose.ui.platform.LocalViewConfiguration import androidx.compose.ui.unit.IntSize import dev.darkpyonix.composerust.design.HostPlatform import dev.darkpyonix.composerust.design.detectHostPlatform +import dev.darkpyonix.composerust.foundation.code.CodePosition import dev.darkpyonix.composerust.protocol.HostEvent import dev.darkpyonix.composerust.protocol.PointerKind import dev.darkpyonix.composerust.protocol.PointerType @@ -120,6 +121,29 @@ internal fun HostNode.pointerKinds(): Int = internal fun HostNode.subscribesToPointer(): Boolean = handler(PropertyKind.OnPointer) != null && pointerKinds() != 0 +/** + * Whether a code editor has both halves of its own subscription: the handler that hears its + * pointer with the text under it, and at least one kind in the same mask a node's has. + */ +internal fun HostNode.subscribesToCodePointer(): Boolean = + handler(PropertyKind.OnCodePointer) != null && pointerKinds() != 0 + +/** + * A code editor's surface, as the pointer events over it see it: what is under a point. + * + * The editor's pointer node routes in the first pass rather than the main one. The text + * the editor draws handles a press in the main pass, so a press the Host consumed has to be + * consumed before then, or the caret would move under a Cmd-click that was the Host's. + */ +interface CodePointerTarget { + /** + * The character under a point of the editor's view, in its pixels, or null where there + * is none: the gutter, past the end of a line, below the last line, or a row the editor + * shows that is not the document's. + */ + fun positionAt(x: Float, y: Float): CodePosition? +} + /** * The modifier of a subscribed node. Call it only for a node that subscribes. * @@ -156,6 +180,38 @@ internal fun hostPointerEvents( ) } +/** + * The modifier of a code editor's view whose node subscribes to [PropertyKind.OnCodePointer]. + * The records are the ones [hostPointerEvents] sends with the character under the pointer + * after them, and every rule is the same: the kinds, the capture, a move a frame, the click + * count, the menu, and a consumed press consumed for Compose too. + */ +@Composable +internal fun codePointerEvents( + node: HostNode, + router: PointerRouter, + dispatcher: EventDispatcher, + target: CodePointerTarget, +): Modifier { + val outer = LocalDensity.current + val view = LocalViewConfiguration.current + val controlClickIsMenu = remember { + (hostPlatformOverride ?: detectHostPlatform()) == HostPlatform.MacOs + } + return HostPointerElement( + node, + router, + dispatcher, + outer.density, + view.doubleTapTimeoutMillis, + view.longPressTimeoutMillis, + view.touchSlop, + controlClickIsMenu, + hostWheelDeltaMode, + target, + ) +} + private data class HostPointerElement( val node: HostNode, val router: PointerRouter, @@ -166,6 +222,8 @@ private data class HostPointerElement( val slop: Float, val controlClickIsMenu: Boolean, val wheelMode: WheelDeltaMode, + /** A code editor's view, for the editor's own events. Null for a node's [PropertyKind.OnPointer]. */ + val code: CodePointerTarget? = null, ) : ModifierNodeElement() { override fun create(): HostPointerNode = HostPointerNode(node, router, dispatcher).also(::configure) @@ -193,6 +251,7 @@ private data class HostPointerElement( node.slop = slop node.controlClickIsMenu = controlClickIsMenu node.wheelMode = wheelMode + node.code = code } } @@ -213,6 +272,9 @@ internal class HostPointerNode( var controlClickIsMenu = false var wheelMode = WheelDeltaMode.Line + /** The code editor this node is the view of, which makes its records `CodePointer` ones. */ + var code: CodePointerTarget? = null + /** The event being dispatched, as this node sees it: its positions are this node's own. */ var current: PointerEvent? = null @@ -281,6 +343,20 @@ internal class HostPointerNode( } override fun onPointerEvent(pointerEvent: PointerEvent, pass: PointerEventPass, bounds: IntSize) { + if (code != null) { + // Routed on the way down, before the editor's text sees the event: the nodes of + // the chain further out are already on the stack, and the editor is the + // innermost subscriber there is. + if (pass != PointerEventPass.Initial) return + current = pointerEvent + router.begin(this) + if (pointerEvent.type == PointerEventType.Scroll && wheelTaken && wants(PointerKind.Wheel)) { + val changes = pointerEvent.changes + for (index in changes.indices) changes[index].consume() + } + router.finish(this, pointerEvent) + return + } when (pass) { // On the way down every subscriber in the path says it is there. The deepest // one is the first to see the main pass, and by then the whole path is known. @@ -351,6 +427,8 @@ internal class HostPointerNode( deltaY: Float = 0f, deltaMode: WheelDeltaMode = WheelDeltaMode.Pixel, ): Boolean { + val editor = code + if (editor != null) return sendCode(editor, kind, button, clickCount, deltaX, deltaY, deltaMode) val handler = host.handler(PropertyKind.OnPointer) ?: return false if (!router.alive(host.id)) return false return dispatcher.dispatch( @@ -374,6 +452,42 @@ internal class HostPointerNode( ) } + /** [send] for a code editor's view: the same record, and the character under the pointer. */ + private fun sendCode( + editor: CodePointerTarget, + kind: PointerKind, + button: Int, + clickCount: Int, + deltaX: Float, + deltaY: Float, + deltaMode: WheelDeltaMode, + ): Boolean { + val handler = host.handler(PropertyKind.OnCodePointer) ?: return false + if (!router.alive(host.id)) return false + val position = editor.positionAt(lastX, lastY) + return dispatcher.dispatch( + HostEvent.CodePointer( + nodeId = host.id, + handlerId = handler, + kind = kind, + pointerId = lastPointerId, + pointerType = lastPointerType, + x = lastX / pxPerUnit, + y = lastY / pxPerUnit, + buttons = lastButtons, + button = button, + modifiers = lastModifiers, + clickCount = clickCount, + deltaX = deltaX, + deltaY = deltaY, + deltaMode = deltaMode, + timestampNanos = lastUptimeMillis * 1_000_000L, + line = position?.line ?: -1, + column = position?.column ?: -1, + ), + ) + } + fun armLongPress() { cancelLongPress() if (!isAttached) return diff --git a/renderer/desktop/test/CodeEditorInputHooksTest.kt b/renderer/desktop/test/CodeEditorInputHooksTest.kt index 774eb6862..1b98ac47f 100644 --- a/renderer/desktop/test/CodeEditorInputHooksTest.kt +++ b/renderer/desktop/test/CodeEditorInputHooksTest.kt @@ -1,11 +1,13 @@ package dev.darkpyonix.composerust.test +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.InternalComposeUiApi import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.test.ComposeUiTest import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.click @@ -15,6 +17,7 @@ import androidx.compose.ui.test.performMouseInput import androidx.compose.ui.test.pressKey import androidx.compose.ui.test.requestFocus import androidx.compose.ui.test.runComposeUiTest +import androidx.compose.ui.unit.Density import dev.darkpyonix.composerust.design.HostPlatform import dev.darkpyonix.composerust.foundation.code.CODE_EDITOR_FIELD_TAG import dev.darkpyonix.composerust.foundation.code.CodeEditorPath @@ -22,12 +25,14 @@ import dev.darkpyonix.composerust.foundation.code.CodePosition import dev.darkpyonix.composerust.foundation.code.defaultCodeEditorPath import dev.darkpyonix.composerust.foundation.code.installDrawnCodeEditor import dev.darkpyonix.composerust.foundation.codeEditorKeyPreview +import dev.darkpyonix.composerust.foundation.pointerKindBit import dev.darkpyonix.composerust.protocol.ColorScheme import dev.darkpyonix.composerust.protocol.DesignSystem import dev.darkpyonix.composerust.protocol.HostEvent import dev.darkpyonix.composerust.protocol.Key as ProtocolKey import dev.darkpyonix.composerust.protocol.Modifier as ProtocolModifier import dev.darkpyonix.composerust.protocol.Mutation +import dev.darkpyonix.composerust.protocol.PointerKind import dev.darkpyonix.composerust.protocol.PropertyKind import dev.darkpyonix.composerust.protocol.PropertyValue import dev.darkpyonix.composerust.protocol.Theme @@ -41,6 +46,7 @@ import dev.darkpyonix.composerust.tooling.FakeHostConnection import dev.darkpyonix.composerust.tooling.HostResponse import dev.darkpyonix.composerust.ui.node.NodeTable import dev.darkpyonix.composerust.ui.node.nodeTestTag +import kotlin.math.abs import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test @@ -50,6 +56,7 @@ import kotlin.test.assertTrue private const val EDITOR = 2 private const val ON_PREVIEW = 81L +private const val ON_CODE_POINTER = 91L /** An editor alone on the page, 300 by 160 dp, with the records the test adds after it. */ private fun page(text: String, vararg extra: Mutation): List = buildList { @@ -80,8 +87,10 @@ class CodeEditorInputHooksTest { private fun ComposeUiTest.show(connection: FakeHostConnection): () -> ComposeRustHost { lateinit var host: ComposeRustHost setContent { - host = rememberComposeRustHost(connection) - ComposeRustContent(host) + CompositionLocalProvider(LocalDensity provides Density(1f)) { + host = rememberComposeRustHost(connection) + ComposeRustContent(host) + } } waitForIdle() return { host } @@ -183,4 +192,94 @@ class CodeEditorInputHooksTest { assertFalse(preview(down, false)) assertEquals(3, sent.size) } + + /** + * Criterion 21.1. Cmd and a click on the `b` of `beta` reaches the Host once, as a + * press of the primary button with Meta held and the line and column of that letter, + * and a press the Host consumed leaves the caret where it was. Let go, the same click + * moves the caret there, and a press over the gutter is over no character. + */ + @Test + fun fr38_editor_pointer_reports_text_position() { + installDrawnCodeEditor() + for (path in listOf(CodeEditorPath.Windowed, CodeEditorPath.Drawn)) { + defaultCodeEditorPath = path + hostPlatformOverride = HostPlatform.MacOs + runComposeUiTest { + var take = true + val connection = FakeHostConnection( + page( + "let alpha = 1;\nlet beta = alpha + 1;\n", + Mutation.SetProp(EDITOR, PropertyKind.OnCodePointer, PropertyValue.Integer(ON_CODE_POINTER)), + Mutation.SetProp( + EDITOR, + PropertyKind.PointerKinds, + PropertyValue.Integer(pointerKindBit(PointerKind.Down).toLong()), + ), + // Where the `b` of `beta` is, which is where the test clicks. + Mutation.QueryPositionRect(EDITOR, 1, 1, 4), + ), + ) + connection.respondWith { event -> + if (event is HostEvent.CodePointer && take) HostResponse(result = 1) else HostResponse() + } + val host = show(connection) + assertEquals(emptyList(), connection.events.filterIsInstance(), "$path") + fun caret() = host().table.node(EDITOR)!!.code!!.selection + fun pointers() = connection.nodeEvents.filterIsInstance() + val letter = connection.nodeEvents.filterIsInstance().single() + assertTrue(letter.found, "$path") + val editor = onNodeWithTag(nodeTestTag(EDITOR)) + val origin = editor.fetchSemanticsNode().positionInRoot + val point = Offset(letter.x + 2f - origin.x, letter.y + letter.height / 2f - origin.y) + + editor.performKeyInput { keyDown(Key.MetaLeft) } + editor.performMouseInput { + moveTo(point) + press() + release() + } + editor.performKeyInput { keyUp(Key.MetaLeft) } + waitForIdle() + val down = pointers().single() + assertEquals(EDITOR, down.nodeId) + assertEquals(ON_CODE_POINTER, down.handlerId) + assertEquals(PointerKind.Down, down.kind) + assertEquals(1 to 4, down.line to down.column, "$path: the press is over the b of beta") + assertEquals(8, down.modifiers and 8, "$path: Meta is held") + assertEquals(0, down.modifiers and 2, "$path: Ctrl is not") + assertEquals(1, down.button) + assertEquals(1, down.clickCount) + assertTrue(abs(point.x - down.x) <= 0.6f && abs(point.y - down.y) <= 0.6f, "$path: at $point, sent $down") + assertTrue(caret().collapsed && caret().caret == CodePosition(0, 0), "$path: a consumed press moved the caret to ${caret()}") + + // The Host lets the same click go: the caret goes to the letter, as it always did. + take = false + mainClock.advanceTimeBy(2_000) + editor.performMouseInput { + moveTo(point) + press() + release() + } + waitForIdle() + assertEquals(2, pointers().size, "$path") + assertEquals(0, pointers().last().modifiers, "$path") + assertEquals(CodePosition(1, 4), caret().caret, "$path: a press the Host let go did not move the caret") + + // Over the gutter there is no character. + mainClock.advanceTimeBy(2_000) + editor.performMouseInput { + moveTo(Offset(2f, point.y)) + press() + release() + } + waitForIdle() + assertEquals(-1 to -1, pointers().last().let { it.line to it.column }, "$path") + } + } + assertTrue(NodeTable.supportsProperty(WidgetKind.CodeEditor, PropertyKind.OnCodePointer)) + assertTrue(NodeTable.supportsProperty(WidgetKind.CodeEditor, PropertyKind.PointerKinds)) + assertFalse(NodeTable.supportsProperty(WidgetKind.CodeEditor, PropertyKind.OnPointer)) + assertFalse(NodeTable.supportsProperty(WidgetKind.TextField, PropertyKind.OnCodePointer)) + } } diff --git a/renderer/desktop/test/ProtocolVectorsTest.kt b/renderer/desktop/test/ProtocolVectorsTest.kt index c77b427ce..e79e873ab 100644 --- a/renderer/desktop/test/ProtocolVectorsTest.kt +++ b/renderer/desktop/test/ProtocolVectorsTest.kt @@ -951,6 +951,12 @@ class ProtocolVectorsTest { // Where the caret is drawn and the answer to the position query, after them. 1439 to HostEvent.CaretRect(12, 30L, 1, 8, 120.5f, 64.25f, 2f, 20f), 1479 to HostEvent.PositionRect(12, 0L, 17, true, 88.75f, 64.25f, 2f, 20f), + // A Cmd-click over the second line, with the place in the text under it. + 1519 to HostEvent.CodePointer( + 12, 31L, dev.darkpyonix.composerust.protocol.PointerKind.Down, 1, + dev.darkpyonix.composerust.protocol.PointerType.Mouse, 96.5f, 30.25f, 1, 1, 8, 1, 0f, 0f, + dev.darkpyonix.composerust.protocol.WheelDeltaMode.Pixel, 123_456_789_000L, 1, 13, + ), ) for ((offset, event) in expected) { val wire = encoded(event) @@ -959,7 +965,7 @@ class ProtocolVectorsTest { "$event at $offset", ) } - assertEquals(1519, bytes.size) + assertEquals(1599, bytes.size) } /** From 49118f708f32b5796552def3553f8de1bece6e11 Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:46:11 +0900 Subject: [PATCH 8/8] Feat: Draw line and range background decorations in the code editor (FR-38, #542) Covers FR-38 criterion 22. Wire: DecorationKind gains LineBackground (5) and RangeBackground (6), appended, in the existing 44 byte decoration record with a ColorRole. Rust: Decoration::line_background(version, line_start, line_end, role), the lines as a range from the start of the first to the start of the last, and Decoration::range_background(version, range, role). The mutation vector's decoration list gains one of each. Renderer: a line background is followed as lines, the way a gutter mark is, and goes only when every one of its lines is deleted; a range background follows like any other range. The field path draws line tints behind the field across the row from the gutter to the right edge, and range tints in the field's own layout; the drawn path draws both per row before the selection and the text. DiffAdded and DiffRemoved take the design system's container tint for a line and the emphasis tint for a range; those four roles are drawn as they are, and any other role as a wash of its colour at the strengths the container and emphasis tints are mixed at. A background without a role is refused with a protocol error. The design showcase's editor gains one of each. Tests: fr38_line_background_spans_the_width_and_follows_edits (22.1) and fr38_range_background_paints_its_characters (22.2) on both paths, and fr38_line_and_range_backgrounds_follow_edits_in_the_model, in CodeEditorBackgroundTest; fr38_line_and_range_backgrounds_round_trip_on_the_wire in code_editor.rs; the decoration vector in ProtocolVectorsTest. --- CHANGELOG.md | 4 + .../android-kotlin/shared/CodeEditorModel.kt | 70 +++++ .../shared/CodeEditorSurface.kt | 64 +++++ .../android-kotlin/shared/HostCodeEditor.kt | 31 ++ .../android-kotlin/shared/Protocol.gen.kt | 8 +- compose-rust/schema-hash.txt | 2 +- compose-rust/src/code.rs | 30 ++ compose-rust/src/codegen.rs | 5 +- compose-rust/src/schema.rs | 12 +- compose-rust/tests/code_editor.rs | 44 +++ compose-rust/tests/vectors/mutations.bin | Bin 6071 -> 6159 bytes compose-rust/tests/vectors/vectors.json | 2 +- .../desktop/src/devshell/DesignShowcase.kt | 9 +- renderer/desktop/src/protocol/Protocol.gen.kt | 8 +- .../desktop/src/renderer/CodeEditorModel.kt | 70 +++++ .../desktop/src/renderer/CodeEditorSurface.kt | 64 +++++ .../desktop/src/renderer/DrawnCodeEditor.kt | 17 ++ .../desktop/src/renderer/HostCodeEditor.kt | 31 ++ .../desktop/test/CodeEditorBackgroundTest.kt | 271 ++++++++++++++++++ renderer/desktop/test/ProtocolVectorsTest.kt | 2 + 20 files changed, 730 insertions(+), 14 deletions(-) create mode 100644 renderer/desktop/test/CodeEditorBackgroundTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index ba5f5120c..e807e8e95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Line and range backgrounds in the code editor + +Two decoration kinds are appended: `Decoration::line_background(version, line_start, line_end, role)` (kind 5) tints whole lines across the editor's width, past the end of each line, and `Decoration::range_background(version, range, role)` (kind 6) tints the characters of a range more strongly, which is how a diff view marks a changed line and the words in it that changed. `DiffAdded` and `DiffRemoved` are drawn with the design system's container tint for a line and its emphasis tint for a range; a `*Container` or `*Emphasis` role is drawn as it is, and any other role, `DiffModified` among them, as a light wash of its colour. Both follow the reader's edits like every other decoration: a line typed in front of a tinted line moves the tint down with it ([#542](https://github.com/DarkPyonix/compose-rust/issues/542)). + ### Code editor pointer events with the text under them A `CodeEditor` with the new `OnCodePointer` handler property (tag 197) and a `PointerKinds` mask sends its pointer events in a `CodePointer` event (tag 66): the 72 byte `Pointer` record of a node's pointer event, then the line and the column of the character under the pointer, or none over the gutter, past the end of a line or below the last one. The kinds, the buttons, the modifiers, the click count, the capture, a move a frame and the consumption rules are a node's pointer event's, and a `Down` the handler consumes does not move the caret. Cmd or Ctrl and a click goes to a definition this way, and Cmd or Ctrl and a hover underlines a word ([#555](https://github.com/DarkPyonix/compose-rust/issues/555)). diff --git a/compose-rust/android-kotlin/shared/CodeEditorModel.kt b/compose-rust/android-kotlin/shared/CodeEditorModel.kt index 5566728f2..0ff79d569 100644 --- a/compose-rust/android-kotlin/shared/CodeEditorModel.kt +++ b/compose-rust/android-kotlin/shared/CodeEditorModel.kt @@ -46,6 +46,10 @@ class LiveDecoration( val text: String, ) +/** Whether this is one of the two tints drawn behind the text. */ +val LiveDecoration.isBackground: Boolean + get() = kind == DecorationKind.LineBackground || kind == DecorationKind.RangeBackground + /** * One stretch of lines that can be folded, as it stands in the current version of the * document. Folding keeps [startLine] and hides the lines after it up to [endLine]. @@ -334,6 +338,7 @@ class CodeEditorModel( if (document.contentEquals(text)) return false document.reset(text) decorationList.clear() + backgroundsPresent = false spanList.clear() longestSpanLines = 0 undoStack.clear() @@ -352,6 +357,28 @@ class CodeEditorModel( fun setDecorations(records: List) { decorationList.clear() for (record in records) { + if (record.kind == DecorationKind.LineBackground) { + // Whole lines, the first to the last, kept as the start of each. They are + // followed to where they are now as lines, the way a gutter mark's line is. + val color = record.color ?: run { + output += EditorOutput.Error( + "a line background on lines ${record.startLine} to ${record.endLine} names no colour", + ) + continue + } + val (first, last) = followLines(record.version, record.startLine, record.endLine, "a line background") + ?: continue + decorationList += LiveDecoration( + record.kind, + null, + color, + CodePosition(first, 0), + CodePosition(last, 0), + record.id, + "", + ) + continue + } val range = follow(record.version, record.startLine, record.startColumn, record.endLine, record.endColumn) ?: continue val (start, end) = range @@ -374,11 +401,25 @@ class CodeEditorModel( ) DecorationKind.HoverAnchor -> LiveDecoration(record.kind, null, null, start, end, record.id, "") + // Taken above. + DecorationKind.LineBackground -> continue + DecorationKind.RangeBackground -> { + val color = record.color ?: run { + output += EditorOutput.Error("a range background from $start to $end names no colour") + continue + } + LiveDecoration(record.kind, null, color, start, end, record.id, "") + } } } + backgroundsPresent = decorationList.any { it.isBackground } overlayRevision += 1 } + /** Whether any decoration is a line or a range background, so a frame without one skips them. */ + var backgroundsPresent = false + private set + /** Replaces every colour run with the Host's new list. */ fun setSyntaxSpans(records: List) { spanList.clear() @@ -542,6 +583,18 @@ class CodeEditorModel( (position < it.end || (it.start == it.end && position == it.start)) } + /** The line background of [line], the last one sent where several cover it, or null. */ + fun lineBackgroundAt(line: Int): LiveDecoration? { + if (!backgroundsPresent) return null + for (index in decorationList.indices.reversed()) { + val decoration = decorationList[index] + if (decoration.kind == DecorationKind.LineBackground && decoration.start.line <= line && line <= decoration.end.line) { + return decoration + } + } + return null + } + /** The lenses, grouped by the line they sit above, in line order. */ fun lensesByLine(): List>> = decorationList .filter { it.kind == DecorationKind.CodeLens } @@ -1146,6 +1199,23 @@ class CodeEditorModel( val iterator = decorationList.iterator() while (iterator.hasNext()) { val decoration = iterator.next() + if (decoration.kind == DecorationKind.LineBackground) { + // Lines rather than a stretch of text: a line typed in front of them + // pushes them down, and they go only when every one of them is deleted. + val lines = CodeDocument.mapRange( + CodePosition(decoration.start.line, 0), + CodePosition(decoration.end.line + 1, 0), + change, + ) + val last = lines?.let { if (it.second.column == 0) it.second.line - 1 else it.second.line } + if (lines == null || last == null || last < lines.first.line) { + iterator.remove() + } else { + decoration.start = CodePosition(lines.first.line, 0) + decoration.end = CodePosition(minOf(last, document.lineCount - 1), 0) + } + continue + } val range = CodeDocument.mapRange(decoration.start, decoration.end, change) if (range == null) { iterator.remove() diff --git a/compose-rust/android-kotlin/shared/CodeEditorSurface.kt b/compose-rust/android-kotlin/shared/CodeEditorSurface.kt index e398abcbf..0b5ed6239 100644 --- a/compose-rust/android-kotlin/shared/CodeEditorSurface.kt +++ b/compose-rust/android-kotlin/shared/CodeEditorSurface.kt @@ -195,6 +195,13 @@ class CodeEditorLook( * set in the design system's face. */ val fontFallback: ((String) -> List>)? = null, + /** + * The tint a line background in a role is drawn with, across the editor's width and + * past the end of the line. Unspecified draws nothing. + */ + val lineBackground: (ColorRole) -> Color = { Color.Unspecified }, + /** The stronger tint a range background in a role is drawn with over its characters. */ + val rangeBackground: (ColorRole) -> Color = { Color.Unspecified }, ) /** @@ -1160,6 +1167,7 @@ private fun FieldSurface( .drawBehind { translate(top = -vertical.offset.toFloat()) { drawCurrentLine(window, rows, rowPx, look) + drawLineBackgrounds(model, rows, rowPx, vertical.offset, viewportHeight, 0f, look) } // Read so that typing, a move of the caret and a scroll along the // lines all draw this again, and the caret is reported from here. @@ -1576,6 +1584,33 @@ internal fun HoverReport(tracker: HoverTracker, delayMillis: Long, callbacks: Co } } +/** + * The line backgrounds of the lines on screen, from [left] to the right edge whatever the + * length of the line, over the current line's band and behind everything else. + */ +internal fun DrawScope.drawLineBackgrounds( + model: CodeEditorModel, + rows: RowMap, + rowPx: Int, + scroll: Int, + viewportHeight: Int, + left: Float, + look: CodeEditorLook, +) { + model.overlayRevision + if (!model.backgroundsPresent) return + val first = rows.lineAtRow(scroll / rowPx) + val last = min(rows.lineCount - 1, rows.lineAtRow((scroll + viewportHeight) / rowPx + 1)) + for (line in first..last) { + if (rows.isHidden(line)) continue + val background = model.lineBackgroundAt(line) ?: continue + val color = look.lineBackground(background.color ?: continue) + if (color == Color.Unspecified || color.alpha == 0f) continue + val top = rows.textRow(line) * rowPx.toFloat() + drawRect(color, Offset(left, top), Size(size.width - left, rowPx.toFloat())) + } +} + /** The line the caret is on, across the whole width, behind the text. */ private fun DrawScope.drawCurrentLine(window: FieldWindow, rows: RowMap, rowPx: Int, look: CodeEditorLook) { window.revision @@ -1701,6 +1736,7 @@ private fun DrawScope.drawDecorations(window: FieldWindow, layout: TextLayoutRes model.overlayRevision window.revision val textLength = layout.layoutInput.text.length + if (model.backgroundsPresent) drawRangeBackgrounds(window, layout, look) for (decoration in model.decorations) { if (decoration.kind != DecorationKind.Underline) continue if (decoration.end.line < window.start || decoration.start.line >= window.end) continue @@ -1726,6 +1762,34 @@ private fun DrawScope.drawDecorations(window: FieldWindow, layout: TextLayoutRes } } +/** The range backgrounds over the characters they cover, in the field's own coordinates. */ +private fun DrawScope.drawRangeBackgrounds(window: FieldWindow, layout: TextLayoutResult, look: CodeEditorLook) { + val model = window.model + val textLength = layout.layoutInput.text.length + for (decoration in model.decorations) { + if (decoration.kind != DecorationKind.RangeBackground || decoration.start == decoration.end) continue + if (decoration.end.line < window.start || decoration.start.line >= window.end) continue + val color = look.rangeBackground(decoration.color ?: continue) + if (color == Color.Unspecified || color.alpha == 0f) continue + val from = window.toField(maxOf(decoration.start, CodePosition(window.start, 0))) ?: continue + val lastLine = window.end - 1 + val to = window.toField(minOf(decoration.end, CodePosition(lastLine, model.document.line(lastLine).length))) + ?: continue + val shownFrom = window.toShown(from, asEnd = false).coerceIn(0, textLength) + val shownTo = window.toShown(to, asEnd = true).coerceIn(0, textLength) + if (shownTo <= shownFrom) continue + val firstLine = layout.getLineForOffset(shownFrom) + val lastShownLine = layout.getLineForOffset(shownTo) + for (line in firstLine..lastShownLine) { + val left = if (line == firstLine) layout.getHorizontalPosition(shownFrom, true) else layout.getLineLeft(line) + val right = if (line == lastShownLine) layout.getHorizontalPosition(shownTo, true) else layout.getLineRight(line) + if (right <= left) continue + val top = layout.getLineTop(line) + drawRect(color, Offset(left, top), Size(right - left, layout.getLineBottom(line) - top)) + } + } +} + internal fun DrawScope.drawUnderline(shape: UnderlineShape, color: Color, left: Float, right: Float, y: Float, stroke: Float) { when (shape) { UnderlineShape.Straight -> drawLine(color, Offset(left, y), Offset(right, y), stroke) diff --git a/compose-rust/android-kotlin/shared/HostCodeEditor.kt b/compose-rust/android-kotlin/shared/HostCodeEditor.kt index 9567c510a..54238a772 100644 --- a/compose-rust/android-kotlin/shared/HostCodeEditor.kt +++ b/compose-rust/android-kotlin/shared/HostCodeEditor.kt @@ -6,6 +6,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.type @@ -20,6 +21,7 @@ import dev.darkpyonix.composerust.foundation.code.CodeEditorSurface import dev.darkpyonix.composerust.foundation.code.EditorOutput import dev.darkpyonix.composerust.foundation.code.EditorScroll import dev.darkpyonix.composerust.protocol.CodeEditorColorsRecord +import dev.darkpyonix.composerust.protocol.ColorRole import dev.darkpyonix.composerust.protocol.CodeEditorRecords import dev.darkpyonix.composerust.protocol.FontRefRecords import dev.darkpyonix.composerust.protocol.HostEvent @@ -249,9 +251,38 @@ internal fun codeEditorLook( lineNumbers = node.flag(PropertyKind.LineNumbers, default = true), gutterMinWidth = node.lengthOrNull(PropertyKind.GutterMinWidthDp) ?: 0.dp, fontFallback = fontChain?.let { chain -> { text: String -> chain.spans(text) } }, + lineBackground = { role -> diffTint(role, theme, strong = false) }, + rangeBackground = { role -> diffTint(role, theme, strong = true) }, ) } +/** + * What a line background ([strong] false) or a range background ([strong] true) in a role + * is drawn with. An added or a removed line takes the design system's container tint for + * it and the changed characters its emphasis tint, the same pair a diff badge uses. A role + * that is already one of those tints is drawn as it is. Any other role is laid over the + * text as a wash, light enough that the code stays readable. + */ +internal fun diffTint(role: ColorRole, theme: ResolvedTheme, strong: Boolean): Color = when (role) { + ColorRole.DiffAdded -> theme.color(if (strong) ColorRole.DiffAddedEmphasis else ColorRole.DiffAddedContainer) + ColorRole.DiffRemoved -> theme.color(if (strong) ColorRole.DiffRemovedEmphasis else ColorRole.DiffRemovedContainer) + ColorRole.DiffAddedContainer, + ColorRole.DiffRemovedContainer, + ColorRole.DiffAddedEmphasis, + ColorRole.DiffRemovedEmphasis, + -> theme.color(role) + else -> theme.color(role).let { ink -> + // The same strengths the container and the emphasis tints are mixed at. + val wash = when { + strong && theme.dark -> 0.40f + strong -> 0.30f + theme.dark -> 0.20f + else -> 0.12f + } + ink.copy(alpha = ink.alpha * wash) + } +} + /** * Turns what an editor's model queued into events for the Host, in the order it was queued. * diff --git a/compose-rust/android-kotlin/shared/Protocol.gen.kt b/compose-rust/android-kotlin/shared/Protocol.gen.kt index abd9815ef..777fe367a 100644 --- a/compose-rust/android-kotlin/shared/Protocol.gen.kt +++ b/compose-rust/android-kotlin/shared/Protocol.gen.kt @@ -94,7 +94,7 @@ enum class AnimationEventKind { Ready, Active, Iteration, End } enum class ReducedMotion { Off, On, Unknown } -enum class DecorationKind { Underline, CodeLens, HoverAnchor, GhostText } +enum class DecorationKind { Underline, CodeLens, HoverAnchor, GhostText, LineBackground, RangeBackground } enum class Severity { Error, Warning, Information, Hint } @@ -875,6 +875,8 @@ object CodeEditorRecords { 2 -> DecorationKind.CodeLens 3 -> DecorationKind.HoverAnchor 4 -> DecorationKind.GhostText + 5 -> DecorationKind.LineBackground + 6 -> DecorationKind.RangeBackground else -> null } @@ -1607,7 +1609,7 @@ class ProtocolException(message: String, val offset: Int) : IllegalArgumentException("$message at byte offset $offset") object Protocol { - const val SCHEMA_HASH: Long = -8415703039461350493L + const val SCHEMA_HASH: Long = -713190573993818651L const val PROTOCOL_VERSION: Int = 1 private const val TAG_ENVELOPE = 0 @@ -3352,6 +3354,8 @@ object Protocol { 2 -> DecorationKind.CodeLens 3 -> DecorationKind.HoverAnchor 4 -> DecorationKind.GhostText + 5 -> DecorationKind.LineBackground + 6 -> DecorationKind.RangeBackground else -> throw ProtocolException("unknown DecorationKind tag $tag", offset) } diff --git a/compose-rust/schema-hash.txt b/compose-rust/schema-hash.txt index 140590c02..9e24b1ee1 100644 --- a/compose-rust/schema-hash.txt +++ b/compose-rust/schema-hash.txt @@ -1 +1 @@ -0x8b356aac85bb23a3 +0xf61a3cf39bf105e5 diff --git a/compose-rust/src/code.rs b/compose-rust/src/code.rs index 1b33b050d..e205734ef 100644 --- a/compose-rust/src/code.rs +++ b/compose-rust/src/code.rs @@ -365,6 +365,36 @@ impl Decoration { } } + /// A tint across lines `line_start` to `line_end`, both included, the whole width of the + /// editor and past the end of each line. `color` is a role such as `DiffAdded`, + /// `DiffRemoved` or `DiffModified`, and the design system decides how strong the tint + /// of each is. The lines follow the reader's edits like every other decoration. + pub fn line_background(version: u32, line_start: u32, line_end: u32, color: ColorRole) -> Self { + Self { + version, + kind: DecorationKind::LineBackground, + severity: None, + color: Some(color), + range: CodeRange::of(line_start, 0, line_end, 0), + id: 0, + text: String::new(), + } + } + + /// A tint over the characters of `range`, stronger than a line background in the same + /// role, for the part of a changed line that changed. + pub fn range_background(version: u32, range: CodeRange, color: ColorRole) -> Self { + Self { + version, + kind: DecorationKind::RangeBackground, + severity: None, + color: Some(color), + range, + id: 0, + text: String::new(), + } + } + /// Draws an underline in this role rather than the one the design system would pick. pub fn with_color(mut self, role: ColorRole) -> Self { self.color = Some(role); diff --git a/compose-rust/src/codegen.rs b/compose-rust/src/codegen.rs index f3f6cf553..b0613907d 100644 --- a/compose-rust/src/codegen.rs +++ b/compose-rust/src/codegen.rs @@ -2803,7 +2803,8 @@ pub fn spans_vector() -> crate::spans::TextSpans { /// is one a byte count or a character count would get wrong. pub const CODE_VECTOR_TEXT: &str = "fn main() {\n let 한 = \"😀\";\n}\n"; -/// One decoration of each kind, with a colour role on one of them and text on two. +/// One decoration of each kind, with a colour role on one of them and text on two, and the +/// two backgrounds after them. fn code_decoration_vector() -> crate::code::Decorations { use crate::code::{CodeRange, Decoration, Position}; use crate::schema::Severity; @@ -2813,6 +2814,8 @@ fn code_decoration_vector() -> crate::code::Decorations { Decoration::code_lens(0, 0, "Run", 41), Decoration::hover_anchor(0, CodeRange::of(0, 3, 0, 7), 42), Decoration::ghost_text(0, Position::new(2, 1), " // end", 43), + Decoration::line_background(0, 1, 2, ColorRole::DiffAdded), + Decoration::range_background(0, CodeRange::of(1, 8, 1, 9), ColorRole::DiffAdded), ]) } diff --git a/compose-rust/src/schema.rs b/compose-rust/src/schema.rs index a8ef5e5fc..b63b61e7b 100644 --- a/compose-rust/src/schema.rs +++ b/compose-rust/src/schema.rs @@ -1151,15 +1151,19 @@ define_wire_enum!(SLOT_ROLE_SCHEMA, SlotRole { Content = 4, }); -// What a code editor decoration is. Four kinds and no more: a mark under a range, a line of -// text above a line, a range that answers a resting pointer, and a suggestion shown in -// place. Each is what a language server or an extension host already speaks in, so an -// application can pass its answers through without inventing a fifth. +// What a code editor decoration is: a mark under a range, a line of text above a line, a +// range that answers a resting pointer, and a suggestion shown in place. Each is what a +// language server or an extension host already speaks in, so an application can pass its +// answers through without inventing its own. After them, the two backgrounds a diff view +// is drawn with: a tint across whole lines, the width of the editor, and a stronger one +// over the characters that changed. Values are only appended. define_wire_enum!(DECORATION_KIND_SCHEMA, DecorationKind { Underline = 1, CodeLens = 2, HoverAnchor = 3, GhostText = 4, + LineBackground = 5, + RangeBackground = 6, }); // How serious an underlined diagnostic is. The four a language server reports, in its diff --git a/compose-rust/tests/code_editor.rs b/compose-rust/tests/code_editor.rs index 9d8a7aeec..126cc85c6 100644 --- a/compose-rust/tests/code_editor.rs +++ b/compose-rust/tests/code_editor.rs @@ -1378,3 +1378,47 @@ fn fr38_editor_pointer_reports_text_position_on_the_wire() { .unwrap(); assert_eq!(&events[1519..1599], expected.as_slice()); } + +/// The two backgrounds are decoration kinds 5 and 6, after the four there were, in the +/// same 44 byte record: lines as a range from the start of the first to the start of the +/// last, characters as an ordinary range, each with the role it is tinted in. Read back, +/// they are what was written, and a list with the older kinds keeps its records. +#[test] +fn fr38_line_and_range_backgrounds_round_trip_on_the_wire() { + assert_eq!(DecorationKind::LineBackground as u16, 5); + assert_eq!(DecorationKind::RangeBackground as u16, 6); + let line = Decoration::line_background(3, 4, 6, ColorRole::DiffAdded); + let range = Decoration::range_background(3, CodeRange::of(5, 2, 5, 9), ColorRole::DiffRemoved); + assert_eq!(line.range, CodeRange::of(4, 0, 6, 0)); + assert_eq!(line.color, Some(ColorRole::DiffAdded)); + assert_eq!(range.color, Some(ColorRole::DiffRemoved)); + let lens = Decoration::code_lens(3, 0, "Run", 41); + let list = Decorations::new([lens.clone(), line.clone(), range.clone()]); + assert_eq!(list.as_bytes().len(), 3 * DECORATION_LEN + "Run".len()); + let record = &list.as_bytes()[DECORATION_LEN..2 * DECORATION_LEN]; + assert_eq!(u16::from_le_bytes([record[4], record[5]]), 5); + assert_eq!( + u16::from_le_bytes([record[8], record[9]]), + ColorRole::DiffAdded as u16 + ); + assert_eq!(list.decorations(), vec![lens, line, range]); + + // In a batch the blob travels as it was written. + let mut encoder = BatchEncoder::default(); + encoder + .encode(&Mutation::SetProp { + node_id: 2, + property: PropertyKind::Decorations, + value: PropertyValue::Bytes(list.as_bytes()), + }) + .unwrap(); + let batch = encoder.finish().unwrap().to_vec(); + assert_eq!( + records(&batch), + vec![Record::Prop( + 2, + PropertyKind::Decorations, + Value::Bytes(list.as_bytes().to_vec()) + )] + ); +} diff --git a/compose-rust/tests/vectors/mutations.bin b/compose-rust/tests/vectors/mutations.bin index eaa243112fbc4e07b8b9e4b0568633d8c4d146b8..1a674ca7fb116d3cb0b3bb7471db42c723d2671a 100644 GIT binary patch delta 378 zcmXw#ze)o^5XNUVckwj3_eb~khzJ@GArb$9onWDYg_T$d3KrU2D`~W_vs4(tO2`Wc zLLyq&_yk(|2&n`gK=9j@8yJ4G-#0V2w=c^#D^I)HWK2F36*P|OltQ|cBi%8BoG5@& zIVGG|dC-=>Be2PXXP8G11t4pi4SEx z`QS4N(@idAC*7Jau_eLe1?aAE4Nib};4C-;bs&%F^!_`P1t>#s6#N0*#2orkqAP{E zhWv%@!qNSP^E3DXu|IP`q@l+}znPuaRK#*?+753(gJo#irh(TPaa#}}(tViaB%hSe aC|IrD&bjr<1tTN|{q+DJzPE4l9{&NHZZP5i delta 304 zcmeA-*sj09gHLo90|YQJNHFjKnW+q{3@Vdj`Lso2#26S@fFdxNY@kfSUuOxK~sEiBA5D_4II#B5ovB`1#VoYzuCYSM-F?|u6{0_+bBQ}{$K#!4W zvZ=s%M!w0cg7%EUlU)U!RfWYF7zBVim4P(K8Tvq)7f9OxX$2rH3lxo+yjD;;C=)26 z4iuRHq&b1~Odt)?p$Jqb$iUFR1Y|P<@lv2T2!LpiH$d`2KzSAhMlgRRP@E4azFmB? llu!vX(*}mg6GXK@)E*$UnPKt^Q7zWZKn3iZ^Tif00szgzFns_3 diff --git a/compose-rust/tests/vectors/vectors.json b/compose-rust/tests/vectors/vectors.json index 66526af3e..79d04bf03 100644 --- a/compose-rust/tests/vectors/vectors.json +++ b/compose-rust/tests/vectors/vectors.json @@ -1,6 +1,6 @@ { "format": "compose-rust protocol vectors v1", - "schemaHashUnsigned": "10031041034248201123", + "schemaHashUnsigned": "17733553499715732965", "byteOrder": "little-endian", "mutations": { "file": "mutations.bin", diff --git a/renderer/desktop/src/devshell/DesignShowcase.kt b/renderer/desktop/src/devshell/DesignShowcase.kt index 21c7b2cb6..e5543d731 100644 --- a/renderer/desktop/src/devshell/DesignShowcase.kt +++ b/renderer/desktop/src/devshell/DesignShowcase.kt @@ -597,14 +597,17 @@ private fun codeShowcase(): CodeShowcase { range.forEach(spanBytes::putInt) spanBytes.putLong(roleBits(role)) } - // kind, severity, range, id, text - class Spec(val kind: Int, val severity: Int, val range: IntArray, val id: Long, val text: String) + // kind, severity, range, id, text, colour role (0 for the design system's) + class Spec(val kind: Int, val severity: Int, val range: IntArray, val id: Long, val text: String, val color: Int = 0) val specs = listOf( Spec(1, 2, runOf(2, "name}"), 0L, "").also { it.range[3] -= 1 }, Spec(2, 0, intArrayOf(1, 0, 1, 0), 1L, "Run"), Spec(2, 0, intArrayOf(1, 0, 1, 0), 2L, "1 reference"), Spec(3, 0, runOf(1, "greet"), 3L, ""), Spec(4, 0, intArrayOf(3, 1, 3, 1), 4L, "\n\ngreet(\"world\");"), + // The line a diff added, and the words in it that changed. + Spec(5, 0, intArrayOf(2, 0, 2, 0), 0L, "", ColorRole.DiffAdded.ordinal + 1), + Spec(6, 0, runOf(2, "Hello"), 0L, "", ColorRole.DiffAdded.ordinal + 1), ) val texts = specs.map { it.text.toByteArray(Charsets.UTF_8) } val recordsLength = specs.size * 44 @@ -615,7 +618,7 @@ private fun codeShowcase(): CodeShowcase { decorationBytes.putInt(0) decorationBytes.putShort(spec.kind.toShort()) decorationBytes.putShort(spec.severity.toShort()) - decorationBytes.putShort(0) + decorationBytes.putShort(spec.color.toShort()) decorationBytes.putShort(0) spec.range.forEach(decorationBytes::putInt) decorationBytes.putLong(spec.id) diff --git a/renderer/desktop/src/protocol/Protocol.gen.kt b/renderer/desktop/src/protocol/Protocol.gen.kt index abd9815ef..777fe367a 100644 --- a/renderer/desktop/src/protocol/Protocol.gen.kt +++ b/renderer/desktop/src/protocol/Protocol.gen.kt @@ -94,7 +94,7 @@ enum class AnimationEventKind { Ready, Active, Iteration, End } enum class ReducedMotion { Off, On, Unknown } -enum class DecorationKind { Underline, CodeLens, HoverAnchor, GhostText } +enum class DecorationKind { Underline, CodeLens, HoverAnchor, GhostText, LineBackground, RangeBackground } enum class Severity { Error, Warning, Information, Hint } @@ -875,6 +875,8 @@ object CodeEditorRecords { 2 -> DecorationKind.CodeLens 3 -> DecorationKind.HoverAnchor 4 -> DecorationKind.GhostText + 5 -> DecorationKind.LineBackground + 6 -> DecorationKind.RangeBackground else -> null } @@ -1607,7 +1609,7 @@ class ProtocolException(message: String, val offset: Int) : IllegalArgumentException("$message at byte offset $offset") object Protocol { - const val SCHEMA_HASH: Long = -8415703039461350493L + const val SCHEMA_HASH: Long = -713190573993818651L const val PROTOCOL_VERSION: Int = 1 private const val TAG_ENVELOPE = 0 @@ -3352,6 +3354,8 @@ object Protocol { 2 -> DecorationKind.CodeLens 3 -> DecorationKind.HoverAnchor 4 -> DecorationKind.GhostText + 5 -> DecorationKind.LineBackground + 6 -> DecorationKind.RangeBackground else -> throw ProtocolException("unknown DecorationKind tag $tag", offset) } diff --git a/renderer/desktop/src/renderer/CodeEditorModel.kt b/renderer/desktop/src/renderer/CodeEditorModel.kt index 5566728f2..0ff79d569 100644 --- a/renderer/desktop/src/renderer/CodeEditorModel.kt +++ b/renderer/desktop/src/renderer/CodeEditorModel.kt @@ -46,6 +46,10 @@ class LiveDecoration( val text: String, ) +/** Whether this is one of the two tints drawn behind the text. */ +val LiveDecoration.isBackground: Boolean + get() = kind == DecorationKind.LineBackground || kind == DecorationKind.RangeBackground + /** * One stretch of lines that can be folded, as it stands in the current version of the * document. Folding keeps [startLine] and hides the lines after it up to [endLine]. @@ -334,6 +338,7 @@ class CodeEditorModel( if (document.contentEquals(text)) return false document.reset(text) decorationList.clear() + backgroundsPresent = false spanList.clear() longestSpanLines = 0 undoStack.clear() @@ -352,6 +357,28 @@ class CodeEditorModel( fun setDecorations(records: List) { decorationList.clear() for (record in records) { + if (record.kind == DecorationKind.LineBackground) { + // Whole lines, the first to the last, kept as the start of each. They are + // followed to where they are now as lines, the way a gutter mark's line is. + val color = record.color ?: run { + output += EditorOutput.Error( + "a line background on lines ${record.startLine} to ${record.endLine} names no colour", + ) + continue + } + val (first, last) = followLines(record.version, record.startLine, record.endLine, "a line background") + ?: continue + decorationList += LiveDecoration( + record.kind, + null, + color, + CodePosition(first, 0), + CodePosition(last, 0), + record.id, + "", + ) + continue + } val range = follow(record.version, record.startLine, record.startColumn, record.endLine, record.endColumn) ?: continue val (start, end) = range @@ -374,11 +401,25 @@ class CodeEditorModel( ) DecorationKind.HoverAnchor -> LiveDecoration(record.kind, null, null, start, end, record.id, "") + // Taken above. + DecorationKind.LineBackground -> continue + DecorationKind.RangeBackground -> { + val color = record.color ?: run { + output += EditorOutput.Error("a range background from $start to $end names no colour") + continue + } + LiveDecoration(record.kind, null, color, start, end, record.id, "") + } } } + backgroundsPresent = decorationList.any { it.isBackground } overlayRevision += 1 } + /** Whether any decoration is a line or a range background, so a frame without one skips them. */ + var backgroundsPresent = false + private set + /** Replaces every colour run with the Host's new list. */ fun setSyntaxSpans(records: List) { spanList.clear() @@ -542,6 +583,18 @@ class CodeEditorModel( (position < it.end || (it.start == it.end && position == it.start)) } + /** The line background of [line], the last one sent where several cover it, or null. */ + fun lineBackgroundAt(line: Int): LiveDecoration? { + if (!backgroundsPresent) return null + for (index in decorationList.indices.reversed()) { + val decoration = decorationList[index] + if (decoration.kind == DecorationKind.LineBackground && decoration.start.line <= line && line <= decoration.end.line) { + return decoration + } + } + return null + } + /** The lenses, grouped by the line they sit above, in line order. */ fun lensesByLine(): List>> = decorationList .filter { it.kind == DecorationKind.CodeLens } @@ -1146,6 +1199,23 @@ class CodeEditorModel( val iterator = decorationList.iterator() while (iterator.hasNext()) { val decoration = iterator.next() + if (decoration.kind == DecorationKind.LineBackground) { + // Lines rather than a stretch of text: a line typed in front of them + // pushes them down, and they go only when every one of them is deleted. + val lines = CodeDocument.mapRange( + CodePosition(decoration.start.line, 0), + CodePosition(decoration.end.line + 1, 0), + change, + ) + val last = lines?.let { if (it.second.column == 0) it.second.line - 1 else it.second.line } + if (lines == null || last == null || last < lines.first.line) { + iterator.remove() + } else { + decoration.start = CodePosition(lines.first.line, 0) + decoration.end = CodePosition(minOf(last, document.lineCount - 1), 0) + } + continue + } val range = CodeDocument.mapRange(decoration.start, decoration.end, change) if (range == null) { iterator.remove() diff --git a/renderer/desktop/src/renderer/CodeEditorSurface.kt b/renderer/desktop/src/renderer/CodeEditorSurface.kt index e398abcbf..0b5ed6239 100644 --- a/renderer/desktop/src/renderer/CodeEditorSurface.kt +++ b/renderer/desktop/src/renderer/CodeEditorSurface.kt @@ -195,6 +195,13 @@ class CodeEditorLook( * set in the design system's face. */ val fontFallback: ((String) -> List>)? = null, + /** + * The tint a line background in a role is drawn with, across the editor's width and + * past the end of the line. Unspecified draws nothing. + */ + val lineBackground: (ColorRole) -> Color = { Color.Unspecified }, + /** The stronger tint a range background in a role is drawn with over its characters. */ + val rangeBackground: (ColorRole) -> Color = { Color.Unspecified }, ) /** @@ -1160,6 +1167,7 @@ private fun FieldSurface( .drawBehind { translate(top = -vertical.offset.toFloat()) { drawCurrentLine(window, rows, rowPx, look) + drawLineBackgrounds(model, rows, rowPx, vertical.offset, viewportHeight, 0f, look) } // Read so that typing, a move of the caret and a scroll along the // lines all draw this again, and the caret is reported from here. @@ -1576,6 +1584,33 @@ internal fun HoverReport(tracker: HoverTracker, delayMillis: Long, callbacks: Co } } +/** + * The line backgrounds of the lines on screen, from [left] to the right edge whatever the + * length of the line, over the current line's band and behind everything else. + */ +internal fun DrawScope.drawLineBackgrounds( + model: CodeEditorModel, + rows: RowMap, + rowPx: Int, + scroll: Int, + viewportHeight: Int, + left: Float, + look: CodeEditorLook, +) { + model.overlayRevision + if (!model.backgroundsPresent) return + val first = rows.lineAtRow(scroll / rowPx) + val last = min(rows.lineCount - 1, rows.lineAtRow((scroll + viewportHeight) / rowPx + 1)) + for (line in first..last) { + if (rows.isHidden(line)) continue + val background = model.lineBackgroundAt(line) ?: continue + val color = look.lineBackground(background.color ?: continue) + if (color == Color.Unspecified || color.alpha == 0f) continue + val top = rows.textRow(line) * rowPx.toFloat() + drawRect(color, Offset(left, top), Size(size.width - left, rowPx.toFloat())) + } +} + /** The line the caret is on, across the whole width, behind the text. */ private fun DrawScope.drawCurrentLine(window: FieldWindow, rows: RowMap, rowPx: Int, look: CodeEditorLook) { window.revision @@ -1701,6 +1736,7 @@ private fun DrawScope.drawDecorations(window: FieldWindow, layout: TextLayoutRes model.overlayRevision window.revision val textLength = layout.layoutInput.text.length + if (model.backgroundsPresent) drawRangeBackgrounds(window, layout, look) for (decoration in model.decorations) { if (decoration.kind != DecorationKind.Underline) continue if (decoration.end.line < window.start || decoration.start.line >= window.end) continue @@ -1726,6 +1762,34 @@ private fun DrawScope.drawDecorations(window: FieldWindow, layout: TextLayoutRes } } +/** The range backgrounds over the characters they cover, in the field's own coordinates. */ +private fun DrawScope.drawRangeBackgrounds(window: FieldWindow, layout: TextLayoutResult, look: CodeEditorLook) { + val model = window.model + val textLength = layout.layoutInput.text.length + for (decoration in model.decorations) { + if (decoration.kind != DecorationKind.RangeBackground || decoration.start == decoration.end) continue + if (decoration.end.line < window.start || decoration.start.line >= window.end) continue + val color = look.rangeBackground(decoration.color ?: continue) + if (color == Color.Unspecified || color.alpha == 0f) continue + val from = window.toField(maxOf(decoration.start, CodePosition(window.start, 0))) ?: continue + val lastLine = window.end - 1 + val to = window.toField(minOf(decoration.end, CodePosition(lastLine, model.document.line(lastLine).length))) + ?: continue + val shownFrom = window.toShown(from, asEnd = false).coerceIn(0, textLength) + val shownTo = window.toShown(to, asEnd = true).coerceIn(0, textLength) + if (shownTo <= shownFrom) continue + val firstLine = layout.getLineForOffset(shownFrom) + val lastShownLine = layout.getLineForOffset(shownTo) + for (line in firstLine..lastShownLine) { + val left = if (line == firstLine) layout.getHorizontalPosition(shownFrom, true) else layout.getLineLeft(line) + val right = if (line == lastShownLine) layout.getHorizontalPosition(shownTo, true) else layout.getLineRight(line) + if (right <= left) continue + val top = layout.getLineTop(line) + drawRect(color, Offset(left, top), Size(right - left, layout.getLineBottom(line) - top)) + } + } +} + internal fun DrawScope.drawUnderline(shape: UnderlineShape, color: Color, left: Float, right: Float, y: Float, stroke: Float) { when (shape) { UnderlineShape.Straight -> drawLine(color, Offset(left, y), Offset(right, y), stroke) diff --git a/renderer/desktop/src/renderer/DrawnCodeEditor.kt b/renderer/desktop/src/renderer/DrawnCodeEditor.kt index 77070fb3f..1d4ab809b 100644 --- a/renderer/desktop/src/renderer/DrawnCodeEditor.kt +++ b/renderer/desktop/src/renderer/DrawnCodeEditor.kt @@ -30,6 +30,7 @@ import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEvent @@ -576,6 +577,22 @@ private fun DrawScope.drawLines( if (line == selection.caret.line && selection.collapsed && look.currentLine.alpha > 0f) { drawRect(look.currentLine, Offset(gutterWidth, top), Size(size.width - gutterWidth, rowPx)) } + // A line background across the text's whole width, then the stronger tint of a range + // background over its characters, both behind the selection and the text. + if (model.backgroundsPresent) { + model.lineBackgroundAt(line)?.color?.let(look.lineBackground) + ?.takeIf { it != Color.Unspecified && it.alpha > 0f } + ?.let { drawRect(it, Offset(gutterWidth, top), Size(size.width - gutterWidth, rowPx)) } + for (decoration in model.decorations) { + if (decoration.kind != DecorationKind.RangeBackground) continue + if (line < decoration.start.line || line > decoration.end.line) continue + val color = look.rangeBackground(decoration.color ?: continue) + if (color == Color.Unspecified || color.alpha == 0f) continue + val from = if (line == decoration.start.line) view.charX(decoration.start.column) else 0f + val to = if (line == decoration.end.line) view.caretX(decoration.end.column) else view.layout.size.width.toFloat() + if (to > from) drawRect(color, Offset(state.textLeft + from, top), Size(to - from, rowPx)) + } + } lenses[line]?.let { row -> val label = state.measurer!!.measure(row.joinToString(" | ") { it.text }, state.style.copy(color = look.lens)) drawText(label, topLeft = Offset(state.textLeft, top - rowPx)) diff --git a/renderer/desktop/src/renderer/HostCodeEditor.kt b/renderer/desktop/src/renderer/HostCodeEditor.kt index 9567c510a..54238a772 100644 --- a/renderer/desktop/src/renderer/HostCodeEditor.kt +++ b/renderer/desktop/src/renderer/HostCodeEditor.kt @@ -6,6 +6,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.type @@ -20,6 +21,7 @@ import dev.darkpyonix.composerust.foundation.code.CodeEditorSurface import dev.darkpyonix.composerust.foundation.code.EditorOutput import dev.darkpyonix.composerust.foundation.code.EditorScroll import dev.darkpyonix.composerust.protocol.CodeEditorColorsRecord +import dev.darkpyonix.composerust.protocol.ColorRole import dev.darkpyonix.composerust.protocol.CodeEditorRecords import dev.darkpyonix.composerust.protocol.FontRefRecords import dev.darkpyonix.composerust.protocol.HostEvent @@ -249,9 +251,38 @@ internal fun codeEditorLook( lineNumbers = node.flag(PropertyKind.LineNumbers, default = true), gutterMinWidth = node.lengthOrNull(PropertyKind.GutterMinWidthDp) ?: 0.dp, fontFallback = fontChain?.let { chain -> { text: String -> chain.spans(text) } }, + lineBackground = { role -> diffTint(role, theme, strong = false) }, + rangeBackground = { role -> diffTint(role, theme, strong = true) }, ) } +/** + * What a line background ([strong] false) or a range background ([strong] true) in a role + * is drawn with. An added or a removed line takes the design system's container tint for + * it and the changed characters its emphasis tint, the same pair a diff badge uses. A role + * that is already one of those tints is drawn as it is. Any other role is laid over the + * text as a wash, light enough that the code stays readable. + */ +internal fun diffTint(role: ColorRole, theme: ResolvedTheme, strong: Boolean): Color = when (role) { + ColorRole.DiffAdded -> theme.color(if (strong) ColorRole.DiffAddedEmphasis else ColorRole.DiffAddedContainer) + ColorRole.DiffRemoved -> theme.color(if (strong) ColorRole.DiffRemovedEmphasis else ColorRole.DiffRemovedContainer) + ColorRole.DiffAddedContainer, + ColorRole.DiffRemovedContainer, + ColorRole.DiffAddedEmphasis, + ColorRole.DiffRemovedEmphasis, + -> theme.color(role) + else -> theme.color(role).let { ink -> + // The same strengths the container and the emphasis tints are mixed at. + val wash = when { + strong && theme.dark -> 0.40f + strong -> 0.30f + theme.dark -> 0.20f + else -> 0.12f + } + ink.copy(alpha = ink.alpha * wash) + } +} + /** * Turns what an editor's model queued into events for the Host, in the order it was queued. * diff --git a/renderer/desktop/test/CodeEditorBackgroundTest.kt b/renderer/desktop/test/CodeEditorBackgroundTest.kt new file mode 100644 index 000000000..e2c090382 --- /dev/null +++ b/renderer/desktop/test/CodeEditorBackgroundTest.kt @@ -0,0 +1,271 @@ +package dev.darkpyonix.composerust.test + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.PixelMap +import androidx.compose.ui.graphics.toPixelMap +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.captureToImage +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.runComposeUiTest +import androidx.compose.ui.unit.Density +import dev.darkpyonix.composerust.foundation.code.CodeEditorModel +import dev.darkpyonix.composerust.foundation.code.CodeEditorPath +import dev.darkpyonix.composerust.foundation.code.CodePosition +import dev.darkpyonix.composerust.foundation.code.EditOrigin +import dev.darkpyonix.composerust.foundation.code.defaultCodeEditorPath +import dev.darkpyonix.composerust.foundation.code.installDrawnCodeEditor +import dev.darkpyonix.composerust.protocol.ColorRole +import dev.darkpyonix.composerust.protocol.ColorScheme +import dev.darkpyonix.composerust.protocol.DecorationKind +import dev.darkpyonix.composerust.protocol.DecorationRecord +import dev.darkpyonix.composerust.protocol.DesignSystem +import dev.darkpyonix.composerust.protocol.HostEvent +import dev.darkpyonix.composerust.protocol.Modifier as ProtocolModifier +import dev.darkpyonix.composerust.protocol.Mutation +import dev.darkpyonix.composerust.protocol.Paint +import dev.darkpyonix.composerust.protocol.PropertyKind +import dev.darkpyonix.composerust.protocol.PropertyValue +import dev.darkpyonix.composerust.protocol.Theme +import dev.darkpyonix.composerust.protocol.WidgetKind +import dev.darkpyonix.composerust.runtime.ComposeRustContent +import dev.darkpyonix.composerust.runtime.ComposeRustHost +import dev.darkpyonix.composerust.runtime.rememberComposeRustHost +import dev.darkpyonix.composerust.tooling.FakeHostConnection +import dev.darkpyonix.composerust.ui.node.NodeTable +import dev.darkpyonix.composerust.ui.node.TableError +import dev.darkpyonix.composerust.ui.node.nodeTestTag +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.roundToInt +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +private const val EDITOR = 2 +private const val BOX = 3 + +/** The wire tags of the kinds and the role the test sends. */ +private const val LINE_BACKGROUND = 5 +private const val RANGE_BACKGROUND = 6 +private val DIFF_ADDED = ColorRole.DiffAdded.ordinal + 1 + +/** + * Decoration records as the Rust schema lays them out: version, kind, severity, colour + * role, reserved, the range, the id, and an empty text pointing at the end of the records. + */ +private fun backgrounds(vararg records: IntArray): ByteArray { + val buffer = ByteBuffer.allocate(records.size * 44).order(ByteOrder.LITTLE_ENDIAN) + for (record in records) { + val (kind, color) = record[0] to record[1] + buffer.putInt(0).putShort(kind.toShort()).putShort(0).putShort(color.toShort()).putShort(0) + for (index in 2 until 6) buffer.putInt(record[index]) + buffer.putLong(0L).putInt(records.size * 44).putInt(0) + } + return buffer.array() +} + +private fun lineBackground(first: Int, last: Int, color: Int = DIFF_ADDED) = + intArrayOf(LINE_BACKGROUND, color, first, 0, last, 0) + +private fun rangeBackground(line: Int, from: Int, to: Int, color: Int = DIFF_ADDED) = + intArrayOf(RANGE_BACKGROUND, color, line, from, line, to) + +private fun theme() = Mutation.SetTheme(Theme(DesignSystem.Material3, DesignSystem.Material3, ColorScheme.Light, false)) + +/** An editor alone on the page, 320 by 160 dp, with the records the test adds after it. */ +private fun page(text: String, vararg extra: Mutation): List = buildList { + add(theme()) + add(Mutation.Create(EDITOR, WidgetKind.CodeEditor)) + add(Mutation.SetModifier(EDITOR, 0, ProtocolModifier.Size(320f, 160f))) + add(Mutation.SetProp(EDITOR, PropertyKind.Text, PropertyValue.Text(text))) + addAll(extra) +} + +/** + * Criterion 22 of the code editor: a line background tints whole lines, past their end, + * and follows them through edits, and a range background tints only its characters, more + * strongly. Each runs on the field path and on the drawn path. + */ +@OptIn(ExperimentalTestApi::class) +class CodeEditorBackgroundTest { + @AfterTest + fun windowedPath() { + defaultCodeEditorPath = CodeEditorPath.Windowed + } + + private fun ComposeUiTest.show(connection: FakeHostConnection): () -> ComposeRustHost { + lateinit var host: ComposeRustHost + setContent { + CompositionLocalProvider(LocalDensity provides Density(1f)) { + host = rememberComposeRustHost(connection) + ComposeRustContent(host) + } + } + waitForIdle() + return { host } + } + + /** What the theme draws a role as, read from a box painted with it. */ + private fun roleColor(role: ColorRole): Color { + var seen = Color.Unspecified + runComposeUiTest { + val connection = FakeHostConnection( + listOf( + theme(), + Mutation.Create(BOX, WidgetKind.Box), + Mutation.SetModifier(BOX, 0, ProtocolModifier.Size(20f, 20f)), + Mutation.SetModifier(BOX, 1, ProtocolModifier.Background(Paint.Role(role))), + ), + ) + show(connection) + seen = onNodeWithTag(nodeTestTag(BOX)).captureToImage().toPixelMap()[10, 10] + } + return seen + } + + /** The picture of the editor, and where a caret at a position is in it, in its pixels. */ + private fun ComposeUiTest.picture(): PixelMap = onNodeWithTag(nodeTestTag(EDITOR)).captureToImage().toPixelMap() + + private fun ComposeUiTest.placeOf(connection: FakeHostConnection, host: () -> ComposeRustHost, request: Int, line: Int, column: Int): Pair { + connection.scheduleFrame(listOf(Mutation.QueryPositionRect(EDITOR, request, line, column))) + host().renderFrame(0L) + waitForIdle() + val rect = connection.nodeEvents.filterIsInstance().single { it.request == request } + assertTrue(rect.found, "line $line, column $column is on screen") + val origin = onNodeWithTag(nodeTestTag(EDITOR)).fetchSemanticsNode().positionInRoot + return (rect.x - origin.x).roundToInt() to (rect.y - origin.y).roundToInt() + } + + /** + * Criterion 22.1. A `DiffAdded` line background on the second line paints it from the + * text's left edge to the editor's right edge, far past its last character, and no + * other line. A line typed in front of it moves it down with its line. + */ + @Test + fun fr38_line_background_spans_the_width_and_follows_edits() { + installDrawnCodeEditor() + val tint = roleColor(ColorRole.DiffAddedContainer) + for (path in listOf(CodeEditorPath.Windowed, CodeEditorPath.Drawn)) { + defaultCodeEditorPath = path + runComposeUiTest { + val connection = FakeHostConnection( + page( + "a = 1;\nb = 2;\nc = 3;\nd = 4;", + Mutation.SetProp(EDITOR, PropertyKind.Decorations, PropertyValue.Bytes(backgrounds(lineBackground(1, 1)))), + ), + ) + val host = show(connection) + assertEquals(emptyList(), connection.events.filterIsInstance(), "$path") + val (textLeft, secondTop) = placeOf(connection, host, 1, 1, 0) + val (_, thirdTop) = placeOf(connection, host, 2, 2, 0) + val row = thirdTop - secondTop + assertTrue(row > 10, "$path: a row is $row pixels") + val before = picture() + val right = before.width - 3 + // Past the end of the line, at the right edge, and just inside the text area. + for (x in listOf(right, textLeft + 120, textLeft + 1)) { + assertEquals(tint, before[x, secondTop + 2], "$path: the second line at $x") + } + assertNotEquals(tint, before[right, thirdTop + row / 2], "$path: the third line is tinted") + assertNotEquals(tint, before[right, secondTop - row / 2], "$path: the first line is tinted") + + // A line typed in front of everything: the tint goes down with its line. + connection.scheduleFrame(listOf(Mutation.EditCode(EDITOR, 1, 0, 0, 0, 0, 0, "z = 0;\n"))) + host().renderFrame(0L) + waitForIdle() + val after = picture() + assertEquals(tint, after[right, thirdTop + row / 2], "$path: the tint did not follow its line down") + assertNotEquals(tint, after[right, secondTop + 2], "$path: the tint stayed on the line it left") + } + } + } + + /** + * Criterion 22.2. A range background over `value` paints those five characters in the + * stronger tint and nothing either side of them, on a line no other tint is on. + */ + @Test + fun fr38_range_background_paints_its_characters() { + installDrawnCodeEditor() + val strong = roleColor(ColorRole.DiffAddedEmphasis) + for (path in listOf(CodeEditorPath.Windowed, CodeEditorPath.Drawn)) { + defaultCodeEditorPath = path + runComposeUiTest { + val connection = FakeHostConnection( + page( + "// header\nlet value = 42;\n", + Mutation.SetProp(EDITOR, PropertyKind.Decorations, PropertyValue.Bytes(backgrounds(rangeBackground(1, 4, 9)))), + ), + ) + val host = show(connection) + assertEquals(emptyList(), connection.events.filterIsInstance(), "$path") + val (from, top) = placeOf(connection, host, 1, 1, 4) + val (to, _) = placeOf(connection, host, 2, 1, 9) + val (lineStart, _) = placeOf(connection, host, 3, 1, 0) + val pixels = picture() + // The top of the row, above the letters, is the tint and nothing else. + val y = top + 1 + for (x in listOf(from + 2, (from + to) / 2, to - 2)) { + assertEquals(strong, pixels[x, y], "$path: inside the range at $x") + } + for (x in listOf(lineStart + 2, from - 3, to + 3, pixels.width - 3)) { + assertNotEquals(strong, pixels[x, y], "$path: outside the range at $x") + } + } + } + } + + /** + * The two kinds through the model: lines follow edits as lines, a range as text, a + * background with no role is refused, and every edit that takes all of a range or every + * line of a background takes it away. + */ + @Test + fun fr38_line_and_range_backgrounds_follow_edits_in_the_model() { + val model = CodeEditorModel("a\nb\nc\nd") + model.setDecorations( + listOf( + DecorationRecord(0, DecorationKind.LineBackground, null, ColorRole.DiffAdded, 1, 0, 2, 0, 0L, ""), + DecorationRecord(0, DecorationKind.RangeBackground, null, ColorRole.DiffRemoved, 3, 0, 3, 1, 0L, ""), + DecorationRecord(0, DecorationKind.LineBackground, null, null, 0, 0, 0, 0, 0L, ""), + ), + ) + assertEquals(1, model.drainOutput().size, "a background with no colour is reported") + assertEquals(listOf(1, 2), (0..3).filter { model.lineBackgroundAt(it) != null }) + assertEquals(ColorRole.DiffAdded, model.lineBackgroundAt(1)?.color) + + // Typing inside the first tinted line keeps both lines tinted; a line before them + // moves them both. + model.edit(CodePosition(1, 1), CodePosition(1, 1), "x", EditOrigin.Typing) + assertEquals(listOf(1, 2), (0..3).filter { model.lineBackgroundAt(it) != null }) + model.edit(CodePosition(0, 0), CodePosition(0, 0), "new\n", EditOrigin.Reader) + assertEquals(listOf(2, 3), (0..4).filter { model.lineBackgroundAt(it) != null }) + val range = model.decorations.single { it.kind == DecorationKind.RangeBackground } + assertEquals(CodePosition(4, 0) to CodePosition(4, 1), range.start to range.end) + + // Deleting both tinted lines takes the background with them. + model.edit(CodePosition(2, 0), CodePosition(4, 0), "", EditOrigin.Reader) + assertNull((0..2).firstOrNull { model.lineBackgroundAt(it) != null }) + + // Through the interpreter, a list naming a role nobody knows is one error for that record. + val table = NodeTable() + table.apply(Mutation.Create(EDITOR, WidgetKind.CodeEditor)) + table.apply(Mutation.SetProp(EDITOR, PropertyKind.Text, PropertyValue.Text("a\nb"))) + table.drainErrors() + table.apply( + Mutation.SetProp( + EDITOR, + PropertyKind.Decorations, + PropertyValue.Bytes(backgrounds(lineBackground(0, 1), lineBackground(0, 0, color = 60_000))), + ), + ) + assertEquals(listOf(TableError.INVALID_CODE_EDIT), table.drainErrors().map { it.code }) + assertEquals(listOf(0, 1), (0..1).filter { table.node(EDITOR)!!.code!!.lineBackgroundAt(it) != null }) + } +} diff --git a/renderer/desktop/test/ProtocolVectorsTest.kt b/renderer/desktop/test/ProtocolVectorsTest.kt index e79e873ab..58681f557 100644 --- a/renderer/desktop/test/ProtocolVectorsTest.kt +++ b/renderer/desktop/test/ProtocolVectorsTest.kt @@ -908,6 +908,8 @@ class ProtocolVectorsTest { DecorationRecord(0, DecorationKind.CodeLens, null, null, 0, 0, 0, 0, 41L, "Run"), DecorationRecord(0, DecorationKind.HoverAnchor, null, null, 0, 3, 0, 7, 42L, ""), DecorationRecord(0, DecorationKind.GhostText, null, null, 2, 1, 2, 1, 43L, " // end"), + DecorationRecord(0, DecorationKind.LineBackground, null, ColorRole.DiffAdded, 1, 0, 2, 0, 0L, ""), + DecorationRecord(0, DecorationKind.RangeBackground, null, ColorRole.DiffAdded, 1, 8, 1, 9, 0L, ""), ), decorations, )