From 71697c42ce0c2a2ae2a2f64b6efedbc2f21e9fff Mon Sep 17 00:00:00 2001 From: DarkSky Date: Wed, 25 Nov 2026 23:09:41 +0900 Subject: [PATCH] feat(android): add StaticLayout selection gestures and Autofill buffer isolation Implement Android host selection, Autofill isolation, surface lifecycle, predictive back, and PDF rendering in packages/frontend/hosts/android. - Keep ShapedTextLayout as the single layout source across drag, cancel, and selectAll in SelectionGestureController. - Anchor vertical grab offsets to line midpoints and flip active_drag across the locked UTF-16 anchor. - Disambiguate mixed-direction run boundaries and orient same-line teardrop handles outward. - Route Autofill focus, exit, resize, and route changes through HostDocumentBufferController to keep form values separate. - Clear the default surface to 0xFFFA_FAFC with luminance-adaptive text colors. - Check ClipDescription metadata in AndroidClipboardAdapter.hasPlainText and cache paste state outside onDraw. - Add 26 Rust unit tests and 22 Kotlin JNI parity sequences. --- packages/frontend/hosts/android/AGENTS.md | 15 +- .../app/affine/pro/host/MainActivity.kt | 2174 ++++++++++++++++- .../frontend/hosts/android/src/autofill.rs | 463 ++++ packages/frontend/hosts/android/src/ime.rs | 109 + .../frontend/hosts/android/src/jni_bridge.rs | 10 +- .../hosts/android/src/jni_interaction.rs | 959 ++++++++ packages/frontend/hosts/android/src/lib.rs | 264 +- packages/frontend/hosts/android/src/pdf.rs | 243 ++ .../frontend/hosts/android/src/selection.rs | 870 +++++++ .../frontend/hosts/android/src/surface.rs | 147 +- .../frontend/hosts/android/src/text_layout.rs | 395 +++ .../hosts/android/tests/ImeHostParityCheck.kt | 942 ++++++- 12 files changed, 6534 insertions(+), 57 deletions(-) create mode 100644 packages/frontend/hosts/android/src/autofill.rs create mode 100644 packages/frontend/hosts/android/src/jni_interaction.rs create mode 100644 packages/frontend/hosts/android/src/pdf.rs create mode 100644 packages/frontend/hosts/android/src/selection.rs create mode 100644 packages/frontend/hosts/android/src/text_layout.rs diff --git a/packages/frontend/hosts/android/AGENTS.md b/packages/frontend/hosts/android/AGENTS.md index 811501ee91..c2bcdf28c4 100644 --- a/packages/frontend/hosts/android/AGENTS.md +++ b/packages/frontend/hosts/android/AGENTS.md @@ -6,9 +6,18 @@ It combines a hand-written JNI Rust crate with a minimal Kotlin `SurfaceView` ac ## Hard boundaries - Keep zero JNA and zero UniFFI bindings. - Export hand-written `extern "C"` JNI symbols under `#[cfg(any(target_os = "android", test, feature = "host-jni"))]`. + Export hand-written `extern "C"` JNI symbols under `#[cfg(any(target_os = "android", test, feature = "host-jni"))]` across `src/jni_bridge.rs`, `src/jni_interaction.rs`, and `src/jni_storage.rs`. - Keep the main app shell free of any persistent `WebView` and free of `SurfaceHolder.lockCanvas` calls. -- Gate `AutofillManager` integration at API 26 (`should_expose_autofill(sdk_int)` returns `sdk_int >= 26`). +- Use `ShapedTextLayout` (cached Android `StaticLayout` with UAX #9 first-strong BiDi) as the single authoritative layout engine for `HostTextPreviewView` (the transitional host preview layer before S4 shared editor integration), teardrop handle tips, hit-testing, and `AndroidSelectionOverlayView` (`src/text_layout.rs` is the headless pure-Rust fallback). + Compute teardrop handle geometry, line-midpoint grab-offset drag, UTF-16 anchor-authoritative handle ownership (`nativeApplyTextDragEndpoints`), continuous zero-length crossover inversion, off-screen hiding, line-midpoint magnifier focus, and Copy/Cut/Paste/SelectAll actions wired to `ClipboardManager` (`HostClipboard` / `AndroidClipboardAdapter`, checking `primaryClipDescription` metadata without reading `primaryClip` during draw, and writing before deleting on `Cut`) and `InputConnection.performContextMenuAction` in `src/selection.rs`, `src/ime.rs`, and `MainActivity.kt`. + `AndroidSelectionOverlayView` fills a pre-allocated 24-float JNI buffer (`nativeFillSelectionOverlayGeometry`) and draws teardrop `Path` handles, `getSelectionPath` loupe highlights with centered focus carets, and `Copy | Cut | Paste` pills with dividers using zero per-frame allocations, zero Binder IPC in `onDraw`, and zero `SurfaceHolder.lockCanvas` calls. +- Clear the default surface canvas to light `#FAFAFC` (`DEFAULT_CLEAR_COLOR_ARGB = 0xFFFA_FAFC`) and adapt `HostTextPreviewView` text and selection colors to surface luminance. + Preserve viewport size, display density, scroll offset, IME state, and texture generation across `surfaceDestroyed -> surfaceCreated -> surfaceChanged` recreation while gating `is_ready()` on per-generation `surfaceChanged` configuration (`configured_for_generation`). + `SurfaceLifecycleState` models `Vulkan -> Gles3 -> CpuFallback` downgrade on device loss; the current `android_window` runtime probe returns `(false, true)` and starts on EGL/GLES3 with CPU fallback. +- Gate `AutofillManager` virtual view structure and per-field isolated value write-back at API 26 (`should_expose_autofill(sdk_int)` returns `sdk_int >= 26`, `IMPORTANT_FOR_AUTOFILL_YES` on `AffineSurfaceView`, implemented in `src/autofill.rs` and `AndroidAutofillController`). + Never emit synthetic placeholder asterisks or spaces in `ViewStructure`, update IME only when `autofillId == focusedFieldId`, sync manual `InputConnection` edits back to the focused Autofill field via `onFocusedTextEdited`, isolate form credentials from `HostDocumentStore` and `HostTextPreviewView` via `HostDocumentBufferController`, redact sensitive values in `Debug`, and zero cached plaintext on `commit`, `cancel`, and `clear_fields`. +- Dispatch four-phase predictive back (`Start`, `Progress`, `Cancel`, `Commit`) on API 34+ (`OnBackAnimationCallback`, including standalone button/key `onBackInvoked` calls) and single-step atomic commit on API 24-33 (`OnBackInvokedCallback` / `onBackPressed`) against a real destination route stack (`BackNavigationState`) and `HostDocumentStore` driven by `MainActivity.navigateTo` and `MainActivity.openDocument`, blocking re-entrant commits and returning `false` at the root route. +- Render PDF pages in place through `android.graphics.pdf.PdfRenderer` (`AndroidPdfPageRenderer`) with pre-validated Rust bounds, OOM cap (`4096x4096`), clamped `dpi_bucket >= 72` cache keys, and zero-Rust-heap chunked streaming `ARGB_8888 -> RGBA8` conversion with per-call JNI `ExceptionCheck` in `src/pdf.rs` and `src/jni_interaction.rs`. - Open in-place SQLite WAL databases only from the ordered `affine-local-workspace` allowlist. Never scan disk `*.db` files to discover local workspaces. - Store auth sessions in `/datastore/auth-sessions.preferences_pb` using `v1::` AES-GCM envelopes, 1970 Unix millisecond `i64` timestamps, and the persisted `auth-installation-id` key. @@ -27,7 +36,7 @@ CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p affine-android-host --target CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p affine-android-host --target x86_64-linux-android ``` -To run the real Kotlin-to-JNI parity harness on a host with `kotlinc` and `ANDROID_HOME`: +To run the 22-sequence Kotlin-to-JNI parity harness on a host with `kotlinc` and `ANDROID_HOME`: ```sh kotlinc -classpath "$ANDROID_JAR" -d /tmp/affine-android-kotlin \ diff --git a/packages/frontend/hosts/android/kotlin/app/affine/pro/host/MainActivity.kt b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/MainActivity.kt index b813a5ccec..20a6b3759b 100644 --- a/packages/frontend/hosts/android/kotlin/app/affine/pro/host/MainActivity.kt +++ b/packages/frontend/hosts/android/kotlin/app/affine/pro/host/MainActivity.kt @@ -1,20 +1,42 @@ package app.affine.pro.host +import android.annotation.TargetApi import android.app.Activity +import android.content.ClipData +import android.content.ClipDescription +import android.content.ClipboardManager import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Path +import android.graphics.Rect +import android.graphics.RectF +import android.graphics.pdf.PdfRenderer import android.os.Build import android.os.Bundle import android.os.Handler +import android.os.ParcelFileDescriptor import android.text.InputType +import android.text.Layout +import android.text.StaticLayout +import android.text.TextDirectionHeuristics +import android.text.TextPaint +import java.text.BreakIterator +import android.util.SparseArray import android.view.Choreographer import android.view.KeyEvent +import android.view.MotionEvent import android.view.Surface import android.view.SurfaceHolder import android.view.SurfaceView import android.view.View +import android.view.ViewStructure import android.view.WindowInsets import android.view.WindowInsetsAnimation import android.view.autofill.AutofillManager +import android.view.autofill.AutofillValue import android.view.inputmethod.CompletionInfo import android.view.inputmethod.CorrectionInfo import android.view.inputmethod.EditorInfo @@ -23,6 +45,7 @@ import android.view.inputmethod.ExtractedTextRequest import android.view.inputmethod.InputConnection import android.view.inputmethod.InputContentInfo import android.view.inputmethod.TextAttribute +import android.widget.FrameLayout import android.window.BackEvent import android.window.OnBackAnimationCallback import android.window.OnBackInvokedCallback @@ -151,6 +174,153 @@ object NativeBridge { external fun nativeExtractJsonStringField(json: String, field: String): String? external fun nativeJsonStringArrayLen(json: String): Int external fun nativeJsonStringArrayGet(json: String, index: Int): String? + + // Native selection teardrop handles, magnifier loupe, and context action menu. + external fun nativeSetSelectionViewport( + handle: Long, + width: Float, + height: Float, + density: Float, + ) + external fun nativeUpdateSelectionOverlay( + handle: Long, + startX: Float, + startY: Float, + endX: Float, + endY: Float, + lineHeight: Float, + directionCode: Int, + hasSelection: Boolean, + ) + external fun nativeApplyTextDragEndpoints( + handle: Long, + startX: Float, + startY: Float, + endX: Float, + endY: Float, + lineHeight: Float, + directionCode: Int, + activeHandleCode: Int, + ) + external fun nativeSelectionBeginDrag(handle: Long, touchX: Float, touchY: Float): Int + external fun nativeSelectionUpdateDrag(handle: Long, touchX: Float, touchY: Float): Boolean + external fun nativeSelectionEndDrag(handle: Long): Boolean + external fun nativeSelectionCancelDrag(handle: Long) + external fun nativeClearSelectionOverlay(handle: Long) + external fun nativeGetSelectionOverlayJson(handle: Long): String + external fun nativeGetSelectionOverlayGeometry(handle: Long): FloatArray? + external fun nativeFillSelectionOverlayGeometry(handle: Long, outBuffer: FloatArray): Boolean + + // Surface recreation state preservation, effective IME insets, and Vulkan -> GLES3 recovery. + external fun nativeSetSurfaceScrollOffset(handle: Long, scrollX: Float, scrollY: Float) + external fun nativeGetSurfaceScrollY(handle: Long): Float + external fun nativeGetSurfaceDensity(handle: Long): Float + external fun nativeGetTextureGeneration(handle: Long): Long + external fun nativeGetEffectiveImeBottomDp(handle: Long): Float + external fun nativeSelectRenderBackend( + handle: Long, + vulkanAvailable: Boolean, + gles3Available: Boolean, + ): Int + external fun nativeReportVulkanDeviceLost(handle: Long): Int + + // API 26+ AutofillManager virtual view structure and value write-back. + external fun nativeConfigureAutofillSdk(handle: Long, sdkInt: Int): Boolean + external fun nativeUpsertAutofillField( + handle: Long, + autofillId: Int, + kindCode: Int, + left: Int, + top: Int, + right: Int, + bottom: Int, + masked: Boolean, + valueLen: Int, + ): Boolean + external fun nativeFocusAutofillField(handle: Long, autofillId: Int): Int + external fun nativeGetFocusedAutofillFieldId(handle: Long): Int + external fun nativeSetAutofillFieldText(handle: Long, autofillId: Int, text: String): Boolean + external fun nativeApplyAutofillValue(handle: Long, autofillId: Int, value: String): Boolean + external fun nativeGetAutofillValue(handle: Long, autofillId: Int): String? + external fun nativeGetAutofillValueByKind(handle: Long, kindCode: Int): String? + external fun nativeCommitAutofill(handle: Long): Boolean + external fun nativeCancelAutofill(handle: Long): Boolean + external fun nativeClearAutofillFields(handle: Long) + external fun nativeGetAutofillStructureJson(handle: Long): String + + // Predictive back API-level dispatch and destination navigation stack. + external fun nativeBackDispatchMode(sdkInt: Int): Int + external fun nativePushDestination(handle: Long, route: String): Boolean + external fun nativeGetCurrentDestination(handle: Long): String? + external fun nativeSetBackStackDepth(handle: Long, depth: Int) + external fun nativeGetBackStackDepth(handle: Long): Int + + // Native PdfRenderer page validation, cache key, and ARGB_8888 -> RGBA8 conversion. + external fun nativeValidatePdfPageRequest( + pageIndex: Int, + pageCount: Int, + widthPx: Int, + heightPx: Int, + ): Boolean + external fun nativePdfPageCacheKey( + docId: String, + pageIndex: Int, + widthPx: Int, + heightPx: Int, + dpiBucket: Int, + ): String + external fun nativePdfConvertArgbToRgba( + argbPixels: IntArray, + widthPx: Int, + heightPx: Int, + ): ByteArray? +} + +/** + * Testable clipboard bridge wrapping Android `ClipboardManager` so `Copy`, `Cut`, + * and `Paste` interact with the system clipboard without losing text on `Cut`. + */ +interface HostClipboard { + fun setPlainText(label: String, text: String): Boolean + fun getPlainText(): String? + fun hasPlainText(): Boolean = !getPlainText().isNullOrEmpty() +} + +class AndroidClipboardAdapter( + private val manager: ClipboardManager?, +) : HostClipboard { + override fun setPlainText(label: String, text: String): Boolean { + val cm = manager ?: return false + return try { + cm.setPrimaryClip(ClipData.newPlainText(label, text)) + true + } catch (_: Throwable) { + false + } + } + + override fun getPlainText(): String? { + val cm = manager ?: return null + return try { + val clip = cm.primaryClip ?: return null + if (clip.itemCount <= 0) return null + clip.getItemAt(0)?.text?.toString() + } catch (_: Throwable) { + null + } + } + + override fun hasPlainText(): Boolean { + val cm = manager ?: return false + return try { + if (!cm.hasPrimaryClip()) return false + val desc = cm.primaryClipDescription ?: return false + desc.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN) || + desc.hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML) + } catch (_: Throwable) { + false + } + } } /** @@ -160,13 +330,19 @@ object NativeBridge { class AffineImeController( private val handleProvider: () -> Long, private val onMutated: () -> Unit, + private val onTextEdited: (String) -> Unit, ) { - constructor(handleProvider: () -> Long) : this(handleProvider, {}) + constructor(handleProvider: () -> Long) : this(handleProvider, {}, {}) + constructor(handleProvider: () -> Long, onMutated: () -> Unit) : this(handleProvider, onMutated, {}) + + fun currentText(): String = readText() + fun commitText(text: String, newCursorPosition: Int): Boolean { val handle = handleProvider() if (handle == 0L) return false NativeBridge.nativeOnCommitText(handle, text, newCursorPosition) onMutated() + onTextEdited(currentText()) return true } @@ -175,6 +351,7 @@ class AffineImeController( if (handle == 0L) return false NativeBridge.nativeOnSetComposingText(handle, text, newCursorPosition) onMutated() + onTextEdited(currentText()) return true } @@ -191,6 +368,7 @@ class AffineImeController( if (handle == 0L) return false NativeBridge.nativeOnFinishComposingText(handle) onMutated() + onTextEdited(currentText()) return true } @@ -207,6 +385,7 @@ class AffineImeController( if (handle == 0L || beforeLength < 0 || afterLength < 0) return false NativeBridge.nativeOnDeleteSurroundingText(handle, beforeLength, afterLength) onMutated() + onTextEdited(currentText()) return true } @@ -214,7 +393,10 @@ class AffineImeController( val handle = handleProvider() if (handle == 0L || beforeLength < 0 || afterLength < 0) return false val ok = NativeBridge.nativeOnDeleteSurroundingTextInCodePoints(handle, beforeLength, afterLength) - if (ok) onMutated() + if (ok) { + onMutated() + onTextEdited(currentText()) + } return ok } @@ -222,7 +404,10 @@ class AffineImeController( val handle = handleProvider() if (handle == 0L || start < 0 || end < 0) return false val ok = NativeBridge.nativeOnReplaceText(handle, start, end, text, newCursorPosition) - if (ok) onMutated() + if (ok) { + onMutated() + onTextEdited(currentText()) + } return ok } @@ -283,7 +468,10 @@ class AffineImeController( * Direct `InputConnection` implementation backed solely by `AffineImeController` * and Rust `AndroidHostState` with zero Kotlin `Editable` mirror buffer. */ -class AffineInputConnection(private val ime: AffineImeController) : InputConnection { +class AffineInputConnection( + private val ime: AffineImeController, + private val onContextMenuAction: (Int) -> Boolean = { false }, +) : InputConnection { private var batchEditDepth: Int = 0 override fun getTextBeforeCursor(n: Int, flags: Int): CharSequence = ime.getTextBeforeCursor(n) @@ -369,7 +557,13 @@ class AffineInputConnection(private val ime: AffineImeController) : InputConnect override fun performEditorAction(editorAction: Int): Boolean = false - override fun performContextMenuAction(id: Int): Boolean = false + override fun performContextMenuAction(id: Int): Boolean = when (id) { + android.R.id.copy, + android.R.id.cut, + android.R.id.paste, + android.R.id.selectAll -> onContextMenuAction(id) + else -> false + } override fun performPrivateCommand(action: String?, data: Bundle?): Boolean = false @@ -382,35 +576,1679 @@ class AffineInputConnection(private val ime: AffineImeController) : InputConnect override fun requestCursorUpdates(cursorUpdateMode: Int): Boolean = false } +/** + * Selection teardrop handle and magnifier coordinator backed by Rust + * `SelectionOverlayState` without touching `SurfaceHolder.lockCanvas`. + */ +class AndroidSelectionCoordinator( + private val handleProvider: () -> Long, + private val onMutated: () -> Unit = {}, +) { + fun setViewport(width: Float, height: Float, density: Float) { + val handle = handleProvider() + if (handle == 0L) return + NativeBridge.nativeSetSelectionViewport(handle, width, height, density) + onMutated() + } + + fun updateSelection( + startX: Float, + startY: Float, + endX: Float, + endY: Float, + lineHeight: Float, + rtl: Boolean = false, + hasSelection: Boolean = true, + ) { + val handle = handleProvider() + if (handle == 0L) return + NativeBridge.nativeUpdateSelectionOverlay( + handle, + startX, + startY, + endX, + endY, + lineHeight, + if (rtl) 1 else 0, + hasSelection, + ) + onMutated() + } + + fun applyTextDragEndpoints( + startX: Float, + startY: Float, + endX: Float, + endY: Float, + lineHeight: Float, + rtl: Boolean = false, + activeHandleCode: Int, + ) { + val handle = handleProvider() + if (handle == 0L) return + NativeBridge.nativeApplyTextDragEndpoints( + handle, + startX, + startY, + endX, + endY, + lineHeight, + if (rtl) 1 else 0, + activeHandleCode, + ) + onMutated() + } + + fun beginDrag(touchX: Float, touchY: Float): Int { + val handle = handleProvider() + if (handle == 0L) return 0 + val hit = NativeBridge.nativeSelectionBeginDrag(handle, touchX, touchY) + if (hit != 0) onMutated() + return hit + } + + fun updateDrag(touchX: Float, touchY: Float): Boolean { + val handle = handleProvider() + if (handle == 0L) return false + val moved = NativeBridge.nativeSelectionUpdateDrag(handle, touchX, touchY) + if (moved) onMutated() + return moved + } + + fun endDrag(): Boolean { + val handle = handleProvider() + if (handle == 0L) return false + val hasMenu = NativeBridge.nativeSelectionEndDrag(handle) + onMutated() + return hasMenu + } + + fun cancelDrag() { + val handle = handleProvider() + if (handle == 0L) return + NativeBridge.nativeSelectionCancelDrag(handle) + onMutated() + } + + fun clear() { + val handle = handleProvider() + if (handle == 0L) return + NativeBridge.nativeClearSelectionOverlay(handle) + onMutated() + } + + fun snapshotJson(): String { + val handle = handleProvider() + return if (handle == 0L) "{}" else NativeBridge.nativeGetSelectionOverlayJson(handle) + } + + fun overlayGeometry(): FloatArray? { + val handle = handleProvider() + return if (handle == 0L) null else NativeBridge.nativeGetSelectionOverlayGeometry(handle) + } + + fun fillOverlayGeometry(outBuffer: FloatArray): Boolean { + val handle = handleProvider() + if (handle == 0L || outBuffer.size < 24) return false + return NativeBridge.nativeFillSelectionOverlayGeometry(handle, outBuffer) + } + + fun performCopy(ime: AffineImeController, clipboard: HostClipboard): String? { + val selected = ime.getSelectedText() ?: return null + if (!clipboard.setPlainText("AFFiNE", selected)) { + return null + } + return selected + } + + fun performCut(ime: AffineImeController, clipboard: HostClipboard): String? { + val selected = ime.getSelectedText() ?: return null + // Always persist to the system clipboard BEFORE deleting text so Cut never loses content. + if (!clipboard.setPlainText("AFFiNE", selected)) { + return null + } + val start = ime.selectionStart() + val end = ime.selectionEnd() + if (start < end) { + ime.replaceText(start, end, "", 1) + onMutated() + } + return selected + } + + fun performPaste(ime: AffineImeController, clipboard: HostClipboard): String? { + val text = clipboard.getPlainText() ?: return null + val start = ime.selectionStart() + val end = ime.selectionEnd() + if (!ime.replaceText(start, end, text, 1)) { + return null + } + onMutated() + return text + } + + fun performSelectAll(ime: AffineImeController): Boolean { + val len = ime.currentText().length + if (len <= 0) return false + val ok = ime.setSelection(0, len) + if (ok) onMutated() + return ok + } + + fun handleContextMenuAction( + id: Int, + ime: AffineImeController, + clipboard: HostClipboard, + ): Boolean = when (id) { + android.R.id.copy -> performCopy(ime, clipboard) != null + android.R.id.cut -> performCut(ime, clipboard) != null + android.R.id.paste -> performPaste(ime, clipboard) != null + android.R.id.selectAll -> performSelectAll(ime) + else -> false + } +} + +/** + * Caret visual geometry in viewport pixels computed by Android `StaticLayout`. + */ +data class CaretBounds( + val x: Float, + val top: Float, + val bottom: Float, + val lineIndex: Int, + val isRtlParagraph: Boolean, +) { + val lineHeight: Float + get() = (bottom - top).coerceAtLeast(1f) + val midY: Float + get() = (top + bottom) * 0.5f +} + +/** + * Single authoritative text layout contract implemented by Android `ShapedTextLayout` + * (`StaticLayout`) on devices and deterministic proportional harnesses in JVM parity tests. + */ +interface TextLayoutAuthority { + val cachedText: String + fun ensureLayoutReady(text: String, viewportWidthPx: Int, density: Float): Boolean + fun caretBounds( + utf16Offset: Int, + isSelectionEnd: Boolean = false, + selStart: Int = utf16Offset, + selEnd: Int = utf16Offset, + ): CaretBounds? + fun selectionEndCarets(selStart: Int, selEnd: Int): Pair? + fun fillSelectionEndCarets(selStart: Int, selEnd: Int, out: FloatArray): Boolean { + val pair = selectionEndCarets(selStart, selEnd) ?: return false + val (startCaret, endCaret) = pair + out[0] = startCaret.x + out[1] = startCaret.bottom + out[2] = endCaret.x + out[3] = endCaret.bottom + out[4] = startCaret.lineHeight + out[5] = if (startCaret.isRtlParagraph) 1f else 0f + return true + } + fun closestOffset(x: Float, y: Float): Int + fun closestOffset(x: Float, y: Float, preferredOffset: Int): Int = closestOffset(x, y) +} + +/** + * Pure Kotlin handle-drag gesture controller that keeps `TextLayoutAuthority` + * (`ShapedTextLayout`) as the single source of truth across `ACTION_DOWN`, + * `ACTION_MOVE` (line-midpoint vertical probe + cross-anchor `active_drag` flip), + * `ACTION_UP`, and `ACTION_CANCEL` (never reverting to Rust fallback glyph widths). + */ +class SelectionGestureController( + private val coordinator: AndroidSelectionCoordinator, + private val layoutAuthority: TextLayoutAuthority, + private val selectionStartProvider: () -> Int, + private val selectionEndProvider: () -> Int, + private val onSelectionChanged: (Int, Int) -> Unit, + private val onOverlaySynced: () -> Unit = {}, +) { + private val geomBuf = FloatArray(24) + private val dragCaretsBuf = FloatArray(8) + var draggingHandle: Boolean = false + private set + private var dragAnchorOffset: Int = -1 + private var dragMovingOffset: Int = -1 + private var dragInitialHandle: Int = 0 + private var dragGrabDx: Float = 0f + private var dragGrabDy: Float = 0f + + fun syncSelectionFromLayout( + text: String, + selStart: Int, + selEnd: Int, + viewportWidthPx: Int, + density: Float, + ) { + val hasLayout = layoutAuthority.ensureLayoutReady(text, viewportWidthPx, density) + val lo = selStart.coerceIn(0, text.length) + val hi = selEnd.coerceIn(lo, text.length) + if (lo < hi && hasLayout) { + if (layoutAuthority.fillSelectionEndCarets(lo, hi, dragCaretsBuf)) { + coordinator.updateSelection( + startX = dragCaretsBuf[0], + startY = dragCaretsBuf[1], + endX = dragCaretsBuf[2], + endY = dragCaretsBuf[3], + lineHeight = dragCaretsBuf[4], + rtl = dragCaretsBuf[5] >= 0.5f, + hasSelection = true, + ) + } + } else if (!draggingHandle) { + coordinator.clear() + } + onOverlaySynced() + } + + fun onDown(x: Float, y: Float, density: Float): Int { + val hit = coordinator.beginDrag(x, y) + if (hit == 0) return 0 + draggingHandle = true + dragInitialHandle = hit + val selStart = selectionStartProvider() + val selEnd = selectionEndProvider() + dragAnchorOffset = if (hit == 1) selEnd else selStart + val grabbedOffset = if (hit == 1) selStart else selEnd + dragMovingOffset = grabbedOffset + val caret = layoutAuthority.caretBounds( + utf16Offset = grabbedOffset, + isSelectionEnd = hit == 2, + selStart = selStart, + selEnd = selEnd, + ) + if (caret != null) { + // Anchor vertical grab offset to the visual line's vertical midpoint (never getLineBottom), + // so multi-line line-0 handles never jump into line 1 on stationary or horizontal drags. + dragGrabDx = caret.x - x + dragGrabDy = caret.midY - y + } else if (coordinator.fillOverlayGeometry(geomBuf)) { + val ax = if (hit == 1) geomBuf[3] else geomBuf[9] + val tipY = if (hit == 1) geomBuf[4] else geomBuf[10] + val midY = tipY - 12f * density.coerceAtLeast(1f) + dragGrabDx = ax - x + dragGrabDy = midY - y + } + return hit + } + + fun onMove(x: Float, y: Float): Boolean { + if (!draggingHandle) return false + if (dragAnchorOffset >= 0 && layoutAuthority.cachedText.isNotEmpty()) { + val probeX = x + dragGrabDx + val probeY = y + dragGrabDy + val targetOff = layoutAuthority.closestOffset(probeX, probeY, dragMovingOffset) + dragMovingOffset = targetOff + val lo = minOf(dragAnchorOffset, targetOff) + val hi = maxOf(dragAnchorOffset, targetOff) + val activeHandleCode = when { + targetOff < dragAnchorOffset -> 1 + targetOff > dragAnchorOffset -> 2 + else -> dragInitialHandle + } + onSelectionChanged(lo, hi) + if (layoutAuthority.fillSelectionEndCarets(lo, hi, dragCaretsBuf)) { + coordinator.applyTextDragEndpoints( + startX = dragCaretsBuf[0], + startY = dragCaretsBuf[1], + endX = dragCaretsBuf[2], + endY = dragCaretsBuf[3], + lineHeight = dragCaretsBuf[4], + rtl = dragCaretsBuf[5] >= 0.5f, + activeHandleCode = activeHandleCode, + ) + return true + } + } + return coordinator.updateDrag(x, y) + } + + fun onUp(viewportWidthPx: Int, density: Float): Boolean { + if (!draggingHandle) return false + draggingHandle = false + dragAnchorOffset = -1 + dragMovingOffset = -1 + dragInitialHandle = 0 + val hasMenu = coordinator.endDrag() + // Re-apply authoritative layout coordinates so Rust end_drag fallback never overwrites them. + syncSelectionFromLayout( + layoutAuthority.cachedText, + selectionStartProvider(), + selectionEndProvider(), + viewportWidthPx, + density, + ) + return hasMenu + } + + fun onCancel(viewportWidthPx: Int, density: Float): Boolean { + if (!draggingHandle) return false + draggingHandle = false + dragAnchorOffset = -1 + dragMovingOffset = -1 + dragInitialHandle = 0 + coordinator.cancelDrag() + syncSelectionFromLayout( + layoutAuthority.cachedText, + selectionStartProvider(), + selectionEndProvider(), + viewportWidthPx, + density, + ) + return true + } +} + +/** + * Coordinates strict isolation between Autofill form field editing and the + * per-route document buffer (`HostDocumentStore` + `HostTextPreviewView`). + */ +class HostDocumentBufferController( + val documentStore: HostDocumentStore, + private val imeProvider: () -> AffineImeController, + private val autofillProvider: () -> AndroidAutofillController?, + private val onDocumentPreviewUpdated: (String) -> Unit = {}, +) { + private var syncingAutofillFocus: Boolean = false + private var syncingDocumentSwitch: Boolean = false + private var autofillDirtiedIme: Boolean = false + private var docSelectionStart: Int = 0 + private var docSelectionEnd: Int = 0 + var lastPreviewText: String = documentStore.readDocument(documentStore.activeDocumentId) + private set + + fun isAutofillFocused(): Boolean = autofillProvider()?.focusedFieldId() != null + + fun isFocusedAutofillFieldMasked(): Boolean = + autofillProvider()?.isFocusedFieldMasked() == true + + fun currentDocumentText(): String = documentStore.readDocument(documentStore.activeDocumentId) + + fun recordDocumentSelection(selStart: Int, selEnd: Int) { + if (syncingAutofillFocus || syncingDocumentSwitch || isAutofillFocused() || autofillDirtiedIme) { + return + } + docSelectionStart = selStart + docSelectionEnd = selEnd + } + + fun onImeTextEdited(text: String) { + if (syncingAutofillFocus || syncingDocumentSwitch) return + if (isAutofillFocused()) { + autofillDirtiedIme = true + // Strictly isolate form credentials from document storage and HostTextPreviewView. + autofillProvider()?.onFocusedTextEdited(text) + return + } + if (autofillDirtiedIme) { + restoreDocumentBufferToIme() + return + } + documentStore.saveCurrent(text) + lastPreviewText = text + } + + fun applyAutofillTextToIme(text: String) { + val ime = imeProvider() + autofillDirtiedIme = true + syncingAutofillFocus = true + try { + ime.replaceText(0, ime.currentText().length, text, 1) + } finally { + syncingAutofillFocus = false + } + } + + fun restoreDocumentBufferToIme() { + val docText = currentDocumentText() + val lo = docSelectionStart.coerceIn(0, docText.length) + val hi = docSelectionEnd.coerceIn(lo, docText.length) + val ime = imeProvider() + syncingAutofillFocus = true + try { + ime.replaceText(0, ime.currentText().length, docText, 1) + ime.setSelection(lo, hi) + } finally { + syncingAutofillFocus = false + } + autofillDirtiedIme = false + lastPreviewText = docText + onDocumentPreviewUpdated(docText) + } + + fun onAutofillFocusChanged(nextFieldId: Int?) { + val af = autofillProvider() + val prev = af?.focusedFieldId() + val wasDirty = autofillDirtiedIme + if (prev == null && nextFieldId != null && !wasDirty) { + val ime = imeProvider() + docSelectionStart = ime.selectionStart() + docSelectionEnd = ime.selectionEnd() + } + af?.onFieldFocusChanged(nextFieldId) + val nowFocused = af?.focusedFieldId() != null + if (nowFocused) { + autofillDirtiedIme = true + onDocumentPreviewUpdated(currentDocumentText()) + } else if (prev != null || wasDirty) { + restoreDocumentBufferToIme() + } + } + + fun commitAutofillSession(): Boolean { + val needRestore = isAutofillFocused() || autofillDirtiedIme + val ok = autofillProvider()?.commit() ?: false + if (needRestore) { + restoreDocumentBufferToIme() + } + return ok + } + + fun cancelAutofillSession(): Boolean { + val needRestore = isAutofillFocused() || autofillDirtiedIme + val ok = autofillProvider()?.cancel() ?: false + if (needRestore) { + restoreDocumentBufferToIme() + } + return ok + } + + fun clearAutofillFields() { + val needRestore = isAutofillFocused() || autofillDirtiedIme + autofillProvider()?.clearFields() + if (needRestore) { + restoreDocumentBufferToIme() + } + } + + fun onRouteChanged(nextRoute: String) { + if (documentStore.activeDocumentId == nextRoute) return + val wasAutofillFocused = isAutofillFocused() + val outgoingDocText = if (wasAutofillFocused || autofillDirtiedIme) { + // Preserve the document's own text and exit Autofill focus before loading the new route. + autofillProvider()?.onFieldFocusChanged(null) + currentDocumentText() + } else { + imeProvider().currentText() + } + autofillDirtiedIme = false + docSelectionStart = 0 + docSelectionEnd = 0 + val targetText = documentStore.switchTo(nextRoute, outgoingDocText) + syncingDocumentSwitch = true + try { + val ime = imeProvider() + ime.replaceText(0, ime.currentText().length, targetText, 1) + } finally { + syncingDocumentSwitch = false + } + lastPreviewText = targetText + onDocumentPreviewUpdated(targetText) + } +} + +/** + * Single authoritative Android `StaticLayout` engine cached by `(text, viewportWidthPx, density)` + * and shared by `HostTextPreviewView` and `AndroidSelectionOverlayView` so body text, + * selection highlights, teardrop handle tips, hit-testing, and the magnified loupe are + * 100% pixel-aligned with zero per-frame allocations during handle drags. + */ +class ShapedTextLayout(density: Float) : TextLayoutAuthority { + val textPaint: TextPaint = TextPaint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG).apply { + color = Color.rgb(0x14, 0x16, 0x1C) + textSize = 18f * density.coerceAtLeast(1f) + } + var paddingLeftPx: Float = 24f * density.coerceAtLeast(1f) + private set + var paddingTopPx: Float = 80f * density.coerceAtLeast(1f) + private set + override var cachedText: String = "" + private set + var cachedViewportWidthPx: Int = -1 + private set + var cachedDensity: Float = density.coerceAtLeast(1f) + private set + var cachedLayout: StaticLayout? = null + private set + private val tmpPath = Path() + private val tmpBounds = RectF() + private val breakIterator: BreakIterator = BreakIterator.getCharacterInstance() + + fun applyClearColor(clearColorArgb: Int) { + textPaint.color = if (isLightClearColor(clearColorArgb)) { + Color.rgb(0x14, 0x16, 0x1C) + } else { + Color.rgb(0xF4, 0xF4, 0xF5) + } + } + + override fun ensureLayoutReady(text: String, viewportWidthPx: Int, density: Float): Boolean = + ensureLayout(text, viewportWidthPx, density) != null + + fun ensureLayout(text: String, viewportWidthPx: Int, density: Float): StaticLayout? { + val safeDensity = if (density.isFinite() && density > 0f) density else 1f + val padH = 24f * safeDensity + val contentW = (viewportWidthPx - (padH * 2f).toInt()).coerceAtLeast(120) + if (cachedLayout != null && + cachedText == text && + cachedViewportWidthPx == viewportWidthPx && + cachedDensity == safeDensity + ) { + return cachedLayout + } + paddingLeftPx = padH + paddingTopPx = 80f * safeDensity + textPaint.textSize = 18f * safeDensity + if (cachedText != text) { + breakIterator.setText(text) + } + cachedText = text + cachedViewportWidthPx = viewportWidthPx + cachedDensity = safeDensity + cachedLayout = StaticLayout.Builder.obtain(text, 0, text.length, textPaint, contentW) + .setAlignment(Layout.Alignment.ALIGN_NORMAL) + .setTextDirection(TextDirectionHeuristics.FIRSTSTRONG_LTR) + .setIncludePad(false) + .build() + return cachedLayout + } + + private fun visualLineForOffset(layout: StaticLayout, text: String, off: Int): Int { + var line = layout.getLineForOffset(off) + // Soft-wrap boundary offsets belong to the start of the next visual line. + if (off > 0 && + line + 1 < layout.lineCount && + layout.getLineStart(line + 1) == off && + text[off - 1] != '\n' + ) { + line += 1 + } + return line + } + + private fun caretHorizontalPx( + layout: StaticLayout, + text: String, + off: Int, + paraRtl: Boolean, + isSelectionEnd: Boolean, + selStart: Int, + selEnd: Int, + ): Float { + var localX = layout.getPrimaryHorizontal(off) + if (selStart < selEnd) { + val charIdx = if (isSelectionEnd) { + (off - 1).coerceIn(selStart, text.length - 1) + } else { + off.coerceIn(0, (selEnd - 1).coerceAtLeast(0)) + } + val charRtl = layout.isRtlCharAt(charIdx) + if (charRtl != paraRtl) { + localX = layout.getSecondaryHorizontal(off) + } + } + return paddingLeftPx + localX + } + + override fun caretBounds( + utf16Offset: Int, + isSelectionEnd: Boolean, + selStart: Int, + selEnd: Int, + ): CaretBounds? { + val layout = cachedLayout ?: return null + val text = cachedText + val off = utf16Offset.coerceIn(0, text.length) + val line = visualLineForOffset(layout, text, off) + val top = paddingTopPx + layout.getLineTop(line).toFloat() + val bottom = paddingTopPx + layout.getLineBottom(line).toFloat() + val paraRtl = layout.getParagraphDirection(line) == Layout.DIR_RIGHT_TO_LEFT + val x = caretHorizontalPx(layout, text, off, paraRtl, isSelectionEnd, selStart, selEnd) + return CaretBounds( + x = x, + top = top, + bottom = bottom, + lineIndex = line, + isRtlParagraph = paraRtl, + ) + } + + override fun fillSelectionEndCarets(selStart: Int, selEnd: Int, out: FloatArray): Boolean { + val layout = cachedLayout ?: return false + val text = cachedText + val lo = selStart.coerceIn(0, text.length) + val hi = selEnd.coerceIn(lo, text.length) + val startLine = visualLineForOffset(layout, text, lo) + val endLine = visualLineForOffset(layout, text, hi) + val startTop = paddingTopPx + layout.getLineTop(startLine).toFloat() + val startBottom = paddingTopPx + layout.getLineBottom(startLine).toFloat() + val endBottom = paddingTopPx + layout.getLineBottom(endLine).toFloat() + var startRtl = layout.getParagraphDirection(startLine) == Layout.DIR_RIGHT_TO_LEFT + val endRtl = layout.getParagraphDirection(endLine) == Layout.DIR_RIGHT_TO_LEFT + var startX = caretHorizontalPx(layout, text, lo, startRtl, false, lo, hi) + var endX = caretHorizontalPx(layout, text, hi, endRtl, true, lo, hi) + + // Guard mixed BiDi single-line spans against degenerate identical X coordinates. + if (lo < hi && startLine == endLine && kotlin.math.abs(startX - endX) < 0.5f) { + tmpPath.reset() + layout.getSelectionPath(lo, hi, tmpPath) + tmpPath.computeBounds(tmpBounds, true) + if (!tmpBounds.isEmpty) { + val leftX = paddingLeftPx + tmpBounds.left + val rightX = paddingLeftPx + tmpBounds.right + val charRtl = layout.isRtlCharAt(lo.coerceIn(0, (text.length - 1).coerceAtLeast(0))) + if (charRtl) { + startX = rightX + endX = leftX + startRtl = true + } else { + startX = leftX + endX = rightX + startRtl = false + } + } + } + out[0] = startX + out[1] = startBottom + out[2] = endX + out[3] = endBottom + out[4] = (startBottom - startTop).coerceAtLeast(1f) + out[5] = if (startRtl) 1f else 0f + return true + } + + override fun selectionEndCarets(selStart: Int, selEnd: Int): Pair? { + val lo = selStart.coerceIn(0, cachedText.length) + val hi = selEnd.coerceIn(lo, cachedText.length) + var start = caretBounds(lo, isSelectionEnd = false, selStart = lo, selEnd = hi) ?: return null + var end = caretBounds(hi, isSelectionEnd = true, selStart = lo, selEnd = hi) ?: return null + // Guard mixed BiDi single-line spans against degenerate identical X coordinates. + if (lo < hi && start.lineIndex == end.lineIndex && kotlin.math.abs(start.x - end.x) < 0.5f) { + val layout = cachedLayout + if (layout != null) { + tmpPath.reset() + layout.getSelectionPath(lo, hi, tmpPath) + tmpPath.computeBounds(tmpBounds, true) + if (!tmpBounds.isEmpty) { + val leftX = paddingLeftPx + tmpBounds.left + val rightX = paddingLeftPx + tmpBounds.right + val charRtl = layout.isRtlCharAt(lo.coerceIn(0, (cachedText.length - 1).coerceAtLeast(0))) + if (charRtl) { + start = start.copy(x = rightX, isRtlParagraph = true) + end = end.copy(x = leftX, isRtlParagraph = true) + } else { + start = start.copy(x = leftX, isRtlParagraph = false) + end = end.copy(x = rightX, isRtlParagraph = false) + } + } + } + } + return start to end + } + + private fun snapToGraphemeStart(text: String, raw: Int): Int { + if (raw <= 0 || raw >= text.length) return raw + if (Character.isLowSurrogate(text[raw])) { + return (raw - 1).coerceAtLeast(0) + } + if (breakIterator.isBoundary(raw)) return raw + val prev = breakIterator.preceding(raw) + return if (prev != BreakIterator.DONE) prev else raw + } + + override fun closestOffset(x: Float, y: Float): Int = closestOffset(x, y, -1) + + override fun closestOffset(x: Float, y: Float, preferredOffset: Int): Int { + val layout = cachedLayout ?: return 0 + val text = cachedText + if (text.isEmpty()) return 0 + val localX = (x - paddingLeftPx).coerceAtLeast(0f) + val localY = (y - paddingTopPx).toInt().coerceAtLeast(0) + val line = layout.getLineForVertical(localY) + // Preserve the active endpoint at mixed-direction run boundaries where two logical offsets + // share the same visual X coordinate until the drag moves past the local glyph snap tolerance. + if (preferredOffset in 0..text.length && visualLineForOffset(layout, text, preferredOffset) == line) { + val primX = layout.getPrimaryHorizontal(preferredOffset) + val secX = layout.getSecondaryHorizontal(preferredOffset) + val lineStart = layout.getLineStart(line) + val lineEnd = layout.getLineEnd(line) + var adjAdvance = Float.MAX_VALUE + if (preferredOffset > lineStart) { + val prevX = layout.getPrimaryHorizontal(preferredOffset - 1) + val d1 = kotlin.math.abs(primX - prevX) + val d2 = kotlin.math.abs(secX - prevX) + if (d1 > 0.5f && d1 < adjAdvance) adjAdvance = d1 + if (d2 > 0.5f && d2 < adjAdvance) adjAdvance = d2 + } + if (preferredOffset < lineEnd) { + val nextX = layout.getPrimaryHorizontal(preferredOffset + 1) + val d1 = kotlin.math.abs(nextX - primX) + val d2 = kotlin.math.abs(nextX - secX) + if (d1 > 0.5f && d1 < adjAdvance) adjAdvance = d1 + if (d2 > 0.5f && d2 < adjAdvance) adjAdvance = d2 + } + if (adjAdvance == Float.MAX_VALUE) adjAdvance = 4f + val snapTol = minOf(2.0f * cachedDensity, adjAdvance * 0.35f) + if (kotlin.math.abs(localX - primX) <= snapTol || + kotlin.math.abs(localX - secX) <= snapTol + ) { + return snapToGraphemeStart(text, preferredOffset) + } + } + val raw = layout.getOffsetForHorizontal(line, localX).coerceIn(0, text.length) + return snapToGraphemeStart(text, raw) + } + + fun fillSelectionPath(selStart: Int, selEnd: Int, outPath: Path): Boolean { + outPath.reset() + val layout = cachedLayout ?: return false + val lo = selStart.coerceIn(0, cachedText.length) + val hi = selEnd.coerceIn(lo, cachedText.length) + if (lo >= hi) return false + layout.getSelectionPath(lo, hi, outPath) + return true + } +} + +/** + * In-memory host document store backed by the active destination route stack so + * `openDocument`, `navigateTo`, and predictive back `Cancel`/`Commit` preserve + * and restore real per-document text content. + */ +class HostDocumentStore( + initialRoute: String = "workspace/home", + initialText: String = "", +) { + private val documents = linkedMapOf(initialRoute to initialText) + var activeDocumentId: String = initialRoute + private set + + fun saveCurrent(text: String) { + documents[activeDocumentId] = text + } + + fun switchTo(nextRoute: String, outgoingText: String): String { + documents[activeDocumentId] = outgoingText + activeDocumentId = nextRoute + return documents.getOrPut(nextRoute) { "" } + } + + fun readDocument(route: String): String = documents[route] ?: "" +} + +internal const val DEFAULT_SURFACE_CLEAR_COLOR_ARGB: Int = 0xFFFA_FAFC.toInt() + +internal fun isLightClearColor(argb: Int): Boolean { + val r = ((argb ushr 16) and 0xFF) / 255.0 + val g = ((argb ushr 8) and 0xFF) / 255.0 + val b = (argb and 0xFF) / 255.0 + val luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b + return luminance >= 0.5 +} + +/** + * Lightweight transitional text preview layer (until S4 shared editor integration) + * sharing the exact cached `ShapedTextLayout` with `AndroidSelectionOverlayView` so + * document text and `getSelectionPath` selection highlights align 1:1 with teardrop + * handles and the magnified loupe. + */ +class HostTextPreviewView( + context: Context, + private val shapedLayout: ShapedTextLayout, + private val selectionStartProvider: () -> Int, + private val selectionEndProvider: () -> Int, +) : View(context) { + private val selectionHighlightPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.argb(56, 30, 150, 235) + style = Paint.Style.FILL + } + private val reusableSelectionPath = Path() + + init { + setWillNotDraw(false) + isClickable = false + isFocusable = false + } + + fun applyClearColor(clearColorArgb: Int) { + shapedLayout.applyClearColor(clearColorArgb) + selectionHighlightPaint.color = if (isLightClearColor(clearColorArgb)) { + Color.argb(56, 30, 150, 235) + } else { + Color.argb(96, 56, 178, 255) + } + invalidate() + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + val layout = shapedLayout.cachedLayout ?: return + val selStart = selectionStartProvider() + val selEnd = selectionEndProvider() + canvas.save() + canvas.translate(shapedLayout.paddingLeftPx, shapedLayout.paddingTopPx) + if (shapedLayout.fillSelectionPath(selStart, selEnd, reusableSelectionPath)) { + canvas.drawPath(reusableSelectionPath, selectionHighlightPaint) + } + layout.draw(canvas) + canvas.restore() + } +} + +/** + * Pure Android `View` overlay layered above `AffineSurfaceView` and `HostTextPreviewView` + * in a `FrameLayout` to render teardrop handles, single-authority `ShapedTextLayout` + * magnified loupe (with `getSelectionPath` highlight and vertically centered focus), and + * clickable `Copy | Cut | Paste` action menu pills with zero per-frame allocations and + * without ever calling `SurfaceHolder.lockCanvas`. + */ +class AndroidSelectionOverlayView( + context: Context, + private val coordinator: AndroidSelectionCoordinator, + private val shapedLayout: ShapedTextLayout, + private val selectionStartProvider: () -> Int = { 0 }, + private val selectionEndProvider: () -> Int = { 0 }, + private val onSelectionChanged: (Int, Int) -> Unit = { _, _ -> }, + private val canPaste: () -> Boolean = { false }, + private val onActionCopy: () -> Unit = {}, + private val onActionCut: () -> Unit = {}, + private val onActionPaste: () -> Unit = {}, + private val isOverlaySuppressed: () -> Boolean = { false }, +) : View(context) { + private val handlePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.argb(235, 30, 150, 235) + style = Paint.Style.FILL + } + private val selectionHighlightPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.argb(56, 30, 150, 235) + style = Paint.Style.FILL + } + private val loupeBgPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.rgb(0xFA, 0xFB, 0xFD) + style = Paint.Style.FILL + } + private val loupeBorderPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.argb(235, 30, 150, 235) + style = Paint.Style.STROKE + strokeWidth = 3f + } + private val menuPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.argb(225, 28, 28, 32) + style = Paint.Style.FILL + } + private val menuDividerPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.argb(60, 255, 255, 255) + style = Paint.Style.FILL + } + private val menuTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.WHITE + textSize = 36f + textAlign = Paint.Align.CENTER + } + private val geometryBuffer = FloatArray(24) + private val handlePath = Path() + private val loupeClipPath = Path() + private val reusableSelectionPath = Path() + private val loupeRect = RectF() + private val menuRect = RectF() + private val gestureController = SelectionGestureController( + coordinator = coordinator, + layoutAuthority = shapedLayout, + selectionStartProvider = selectionStartProvider, + selectionEndProvider = selectionEndProvider, + onSelectionChanged = onSelectionChanged, + onOverlaySynced = { invalidate() }, + ) + private var hasVisibleMenu: Boolean = false + private var menuHasPaste: Boolean = false + + init { + setWillNotDraw(false) + isClickable = false + isFocusable = false + } + + fun refreshPasteState() { + menuHasPaste = canPaste() + } + + override fun onWindowFocusChanged(hasWindowFocus: Boolean) { + super.onWindowFocusChanged(hasWindowFocus) + if (hasWindowFocus) { + refreshPasteState() + invalidate() + } + } + + fun syncFromShapedLayout( + text: String, + selStart: Int, + selEnd: Int, + viewportWidthPx: Int, + density: Float, + ) { + val lo = selStart.coerceIn(0, text.length) + val hi = selEnd.coerceIn(lo, text.length) + menuHasPaste = if (lo < hi) canPaste() else false + gestureController.syncSelectionFromLayout(text, lo, hi, viewportWidthPx, density) + } + + override fun onTouchEvent(event: MotionEvent): Boolean { + if (isOverlaySuppressed()) return false + val viewportW = if (width > 0) width else resources.displayMetrics.widthPixels + val density = resources.displayMetrics.density + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + val hit = gestureController.onDown(event.x, event.y, density) + if (hit != 0) { + invalidate() + return true + } + if (hasVisibleMenu && menuRect.contains(event.x, event.y)) { + return true + } + return false + } + MotionEvent.ACTION_MOVE -> { + if (!gestureController.draggingHandle) return false + gestureController.onMove(event.x, event.y) + invalidate() + return true + } + MotionEvent.ACTION_UP -> { + if (gestureController.draggingHandle) { + refreshPasteState() + gestureController.onUp(viewportW, density) + invalidate() + return true + } + if (hasVisibleMenu && menuRect.contains(event.x, event.y)) { + if (menuHasPaste) { + val third = menuRect.width() / 3f + when { + event.x < menuRect.left + third -> onActionCopy() + event.x < menuRect.left + third * 2f -> onActionCut() + else -> onActionPaste() + } + } else { + if (event.x < menuRect.centerX()) { + onActionCopy() + } else { + onActionCut() + } + } + refreshPasteState() + invalidate() + return true + } + return false + } + MotionEvent.ACTION_CANCEL -> { + if (!gestureController.draggingHandle) return false + refreshPasteState() + gestureController.onCancel(viewportW, density) + invalidate() + return true + } + else -> return false + } + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + if (isOverlaySuppressed()) { + hasVisibleMenu = false + return + } + val g = geometryBuffer + if (!coordinator.fillOverlayGeometry(g) || g[0] < 0.5f) { + hasVisibleMenu = false + return + } + if (g[2] >= 0.5f) { + drawTeardropHandle(canvas, g[3], g[4], g[5], g[6], g[7], leanLeft = g[5] < g[3]) + } + if (g[8] >= 0.5f) { + drawTeardropHandle(canvas, g[9], g[10], g[11], g[12], g[13], leanLeft = g[11] < g[9]) + } + if (g[14] >= 0.5f) { + val ax = g[15] + val ay = g[16] + val lx = g[17] + val ly = g[18] + val density = resources.displayMetrics.density + val loupeW = 100f * density + val loupeH = 48f * density + loupeRect.set(lx - loupeW * 0.5f, ly - loupeH * 0.5f, lx + loupeW * 0.5f, ly + loupeH * 0.5f) + loupeClipPath.reset() + loupeClipPath.addRoundRect(loupeRect, loupeH * 0.5f, loupeH * 0.5f, Path.Direction.CW) + val layout = shapedLayout.cachedLayout + canvas.save() + canvas.clipPath(loupeClipPath) + canvas.drawRect(loupeRect, loupeBgPaint) + if (layout != null && shapedLayout.cachedText.isNotEmpty()) { + val selStart = selectionStartProvider() + val selEnd = selectionEndProvider() + val halfCaretH = (shapedLayout.textPaint.textSize * 0.65f).coerceAtLeast(12f) + canvas.scale(1.5f, 1.5f, lx, ly) + canvas.save() + canvas.translate(lx - ax + shapedLayout.paddingLeftPx, ly - ay + shapedLayout.paddingTopPx) + if (shapedLayout.fillSelectionPath(selStart, selEnd, reusableSelectionPath)) { + canvas.drawPath(reusableSelectionPath, selectionHighlightPaint) + } + layout.draw(canvas) + canvas.restore() + // Focus caret bar vertically centered on the dragged line midpoint (lx, ly). + canvas.drawRect(lx - 1.5f, ly - halfCaretH, lx + 1.5f, ly + halfCaretH, handlePaint) + } + canvas.restore() + canvas.drawPath(loupeClipPath, loupeBorderPaint) + } + if (g[19] >= 0.5f) { + val mx = g[20] + val my = g[21] + val mw = g[22] + val mh = g[23] + val density = resources.displayMetrics.density + val marginX = 12f * density + val actualW = if (menuHasPaste) mw * 1.38f else mw + val maxLeft = (width - marginX - actualW).coerceAtLeast(0f) + val minLeft = marginX.coerceAtMost(maxLeft) + val actualX = (mx + (mw - actualW) * 0.5f).coerceIn(minLeft, maxLeft) + menuRect.set(actualX, my, actualX + actualW, my + mh) + hasVisibleMenu = true + canvas.drawRoundRect(menuRect, mh * 0.5f, mh * 0.5f, menuPaint) + val baselineY = menuRect.centerY() + menuTextPaint.textSize * 0.35f + if (menuHasPaste) { + val third = actualW / 3f + val d1 = actualX + third + val d2 = actualX + third * 2f + canvas.drawRect(d1 - 1f, my + mh * 0.22f, d1 + 1f, my + mh * 0.78f, menuDividerPaint) + canvas.drawRect(d2 - 1f, my + mh * 0.22f, d2 + 1f, my + mh * 0.78f, menuDividerPaint) + canvas.drawText("Copy", actualX + third * 0.5f, baselineY, menuTextPaint) + canvas.drawText("Cut", actualX + third * 1.5f, baselineY, menuTextPaint) + canvas.drawText("Paste", actualX + third * 2.5f, baselineY, menuTextPaint) + } else { + val dividerX = actualX + actualW * 0.5f + canvas.drawRect(dividerX - 1f, my + mh * 0.22f, dividerX + 1f, my + mh * 0.78f, menuDividerPaint) + canvas.drawText("Copy", actualX + actualW * 0.25f, baselineY, menuTextPaint) + canvas.drawText("Cut", actualX + actualW * 0.75f, baselineY, menuTextPaint) + } + } else { + hasVisibleMenu = false + } + } + + private fun drawTeardropHandle( + canvas: Canvas, + tipX: Float, + tipY: Float, + centerX: Float, + centerY: Float, + radius: Float, + leanLeft: Boolean, + ) { + // Draw vertical selection stem above the tip + teardrop bulb curving into tip. + val stemHeight = radius * 1.4f + canvas.drawRect(tipX - 2f, tipY - stemHeight, tipX + 2f, tipY, handlePaint) + handlePath.reset() + handlePath.moveTo(tipX, tipY) + if (leanLeft) { + handlePath.quadTo(tipX, centerY - radius * 0.4f, centerX + radius, centerY) + } else { + handlePath.quadTo(tipX, centerY - radius * 0.4f, centerX - radius, centerY) + } + handlePath.addCircle(centerX, centerY, radius, Path.Direction.CW) + canvas.drawPath(handlePath, handlePaint) + } +} + +data class VirtualAutofillNode( + val autofillId: Int, + val kindCode: Int, + val hint: String, + val left: Int, + val top: Int, + val right: Int, + val bottom: Int, + val masked: Boolean, + val valueLen: Int, +) + +interface AutofillPlatformBackend { + fun notifyViewEntered(autofillId: Int, left: Int, top: Int, right: Int, bottom: Int) + fun notifyViewExited(autofillId: Int) + fun notifyValueChanged(autofillId: Int, text: String) + fun commit() + fun cancel() +} + +@TargetApi(Build.VERSION_CODES.O) +class SystemAutofillPlatformBackend( + private val hostView: View, + private val manager: AutofillManager, +) : AutofillPlatformBackend { + override fun notifyViewEntered(autofillId: Int, left: Int, top: Int, right: Int, bottom: Int) { + manager.notifyViewEntered(hostView, autofillId, Rect(left, top, right, bottom)) + } + + override fun notifyViewExited(autofillId: Int) { + manager.notifyViewExited(hostView, autofillId) + } + + override fun notifyValueChanged(autofillId: Int, text: String) { + manager.notifyValueChanged(hostView, autofillId, AutofillValue.forText(text)) + } + + override fun commit() { + manager.commit() + } + + override fun cancel() { + manager.cancel() + } +} + +/** + * API 26+ `AutofillManager` virtual view structure controller. + * Safely degrades to a no-op on API 24 and 25 without touching API 26 classes. + */ +class AndroidAutofillController( + private val sdkInt: Int, + private val handleProvider: () -> Long, + private val backend: AutofillPlatformBackend? = null, + private val onMutated: () -> Unit = {}, + private val onValueCommitted: (Int, String) -> Unit = { _, _ -> }, + private val onFocusedFieldTextSync: (Int, String) -> Unit = { _, _ -> }, +) { + private val nodes = linkedMapOf() + private var focusedId: Int? = null + + val isEnabled: Boolean + get() = sdkInt >= Build.VERSION_CODES.O && NativeBridge.nativeShouldExposeAutofill(sdkInt) + + fun focusedFieldId(): Int? = if (isEnabled) focusedId else null + + fun isFocusedFieldMasked(): Boolean { + val id = focusedFieldId() ?: return false + return nodes[id]?.masked == true + } + + fun readFormValues(): Map { + if (!isEnabled) return emptyMap() + val handle = handleProvider() + if (handle == 0L) return emptyMap() + val out = linkedMapOf() + NativeBridge.nativeGetAutofillValueByKind(handle, 0)?.let { out["username"] = it } + NativeBridge.nativeGetAutofillValueByKind(handle, 1)?.let { out["email"] = it } + NativeBridge.nativeGetAutofillValueByKind(handle, 2)?.let { out["password"] = it } + NativeBridge.nativeGetAutofillValueByKind(handle, 3)?.let { out["otp"] = it } + return out + } + + fun onFocusedTextEdited(text: String): Boolean { + val active = focusedId ?: return false + return updateFieldText(active, text) + } + + init { + val handle = handleProvider() + if (handle != 0L) { + NativeBridge.nativeConfigureAutofillSdk(handle, sdkInt) + } + } + + fun registerField( + autofillId: Int, + kindCode: Int, + left: Int, + top: Int, + right: Int, + bottom: Int, + masked: Boolean, + valueLen: Int = 0, + ): Boolean { + if (!isEnabled) return false + val handle = handleProvider() + if (handle == 0L) return false + val ok = NativeBridge.nativeUpsertAutofillField( + handle, + autofillId, + kindCode, + left, + top, + right, + bottom, + masked, + valueLen, + ) + if (ok) { + val hint = when (kindCode) { + 0 -> View.AUTOFILL_HINT_USERNAME + 1 -> View.AUTOFILL_HINT_EMAIL_ADDRESS + 2 -> View.AUTOFILL_HINT_PASSWORD + else -> "smsOTPCode" + } + nodes[autofillId] = VirtualAutofillNode( + autofillId = autofillId, + kindCode = kindCode, + hint = hint, + left = minOf(left, right), + top = minOf(top, bottom), + right = maxOf(left, right), + bottom = maxOf(top, bottom), + masked = masked, + valueLen = valueLen.coerceAtLeast(0), + ) + } + return ok + } + + fun updateFieldText(autofillId: Int, text: String): Boolean { + if (!isEnabled) return false + val handle = handleProvider() + if (handle == 0L) return false + val ok = NativeBridge.nativeSetAutofillFieldText(handle, autofillId, text) + if (ok) { + val existing = nodes[autofillId] + if (existing != null) { + nodes[autofillId] = existing.copy(valueLen = text.length) + } + backend?.notifyValueChanged(autofillId, text) + } + return ok + } + + fun resolveVirtualFieldValueForStructure(autofillId: Int): String? { + if (!isEnabled) return null + val handle = handleProvider() + if (handle == 0L) return null + return NativeBridge.nativeGetAutofillValue(handle, autofillId)?.takeIf { it.isNotEmpty() } + } + + fun onFieldFocusChanged(nextAutofillId: Int?) { + if (!isEnabled) return + val handle = handleProvider() + if (handle == 0L) return + val validNext = if (nextAutofillId != null && nodes.containsKey(nextAutofillId)) { + nextAutofillId + } else { + null + } + if (focusedId == validNext) return + val prev = focusedId + focusedId = validNext + NativeBridge.nativeFocusAutofillField(handle, validNext ?: 0) + if (prev != null) { + backend?.notifyViewExited(prev) + } + if (validNext != null) { + val node = nodes[validNext] + if (node != null) { + backend?.notifyViewEntered(node.autofillId, node.left, node.top, node.right, node.bottom) + } + onFocusedFieldTextSync(validNext, resolveVirtualFieldValueForStructure(validNext) ?: "") + } + } + + fun virtualNodesSnapshot(): List = + if (!isEnabled) emptyList() else nodes.values.toList() + + @TargetApi(Build.VERSION_CODES.O) + fun populateVirtualStructure(structure: ViewStructure) { + if (!isEnabled || nodes.isEmpty()) return + val parentId = structure.autofillId ?: return + val ordered = nodes.values.toList() + val baseIndex = structure.addChildCount(ordered.size) + ordered.forEachIndexed { offset, node -> + val child = structure.newChild(baseIndex + offset) + child.setAutofillId(parentId, node.autofillId) + child.setAutofillType(View.AUTOFILL_TYPE_TEXT) + child.setAutofillHints(arrayOf(node.hint)) + child.setInputType( + when (node.kindCode) { + 1 -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS + 2 -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD + 3 -> InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_NORMAL + else -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_NORMAL + }, + ) + child.setDimens( + node.left, + node.top, + 0, + 0, + (node.right - node.left).coerceAtLeast(0), + (node.bottom - node.top).coerceAtLeast(0), + ) + val realText = resolveVirtualFieldValueForStructure(node.autofillId) + if (!realText.isNullOrEmpty()) { + child.setAutofillValue(AutofillValue.forText(realText)) + } + } + } + + fun onAutofillValues(values: Map): Int { + if (!isEnabled) return 0 + val handle = handleProvider() + if (handle == 0L) return 0 + var applied = 0 + val activeFocus = focusedId + for ((id, text) in values) { + if (NativeBridge.nativeApplyAutofillValue(handle, id, text)) { + applied += 1 + val existing = nodes[id] + if (existing != null) { + nodes[id] = existing.copy(valueLen = text.length) + } + if (activeFocus != null && id == activeFocus) { + onValueCommitted(id, text) + } + backend?.notifyValueChanged(id, text) + } + } + if (applied > 0) onMutated() + return applied + } + + @TargetApi(Build.VERSION_CODES.O) + fun onAutofillSparseArray(values: SparseArray): Int { + if (!isEnabled) return 0 + val map = linkedMapOf() + for (idx in 0 until values.size()) { + val id = values.keyAt(idx) + val value = values.valueAt(idx) + if (value != null && value.isText) { + map[id] = value.textValue.toString() + } + } + return onAutofillValues(map) + } + + fun commit(): Boolean { + if (!isEnabled) return false + val handle = handleProvider() + if (handle == 0L) return false + focusedId = null + val ok = NativeBridge.nativeCommitAutofill(handle) + if (ok) backend?.commit() + return ok + } + + fun cancel(): Boolean { + if (!isEnabled) return false + val handle = handleProvider() + if (handle == 0L) return false + focusedId = null + val ok = NativeBridge.nativeCancelAutofill(handle) + if (ok) backend?.cancel() + return ok + } + + fun clearFields() { + nodes.clear() + focusedId = null + val handle = handleProvider() + if (handle != 0L) { + NativeBridge.nativeClearAutofillFields(handle) + } + } + + fun virtualStructureJson(): String { + val handle = handleProvider() + return if (handle == 0L) "{}" else NativeBridge.nativeGetAutofillStructureJson(handle) + } +} + +/** + * Four-phase predictive back (API 34+) and legacy single-commit (API 24-33) + * dispatcher backed by Rust `back_stack_depth`, with re-entrancy protection + * and full support for standalone API 34+ button/key `onBackInvoked()` calls. + */ +class AndroidBackDispatcher( + private val sdkInt: Int, + private val handleProvider: () -> Long, + private val onMutated: () -> Unit = {}, + private val onDestinationChanged: (String?) -> Unit = {}, + private val onSystemExit: () -> Unit = {}, +) { + val dispatchMode: Int = NativeBridge.nativeBackDispatchMode(sdkInt) + private var gestureActive: Boolean = false + private var inDispatch: Boolean = false + + fun pushDestination(route: String): Boolean { + val handle = handleProvider() + if (handle == 0L) return false + val ok = NativeBridge.nativePushDestination(handle, route) + if (ok) { + onDestinationChanged(currentDestination()) + onMutated() + } + return ok + } + + fun navigateTo(destination: String): Boolean = pushDestination(destination) + + fun openDocument(docId: String): Boolean { + val clean = docId.trim().removePrefix("/") + if (clean.isEmpty()) return false + val route = if (clean.startsWith("doc/")) clean else "doc/$clean" + return pushDestination(route) + } + + fun currentDestination(): String? { + val handle = handleProvider() + return if (handle == 0L) null else NativeBridge.nativeGetCurrentDestination(handle) + } + + fun onBackStarted(progress: Float = 0f): Boolean { + if (dispatchMode < 2) return false + val handle = handleProvider() + if (handle == 0L) return false + val ok = NativeBridge.nativeOnBackGesturePhase(handle, 0, progress) + if (ok) { + gestureActive = true + onMutated() + } + return ok + } + + fun onBackProgressed(progress: Float): Boolean { + if (dispatchMode < 2 || !gestureActive) return false + val handle = handleProvider() + if (handle == 0L) return false + val ok = NativeBridge.nativeOnBackGesturePhase(handle, 1, progress) + if (ok) onMutated() + return ok + } + + fun onBackCancelled(): Boolean { + if (dispatchMode < 2 || !gestureActive) return false + val handle = handleProvider() + if (handle == 0L) return false + gestureActive = false + val ok = NativeBridge.nativeOnBackGesturePhase(handle, 2, 0f) + if (ok) onMutated() + return ok + } + + fun onBackInvoked(): Boolean { + if (inDispatch) return false + inDispatch = true + try { + gestureActive = false + val handle = handleProvider() + val consumed = handle != 0L && NativeBridge.nativeOnBackGesturePhase(handle, 3, 1f) + if (consumed) { + onDestinationChanged(currentDestination()) + onMutated() + } else { + onSystemExit() + } + return consumed + } finally { + inDispatch = false + } + } + + fun onLegacyBackPressed(invokeSystemExit: Boolean = true): Boolean { + if (inDispatch) return false + inDispatch = true + try { + gestureActive = false + val handle = handleProvider() + val consumed = handle != 0L && NativeBridge.nativeOnBackGesturePhase(handle, 3, 1f) + if (consumed) { + onDestinationChanged(currentDestination()) + onMutated() + } else if (invokeSystemExit) { + onSystemExit() + } + return consumed + } finally { + inDispatch = false + } + } +} + +interface PdfPageBackend : AutoCloseable { + fun pageCount(): Int + fun renderPageArgb(pageIndex: Int, widthPx: Int, heightPx: Int): IntArray +} + +data class RenderedPdfPage( + val cacheKey: String, + val pageIndex: Int, + val widthPx: Int, + val heightPx: Int, + val rgbaBytes: ByteArray, +) + +class SystemPdfRendererBackend( + private val descriptor: ParcelFileDescriptor, +) : PdfPageBackend { + private val renderer = PdfRenderer(descriptor) + + override fun pageCount(): Int = renderer.pageCount + + override fun renderPageArgb(pageIndex: Int, widthPx: Int, heightPx: Int): IntArray { + renderer.openPage(pageIndex).use { page -> + val bitmap = Bitmap.createBitmap(widthPx, heightPx, Bitmap.Config.ARGB_8888) + try { + Canvas(bitmap).drawColor(Color.WHITE) + page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY) + val pixels = IntArray(widthPx * heightPx) + bitmap.getPixels(pixels, 0, widthPx, 0, 0, widthPx, heightPx) + return pixels + } finally { + bitmap.recycle() + } + } + } + + override fun close() { + renderer.close() + descriptor.close() + } +} + +/** + * In-place Android `PdfRenderer` page renderer with Rust OOM/bounds validation + * and deterministic `ARGB_8888 -> RGBA8` conversion. + */ +class AndroidPdfPageRenderer( + private val docId: String, + private val backend: PdfPageBackend, +) : AutoCloseable { + fun renderPageRgba( + pageIndex: Int, + widthPx: Int, + heightPx: Int, + dpiBucket: Int = 160, + ): RenderedPdfPage? { + if (!NativeBridge.nativeValidatePdfPageRequest(pageIndex, backend.pageCount(), widthPx, heightPx)) { + return null + } + val argb = backend.renderPageArgb(pageIndex, widthPx, heightPx) + val rgba = NativeBridge.nativePdfConvertArgbToRgba(argb, widthPx, heightPx) ?: return null + val safeDpi = dpiBucket.coerceAtLeast(72) + val key = NativeBridge.nativePdfPageCacheKey(docId, pageIndex, widthPx, heightPx, safeDpi) + return RenderedPdfPage( + cacheKey = key, + pageIndex = pageIndex, + widthPx = widthPx, + heightPx = heightPx, + rgbaBytes = rgba, + ) + } + + override fun close() { + backend.close() + } +} + internal class AffineSurfaceView( context: Context, private val handleProvider: () -> Long, private val onMutated: () -> Unit = {}, + private val onTextEdited: (String) -> Unit = {}, + private val onContextMenuAction: (Int) -> Boolean = { false }, + private val autofillProvider: () -> AndroidAutofillController? = { null }, ) : SurfaceView(context) { init { isFocusable = true isFocusableInTouchMode = true + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + markImportantForAutofillApi26() + } + } + + @TargetApi(Build.VERSION_CODES.O) + private fun markImportantForAutofillApi26() { + importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_YES } override fun onCheckIsTextEditor(): Boolean = true override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection = - createInputConnection(handleProvider, outAttrs, onMutated) + createInputConnection(handleProvider, outAttrs, onMutated, onTextEdited, onContextMenuAction) + + @TargetApi(Build.VERSION_CODES.O) + override fun onProvideAutofillVirtualStructure(structure: ViewStructure, flags: Int) { + super.onProvideAutofillVirtualStructure(structure, flags) + autofillProvider()?.populateVirtualStructure(structure) + } + + @TargetApi(Build.VERSION_CODES.O) + override fun autofill(values: SparseArray) { + autofillProvider()?.onAutofillSparseArray(values) + } companion object { + internal fun dispatchAutofillBatch( + controller: AndroidAutofillController, + values: Map, + ): Int = controller.onAutofillValues(values) + internal fun createInputConnection( handleProvider: () -> Long, outAttrs: EditorInfo? = null, onMutated: () -> Unit = {}, + onTextEdited: (String) -> Unit = {}, + onContextMenuAction: (Int) -> Boolean = { false }, ): InputConnection { - val ime = AffineImeController(handleProvider, onMutated) + val ime = AffineImeController(handleProvider, onMutated, onTextEdited) if (outAttrs != null) { outAttrs.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI outAttrs.initialSelStart = ime.selectionStart() outAttrs.initialSelEnd = ime.selectionEnd() } - return AffineInputConnection(ime) + return AffineInputConnection(ime, onContextMenuAction) } } } @@ -418,10 +2256,26 @@ internal class AffineSurfaceView( class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCallback { private var nativeHandle: Long = 0L private lateinit var surfaceView: AffineSurfaceView + private lateinit var textPreviewView: HostTextPreviewView + private lateinit var selectionOverlayView: AndroidSelectionOverlayView + private lateinit var shapedLayout: ShapedTextLayout private lateinit var bootstrapCoordinator: AndroidBootstrapCoordinator + private lateinit var selectionCoordinator: AndroidSelectionCoordinator + private lateinit var backDispatcher: AndroidBackDispatcher + private lateinit var imeController: AffineImeController + private lateinit var clipboardAdapter: HostClipboard + private val documentStore = HostDocumentStore() + private lateinit var documentBufferController: HostDocumentBufferController + private var autofillController: AndroidAutofillController? = null + private var syncingOverlay: Boolean = false + private var lastViewportWidthPx: Int = 0 + private var clearColorArgb: Int = DEFAULT_SURFACE_CLEAR_COLOR_ARGB @Volatile var lastBootstrapOutcome: BootstrapOutcome? = null private set + @Volatile + var currentDestination: String = "workspace/home" + private set private var frameLoopActive: Boolean = false private var frameCallbackPosted: Boolean = false private var surfaceReady: Boolean = false @@ -434,16 +2288,175 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall } nativeHandle = NativeBridge.nativeCreateHost() + shapedLayout = ShapedTextLayout(resources.displayMetrics.density).apply { + applyClearColor(clearColorArgb) + } + clipboardAdapter = AndroidClipboardAdapter( + getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager, + ) + documentBufferController = HostDocumentBufferController( + documentStore = documentStore, + imeProvider = { imeController }, + autofillProvider = { autofillController }, + onDocumentPreviewUpdated = { docText -> + syncShapedLayoutAndOverlay(docText) + }, + ) + val onImeMutated: () -> Unit = { + if (!syncingOverlay) { + if (documentBufferController.isAutofillFocused()) { + if (::selectionCoordinator.isInitialized) { + selectionCoordinator.clear() + } + } else { + documentBufferController.recordDocumentSelection( + imeController.selectionStart(), + imeController.selectionEnd(), + ) + syncShapedLayoutAndOverlay(imeController.currentText()) + } + } + if (::textPreviewView.isInitialized) { + textPreviewView.invalidate() + } + if (::selectionOverlayView.isInitialized) { + selectionOverlayView.invalidate() + } + requestFrameAndSchedule() + } + val onImeTextEdited: (String) -> Unit = { text -> + documentBufferController.onImeTextEdited(text) + } + imeController = AffineImeController( + handleProvider = { nativeHandle }, + onMutated = onImeMutated, + onTextEdited = onImeTextEdited, + ) + selectionCoordinator = AndroidSelectionCoordinator( + handleProvider = { nativeHandle }, + onMutated = { + if (::selectionOverlayView.isInitialized) { + selectionOverlayView.invalidate() + } + requestFrameAndSchedule() + }, + ) + val onContextMenuAction: (Int) -> Boolean = { actionId -> + if (documentBufferController.isAutofillFocused()) { + if ((actionId == android.R.id.copy || actionId == android.R.id.cut) && + documentBufferController.isFocusedAutofillFieldMasked() + ) { + false + } else { + val handled = selectionCoordinator.handleContextMenuAction(actionId, imeController, clipboardAdapter) + selectionCoordinator.clear() + handled + } + } else { + val handled = selectionCoordinator.handleContextMenuAction(actionId, imeController, clipboardAdapter) + if (handled) { + syncShapedLayoutAndOverlay(imeController.currentText()) + } + handled + } + } + backDispatcher = AndroidBackDispatcher( + sdkInt = Build.VERSION.SDK_INT, + handleProvider = { nativeHandle }, + onMutated = { requestFrameAndSchedule() }, + onDestinationChanged = { dest -> + if (dest != null) { + currentDestination = dest + documentBufferController.onRouteChanged(dest) + } + requestFrameAndSchedule() + }, + onSystemExit = { finish() }, + ) surfaceView = AffineSurfaceView( context = this, handleProvider = { nativeHandle }, - onMutated = { requestFrameAndSchedule() }, + onMutated = onImeMutated, + onTextEdited = onImeTextEdited, + onContextMenuAction = onContextMenuAction, + autofillProvider = { autofillController }, ).apply { holder.addCallback(this@MainActivity) } - setContentView(surfaceView) + textPreviewView = HostTextPreviewView( + context = this, + shapedLayout = shapedLayout, + selectionStartProvider = { + if (documentBufferController.isAutofillFocused()) 0 else imeController.selectionStart() + }, + selectionEndProvider = { + if (documentBufferController.isAutofillFocused()) 0 else imeController.selectionEnd() + }, + ).apply { + applyClearColor(clearColorArgb) + } + selectionOverlayView = AndroidSelectionOverlayView( + context = this, + coordinator = selectionCoordinator, + shapedLayout = shapedLayout, + selectionStartProvider = { imeController.selectionStart() }, + selectionEndProvider = { imeController.selectionEnd() }, + onSelectionChanged = { lo, hi -> + syncingOverlay = true + try { + imeController.setSelection(lo, hi) + } finally { + syncingOverlay = false + } + if (::textPreviewView.isInitialized) { + textPreviewView.invalidate() + } + }, + canPaste = { clipboardAdapter.hasPlainText() }, + onActionCopy = { + if (!documentBufferController.isAutofillFocused()) { + selectionCoordinator.performCopy(imeController, clipboardAdapter) + } + }, + onActionCut = { + if (!documentBufferController.isAutofillFocused()) { + selectionCoordinator.performCut(imeController, clipboardAdapter) + } + }, + onActionPaste = { + if (!documentBufferController.isAutofillFocused()) { + selectionCoordinator.performPaste(imeController, clipboardAdapter) + } + }, + isOverlaySuppressed = { documentBufferController.isAutofillFocused() }, + ) + val rootContainer = FrameLayout(this).apply { + setBackgroundColor(clearColorArgb) + addView( + surfaceView, + FrameLayout.LayoutParams( + FrameLayout.LayoutParams.MATCH_PARENT, + FrameLayout.LayoutParams.MATCH_PARENT, + ), + ) + addView( + textPreviewView, + FrameLayout.LayoutParams( + FrameLayout.LayoutParams.MATCH_PARENT, + FrameLayout.LayoutParams.MATCH_PARENT, + ), + ) + addView( + selectionOverlayView, + FrameLayout.LayoutParams( + FrameLayout.LayoutParams.MATCH_PARENT, + FrameLayout.LayoutParams.MATCH_PARENT, + ), + ) + } + setContentView(rootContainer) - installInsetsBridge(surfaceView) + installInsetsBridge(rootContainer) installPredictiveBackBridge() configureAutofillIfSupported() @@ -525,13 +2538,59 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { if (nativeHandle != 0L) { + lastViewportWidthPx = width NativeBridge.nativeOnSurfaceChanged(nativeHandle, format, width, height) + selectionCoordinator.setViewport( + width.toFloat(), + height.toFloat(), + resources.displayMetrics.density, + ) + val previewText = if (documentBufferController.isAutofillFocused()) { + documentBufferController.currentDocumentText() + } else { + imeController.currentText() + } + syncShapedLayoutAndOverlay(previewText) if (surfaceReady && width > 0 && height > 0) { requestFrameAndSchedule() } } } + private fun syncShapedLayoutAndOverlay(text: String) { + if (syncingOverlay) return + syncingOverlay = true + try { + val viewportW = if (lastViewportWidthPx > 0) { + lastViewportWidthPx + } else { + resources.displayMetrics.widthPixels + } + val autofillFocused = documentBufferController.isAutofillFocused() + val safeText = if (autofillFocused) { + documentBufferController.currentDocumentText() + } else { + text + } + val selStart = if (autofillFocused) 0 else imeController.selectionStart() + val selEnd = if (autofillFocused) 0 else imeController.selectionEnd() + if (::selectionOverlayView.isInitialized) { + selectionOverlayView.syncFromShapedLayout( + text = safeText, + selStart = selStart, + selEnd = selEnd, + viewportWidthPx = viewportW, + density = resources.displayMetrics.density, + ) + } + if (::textPreviewView.isInitialized) { + textPreviewView.invalidate() + } + } finally { + syncingOverlay = false + } + } + override fun surfaceDestroyed(holder: SurfaceHolder) { surfaceReady = false if (frameCallbackPosted) { @@ -559,7 +2618,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall @Suppress("DEPRECATION") override fun onBackPressed() { - val consumed = nativeHandle != 0L && NativeBridge.nativeOnBackGesturePhase(nativeHandle, 3, 1f) + val consumed = backDispatcher.onLegacyBackPressed(invokeSystemExit = false) if (!consumed) { super.onBackPressed() } @@ -621,33 +2680,19 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { val callback = object : OnBackAnimationCallback { override fun onBackStarted(backEvent: BackEvent) { - if (nativeHandle != 0L) { - NativeBridge.nativeOnBackGesturePhase(nativeHandle, 0, backEvent.progress) - requestFrameAndSchedule() - } + backDispatcher.onBackStarted(backEvent.progress) } override fun onBackProgressed(backEvent: BackEvent) { - if (nativeHandle != 0L) { - NativeBridge.nativeOnBackGesturePhase(nativeHandle, 1, backEvent.progress) - requestFrameAndSchedule() - } + backDispatcher.onBackProgressed(backEvent.progress) } override fun onBackCancelled() { - if (nativeHandle != 0L) { - NativeBridge.nativeOnBackGesturePhase(nativeHandle, 2, 0f) - requestFrameAndSchedule() - } + backDispatcher.onBackCancelled() } override fun onBackInvoked() { - val consumed = nativeHandle != 0L && NativeBridge.nativeOnBackGesturePhase(nativeHandle, 3, 1f) - if (consumed) { - requestFrameAndSchedule() - } else { - finish() - } + backDispatcher.onBackInvoked() } } backCallback = callback @@ -657,10 +2702,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall ) } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { val callback = OnBackInvokedCallback { - val consumed = nativeHandle != 0L && NativeBridge.nativeOnBackGesturePhase(nativeHandle, 3, 1f) - if (!consumed) { - finish() - } + backDispatcher.onLegacyBackPressed() } backCallback = callback onBackInvokedDispatcher.registerOnBackInvokedCallback( @@ -671,10 +2713,70 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall } private fun configureAutofillIfSupported() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && + val platformBackend = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && NativeBridge.nativeShouldExposeAutofill(Build.VERSION.SDK_INT) ) { - getSystemService(AutofillManager::class.java) + getSystemService(AutofillManager::class.java)?.let { manager -> + SystemAutofillPlatformBackend(surfaceView, manager) + } + } else { + null } + autofillController = AndroidAutofillController( + sdkInt = Build.VERSION.SDK_INT, + handleProvider = { nativeHandle }, + backend = platformBackend, + onMutated = { requestFrameAndSchedule() }, + onValueCommitted = { id, text -> + if (autofillController?.focusedFieldId() == id) { + applyAutofillTextToIme(text) + } + }, + onFocusedFieldTextSync = { _, text -> applyAutofillTextToIme(text) }, + ) + } + + fun navigateTo(destination: String): Boolean = backDispatcher.navigateTo(destination) + + fun openDocument(docId: String): Boolean = backDispatcher.openDocument(docId) + + fun readAutofillFormValues(): Map = + autofillController?.readFormValues() ?: emptyMap() + + private fun applyAutofillTextToIme(text: String) { + if (nativeHandle == 0L) return + documentBufferController.applyAutofillTextToIme(text) + } + + fun registerAutofillField( + autofillId: Int, + kindCode: Int, + left: Int, + top: Int, + right: Int, + bottom: Int, + masked: Boolean, + valueLen: Int = 0, + ): Boolean = autofillController?.registerField( + autofillId, + kindCode, + left, + top, + right, + bottom, + masked, + valueLen, + ) ?: false + + fun focusAutofillField(autofillId: Int?) { + documentBufferController.onAutofillFocusChanged(autofillId) + } + + fun commitAutofillSession(): Boolean = documentBufferController.commitAutofillSession() + + fun cancelAutofillSession(): Boolean = documentBufferController.cancelAutofillSession() + + fun clearAutofillFields() { + documentBufferController.clearAutofillFields() } } diff --git a/packages/frontend/hosts/android/src/autofill.rs b/packages/frontend/hosts/android/src/autofill.rs new file mode 100644 index 0000000000..4f70650eda --- /dev/null +++ b/packages/frontend/hosts/android/src/autofill.rs @@ -0,0 +1,463 @@ +//! API 26+ Android `AutofillManager` virtual view structure and value write-back +//! state machine, with deterministic API 24/25 degradation. + +use std::collections::BTreeMap; +use std::fmt; +use std::sync::atomic::{Ordering, compiler_fence}; + +use serde::Serialize; + +use crate::should_expose_autofill; + +/// Sensitive string buffer that zeroes its backing bytes on drop without unsafe code. +#[derive(Clone, PartialEq, Eq)] +struct ZeroizingString { + bytes: Vec, +} + +impl ZeroizingString { + fn from_str(text: &str) -> Self { + Self { + bytes: text.as_bytes().to_vec(), + } + } + + fn as_str(&self) -> &str { + std::str::from_utf8(&self.bytes).unwrap_or("") + } +} + +impl Drop for ZeroizingString { + fn drop(&mut self) { + for b in &mut self.bytes { + *b = 0; + } + compiler_fence(Ordering::SeqCst); + } +} + +/// Semantic autofill field category exposed as virtual nodes on API 26+. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[repr(i32)] +pub enum AutofillFieldKind { + Username = 0, + Email = 1, + Password = 2, + OneTimeCode = 3, +} + +impl AutofillFieldKind { + /// Converts a raw JNI integer code into an [`AutofillFieldKind`]. + pub const fn from_code(code: i32) -> Option { + match code { + 0 => Some(Self::Username), + 1 => Some(Self::Email), + 2 => Some(Self::Password), + 3 => Some(Self::OneTimeCode), + _ => None, + } + } + + /// Returns the Android `View.AUTOFILL_HINT_*` constant string for this field. + pub const fn android_hint(self) -> &'static str { + match self { + Self::Username => "username", + Self::Email => "emailAddress", + Self::Password => "password", + Self::OneTimeCode => "smsOTPCode", + } + } +} + +/// Screen pixel rectangle for an autofill virtual node. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +pub struct AutofillRect { + pub left: i32, + pub top: i32, + pub right: i32, + pub bottom: i32, +} + +impl AutofillRect { + /// Normalizes bounds so `right >= left` and `bottom >= top`. + pub const fn normalized(left: i32, top: i32, right: i32, bottom: i32) -> Self { + let (l, r) = if left <= right { + (left, right) + } else { + (right, left) + }; + let (t, b) = if top <= bottom { + (top, bottom) + } else { + (bottom, top) + }; + Self { + left: l, + top: t, + right: r, + bottom: b, + } + } +} + +/// Virtual autofill node registered by the host UI. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct AutofillFieldNode { + pub autofill_id: i32, + pub kind: AutofillFieldKind, + pub hint: &'static str, + pub bounds: AutofillRect, + pub masked: bool, + pub value_len: usize, + pub focused: bool, +} + +/// Notification emitted for the platform `AutofillManager` adapter. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub enum AutofillEvent { + ViewEntered { autofill_id: i32 }, + ViewExited { autofill_id: i32 }, + ValueChanged { autofill_id: i32, value_len: usize }, + Commit, + Cancel, +} + +#[derive(Serialize)] +struct VirtualStructurePayload<'a> { + enabled: bool, + sdk_int: u32, + focused_id: Option, + commit_count: u64, + fields: Vec<&'a AutofillFieldNode>, +} + +/// Host-side autofill state gated strictly at `sdk_int >= 26`. +#[derive(Clone, PartialEq, Eq)] +pub struct AutofillState { + sdk_int: u32, + fields: BTreeMap, + filled_values: BTreeMap, + focused_id: Option, + commit_count: u64, +} + +impl fmt::Debug for AutofillState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("AutofillState") + .field("sdk_int", &self.sdk_int) + .field("fields", &self.fields) + .field("filled_value_count", &self.filled_values.len()) + .field("focused_id", &self.focused_id) + .field("commit_count", &self.commit_count) + .finish() + } +} + +impl Default for AutofillState { + fn default() -> Self { + Self::new(0) + } +} + +impl AutofillState { + /// Creates an autofill state machine configured for `sdk_int`. + pub fn new(sdk_int: u32) -> Self { + Self { + sdk_int, + fields: BTreeMap::new(), + filled_values: BTreeMap::new(), + focused_id: None, + commit_count: 0, + } + } + + /// Updates the device API level. Clears virtual state when below API 26. + pub fn set_sdk_int(&mut self, sdk_int: u32) -> bool { + self.sdk_int = sdk_int; + if !self.is_enabled() { + self.fields.clear(); + self.filled_values.clear(); + self.focused_id = None; + return false; + } + true + } + + /// Returns `true` when Android `AutofillManager` is supported (`sdk_int >= 26`). + pub const fn is_enabled(&self) -> bool { + should_expose_autofill(self.sdk_int) + } + + /// Returns the currently focused virtual field ID, if any. + pub const fn focused_id(&self) -> Option { + self.focused_id + } + + /// Returns the number of committed autofill sessions. + pub const fn commit_count(&self) -> u64 { + self.commit_count + } + + /// Registers or updates a virtual login field. Returns `false` on API < 26. + pub fn upsert_field( + &mut self, + autofill_id: i32, + kind: AutofillFieldKind, + bounds: AutofillRect, + masked: bool, + value_len: usize, + ) -> bool { + if !self.is_enabled() || autofill_id <= 0 { + return false; + } + let focused = self.focused_id == Some(autofill_id); + self.fields.insert( + autofill_id, + AutofillFieldNode { + autofill_id, + kind, + hint: kind.android_hint(), + bounds, + masked, + value_len, + focused, + }, + ); + true + } + + /// Removes a virtual field and clears focus if it was focused. + pub fn remove_field(&mut self, autofill_id: i32) -> bool { + if !self.is_enabled() { + return false; + } + if self.focused_id == Some(autofill_id) { + self.focused_id = None; + } + self.filled_values.remove(&autofill_id); + self.fields.remove(&autofill_id).is_some() + } + + /// Moves autofill focus to `next_id`, returning `ViewExited`/`ViewEntered` events. + pub fn focus_field(&mut self, next_id: Option) -> Vec { + if !self.is_enabled() { + return Vec::new(); + } + let valid_next = next_id.filter(|id| self.fields.contains_key(id)); + if self.focused_id == valid_next { + return Vec::new(); + } + let mut events = Vec::with_capacity(2); + if let Some(prev_id) = self.focused_id.take() { + if let Some(node) = self.fields.get_mut(&prev_id) { + node.focused = false; + } + events.push(AutofillEvent::ViewExited { + autofill_id: prev_id, + }); + } + if let Some(id) = valid_next { + if let Some(node) = self.fields.get_mut(&id) { + node.focused = true; + } + self.focused_id = Some(id); + events.push(AutofillEvent::ViewEntered { autofill_id: id }); + } + events + } + + /// Synchronizes the field's real current text without exposing plaintext in + /// `virtual_structure_json()`. Clearing to empty removes the cached value so + /// `ViewStructure` never emits synthetic placeholders. + pub fn set_field_text(&mut self, autofill_id: i32, text: &str) -> bool { + if !self.is_enabled() { + return false; + } + let Some(node) = self.fields.get_mut(&autofill_id) else { + return false; + }; + node.value_len = text.encode_utf16().count(); + if text.is_empty() { + self.filled_values.remove(&autofill_id); + } else { + self.filled_values + .insert(autofill_id, ZeroizingString::from_str(text)); + } + true + } + + /// Applies an autofill value delivered by Android `autofill(SparseArray)`. + pub fn apply_autofill_value(&mut self, autofill_id: i32, value: &str) -> bool { + self.set_field_text(autofill_id, value) + } + + /// Reads the latest autofilled text for `autofill_id`, if present. + pub fn filled_value(&self, autofill_id: i32) -> Option<&str> { + if !self.is_enabled() { + return None; + } + self.filled_values + .get(&autofill_id) + .map(ZeroizingString::as_str) + } + + /// Reads the latest value for the first registered field matching `kind`. + pub fn filled_value_by_kind(&self, kind: AutofillFieldKind) -> Option<&str> { + if !self.is_enabled() { + return None; + } + self.fields + .values() + .find(|node| node.kind == kind) + .and_then(|node| self.filled_value(node.autofill_id)) + } + + /// Marks the active autofill context as committed, clears field focus, and + /// wipes cached plaintext values. + pub fn commit(&mut self) -> bool { + if !self.is_enabled() { + return false; + } + if let Some(prev_id) = self.focused_id.take() + && let Some(node) = self.fields.get_mut(&prev_id) + { + node.focused = false; + } + self.filled_values.clear(); + self.commit_count = self.commit_count.saturating_add(1); + true + } + + /// Cancels the active autofill session, clears focus, and wipes cached plaintext values. + pub fn cancel(&mut self) -> bool { + if !self.is_enabled() { + return false; + } + if let Some(prev_id) = self.focused_id.take() + && let Some(node) = self.fields.get_mut(&prev_id) + { + node.focused = false; + } + self.filled_values.clear(); + true + } + + /// Clears all registered virtual fields, focus, and cached plaintext values + /// (called on page navigation or form unmount). + pub fn clear_fields(&mut self) { + self.fields.clear(); + self.filled_values.clear(); + self.focused_id = None; + } + + /// Serializes the virtual view structure to JSON for Kotlin `ViewStructure` population. + pub fn virtual_structure_json(&self) -> String { + let payload = VirtualStructurePayload { + enabled: self.is_enabled(), + sdk_int: self.sdk_int, + focused_id: if self.is_enabled() { + self.focused_id + } else { + None + }, + commit_count: self.commit_count, + fields: if self.is_enabled() { + self.fields.values().collect() + } else { + Vec::new() + }, + }; + serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn autofill_degrades_safely_below_api_26_and_roundtrips_at_api_26_plus() { + for sdk in [24_u32, 25] { + let mut state = AutofillState::new(sdk); + assert!(!state.is_enabled()); + assert!(!state.upsert_field( + 1, + AutofillFieldKind::Username, + AutofillRect::normalized(10, 20, 300, 80), + false, + 0, + )); + assert!(state.focus_field(Some(1)).is_empty()); + assert!(!state.apply_autofill_value(1, "alice@affine.pro")); + assert_eq!(state.filled_value(1), None); + assert!(!state.commit()); + assert!(state.virtual_structure_json().contains("\"enabled\":false")); + } + + for sdk in [26_u32, 33, 35] { + let mut state = AutofillState::new(sdk); + assert!(state.is_enabled()); + assert!(state.upsert_field( + 101, + AutofillFieldKind::Email, + AutofillRect::normalized(20, 100, 900, 180), + false, + 0, + )); + assert!(state.upsert_field( + 102, + AutofillFieldKind::Password, + AutofillRect::normalized(20, 200, 900, 280), + true, + 0, + )); + assert!(state.upsert_field( + 103, + AutofillFieldKind::OneTimeCode, + AutofillRect::normalized(20, 300, 900, 380), + false, + 0, + )); + + assert_eq!( + state.focus_field(Some(101)), + vec![AutofillEvent::ViewEntered { autofill_id: 101 }] + ); + assert_eq!( + state.focus_field(Some(102)), + vec![ + AutofillEvent::ViewExited { autofill_id: 101 }, + AutofillEvent::ViewEntered { autofill_id: 102 }, + ] + ); + assert!(state.apply_autofill_value(101, "user@affine.pro")); + assert!(state.apply_autofill_value(102, "s3cr3t!")); + assert_eq!(state.filled_value(101), Some("user@affine.pro")); + assert_eq!(state.filled_value(102), Some("s3cr3t!")); + + let debug_repr = format!("{state:?}"); + assert!(!debug_repr.contains("s3cr3t!")); + assert!(!debug_repr.contains("user@affine.pro")); + + let json = state.virtual_structure_json(); + assert!(json.contains("\"enabled\":true")); + assert!(json.contains("\"emailAddress\"")); + assert!(json.contains("\"password\"")); + assert!(json.contains("\"smsOTPCode\"")); + assert!(!json.contains("s3cr3t!")); + + assert!(state.commit()); + assert_eq!(state.commit_count(), 1); + assert_eq!(state.focused_id(), None); + assert_eq!(state.filled_value(101), None); + assert_eq!(state.filled_value(102), None); + + assert!(state.set_field_text(102, "temp-pass")); + assert_eq!(state.filled_value(102), Some("temp-pass")); + assert!(state.cancel()); + assert_eq!(state.filled_value(102), None); + state.clear_fields(); + assert!(state.virtual_structure_json().contains("\"fields\":[]")); + } + } +} diff --git a/packages/frontend/hosts/android/src/ime.rs b/packages/frontend/hosts/android/src/ime.rs index d0e73201a7..faf423fe52 100644 --- a/packages/frontend/hosts/android/src/ime.rs +++ b/packages/frontend/hosts/android/src/ime.rs @@ -1,6 +1,111 @@ use crate::AndroidHostState; +use crate::selection::SelectionHandleKind; +use crate::text_layout::{ + caret_position_for_offset, closest_offset_for_position, detect_direction_at_offset, +}; impl AndroidHostState { + /// Synchronizes native selection handles with the current UTF-16 selection. + /// + /// Preserves active drag state when passing through zero-length coincidence points. + pub fn sync_selection_overlay_from_ime(&mut self) { + if self.selection.active_drag != SelectionHandleKind::None { + return; + } + let (start, end) = self.selection_range(); + if start == end { + self.selection.clear(); + return; + } + let (sx, sy) = caret_position_for_offset(&self.utf16_text, start, &self.text_layout); + let (ex, ey) = caret_position_for_offset(&self.utf16_text, end, &self.text_layout); + let dir = detect_direction_at_offset(&self.utf16_text, start, &self.text_layout); + self.selection + .update_selection(sx, sy, ex, ey, self.text_layout.line_height, dir, true); + } + + /// Starts dragging a selection handle and locks the opposite UTF-16 anchor so + /// slow drags across zero-length coincidence points smoothly invert selection. + pub fn begin_selection_handle_drag( + &mut self, + touch_x: f32, + touch_y: f32, + ) -> SelectionHandleKind { + let hit = self.selection.begin_drag(touch_x, touch_y); + let (sel_start, sel_end) = self.selection_range(); + self.selection_drag_initial_handle = hit; + self.selection_drag_anchor_utf16 = match hit { + SelectionHandleKind::Start => Some(sel_end), + SelectionHandleKind::End => Some(sel_start), + SelectionHandleKind::None => None, + }; + hit + } + + /// Continues dragging the active selection handle, using UTF-16 offset comparison + /// against the locked anchor as the single authority for handle ownership and + /// magnifier placement. + pub fn update_selection_handle_drag(&mut self, touch_x: f32, touch_y: f32) -> bool { + if let Some(anchor) = self.selection_drag_anchor_utf16 { + let Some((probe_x, probe_y)) = self.selection.probe_drag_position(touch_x, touch_y) + else { + return false; + }; + let offset = + closest_offset_for_position(&self.utf16_text, probe_x, probe_y, &self.text_layout); + let (lo, hi, active_handle) = if offset < anchor { + (offset, anchor, SelectionHandleKind::Start) + } else if offset > anchor { + (anchor, offset, SelectionHandleKind::End) + } else { + (anchor, anchor, self.selection_drag_initial_handle) + }; + self.selected_start = lo; + self.selected_len = hi - lo; + let (sx, sy) = caret_position_for_offset(&self.utf16_text, lo, &self.text_layout); + let (ex, ey) = caret_position_for_offset(&self.utf16_text, hi, &self.text_layout); + let dir = detect_direction_at_offset(&self.utf16_text, lo, &self.text_layout); + self.selection.apply_text_drag_endpoints( + sx, + sy, + ex, + ey, + self.text_layout.line_height, + dir, + active_handle, + ); + return true; + } + self.selection.update_drag(touch_x, touch_y) + } + + /// Finishes dragging a selection handle and snaps handles to the final UTF-16 range. + pub fn end_selection_handle_drag(&mut self) -> bool { + self.selection_drag_anchor_utf16 = None; + self.selection_drag_initial_handle = SelectionHandleKind::None; + let has_menu = self.selection.end_drag().is_some(); + if self.selected_len == 0 && self.selection.has_selection { + // Keep handles only if text selection is non-empty when synced with text. + if !self.utf16_text.is_empty() { + self.selection.clear(); + return false; + } + } else if self.selected_len > 0 { + self.sync_selection_overlay_from_ime(); + } + has_menu + } + + /// Cancels an active handle drag (`ACTION_CANCEL`), hiding the magnifier. + pub fn cancel_selection_handle_drag(&mut self) { + self.selection_drag_anchor_utf16 = None; + self.selection_drag_initial_handle = SelectionHandleKind::None; + let _ = self.selection.end_drag(); + if !self.utf16_text.is_empty() { + self.sync_selection_overlay_from_ime(); + } + } + pub fn text_string(&self) -> String { String::from_utf16_lossy(&self.utf16_text) } @@ -43,6 +148,7 @@ impl AndroidHostState { let (lo, hi) = if a <= b { (a, b) } else { (b, a) }; self.selected_start = lo; self.selected_len = hi - lo; + self.sync_selection_overlay_from_ime(); } fn active_replace_span(&self) -> (usize, usize) { @@ -85,6 +191,7 @@ impl AndroidHostState { self.selected_start = Self::cursor_after_edit(start, utf16.len(), new_cursor_pos, self.utf16_text.len()); self.selected_len = 0; + self.sync_selection_overlay_from_ime(); } /// Updates the composing text from `InputConnection.setComposingText`. @@ -101,6 +208,7 @@ impl AndroidHostState { self.selected_start = Self::cursor_after_edit(start, utf16.len(), new_cursor_pos, self.utf16_text.len()); self.selected_len = 0; + self.sync_selection_overlay_from_ime(); } /// Sets or clears the composing span without altering text or selection, @@ -138,6 +246,7 @@ impl AndroidHostState { self.selected_start = Self::cursor_after_edit(lo, utf16.len(), new_cursor_pos, self.utf16_text.len()); self.selected_len = 0; + self.sync_selection_overlay_from_ime(); } fn is_high_surrogate(u: u16) -> bool { diff --git a/packages/frontend/hosts/android/src/jni_bridge.rs b/packages/frontend/hosts/android/src/jni_bridge.rs index 4c55ae522f..28e80e6e3d 100644 --- a/packages/frontend/hosts/android/src/jni_bridge.rs +++ b/packages/frontend/hosts/android/src/jni_bridge.rs @@ -197,7 +197,7 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetHasBackDestinat has_destination: JBoolean, ) { let _ = with_host_mut(handle, |host| { - host.has_back_destination = has_destination != 0; + host.set_has_back_destination(has_destination != 0); }); } @@ -329,6 +329,7 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceInsetsPx( density: JFloat, ) { let _ = with_host_mut(handle, |host| { + host.surface.set_density(density); host.insets = physical_insets_to_logical_dp( safe_top_px, safe_right_px, @@ -337,6 +338,13 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceInsetsPx( ime_bottom_px, density, ); + if host.surface.width_px > 0 && host.surface.height_px > 0 { + host.selection.set_viewport( + host.surface.width_px as f32, + host.surface.height_px as f32, + host.surface.density, + ); + } }); } diff --git a/packages/frontend/hosts/android/src/jni_interaction.rs b/packages/frontend/hosts/android/src/jni_interaction.rs new file mode 100644 index 0000000000..9af00eb2a8 --- /dev/null +++ b/packages/frontend/hosts/android/src/jni_interaction.rs @@ -0,0 +1,959 @@ +#![allow(unsafe_code)] + +//! Thin hand-written JNI exports for Android selection overlays, surface +//! recreation/fallback recovery, API 26+ autofill, predictive back navigation, +//! and zero-heap streaming `PdfRenderer` pixel conversion with per-call +//! `ExceptionCheck`. + +use core::ffi::c_void; + +use crate::autofill::{AutofillFieldKind, AutofillRect}; +use crate::back_dispatch_mode; +use crate::jni_bridge::{ + JBoolean, JClass, JFloat, JInt, JLong, JObject, JSize, JString, JniEnvPtr, new_jstring, + read_jstring_utf8, with_host_mut, with_host_ref, +}; +use crate::pdf::{ + convert_argb8888_i32_chunk_to_rgba8_slice, pdf_page_cache_key, validate_pdf_dimensions, + validate_pdf_page_request, +}; +use crate::selection::{SelectionHandleKind, TextDirection}; + +pub type JIntArray = JObject; +pub type JByteArray = JObject; +pub type JFloatArray = JObject; + +// Standard JNI 1.2+ `JNINativeInterface` vtable indices. +const JNI_GET_ARRAY_LENGTH_INDEX: usize = 171; +const JNI_NEW_BYTE_ARRAY_INDEX: usize = 176; +const JNI_NEW_FLOAT_ARRAY_INDEX: usize = 181; +const JNI_GET_INT_ARRAY_REGION_INDEX: usize = 203; +const JNI_SET_BYTE_ARRAY_REGION_INDEX: usize = 208; +const JNI_SET_FLOAT_ARRAY_REGION_INDEX: usize = 213; +const JNI_EXCEPTION_CHECK_INDEX: usize = 228; +const PDF_STREAM_CHUNK_PIXELS: usize = 4096; + +type GetArrayLengthFn = unsafe extern "C" fn(JniEnvPtr, JObject) -> JSize; +type NewByteArrayFn = unsafe extern "C" fn(JniEnvPtr, JSize) -> JByteArray; +type NewFloatArrayFn = unsafe extern "C" fn(JniEnvPtr, JSize) -> JFloatArray; +type GetIntArrayRegionFn = unsafe extern "C" fn(JniEnvPtr, JIntArray, JSize, JSize, *mut JInt); +type SetByteArrayRegionFn = unsafe extern "C" fn(JniEnvPtr, JByteArray, JSize, JSize, *const i8); +type SetFloatArrayRegionFn = unsafe extern "C" fn(JniEnvPtr, JFloatArray, JSize, JSize, *const f32); +type ExceptionCheckFn = unsafe extern "C" fn(JniEnvPtr) -> JBoolean; + +unsafe fn new_jfloat_array(env: JniEnvPtr, values: &[f32]) -> JFloatArray { + if env.is_null() { + return core::ptr::null_mut(); + } + let Ok(len) = JSize::try_from(values.len()) else { + return core::ptr::null_mut(); + }; + let vtable = unsafe { *(env as *const *const *const c_void) }; + if vtable.is_null() { + return core::ptr::null_mut(); + } + let new_arr_ptr = unsafe { *vtable.add(JNI_NEW_FLOAT_ARRAY_INDEX) }; + let set_region_ptr = unsafe { *vtable.add(JNI_SET_FLOAT_ARRAY_REGION_INDEX) }; + let exc_check_ptr = unsafe { *vtable.add(JNI_EXCEPTION_CHECK_INDEX) }; + if new_arr_ptr.is_null() || set_region_ptr.is_null() || exc_check_ptr.is_null() { + return core::ptr::null_mut(); + } + let new_arr: NewFloatArrayFn = unsafe { core::mem::transmute(new_arr_ptr) }; + let set_region: SetFloatArrayRegionFn = unsafe { core::mem::transmute(set_region_ptr) }; + let exc_check: ExceptionCheckFn = unsafe { core::mem::transmute(exc_check_ptr) }; + + if unsafe { exc_check(env) } != 0 { + return core::ptr::null_mut(); + } + let arr = unsafe { new_arr(env, len) }; + if arr.is_null() || unsafe { exc_check(env) } != 0 { + return core::ptr::null_mut(); + } + if len > 0 { + unsafe { set_region(env, arr, 0, len, values.as_ptr()) }; + if unsafe { exc_check(env) } != 0 { + return core::ptr::null_mut(); + } + } + arr +} + +unsafe fn fill_jfloat_array(env: JniEnvPtr, arr: JFloatArray, values: &[f32]) -> bool { + if env.is_null() || arr.is_null() { + return false; + } + let Ok(len) = JSize::try_from(values.len()) else { + return false; + }; + let vtable = unsafe { *(env as *const *const *const c_void) }; + if vtable.is_null() { + return false; + } + let get_len_ptr = unsafe { *vtable.add(JNI_GET_ARRAY_LENGTH_INDEX) }; + let set_region_ptr = unsafe { *vtable.add(JNI_SET_FLOAT_ARRAY_REGION_INDEX) }; + let exc_check_ptr = unsafe { *vtable.add(JNI_EXCEPTION_CHECK_INDEX) }; + if get_len_ptr.is_null() || set_region_ptr.is_null() || exc_check_ptr.is_null() { + return false; + } + let get_len: GetArrayLengthFn = unsafe { core::mem::transmute(get_len_ptr) }; + let set_region: SetFloatArrayRegionFn = unsafe { core::mem::transmute(set_region_ptr) }; + let exc_check: ExceptionCheckFn = unsafe { core::mem::transmute(exc_check_ptr) }; + + if unsafe { exc_check(env) } != 0 { + return false; + } + let actual_len = unsafe { get_len(env, arr) }; + if unsafe { exc_check(env) } != 0 || actual_len < len { + return false; + } + if len > 0 { + unsafe { set_region(env, arr, 0, len, values.as_ptr()) }; + if unsafe { exc_check(env) } != 0 { + return false; + } + } + true +} + +// --- Selection Handles & IME-Integrated Drag --- + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetSelectionViewport( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + width: JFloat, + height: JFloat, + density: JFloat, +) { + let _ = with_host_mut(handle, |host| { + host.text_layout.update_viewport(width, density); + host.selection.set_viewport(width, height, density); + if host.selected_len > 0 { + host.sync_selection_overlay_from_ime(); + } + }); +} + +#[unsafe(no_mangle)] +#[allow(clippy::too_many_arguments)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeUpdateSelectionOverlay( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + start_x: JFloat, + start_y: JFloat, + end_x: JFloat, + end_y: JFloat, + line_height: JFloat, + direction_code: JInt, + has_selection: JBoolean, +) { + let direction = TextDirection::from_code(direction_code); + let _ = with_host_mut(handle, |host| { + host.selection.update_selection( + start_x, + start_y, + end_x, + end_y, + line_height, + direction, + has_selection != 0, + ); + }); +} + +#[unsafe(no_mangle)] +#[allow(clippy::too_many_arguments)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeApplyTextDragEndpoints( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + start_x: JFloat, + start_y: JFloat, + end_x: JFloat, + end_y: JFloat, + line_height: JFloat, + direction_code: JInt, + active_handle_code: JInt, +) { + let direction = TextDirection::from_code(direction_code); + let active_handle = SelectionHandleKind::from_code(active_handle_code); + let _ = with_host_mut(handle, |host| { + host.selection.apply_text_drag_endpoints( + start_x, + start_y, + end_x, + end_y, + line_height, + direction, + active_handle, + ); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSelectionBeginDrag( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + touch_x: JFloat, + touch_y: JFloat, +) -> JInt { + with_host_mut(handle, |host| { + host.begin_selection_handle_drag(touch_x, touch_y) as JInt + }) + .unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSelectionUpdateDrag( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + touch_x: JFloat, + touch_y: JFloat, +) -> JBoolean { + with_host_mut(handle, |host| { + u8::from(host.update_selection_handle_drag(touch_x, touch_y)) + }) + .unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSelectionEndDrag( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + with_host_mut(handle, |host| u8::from(host.end_selection_handle_drag())).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSelectionCancelDrag( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + let _ = with_host_mut(handle, |host| { + host.cancel_selection_handle_drag(); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeClearSelectionOverlay( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + let _ = with_host_mut(handle, |host| { + host.selection_drag_anchor_utf16 = None; + host.selection_drag_initial_handle = SelectionHandleKind::None; + host.selection.clear(); + }); +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetSelectionOverlayJson( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JString { + let json = with_host_ref(handle, |host| host.selection.to_json()).unwrap_or_default(); + unsafe { new_jstring(env, &json) } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetSelectionOverlayGeometry( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JFloatArray { + let packed = + with_host_ref(handle, |host| host.selection.pack_overlay_floats()).unwrap_or([0.0; 24]); + unsafe { new_jfloat_array(env, &packed) } +} + +/// Fills a caller-owned `FloatArray` (length >= 24) with packed overlay geometry +/// without per-frame JNI array allocation. +/// +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `out` must be null or a valid `jfloatArray`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeFillSelectionOverlayGeometry( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + out: JFloatArray, +) -> JBoolean { + let Some(packed) = with_host_ref(handle, |host| host.selection.pack_overlay_floats()) else { + return 0; + }; + u8::from(unsafe { fill_jfloat_array(env, out, &packed) }) +} + +// --- Surface Recreation, Scroll/DPI State Preservation & Vulkan -> GLES3 Recovery --- + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetSurfaceScrollOffset( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + scroll_x: JFloat, + scroll_y: JFloat, +) { + let _ = with_host_mut(handle, |host| { + host.surface.set_scroll_offset(scroll_x, scroll_y); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetSurfaceScrollY( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JFloat { + with_host_ref(handle, |host| host.surface.scroll_offset_y).unwrap_or(0.0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetSurfaceDensity( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JFloat { + with_host_ref(handle, |host| host.surface.density).unwrap_or(1.0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetTextureGeneration( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JLong { + with_host_ref(handle, |host| host.surface.texture_generation as JLong).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetEffectiveImeBottomDp( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JFloat { + with_host_ref(handle, |host| host.insets.effective_ime_above_nav_bar()).unwrap_or(0.0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSelectRenderBackend( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + vulkan_available: JBoolean, + gles3_available: JBoolean, +) -> JInt { + with_host_mut(handle, |host| { + host.surface + .select_backend(vulkan_available != 0, gles3_available != 0) as JInt + }) + .unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeReportVulkanDeviceLost( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JInt { + with_host_mut(handle, |host| { + host.surface.report_vulkan_device_lost() as JInt + }) + .unwrap_or(0) +} + +// --- API 26+ AutofillManager Virtual Structure Bridge --- + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeConfigureAutofillSdk( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + sdk_int: JInt, +) -> JBoolean { + let sdk = u32::try_from(sdk_int).unwrap_or(0); + with_host_mut(handle, |host| u8::from(host.autofill.set_sdk_int(sdk))).unwrap_or(0) +} + +#[unsafe(no_mangle)] +#[allow(clippy::too_many_arguments)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeUpsertAutofillField( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + autofill_id: JInt, + kind_code: JInt, + left: JInt, + top: JInt, + right: JInt, + bottom: JInt, + masked: JBoolean, + value_len: JInt, +) -> JBoolean { + let Some(kind) = AutofillFieldKind::from_code(kind_code) else { + return 0; + }; + let len = usize::try_from(value_len).unwrap_or(0); + let bounds = AutofillRect::normalized(left, top, right, bottom); + with_host_mut(handle, |host| { + u8::from( + host.autofill + .upsert_field(autofill_id, kind, bounds, masked != 0, len), + ) + }) + .unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeFocusAutofillField( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + autofill_id: JInt, +) -> JInt { + let next = if autofill_id > 0 { + Some(autofill_id) + } else { + None + }; + with_host_mut(handle, |host| host.autofill.focus_field(next).len() as JInt).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetFocusedAutofillFieldId( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JInt { + with_host_ref(handle, |host| host.autofill.focused_id().unwrap_or(0)).unwrap_or(0) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `text` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetAutofillFieldText( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + autofill_id: JInt, + text: JString, +) -> JBoolean { + let Some(val) = (unsafe { read_jstring_utf8(env, text) }) else { + return 0; + }; + with_host_mut(handle, |host| { + u8::from(host.autofill.set_field_text(autofill_id, &val)) + }) + .unwrap_or(0) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `value` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeApplyAutofillValue( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + autofill_id: JInt, + value: JString, +) -> JBoolean { + let Some(text) = (unsafe { read_jstring_utf8(env, value) }) else { + return 0; + }; + with_host_mut(handle, |host| { + u8::from(host.autofill.apply_autofill_value(autofill_id, &text)) + }) + .unwrap_or(0) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetAutofillValue( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + autofill_id: JInt, +) -> JString { + let value = with_host_ref(handle, |host| { + host.autofill.filled_value(autofill_id).map(str::to_string) + }) + .flatten(); + match value { + Some(v) => unsafe { new_jstring(env, &v) }, + None => core::ptr::null_mut(), + } +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetAutofillValueByKind( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + kind_code: JInt, +) -> JString { + let Some(kind) = AutofillFieldKind::from_code(kind_code) else { + return core::ptr::null_mut(); + }; + let value = with_host_ref(handle, |host| { + host.autofill.filled_value_by_kind(kind).map(str::to_string) + }) + .flatten(); + match value { + Some(v) => unsafe { new_jstring(env, &v) }, + None => core::ptr::null_mut(), + } +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeCommitAutofill( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + with_host_mut(handle, |host| u8::from(host.autofill.commit())).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeCancelAutofill( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JBoolean { + with_host_mut(handle, |host| u8::from(host.autofill.cancel())).unwrap_or(0) +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeClearAutofillFields( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) { + let _ = with_host_mut(handle, |host| { + host.autofill.clear_fields(); + }); +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetAutofillStructureJson( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JString { + let json = + with_host_ref(handle, |host| host.autofill.virtual_structure_json()).unwrap_or_default(); + unsafe { new_jstring(env, &json) } +} + +// --- Predictive Back API-Level Dispatch & Destination Navigation Stack --- + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeBackDispatchMode( + _env: JniEnvPtr, + _class: JClass, + sdk_int: JInt, +) -> JInt { + let sdk = u32::try_from(sdk_int).unwrap_or(0); + back_dispatch_mode(sdk) as JInt +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `route` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativePushDestination( + env: JniEnvPtr, + _class: JClass, + handle: JLong, + route: JString, +) -> JBoolean { + let Some(route_str) = (unsafe { read_jstring_utf8(env, route) }) else { + return 0; + }; + with_host_mut(handle, |host| { + u8::from(host.push_back_destination(route_str)) + }) + .unwrap_or(0) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetCurrentDestination( + env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JString { + let dest = with_host_ref(handle, |host| { + host.current_back_destination().map(str::to_string) + }) + .flatten(); + match dest { + Some(route) => unsafe { new_jstring(env, &route) }, + None => core::ptr::null_mut(), + } +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetBackStackDepth( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, + depth: JInt, +) { + let safe_depth = u32::try_from(depth).unwrap_or(0); + let _ = with_host_mut(handle, |host| { + host.set_back_stack_depth(safe_depth); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetBackStackDepth( + _env: JniEnvPtr, + _class: JClass, + handle: JLong, +) -> JInt { + with_host_ref(handle, |host| { + host.back_stack_depth().min(i32::MAX as u32) as JInt + }) + .unwrap_or(0) +} + +// --- Native PdfRenderer Validation, Cache Key & Zero-Heap Streaming ARGB_8888 -> RGBA8 --- + +#[unsafe(no_mangle)] +pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeValidatePdfPageRequest( + _env: JniEnvPtr, + _class: JClass, + page_index: JInt, + page_count: JInt, + width_px: JInt, + height_px: JInt, +) -> JBoolean { + let (Ok(idx), Ok(count), Ok(w), Ok(h)) = ( + u32::try_from(page_index), + u32::try_from(page_count), + u32::try_from(width_px), + u32::try_from(height_px), + ) else { + return 0; + }; + u8::from(validate_pdf_page_request(idx, count, w, h).is_ok()) +} + +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `doc_id` must be null or a valid `jstring`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativePdfPageCacheKey( + env: JniEnvPtr, + _class: JClass, + doc_id: JString, + page_index: JInt, + width_px: JInt, + height_px: JInt, + dpi_bucket: JInt, +) -> JString { + let doc = unsafe { read_jstring_utf8(env, doc_id) }.unwrap_or_default(); + let idx = page_index.max(0) as u32; + let w = width_px.max(0) as u32; + let h = height_px.max(0) as u32; + let dpi = dpi_bucket.max(72) as u32; + let key = pdf_page_cache_key(&doc, idx, w, h, dpi); + unsafe { new_jstring(env, &key) } +} + +/// Converts a JNI `jintArray` (`ARGB_8888`) directly into a freshly allocated +/// Java `jbyteArray` (`RGBA8`) using stack-only 4096-pixel chunk buffers (0 B +/// Rust heap allocation) and checking `ExceptionCheck` after every JNI call. +/// +/// # Safety +/// `env` must be null or a valid `JNIEnv*`; `argb_pixels` must be null or a valid `jintArray`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativePdfConvertArgbToRgba( + env: JniEnvPtr, + _class: JClass, + argb_pixels: JIntArray, + width_px: JInt, + height_px: JInt, +) -> JByteArray { + if env.is_null() || argb_pixels.is_null() { + return core::ptr::null_mut(); + } + let (Ok(w), Ok(h)) = (u32::try_from(width_px), u32::try_from(height_px)) else { + return core::ptr::null_mut(); + }; + let Ok(expected_pixels) = validate_pdf_dimensions(w, h) else { + return core::ptr::null_mut(); + }; + let Ok(expected_jlen) = JSize::try_from(expected_pixels) else { + return core::ptr::null_mut(); + }; + let Some(total_rgba_bytes_usize) = expected_pixels.checked_mul(4) else { + return core::ptr::null_mut(); + }; + let Ok(total_rgba_bytes) = JSize::try_from(total_rgba_bytes_usize) else { + return core::ptr::null_mut(); + }; + + let vtable = unsafe { *(env as *const *const *const c_void) }; + if vtable.is_null() { + return core::ptr::null_mut(); + } + let get_len_ptr = unsafe { *vtable.add(JNI_GET_ARRAY_LENGTH_INDEX) }; + let new_arr_ptr = unsafe { *vtable.add(JNI_NEW_BYTE_ARRAY_INDEX) }; + let get_region_ptr = unsafe { *vtable.add(JNI_GET_INT_ARRAY_REGION_INDEX) }; + let set_region_ptr = unsafe { *vtable.add(JNI_SET_BYTE_ARRAY_REGION_INDEX) }; + let exc_check_ptr = unsafe { *vtable.add(JNI_EXCEPTION_CHECK_INDEX) }; + if get_len_ptr.is_null() + || new_arr_ptr.is_null() + || get_region_ptr.is_null() + || set_region_ptr.is_null() + || exc_check_ptr.is_null() + { + return core::ptr::null_mut(); + } + let get_len: GetArrayLengthFn = unsafe { core::mem::transmute(get_len_ptr) }; + let new_arr: NewByteArrayFn = unsafe { core::mem::transmute(new_arr_ptr) }; + let get_region: GetIntArrayRegionFn = unsafe { core::mem::transmute(get_region_ptr) }; + let set_region: SetByteArrayRegionFn = unsafe { core::mem::transmute(set_region_ptr) }; + let exc_check: ExceptionCheckFn = unsafe { core::mem::transmute(exc_check_ptr) }; + + if unsafe { exc_check(env) } != 0 { + return core::ptr::null_mut(); + } + let actual_len = unsafe { get_len(env, argb_pixels) }; + if unsafe { exc_check(env) } != 0 || actual_len != expected_jlen { + return core::ptr::null_mut(); + } + + let out_arr = unsafe { new_arr(env, total_rgba_bytes) }; + if out_arr.is_null() || unsafe { exc_check(env) } != 0 { + return core::ptr::null_mut(); + } + + let mut argb_chunk = [0_i32; PDF_STREAM_CHUNK_PIXELS]; + let mut rgba_chunk = [0_u8; PDF_STREAM_CHUNK_PIXELS * 4]; + let mut offset = 0usize; + while offset < expected_pixels { + let count = (expected_pixels - offset).min(PDF_STREAM_CHUNK_PIXELS); + unsafe { + get_region( + env, + argb_pixels, + offset as JSize, + count as JSize, + argb_chunk.as_mut_ptr(), + ); + } + if unsafe { exc_check(env) } != 0 { + return core::ptr::null_mut(); + } + convert_argb8888_i32_chunk_to_rgba8_slice( + &argb_chunk[..count], + &mut rgba_chunk[..count * 4], + ); + unsafe { + set_region( + env, + out_arr, + (offset * 4) as JSize, + (count * 4) as JSize, + rgba_chunk.as_ptr() as *const i8, + ); + } + if unsafe { exc_check(env) } != 0 { + return core::ptr::null_mut(); + } + offset += count; + } + out_arr +} + +#[cfg(test)] +mod tests { + use super::*; + + #[repr(C)] + struct MockJniEnv { + vtable: *const *const c_void, + input_pixels: Vec, + output_bytes: Vec, + pending_exception: bool, + fail_get_region_on_call: Option, + fail_set_region_on_call: Option, + get_region_calls: usize, + set_region_calls: usize, + } + + unsafe extern "C" fn mock_get_array_len(env: JniEnvPtr, _arr: JObject) -> JSize { + let state = unsafe { &*(env as *const MockJniEnv) }; + state.input_pixels.len() as JSize + } + + unsafe extern "C" fn mock_new_byte_array(env: JniEnvPtr, len: JSize) -> JByteArray { + let state = unsafe { &mut *(env as *mut MockJniEnv) }; + state.output_bytes = vec![0u8; len as usize]; + (&raw mut state.output_bytes) as JByteArray + } + + unsafe extern "C" fn mock_get_int_region( + env: JniEnvPtr, + _arr: JIntArray, + start: JSize, + len: JSize, + buf: *mut JInt, + ) { + let state = unsafe { &mut *(env as *mut MockJniEnv) }; + assert!( + !state.pending_exception, + "must never call GetIntArrayRegion with pending exception" + ); + let call_idx = state.get_region_calls; + state.get_region_calls += 1; + if state.fail_get_region_on_call == Some(call_idx) { + state.pending_exception = true; + return; + } + let s = start as usize; + let n = len as usize; + let dst = unsafe { core::slice::from_raw_parts_mut(buf, n) }; + dst.copy_from_slice(&state.input_pixels[s..s + n]); + } + + unsafe extern "C" fn mock_set_byte_region( + env: JniEnvPtr, + _arr: JByteArray, + start: JSize, + len: JSize, + buf: *const i8, + ) { + let state = unsafe { &mut *(env as *mut MockJniEnv) }; + assert!( + !state.pending_exception, + "must never call SetByteArrayRegion with pending exception" + ); + let call_idx = state.set_region_calls; + state.set_region_calls += 1; + if state.fail_set_region_on_call == Some(call_idx) { + state.pending_exception = true; + return; + } + let s = start as usize; + let n = len as usize; + let src = unsafe { core::slice::from_raw_parts(buf as *const u8, n) }; + state.output_bytes[s..s + n].copy_from_slice(src); + } + + unsafe extern "C" fn mock_exception_check(env: JniEnvPtr) -> JBoolean { + let state = unsafe { &*(env as *const MockJniEnv) }; + u8::from(state.pending_exception) + } + + fn build_mock_vtable() -> [*const c_void; 232] { + let mut table = [core::ptr::null(); 232]; + table[JNI_GET_ARRAY_LENGTH_INDEX] = mock_get_array_len as *const c_void; + table[JNI_NEW_BYTE_ARRAY_INDEX] = mock_new_byte_array as *const c_void; + table[JNI_GET_INT_ARRAY_REGION_INDEX] = mock_get_int_region as *const c_void; + table[JNI_SET_BYTE_ARRAY_REGION_INDEX] = mock_set_byte_region as *const c_void; + table[JNI_EXCEPTION_CHECK_INDEX] = mock_exception_check as *const c_void; + table + } + + #[test] + fn pdf_jni_streaming_aborts_immediately_on_exception_and_streams_multi_chunk() { + let vtable = build_mock_vtable(); + let fake_arr = 0x1000usize as JIntArray; + + // 1. Multi-chunk success (5000 pixels > 4096 chunk size -> 2 Get + 2 Set calls). + let mut env = MockJniEnv { + vtable: vtable.as_ptr(), + input_pixels: vec![0xFF11_2233_u32 as i32; 5000], + output_bytes: Vec::new(), + pending_exception: false, + fail_get_region_on_call: None, + fail_set_region_on_call: None, + get_region_calls: 0, + set_region_calls: 0, + }; + let out = unsafe { + Java_app_affine_pro_host_NativeBridge_nativePdfConvertArgbToRgba( + (&raw mut env) as JniEnvPtr, + core::ptr::null_mut(), + fake_arr, + 100, + 50, + ) + }; + assert!(!out.is_null()); + assert_eq!(env.get_region_calls, 2); + assert_eq!(env.set_region_calls, 2); + assert_eq!(&env.output_bytes[0..4], &[0x11, 0x22, 0x33, 0xFF]); + assert_eq!( + &env.output_bytes[4999 * 4..5000 * 4], + &[0x11, 0x22, 0x33, 0xFF] + ); + + // 2. Pending exception raised during chunk 1 GetIntArrayRegion -> aborts before SetByteArrayRegion #1. + let mut env_fail_get = MockJniEnv { + vtable: vtable.as_ptr(), + input_pixels: vec![0xFF11_2233_u32 as i32; 5000], + output_bytes: Vec::new(), + pending_exception: false, + fail_get_region_on_call: Some(1), + fail_set_region_on_call: None, + get_region_calls: 0, + set_region_calls: 0, + }; + let out_fail_get = unsafe { + Java_app_affine_pro_host_NativeBridge_nativePdfConvertArgbToRgba( + (&raw mut env_fail_get) as JniEnvPtr, + core::ptr::null_mut(), + fake_arr, + 100, + 50, + ) + }; + assert!(out_fail_get.is_null()); + assert_eq!(env_fail_get.get_region_calls, 2); + assert_eq!(env_fail_get.set_region_calls, 1); + + // 3. Pending exception raised during chunk 0 SetByteArrayRegion -> aborts before chunk 1 GetIntArrayRegion. + let mut env_fail_set = MockJniEnv { + vtable: vtable.as_ptr(), + input_pixels: vec![0xFF11_2233_u32 as i32; 5000], + output_bytes: Vec::new(), + pending_exception: false, + fail_get_region_on_call: None, + fail_set_region_on_call: Some(0), + get_region_calls: 0, + set_region_calls: 0, + }; + let out_fail_set = unsafe { + Java_app_affine_pro_host_NativeBridge_nativePdfConvertArgbToRgba( + (&raw mut env_fail_set) as JniEnvPtr, + core::ptr::null_mut(), + fake_arr, + 100, + 50, + ) + }; + assert!(out_fail_set.is_null()); + assert_eq!(env_fail_set.get_region_calls, 1); + assert_eq!(env_fail_set.set_region_calls, 1); + } +} diff --git a/packages/frontend/hosts/android/src/lib.rs b/packages/frontend/hosts/android/src/lib.rs index 3109d514f5..cfbb50ee2d 100644 --- a/packages/frontend/hosts/android/src/lib.rs +++ b/packages/frontend/hosts/android/src/lib.rs @@ -16,16 +16,33 @@ use serde::{Deserialize, Serialize}; #[cfg(target_os = "android")] mod android_window; +pub mod autofill; pub mod datastore; mod ime; +pub mod pdf; +pub mod selection; pub mod storage; pub mod surface; +pub mod text_layout; #[cfg(any(target_os = "android", test, feature = "host-jni"))] pub mod jni_bridge; #[cfg(any(target_os = "android", test, feature = "host-jni"))] +pub mod jni_interaction; +#[cfg(any(target_os = "android", test, feature = "host-jni"))] pub mod jni_storage; +pub use autofill::{ + AutofillEvent, AutofillFieldKind, AutofillFieldNode, AutofillRect, AutofillState, +}; +pub use pdf::{ + MAX_PDF_RENDER_DIM_PX, MAX_PDF_RENDER_PIXELS, PdfRenderError, argb8888_i32_to_rgba8, + argb8888_to_rgba8, pdf_page_cache_key, validate_pdf_page_request, +}; +pub use selection::{ + HandleGeometry, MagnifierState, RectF, SelectionHandleKind, SelectionOverlayState, + TeardropOrientation, TextDirection, +}; pub use storage::{ AndroidSqliteBridge, AndroidWorkspaceCatalog, LOCAL_WORKSPACE_LOCAL_STORAGE_KEY, }; @@ -94,6 +111,37 @@ pub struct LogicalWindowInsets { pub ime_bottom: f32, } +impl LogicalWindowInsets { + /// Returns keyboard height strictly above the bottom navigation bar in logical `dp`, + /// preventing double-deduction when combining `safe_bottom` and `ime_bottom`. + pub fn effective_ime_above_nav_bar(&self) -> f32 { + (self.ime_bottom - self.safe_bottom).max(0.0) + } +} + +/// Android back navigation dispatch strategy by API level. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(i32)] +pub enum BackDispatchMode { + /// API 24-32: legacy `Activity.onBackPressed()` single-step commit. + LegacyOnBackPressed = 0, + /// API 33: `OnBackInvokedCallback` single-step commit. + OnBackInvoked = 1, + /// API 34+: `OnBackAnimationCallback` four-phase predictive back. + OnBackAnimation = 2, +} + +/// Selects the Android back dispatch strategy for `sdk_int`. +pub const fn back_dispatch_mode(sdk_int: u32) -> BackDispatchMode { + if sdk_int >= 34 { + BackDispatchMode::OnBackAnimation + } else if sdk_int >= 33 { + BackDispatchMode::OnBackInvoked + } else { + BackDispatchMode::LegacyOnBackPressed + } +} + /// Converts Android `WindowInsets` physical pixel measurements into logical `dp`. pub fn physical_insets_to_logical_dp( safe_top_px: i32, @@ -416,13 +464,83 @@ pub fn verify_legacy_writeback_result( Ok(()) } +/// Default root destination route for the Android host navigation stack. +pub const DEFAULT_ROOT_DESTINATION: &str = "workspace/home"; + +/// Destination route stack driving Android back navigation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BackNavigationState { + destinations: Vec, +} + +impl Default for BackNavigationState { + fn default() -> Self { + Self::new() + } +} + +impl BackNavigationState { + /// Creates a navigation stack seeded with the root destination (`depth == 0`). + pub fn new() -> Self { + Self { + destinations: vec![DEFAULT_ROOT_DESTINATION.to_string()], + } + } + + /// Returns the currently active destination route. + pub fn current_destination(&self) -> Option<&str> { + self.destinations.last().map(String::as_str) + } + + /// Pushes a non-empty destination route onto the navigation stack. + pub fn push_destination(&mut self, route: impl Into) -> bool { + let route = route.into(); + if route.is_empty() { + return false; + } + if self.destinations.is_empty() { + self.destinations.push(DEFAULT_ROOT_DESTINATION.to_string()); + } + self.destinations.push(route); + true + } + + /// Pops the top non-root destination, returning `None` when already at root. + pub fn pop_destination(&mut self) -> Option { + if self.destinations.len() > 1 { + self.destinations.pop() + } else { + None + } + } + + /// Returns the number of poppable non-root destinations. + pub fn depth(&self) -> u32 { + self.destinations.len().saturating_sub(1) as u32 + } + + /// Rebuilds synthetic stack entries to match an explicit poppable depth. + pub fn set_depth(&mut self, depth: u32) { + self.destinations.clear(); + self.destinations.push(DEFAULT_ROOT_DESTINATION.to_string()); + for level in 1..=depth { + self.destinations.push(format!("route/{level}")); + } + } +} + /// Pure safe-Rust state held behind an Android JNI host handle. #[derive(Debug)] pub struct AndroidHostState { pub back_gesture: BackGestureMachine, - pub has_back_destination: bool, + pub back_navigation: BackNavigationState, pub insets: LogicalWindowInsets, pub surface: SurfaceLifecycleState, + pub selection: SelectionOverlayState, + pub text_layout: text_layout::TextLayoutMetrics, + pub selection_drag_anchor_utf16: Option, + pub selection_drag_initial_handle: SelectionHandleKind, + pub autofill: AutofillState, pub upgrade_import: LegacyUpgradeImportState, pub workspace_catalog: AndroidWorkspaceCatalog, /// Losslessly preserves the raw `affine-local-workspace` value read on upgrade @@ -443,9 +561,14 @@ impl Default for AndroidHostState { fn default() -> Self { Self { back_gesture: BackGestureMachine::new(), - has_back_destination: false, + back_navigation: BackNavigationState::new(), insets: LogicalWindowInsets::default(), surface: SurfaceLifecycleState::new(), + selection: SelectionOverlayState::new(), + text_layout: text_layout::TextLayoutMetrics::default(), + selection_drag_anchor_utf16: None, + selection_drag_initial_handle: SelectionHandleKind::None, + autofill: AutofillState::default(), upgrade_import: LegacyUpgradeImportState::Pending, workspace_catalog: AndroidWorkspaceCatalog::default(), raw_local_workspace_value: None, @@ -474,13 +597,44 @@ impl AndroidHostState { ) } + /// Pushes a destination route onto the host navigation stack. + pub fn push_back_destination(&mut self, route: impl Into) -> bool { + self.back_navigation.push_destination(route) + } + + /// Returns the currently active destination route. + pub fn current_back_destination(&self) -> Option<&str> { + self.back_navigation.current_destination() + } + + /// Sets the number of poppable navigation entries on the back stack. + pub fn set_back_stack_depth(&mut self, depth: u32) { + self.back_navigation.set_depth(depth); + } + + /// Returns the remaining number of poppable navigation entries. + pub fn back_stack_depth(&self) -> u32 { + self.back_navigation.depth() + } + + /// Sets whether at least one back destination exists (`0` or `1` stack depth). + pub fn set_has_back_destination(&mut self, has_destination: bool) { + self.back_navigation.set_depth(u32::from(has_destination)); + } + + /// Returns `true` when at least one back destination can be popped. + pub fn has_back_destination(&self) -> bool { + self.back_navigation.depth() > 0 + } + /// Handles a back gesture phase; returns `true` only when the host consumed - /// the event (an unconsumed `Commit` at the navigation root returns `false` - /// so Android delegates to the system back action). + /// the event. Each `Commit` atomically pops the top destination from + /// `back_navigation` and returns `false` at the root so Android delegates to + /// system exit. `Cancel` leaves the active destination unchanged. pub fn handle_back_phase(&mut self, phase: BackGesturePhase, progress: f32) -> bool { - if phase == BackGesturePhase::Commit && !self.has_back_destination { + if phase == BackGesturePhase::Commit { let _ = self.back_gesture.transition(phase, progress); - return false; + return self.back_navigation.pop_destination().is_some(); } self.back_gesture.transition(phase, progress).is_ok() } @@ -596,6 +750,67 @@ impl AndroidHostState { mod tests { use super::*; + #[test] + fn back_dispatch_mode_and_effective_ime_insets_follow_api_and_nav_bar_rules() { + let mode_cases = [ + (24_u32, BackDispatchMode::LegacyOnBackPressed), + (25, BackDispatchMode::LegacyOnBackPressed), + (32, BackDispatchMode::LegacyOnBackPressed), + (33, BackDispatchMode::OnBackInvoked), + (34, BackDispatchMode::OnBackAnimation), + (35, BackDispatchMode::OnBackAnimation), + ]; + for (sdk_int, expected) in mode_cases { + assert_eq!(back_dispatch_mode(sdk_int), expected); + } + + let inset_cases = [ + // Keyboard taller than navigation bar -> deducts safe_bottom to avoid double subtraction. + ((72, 900, 3.0_f32), 276.0_f32), + // Keyboard hidden (ime_bottom == 0) -> clamps to 0. + ((72, 0, 3.0_f32), 0.0_f32), + // Keyboard inset smaller than nav bar -> clamps to 0. + ((72, 48, 3.0_f32), 0.0_f32), + ]; + for ((nav_px, ime_px, density), expected_effective) in inset_cases { + let insets = physical_insets_to_logical_dp(0, 0, nav_px, 0, ime_px, density); + assert_eq!(insets.effective_ime_above_nav_bar(), expected_effective); + } + + // Real destination navigation stack pops route-by-route, preserves route on Cancel, + // and returns false at root destination. + let mut host = AndroidHostState::new(); + assert_eq!( + host.current_back_destination(), + Some(DEFAULT_ROOT_DESTINATION) + ); + assert!(host.push_back_destination("doc/welcome")); + assert!(host.push_back_destination("doc/settings")); + assert_eq!(host.back_stack_depth(), 2); + assert_eq!(host.current_back_destination(), Some("doc/settings")); + assert!(host.handle_back_phase(BackGesturePhase::Start, 0.0)); + assert!(host.handle_back_phase(BackGesturePhase::Progress, 0.4)); + assert!(host.handle_back_phase(BackGesturePhase::Cancel, 0.0)); + assert_eq!(host.current_back_destination(), Some("doc/settings")); + assert_eq!(host.back_stack_depth(), 2); + assert!(host.handle_back_phase(BackGesturePhase::Commit, 1.0)); + assert_eq!(host.current_back_destination(), Some("doc/welcome")); + assert_eq!(host.back_stack_depth(), 1); + assert!(host.handle_back_phase(BackGesturePhase::Start, 0.0)); + assert!(host.handle_back_phase(BackGesturePhase::Progress, 0.6)); + assert!(host.handle_back_phase(BackGesturePhase::Commit, 1.0)); + assert_eq!( + host.current_back_destination(), + Some(DEFAULT_ROOT_DESTINATION) + ); + assert_eq!(host.back_stack_depth(), 0); + assert!(!host.handle_back_phase(BackGesturePhase::Commit, 1.0)); + assert_eq!( + host.current_back_destination(), + Some(DEFAULT_ROOT_DESTINATION) + ); + } + #[test] fn autofill_gate_enforces_api_26_floor() { let cases = [ @@ -1068,4 +1283,41 @@ mod tests { assert_eq!(jni_bridge::snapshot_text(handle), None); } } + + #[test] + fn single_line_vertical_drag_beyond_half_line_never_flips_handle_or_loupe() { + let mut host = AndroidHostState::new(); + host.text_layout = crate::text_layout::TextLayoutMetrics::for_viewport(1080.0, 3.0); + host.selection.set_viewport(1080.0, 2400.0, 3.0); + let text: Vec = "Hello world".encode_utf16().collect(); + host.commit_text_utf16(&text, 1); + host.set_selection(6, 11); + + let initial_end_x = host.selection.end_handle.tip_x; + let end_cx = host.selection.end_handle.center_x; + let end_cy = host.selection.end_handle.center_y; + assert_eq!( + host.begin_selection_handle_drag(end_cx, end_cy), + SelectionHandleKind::End + ); + + for dy in [-43.0_f32, -60.0, -120.0, 0.0, 43.0, 120.0, 0.0] { + assert!(host.update_selection_handle_drag(end_cx, end_cy + dy)); + assert_eq!( + host.selection_range(), + (6, 11), + "selection must remain [6, 11) at dy={dy}" + ); + assert_eq!( + host.selection.active_drag, + SelectionHandleKind::End, + "active_drag must remain End at dy={dy}" + ); + assert!( + (host.selection.magnifier.anchor_x - initial_end_x).abs() < 0.01, + "magnifier anchor_x ({}) must stay at right end ({initial_end_x}) at dy={dy}", + host.selection.magnifier.anchor_x + ); + } + } } diff --git a/packages/frontend/hosts/android/src/pdf.rs b/packages/frontend/hosts/android/src/pdf.rs new file mode 100644 index 0000000000..22002f046d --- /dev/null +++ b/packages/frontend/hosts/android/src/pdf.rs @@ -0,0 +1,243 @@ +//! Native Android `PdfRenderer` page validation, memory ceiling enforcement, +//! deterministic cache key generation, and `ARGB_8888 -> RGBA8` pixel conversion. + +/// Maximum single-axis dimension (pixels) allowed for an in-place PDF page render. +pub const MAX_PDF_RENDER_DIM_PX: u32 = 4096; + +/// Maximum total pixel count per rendered PDF page (4096 * 4096 = 64 MiB RGBA8). +pub const MAX_PDF_RENDER_PIXELS: u64 = 16_777_216; + +/// Validation or conversion error for an Android `PdfRenderer` page request. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PdfRenderError { + OutOfBoundsPage { page_index: u32, page_count: u32 }, + InvalidDimensions { width_px: u32, height_px: u32 }, + ExceedsMemoryCap { width_px: u32, height_px: u32 }, + PixelBufferMismatch { expected: usize, actual: usize }, +} + +/// Validates page bounds and OOM dimension limits before invoking `PdfRenderer`. +pub const fn validate_pdf_page_request( + page_index: u32, + page_count: u32, + width_px: u32, + height_px: u32, +) -> Result<(), PdfRenderError> { + if page_count == 0 || page_index >= page_count { + return Err(PdfRenderError::OutOfBoundsPage { + page_index, + page_count, + }); + } + if width_px == 0 || height_px == 0 { + return Err(PdfRenderError::InvalidDimensions { + width_px, + height_px, + }); + } + if width_px > MAX_PDF_RENDER_DIM_PX || height_px > MAX_PDF_RENDER_DIM_PX { + return Err(PdfRenderError::ExceedsMemoryCap { + width_px, + height_px, + }); + } + let pixels = (width_px as u64) * (height_px as u64); + if pixels > MAX_PDF_RENDER_PIXELS { + return Err(PdfRenderError::ExceedsMemoryCap { + width_px, + height_px, + }); + } + Ok(()) +} + +/// Computes a deterministic cache key for a rendered PDF page tile. +pub fn pdf_page_cache_key( + doc_id: &str, + page_index: u32, + width_px: u32, + height_px: u32, + dpi_bucket: u32, +) -> String { + let safe_dpi = dpi_bucket.max(72); + format!("pdf:{doc_id}:p{page_index}:{width_px}x{height_px}@{safe_dpi}dpi") +} + +/// Validates rendered PDF bitmap dimensions against the OOM cap and returns +/// the exact expected pixel count. +pub const fn validate_pdf_dimensions( + width_px: u32, + height_px: u32, +) -> Result { + if width_px == 0 || height_px == 0 { + return Err(PdfRenderError::InvalidDimensions { + width_px, + height_px, + }); + } + if width_px > MAX_PDF_RENDER_DIM_PX || height_px > MAX_PDF_RENDER_DIM_PX { + return Err(PdfRenderError::ExceedsMemoryCap { + width_px, + height_px, + }); + } + let expected_u64 = (width_px as u64) * (height_px as u64); + if expected_u64 > MAX_PDF_RENDER_PIXELS { + return Err(PdfRenderError::ExceedsMemoryCap { + width_px, + height_px, + }); + } + Ok(expected_u64 as usize) +} + +/// Converts Android `Bitmap.Config.ARGB_8888` pixels (`0xAARRGGBB`) into tightly +/// packed `RGBA8` bytes (`[R, G, B, A]`), enforcing the OOM pixel cap. +pub fn argb8888_to_rgba8( + argb_pixels: &[u32], + width_px: u32, + height_px: u32, +) -> Result, PdfRenderError> { + let expected = validate_pdf_dimensions(width_px, height_px)?; + if argb_pixels.len() != expected { + return Err(PdfRenderError::PixelBufferMismatch { + expected, + actual: argb_pixels.len(), + }); + } + + let mut rgba = Vec::with_capacity(expected * 4); + for &argb in argb_pixels { + let a = ((argb >> 24) & 0xFF) as u8; + let r = ((argb >> 16) & 0xFF) as u8; + let g = ((argb >> 8) & 0xFF) as u8; + let b = (argb & 0xFF) as u8; + rgba.extend_from_slice(&[r, g, b, a]); + } + Ok(rgba) +} + +/// Converts one chunk of signed JNI `jint` `ARGB_8888` pixels directly into a +/// pre-allocated stack/slice `RGBA8` buffer (`out_rgba.len() == argb_chunk.len() * 4`) +/// with zero heap allocation. +pub fn convert_argb8888_i32_chunk_to_rgba8_slice(argb_chunk: &[i32], out_rgba: &mut [u8]) { + debug_assert_eq!(out_rgba.len(), argb_chunk.len() * 4); + for (&px, dst) in argb_chunk.iter().zip(out_rgba.chunks_exact_mut(4)) { + let argb = px as u32; + dst[0] = ((argb >> 16) & 0xFF) as u8; + dst[1] = ((argb >> 8) & 0xFF) as u8; + dst[2] = (argb & 0xFF) as u8; + dst[3] = ((argb >> 24) & 0xFF) as u8; + } +} + +/// Appends one chunk of signed JNI `jint` `ARGB_8888` pixels directly into an +/// `RGBA8` byte buffer without intermediate allocations. +pub fn append_argb8888_i32_chunk_to_rgba8(argb_chunk: &[i32], out_rgba: &mut Vec) { + let start = out_rgba.len(); + out_rgba.resize(start + argb_chunk.len() * 4, 0); + convert_argb8888_i32_chunk_to_rgba8_slice(argb_chunk, &mut out_rgba[start..]); +} + +/// Converts signed JNI `jint` `ARGB_8888` pixels directly into tightly packed +/// `RGBA8` bytes with zero intermediate `Vec` copy. +pub fn argb8888_i32_to_rgba8( + argb_pixels: &[i32], + width_px: u32, + height_px: u32, +) -> Result, PdfRenderError> { + let expected = validate_pdf_dimensions(width_px, height_px)?; + if argb_pixels.len() != expected { + return Err(PdfRenderError::PixelBufferMismatch { + expected, + actual: argb_pixels.len(), + }); + } + let mut rgba = Vec::with_capacity(expected * 4); + append_argb8888_i32_chunk_to_rgba8(argb_pixels, &mut rgba); + Ok(rgba) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pdf_request_validation_enforces_bounds_and_oom_cap() { + let cases = [ + ((0, 3, 1080, 1920), Ok(())), + ((2, 3, 4096, 4096), Ok(())), + ( + (0, 0, 100, 100), + Err(PdfRenderError::OutOfBoundsPage { + page_index: 0, + page_count: 0, + }), + ), + ( + (3, 3, 100, 100), + Err(PdfRenderError::OutOfBoundsPage { + page_index: 3, + page_count: 3, + }), + ), + ( + (0, 2, 0, 100), + Err(PdfRenderError::InvalidDimensions { + width_px: 0, + height_px: 100, + }), + ), + ( + (0, 2, 4097, 100), + Err(PdfRenderError::ExceedsMemoryCap { + width_px: 4097, + height_px: 100, + }), + ), + ]; + + for ((page_index, page_count, width_px, height_px), expected) in cases { + assert_eq!( + validate_pdf_page_request(page_index, page_count, width_px, height_px), + expected + ); + } + } + + #[test] + fn pdf_cache_key_and_argb8888_to_rgba8_conversion_are_deterministic() { + assert_eq!( + pdf_page_cache_key("doc-42", 2, 1080, 1440, 320), + "pdf:doc-42:p2:1080x1440@320dpi" + ); + assert_eq!( + pdf_page_cache_key("doc-42", 0, 100, 100, 0), + "pdf:doc-42:p0:100x100@72dpi" + ); + + let argb = [ + 0xFF_11_22_33_u32, // opaque + 0x80_AA_BB_CC_u32, // semi-transparent + 0xFF_FF_FF_FF_u32, // white background + 0x00_01_02_03_u32, // zero alpha + ]; + let rgba = argb8888_to_rgba8(&argb, 2, 2).expect("valid 2x2 conversion"); + assert_eq!( + rgba, + vec![ + 0x11, 0x22, 0x33, 0xFF, // pixel 0 + 0xAA, 0xBB, 0xCC, 0x80, // pixel 1 + 0xFF, 0xFF, 0xFF, 0xFF, // pixel 2 + 0x01, 0x02, 0x03, 0x00, // pixel 3 + ] + ); + assert_eq!( + argb8888_to_rgba8(&argb[..3], 2, 2), + Err(PdfRenderError::PixelBufferMismatch { + expected: 4, + actual: 3, + }) + ); + } +} diff --git a/packages/frontend/hosts/android/src/selection.rs b/packages/frontend/hosts/android/src/selection.rs new file mode 100644 index 0000000000..f0af8eb713 --- /dev/null +++ b/packages/frontend/hosts/android/src/selection.rs @@ -0,0 +1,870 @@ +//! Native Android text selection teardrop handles, magnifier loupe anchor, +//! and post-release context action menu geometry. +//! +//! Coordinates are kept in viewport pixel space scaled by `density` so the +//! Kotlin host can position overlay views without calling `SurfaceHolder.lockCanvas`. + +use serde::Serialize; + +/// Text layout direction controlling teardrop handle orientation. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +#[repr(i32)] +pub enum TextDirection { + #[default] + Ltr = 0, + Rtl = 1, +} + +impl TextDirection { + /// Converts a raw JNI integer code into a [`TextDirection`]. + pub const fn from_code(code: i32) -> Self { + match code { + 1 => Self::Rtl, + _ => Self::Ltr, + } + } +} + +/// Active selection handle identifier. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +#[repr(i32)] +pub enum SelectionHandleKind { + #[default] + None = 0, + Start = 1, + End = 2, +} + +impl SelectionHandleKind { + /// Converts a raw JNI integer code into a [`SelectionHandleKind`]. + pub const fn from_code(code: i32) -> Self { + match code { + 1 => Self::Start, + 2 => Self::End, + _ => Self::None, + } + } +} + +/// Visual teardrop lean direction for a selection handle. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +pub enum TeardropOrientation { + #[default] + LeftLeaning, + RightLeaning, +} + +/// Axis-aligned rectangle in viewport pixels. +#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize)] +pub struct RectF { + pub x: f32, + pub y: f32, + pub width: f32, + pub height: f32, +} + +/// Computed geometry for a single teardrop selection handle. +#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize)] +pub struct HandleGeometry { + pub kind: SelectionHandleKind, + pub tip_x: f32, + pub tip_y: f32, + pub center_x: f32, + pub center_y: f32, + pub radius: f32, + pub orientation: TeardropOrientation, + pub bounds: RectF, + pub visible: bool, +} + +/// Magnifier loupe position and visibility while dragging a selection handle. +#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize)] +pub struct MagnifierState { + pub visible: bool, + pub anchor_x: f32, + pub anchor_y: f32, + pub loupe_x: f32, + pub loupe_y: f32, + pub zoom: f32, +} + +/// Complete native selection overlay state for the Android host. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct SelectionOverlayState { + pub viewport_width: f32, + pub viewport_height: f32, + pub density: f32, + pub direction: TextDirection, + pub has_selection: bool, + pub active_drag: SelectionHandleKind, + pub line_height: f32, + pub start_handle: HandleGeometry, + pub end_handle: HandleGeometry, + pub magnifier: MagnifierState, + pub action_menu_rect: Option, + pub probe_x: f32, + pub probe_y: f32, + #[serde(skip)] + raw_start_x: f32, + #[serde(skip)] + raw_start_y: f32, + #[serde(skip)] + raw_end_x: f32, + #[serde(skip)] + raw_end_y: f32, + #[serde(skip)] + grab_dx: f32, + #[serde(skip)] + grab_dy: f32, +} + +const HANDLE_RADIUS_DP: f32 = 11.0; +const HANDLE_HIT_SLOP_DP: f32 = 24.0; +const LOUPE_WIDTH_DP: f32 = 100.0; +const LOUPE_HEIGHT_DP: f32 = 48.0; +const LOUPE_OFFSET_Y_DP: f32 = 56.0; +const LOUPE_DEFAULT_ZOOM: f32 = 1.25; +const ACTION_MENU_WIDTH_DP: f32 = 220.0; +const ACTION_MENU_HEIGHT_DP: f32 = 44.0; +const ACTION_MENU_GAP_DP: f32 = 12.0; + +impl Default for SelectionOverlayState { + fn default() -> Self { + Self::new() + } +} + +impl SelectionOverlayState { + /// Creates an empty selection overlay state. + pub fn new() -> Self { + Self { + viewport_width: 0.0, + viewport_height: 0.0, + density: 1.0, + direction: TextDirection::Ltr, + has_selection: false, + active_drag: SelectionHandleKind::None, + line_height: 24.0, + start_handle: HandleGeometry { + kind: SelectionHandleKind::Start, + orientation: TeardropOrientation::LeftLeaning, + ..HandleGeometry::default() + }, + end_handle: HandleGeometry { + kind: SelectionHandleKind::End, + orientation: TeardropOrientation::RightLeaning, + ..HandleGeometry::default() + }, + magnifier: MagnifierState { + zoom: LOUPE_DEFAULT_ZOOM, + ..MagnifierState::default() + }, + action_menu_rect: None, + probe_x: 0.0, + probe_y: 0.0, + raw_start_x: 0.0, + raw_start_y: 0.0, + raw_end_x: 0.0, + raw_end_y: 0.0, + grab_dx: 0.0, + grab_dy: 0.0, + } + } + + /// Updates viewport dimensions and display density, reclamping active overlays. + pub fn set_viewport(&mut self, width: f32, height: f32, density: f32) { + self.viewport_width = sanitize_non_negative(width); + self.viewport_height = sanitize_non_negative(height); + self.density = sanitize_positive(density, 1.0); + self.recompute(); + } + + /// Updates the selection endpoints, line height, and text direction. + #[allow(clippy::too_many_arguments)] + pub fn update_selection( + &mut self, + start_x: f32, + start_y: f32, + end_x: f32, + end_y: f32, + line_height: f32, + direction: TextDirection, + has_selection: bool, + ) { + self.direction = direction; + self.line_height = sanitize_positive(line_height, 24.0 * self.density); + self.has_selection = has_selection; + if !has_selection { + self.clear(); + return; + } + self.raw_start_x = sanitize_finite(start_x); + self.raw_start_y = sanitize_finite(start_y); + self.raw_end_x = sanitize_finite(end_x); + self.raw_end_y = sanitize_finite(end_y); + self.recompute(); + } + + /// Hit-tests a finger-down coordinate against the visible start and end teardrop handles, + /// recording the grab offset so a zero-pixel drag keeps the endpoint stationary. + pub fn begin_drag(&mut self, touch_x: f32, touch_y: f32) -> SelectionHandleKind { + if !self.has_selection || !touch_x.is_finite() || !touch_y.is_finite() { + self.active_drag = SelectionHandleKind::None; + self.grab_dx = 0.0; + self.grab_dy = 0.0; + return SelectionHandleKind::None; + } + let hit_radius = HANDLE_HIT_SLOP_DP * self.density; + let max_dist_sq = hit_radius * hit_radius; + + let start_dist_sq = if self.start_handle.visible { + dist_sq( + touch_x, + touch_y, + self.start_handle.center_x, + self.start_handle.center_y, + ) + } else { + f32::INFINITY + }; + let end_dist_sq = if self.end_handle.visible { + dist_sq( + touch_x, + touch_y, + self.end_handle.center_x, + self.end_handle.center_y, + ) + } else { + f32::INFINITY + }; + + let hit = match (start_dist_sq <= max_dist_sq, end_dist_sq <= max_dist_sq) { + (true, true) => { + if start_dist_sq <= end_dist_sq { + SelectionHandleKind::Start + } else { + SelectionHandleKind::End + } + } + (true, false) => SelectionHandleKind::Start, + (false, true) => SelectionHandleKind::End, + (false, false) => SelectionHandleKind::None, + }; + + self.active_drag = hit; + if hit != SelectionHandleKind::None { + let (ax, ay) = self.active_anchor(); + self.grab_dx = ax - touch_x; + self.grab_dy = ay - touch_y; + self.action_menu_rect = None; + let focus_y = (ay - 0.5 * self.line_height).max(0.0); + self.update_magnifier(ax, focus_y, true); + } else { + self.grab_dx = 0.0; + self.grab_dy = 0.0; + } + hit + } + + /// Computes and clamps the grab-offset-compensated drag probe without mutating + /// handle ownership, allowing UTF-16 text layout to be the single authority for + /// start/end handle inversion and magnifier anchoring. + pub fn probe_drag_position(&mut self, touch_x: f32, touch_y: f32) -> Option<(f32, f32)> { + if self.active_drag == SelectionHandleKind::None + || !touch_x.is_finite() + || !touch_y.is_finite() + { + return None; + } + let next_x = self.clamp_x(touch_x + self.grab_dx); + let next_y = self.clamp_y(touch_y + self.grab_dy); + self.probe_x = next_x; + self.probe_y = next_y; + Some((next_x, next_y)) + } + + /// Applies authoritative text-layout selection endpoints and active handle kind + /// during a text-driven handle drag without applying a secondary pixel-based swap. + #[allow(clippy::too_many_arguments)] + pub fn apply_text_drag_endpoints( + &mut self, + start_x: f32, + start_y: f32, + end_x: f32, + end_y: f32, + line_height: f32, + direction: TextDirection, + active_handle: SelectionHandleKind, + ) { + self.has_selection = true; + self.direction = direction; + self.line_height = if line_height.is_finite() && line_height > 0.0 { + line_height + } else { + 24.0 * self.density + }; + self.raw_start_x = if start_x.is_finite() { start_x } else { 0.0 }; + self.raw_start_y = if start_y.is_finite() { start_y } else { 0.0 }; + self.raw_end_x = if end_x.is_finite() { end_x } else { 0.0 }; + self.raw_end_y = if end_y.is_finite() { end_y } else { 0.0 }; + self.active_drag = active_handle; + self.recompute(); + } + + /// Moves the actively dragged selection handle using the recorded grab offset + /// and updates the magnifier anchor. + /// + /// Automatically swaps start and end endpoints and flips `active_drag` when the + /// dragged handle crosses past the opposite handle (same-line or cross-line). + pub fn update_drag(&mut self, touch_x: f32, touch_y: f32) -> bool { + if self.active_drag == SelectionHandleKind::None + || !touch_x.is_finite() + || !touch_y.is_finite() + { + return false; + } + let next_x = self.clamp_x(touch_x + self.grab_dx); + let next_y = self.clamp_y(touch_y + self.grab_dy); + self.probe_x = next_x; + self.probe_y = next_y; + match self.active_drag { + SelectionHandleKind::Start => { + self.raw_start_x = next_x; + self.raw_start_y = next_y; + } + SelectionHandleKind::End => { + self.raw_end_x = next_x; + self.raw_end_y = next_y; + } + SelectionHandleKind::None => return false, + } + if self.is_selection_inverted() { + core::mem::swap(&mut self.raw_start_x, &mut self.raw_end_x); + core::mem::swap(&mut self.raw_start_y, &mut self.raw_end_y); + self.active_drag = match self.active_drag { + SelectionHandleKind::Start => SelectionHandleKind::End, + SelectionHandleKind::End => SelectionHandleKind::Start, + SelectionHandleKind::None => SelectionHandleKind::None, + }; + } + self.recompute(); + true + } + + fn is_selection_inverted(&self) -> bool { + let sy = self.raw_start_y; + let ey = self.raw_end_y; + let same_line_tol = 0.5 * self.line_height.max(16.0); + if (sy - ey).abs() > same_line_tol { + return sy > ey; + } + match self.direction { + TextDirection::Ltr => self.raw_start_x > self.raw_end_x, + TextDirection::Rtl => self.raw_start_x < self.raw_end_x, + } + } + + /// Packs the overlay geometry into a fixed 24-float array for zero-allocation, + /// zero-JSON per-frame `AndroidSelectionOverlayView.onDraw` rendering. + pub fn pack_overlay_floats(&self) -> [f32; 24] { + let (menu_vis, mx, my, mw, mh) = match self.action_menu_rect { + Some(r) => (1.0, r.x, r.y, r.width, r.height), + None => (0.0, 0.0, 0.0, 0.0, 0.0), + }; + [ + if self.has_selection { 1.0 } else { 0.0 }, + match self.direction { + TextDirection::Ltr => 0.0, + TextDirection::Rtl => 1.0, + }, + if self.start_handle.visible { 1.0 } else { 0.0 }, + self.start_handle.tip_x, + self.start_handle.tip_y, + self.start_handle.center_x, + self.start_handle.center_y, + self.start_handle.radius, + if self.end_handle.visible { 1.0 } else { 0.0 }, + self.end_handle.tip_x, + self.end_handle.tip_y, + self.end_handle.center_x, + self.end_handle.center_y, + self.end_handle.radius, + if self.magnifier.visible { 1.0 } else { 0.0 }, + self.magnifier.anchor_x, + self.magnifier.anchor_y, + self.magnifier.loupe_x, + self.magnifier.loupe_y, + menu_vis, + mx, + my, + mw, + mh, + ] + } + + /// Ends handle dragging, hides the magnifier, and computes the context action menu rect. + pub fn end_drag(&mut self) -> Option { + self.active_drag = SelectionHandleKind::None; + self.grab_dx = 0.0; + self.grab_dy = 0.0; + self.magnifier.visible = false; + self.recompute(); + self.action_menu_rect + } + + /// Clears the selection handles, magnifier, and context action menu. + pub fn clear(&mut self) { + self.has_selection = false; + self.active_drag = SelectionHandleKind::None; + self.grab_dx = 0.0; + self.grab_dy = 0.0; + self.start_handle.visible = false; + self.end_handle.visible = false; + self.magnifier.visible = false; + self.action_menu_rect = None; + } + + /// Serializes the current selection overlay state to JSON for JNI consumers. + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string()) + } + + fn is_y_in_viewport(&self, raw_y: f32) -> bool { + if self.viewport_height <= 0.0 { + return raw_y >= 0.0; + } + raw_y >= 0.0 && raw_y <= self.viewport_height + } + + fn recompute(&mut self) { + let same_line = + (self.raw_start_y - self.raw_end_y).abs() < 0.5 * self.line_height.max(16.0); + let (start_orient, end_orient) = + if same_line && (self.raw_start_x - self.raw_end_x).abs() > 0.01 { + if self.raw_start_x < self.raw_end_x { + ( + TeardropOrientation::LeftLeaning, + TeardropOrientation::RightLeaning, + ) + } else { + ( + TeardropOrientation::RightLeaning, + TeardropOrientation::LeftLeaning, + ) + } + } else { + match self.direction { + TextDirection::Ltr => ( + TeardropOrientation::LeftLeaning, + TeardropOrientation::RightLeaning, + ), + TextDirection::Rtl => ( + TeardropOrientation::RightLeaning, + TeardropOrientation::LeftLeaning, + ), + } + }; + + let start_visible = self.has_selection && self.is_y_in_viewport(self.raw_start_y); + let end_visible = self.has_selection && self.is_y_in_viewport(self.raw_end_y); + + let start_tip = ( + self.clamp_x(self.raw_start_x), + self.clamp_y(self.raw_start_y), + ); + let end_tip = (self.clamp_x(self.raw_end_x), self.clamp_y(self.raw_end_y)); + + self.start_handle = self.build_handle( + SelectionHandleKind::Start, + start_tip.0, + start_tip.1, + start_orient, + start_visible, + ); + self.end_handle = self.build_handle( + SelectionHandleKind::End, + end_tip.0, + end_tip.1, + end_orient, + end_visible, + ); + + if !self.has_selection { + self.magnifier.visible = false; + self.action_menu_rect = None; + return; + } + + if self.active_drag != SelectionHandleKind::None { + let (ax, ay) = self.active_anchor(); + let focus_y = (ay - 0.5 * self.line_height).max(0.0); + self.update_magnifier(ax, focus_y, true); + self.action_menu_rect = None; + } else if start_visible || end_visible { + self.magnifier.visible = false; + self.action_menu_rect = Some(self.compute_action_menu_rect()); + } else { + self.magnifier.visible = false; + self.action_menu_rect = None; + } + } + + fn build_handle( + &self, + kind: SelectionHandleKind, + tip_x: f32, + tip_y: f32, + orientation: TeardropOrientation, + visible: bool, + ) -> HandleGeometry { + let r = HANDLE_RADIUS_DP * self.density; + let diameter = r * 2.0; + let lean = match orientation { + TeardropOrientation::LeftLeaning => -0.7 * r, + TeardropOrientation::RightLeaning => 0.7 * r, + }; + let raw_cx = tip_x + lean; + let raw_cy = tip_y + r; + + let width = if self.viewport_width > 0.0 { + diameter.min(self.viewport_width) + } else { + diameter + }; + let height = if self.viewport_height > 0.0 { + diameter.min(self.viewport_height) + } else { + diameter + }; + let bounds_x = clamp_rect_origin(raw_cx - width * 0.5, width, self.viewport_width); + let bounds_y = clamp_rect_origin(raw_cy - height * 0.5, height, self.viewport_height); + + HandleGeometry { + kind, + tip_x, + tip_y, + center_x: bounds_x + width * 0.5, + center_y: bounds_y + height * 0.5, + radius: r, + orientation, + bounds: RectF { + x: bounds_x, + y: bounds_y, + width, + height, + }, + visible, + } + } + + fn active_anchor(&self) -> (f32, f32) { + match self.active_drag { + SelectionHandleKind::Start => (self.start_handle.tip_x, self.start_handle.tip_y), + SelectionHandleKind::End => (self.end_handle.tip_x, self.end_handle.tip_y), + SelectionHandleKind::None => (0.0, 0.0), + } + } + + fn update_magnifier(&mut self, anchor_x: f32, anchor_y: f32, visible: bool) { + let half_w = LOUPE_WIDTH_DP * 0.5 * self.density; + let half_h = LOUPE_HEIGHT_DP * 0.5 * self.density; + let offset_y = LOUPE_OFFSET_Y_DP * self.density; + + let loupe_x = clamp_center(anchor_x, half_w, self.viewport_width); + let loupe_y = clamp_center(anchor_y - offset_y, half_h, self.viewport_height); + + self.magnifier = MagnifierState { + visible, + anchor_x, + anchor_y, + loupe_x, + loupe_y, + zoom: LOUPE_DEFAULT_ZOOM, + }; + } + + fn compute_action_menu_rect(&self) -> RectF { + let menu_w = if self.viewport_width > 0.0 { + (ACTION_MENU_WIDTH_DP * self.density).min(self.viewport_width) + } else { + ACTION_MENU_WIDTH_DP * self.density + }; + let menu_h = if self.viewport_height > 0.0 { + (ACTION_MENU_HEIGHT_DP * self.density).min(self.viewport_height) + } else { + ACTION_MENU_HEIGHT_DP * self.density + }; + let gap = ACTION_MENU_GAP_DP * self.density; + + let mid_x = (self.start_handle.tip_x + self.end_handle.tip_x) * 0.5; + let top_y = self.start_handle.tip_y.min(self.end_handle.tip_y); + let bottom_y = self.start_handle.tip_y.max(self.end_handle.tip_y); + + let preferred_y = top_y - self.line_height - menu_h - gap; + let y = if preferred_y >= 0.0 { + preferred_y + } else { + let below_y = bottom_y + HANDLE_RADIUS_DP * 2.0 * self.density + gap; + clamp_rect_origin(below_y, menu_h, self.viewport_height) + }; + let margin_x = 12.0 * self.density; + let x = if self.viewport_width > menu_w + 2.0 * margin_x { + (mid_x - menu_w * 0.5).clamp(margin_x, self.viewport_width - margin_x - menu_w) + } else { + clamp_rect_origin(mid_x - menu_w * 0.5, menu_w, self.viewport_width) + }; + + RectF { + x, + y, + width: menu_w, + height: menu_h, + } + } + + fn clamp_x(&self, value: f32) -> f32 { + let v = if value.is_finite() { value } else { 0.0 }; + if self.viewport_width > 0.0 { + v.clamp(0.0, self.viewport_width) + } else { + v.max(0.0) + } + } + + fn clamp_y(&self, value: f32) -> f32 { + let v = if value.is_finite() { value } else { 0.0 }; + if self.viewport_height > 0.0 { + v.clamp(0.0, self.viewport_height) + } else { + v.max(0.0) + } + } +} + +fn sanitize_finite(value: f32) -> f32 { + if value.is_finite() { value } else { 0.0 } +} + +fn sanitize_non_negative(value: f32) -> f32 { + if value.is_finite() && value > 0.0 { + value + } else { + 0.0 + } +} + +fn sanitize_positive(value: f32, fallback: f32) -> f32 { + if value.is_finite() && value > 0.0 { + value + } else { + fallback + } +} + +fn dist_sq(ax: f32, ay: f32, bx: f32, by: f32) -> f32 { + let dx = ax - bx; + let dy = ay - by; + dx * dx + dy * dy +} + +fn clamp_rect_origin(origin: f32, size: f32, viewport: f32) -> f32 { + if viewport <= 0.0 { + return origin.max(0.0); + } + let max_origin = (viewport - size).max(0.0); + origin.clamp(0.0, max_origin) +} + +fn clamp_center(center: f32, half_size: f32, viewport: f32) -> f32 { + if viewport <= 0.0 { + return center.max(0.0); + } + if viewport <= half_size * 2.0 { + return viewport * 0.5; + } + center.clamp(half_size, viewport - half_size) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn selection_handles_flip_for_rtl_and_clamp_to_viewport() { + let cases = [ + ( + TextDirection::Ltr, + 10.0, + 1075.0, + TeardropOrientation::LeftLeaning, + TeardropOrientation::RightLeaning, + ), + ( + TextDirection::Rtl, + 1075.0, + 10.0, + TeardropOrientation::RightLeaning, + TeardropOrientation::LeftLeaning, + ), + ]; + + for (dir, start_x, end_x, expected_start, expected_end) in cases { + let mut state = SelectionOverlayState::new(); + state.set_viewport(1080.0, 2400.0, 3.0); + state.update_selection(start_x, 400.0, end_x, 400.0, 60.0, dir, true); + assert!(state.start_handle.visible); + assert!(state.end_handle.visible); + assert_eq!(state.start_handle.orientation, expected_start); + assert_eq!(state.end_handle.orientation, expected_end); + assert!(state.start_handle.bounds.x >= 0.0); + assert!(state.end_handle.bounds.x + state.end_handle.bounds.width <= 1080.0); + assert!(state.action_menu_rect.is_some()); + } + } + + #[test] + fn drag_shows_clamped_magnifier_and_release_restores_action_menu() { + let mut state = SelectionOverlayState::new(); + state.set_viewport(1080.0, 2400.0, 3.0); + state.update_selection(200.0, 500.0, 700.0, 500.0, 60.0, TextDirection::Ltr, true); + + // Miss outside touch target. + assert_eq!(state.begin_drag(50.0, 50.0), SelectionHandleKind::None); + assert!(!state.magnifier.visible); + + // Hit end handle center -> magnifier appears, action menu hides. + let hit = state.begin_drag(state.end_handle.center_x, state.end_handle.center_y); + assert_eq!(hit, SelectionHandleKind::End); + assert!(state.magnifier.visible); + assert!(state.action_menu_rect.is_none()); + + // Drag end handle right & upward to top-right edge -> loupe clamps cleanly inside viewport. + // Because grab_dy = tip_y - center_y = -33.0, touch_y = 43.0 places tip_y at 10.0. + assert!(state.update_drag(1200.0, 533.0)); + assert!(state.magnifier.visible); + assert_eq!(state.end_handle.tip_x, 1080.0); + assert_eq!(state.end_handle.tip_y, 500.0); + assert!(state.magnifier.loupe_x <= 1080.0 - 150.0); + assert!(state.magnifier.loupe_y >= 72.0); + assert!(state.action_menu_rect.is_none()); + + // Release -> magnifier hides and action menu flips below near top edge. + let menu = state.end_drag().expect("action menu rect after release"); + assert!(!state.magnifier.visible); + assert!(menu.x >= 0.0 && menu.x + menu.width <= 1080.0); + assert!(menu.y >= 0.0 && menu.y + menu.height <= 2400.0); + } + + #[test] + fn drag_preserves_grab_offset_swaps_on_crossover_and_hides_offscreen_handles() { + // 1. Zero-pixel move after grabbing handle center must not jump the endpoint. + let mut state = SelectionOverlayState::new(); + state.set_viewport(1080.0, 2400.0, 3.0); + state.update_selection(200.0, 500.0, 700.0, 500.0, 60.0, TextDirection::Ltr, true); + let grab_x = state.start_handle.center_x; + let grab_y = state.start_handle.center_y; + assert_eq!(state.begin_drag(grab_x, grab_y), SelectionHandleKind::Start); + assert!(state.update_drag(grab_x, grab_y)); + assert!((state.start_handle.tip_x - 200.0).abs() < 1e-3); + assert!((state.start_handle.tip_y - 500.0).abs() < 1e-3); + + // 2. Same-line LTR crossover: drag Start past End -> swaps endpoints & flips active_drag to End. + let dx_past_end = 700.0; + assert!(state.update_drag(grab_x + dx_past_end, grab_y)); + assert_eq!(state.active_drag, SelectionHandleKind::End); + assert!((state.start_handle.tip_x - 700.0).abs() < 1e-3); + assert!((state.end_handle.tip_x - 900.0).abs() < 1e-3); + assert_eq!( + state.start_handle.orientation, + TeardropOrientation::LeftLeaning + ); + assert_eq!( + state.end_handle.orientation, + TeardropOrientation::RightLeaning + ); + let _ = state.end_drag(); + + // 3. Cross-line crossover: drag Start below End -> swaps endpoints & flips active_drag to End. + state.update_selection(300.0, 400.0, 600.0, 600.0, 60.0, TextDirection::Ltr, true); + let sx = state.start_handle.center_x; + let sy = state.start_handle.center_y; + assert_eq!(state.begin_drag(sx, sy), SelectionHandleKind::Start); + assert!(state.update_drag(sx, sy + 400.0)); + assert_eq!(state.active_drag, SelectionHandleKind::End); + assert!((state.start_handle.tip_y - 600.0).abs() < 1e-3); + assert!((state.end_handle.tip_y - 800.0).abs() < 1e-3); + let _ = state.end_drag(); + + // 4. Same-line RTL crossover: drag Start left of End -> swaps endpoints & flips active_drag. + state.update_selection(800.0, 500.0, 400.0, 500.0, 60.0, TextDirection::Rtl, true); + let rsx = state.start_handle.center_x; + let rsy = state.start_handle.center_y; + assert_eq!(state.begin_drag(rsx, rsy), SelectionHandleKind::Start); + assert!(state.update_drag(rsx - 600.0, rsy)); + assert_eq!(state.active_drag, SelectionHandleKind::End); + assert!((state.start_handle.tip_x - 400.0).abs() < 1e-3); + assert!((state.end_handle.tip_x - 200.0).abs() < 1e-3); + let _ = state.end_drag(); + + // 5. Off-screen scrolled endpoints hide their handles instead of pinning to y=0. + state.update_selection(200.0, -40.0, 700.0, 500.0, 60.0, TextDirection::Ltr, true); + assert!(!state.start_handle.visible); + assert!(state.end_handle.visible); + state.update_selection(200.0, -40.0, 700.0, 2600.0, 60.0, TextDirection::Ltr, true); + assert!(!state.start_handle.visible); + assert!(!state.end_handle.visible); + assert!(state.action_menu_rect.is_none()); + + // 6. Same-line vertical jitter (+/-1px, +/-2px, +/-15px) within 0.5 * line_height + // must NEVER falsely swap Start and End handles. + state.update_selection(200.0, 500.0, 700.0, 500.0, 60.0, TextDirection::Ltr, true); + let ex = state.end_handle.center_x; + let ey = state.end_handle.center_y; + assert_eq!(state.begin_drag(ex, ey), SelectionHandleKind::End); + for dy in [-1.0_f32, 1.0, -2.0, 2.0, -15.0, 15.0] { + assert!(state.update_drag(ex - 20.0, ey + dy)); + assert_eq!( + state.active_drag, + SelectionHandleKind::End, + "vertical jitter {dy}px must not swap End to Start" + ); + assert!(state.end_handle.tip_x > state.start_handle.tip_x); + } + let _ = state.end_drag(); + + // 7. Mixed-BiDi outward teardrop orientation & 12dp menu horizontal margin. + state.update_selection(200.0, 500.0, 240.0, 500.0, 60.0, TextDirection::Rtl, true); + assert_eq!( + state.start_handle.orientation, + TeardropOrientation::LeftLeaning + ); + assert_eq!( + state.end_handle.orientation, + TeardropOrientation::RightLeaning + ); + assert!( + (state.end_handle.center_x - state.start_handle.center_x).abs() + > state.start_handle.radius * 2.0 + ); + state.update_selection(240.0, 500.0, 200.0, 500.0, 60.0, TextDirection::Ltr, true); + assert_eq!( + state.start_handle.orientation, + TeardropOrientation::RightLeaning + ); + assert_eq!( + state.end_handle.orientation, + TeardropOrientation::LeftLeaning + ); + assert!( + (state.start_handle.center_x - state.end_handle.center_x).abs() + > state.start_handle.radius * 2.0 + ); + state.update_selection(10.0, 500.0, 40.0, 500.0, 60.0, TextDirection::Ltr, true); + let menu = state.action_menu_rect.expect("left-edge action menu"); + assert!( + menu.x >= 36.0 - 0.01, + "action menu x ({}) must keep >= 12dp (36px) left margin", + menu.x + ); + } +} diff --git a/packages/frontend/hosts/android/src/surface.rs b/packages/frontend/hosts/android/src/surface.rs index d271b04b05..b14a6cf55f 100644 --- a/packages/frontend/hosts/android/src/surface.rs +++ b/packages/frontend/hosts/android/src/surface.rs @@ -4,8 +4,8 @@ //! Replaces the S1 one-shot `lockCanvas` placeholder and guarantees that //! `pending_frame` is only cleared after a frame successfully presents. -/// Default observable first-frame clear color (opaque `#141414` ARGB). -pub const DEFAULT_CLEAR_COLOR_ARGB: u32 = 0xFF14_1414; +/// Default observable first-frame clear color (opaque `#FAFAFC` ARGB, matching iOS light canvas). +pub const DEFAULT_CLEAR_COLOR_ARGB: u32 = 0xFFFA_FAFC; /// Active Android presentation backend with deterministic fallback order. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -37,17 +37,24 @@ pub enum SurfacePresentError { } /// Lifecycle state for an Android `SurfaceView` native window binding. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq)] pub struct SurfaceLifecycleState { pub active: bool, pub bound: bool, + pub configured_for_generation: bool, pub generation: u64, + pub texture_generation: u64, + pub recreation_count: u64, pub format: i32, pub width_px: u32, pub height_px: u32, + pub density: f32, + pub scroll_offset_x: f32, + pub scroll_offset_y: f32, pub frame_count: u64, pub last_frame_nanos: i64, pub pending_frame: bool, + pub needs_first_frame_after_recreate: bool, pub clear_color_argb: u32, pub backend: AndroidRenderBackend, pub present_failures: u64, @@ -65,19 +72,59 @@ impl SurfaceLifecycleState { Self { active: false, bound: false, + configured_for_generation: false, generation: 0, + texture_generation: 0, + recreation_count: 0, format: 0, width_px: 0, height_px: 0, + density: 1.0, + scroll_offset_x: 0.0, + scroll_offset_y: 0.0, frame_count: 0, last_frame_nanos: 0, pending_frame: true, + needs_first_frame_after_recreate: true, clear_color_argb: DEFAULT_CLEAR_COLOR_ARGB, backend: AndroidRenderBackend::Unselected, present_failures: 0, } } + /// Updates the display density preserved across surface recreation. + pub fn set_density(&mut self, density: f32) { + if density.is_finite() && density > 0.0 { + self.density = density; + } + } + + /// Updates viewport scroll offsets preserved across surface recreation. + pub fn set_scroll_offset(&mut self, scroll_x: f32, scroll_y: f32) { + if scroll_x.is_finite() { + self.scroll_offset_x = scroll_x; + } + if scroll_y.is_finite() { + self.scroll_offset_y = scroll_y; + } + } + + /// Handles a Vulkan device-lost or swapchain init failure by downgrading to GLES3 + /// while preserving viewport, scroll, and session state. + pub fn report_vulkan_device_lost(&mut self) -> AndroidRenderBackend { + self.present_failures = self.present_failures.saturating_add(1); + self.texture_generation = self.texture_generation.saturating_add(1); + self.pending_frame = true; + self.needs_first_frame_after_recreate = true; + if matches!( + self.backend, + AndroidRenderBackend::Unselected | AndroidRenderBackend::Vulkan + ) { + self.backend = AndroidRenderBackend::Gles3; + } + self.backend + } + /// Selects the highest available backend: `Vulkan -> Gles3 -> CpuFallback`. pub fn select_backend( &mut self, @@ -96,13 +143,20 @@ impl SurfaceLifecycleState { /// Handles `SurfaceHolder.Callback.surfaceCreated`. /// - /// Increments the surface generation and marks a pending redraw so - /// background/foreground recreation seamlessly restores the frame. + /// Increments surface and texture generations and marks `configured_for_generation = false` + /// until `surfaceChanged` delivers non-zero dimensions for this generation, while preserving + /// previous viewport dimensions, DPI, and scroll offset for layout memory. pub fn on_created(&mut self, surface_non_null: bool) { self.generation = self.generation.saturating_add(1); + self.texture_generation = self.texture_generation.saturating_add(1); + if self.generation > 1 { + self.recreation_count = self.recreation_count.saturating_add(1); + } self.active = true; self.bound = surface_non_null; + self.configured_for_generation = false; self.pending_frame = true; + self.needs_first_frame_after_recreate = true; } /// Handles `SurfaceHolder.Callback.surfaceChanged(format, width, height)`. @@ -110,19 +164,23 @@ impl SurfaceLifecycleState { self.format = format; self.width_px = width_px; self.height_px = height_px; - if width_px > 0 && height_px > 0 { + self.configured_for_generation = width_px > 0 && height_px > 0; + if self.configured_for_generation { self.pending_frame = true; } } /// Handles `SurfaceHolder.Callback.surfaceDestroyed`. /// - /// Detaches the native surface while keeping `pending_frame = true` so the - /// next `surfaceCreated` + `surfaceChanged` pair immediately presents. + /// Detaches the native surface while preserving viewport size, DPI, scroll, + /// and backend state so the next `surfaceCreated` + `surfaceChanged` pair + /// immediately presents a recovered first frame. pub fn on_destroyed(&mut self) { self.active = false; self.bound = false; + self.configured_for_generation = false; self.pending_frame = true; + self.needs_first_frame_after_recreate = true; } /// Schedules a frame render on the next `Choreographer` tick. @@ -130,9 +188,14 @@ impl SurfaceLifecycleState { self.pending_frame = true; } - /// Returns `true` when the surface is attached and has non-zero dimensions. + /// Returns `true` when the surface is attached and configured with non-zero + /// dimensions for the current generation. pub const fn is_ready(&self) -> bool { - self.active && self.bound && self.width_px > 0 && self.height_px > 0 + self.active + && self.bound + && self.configured_for_generation + && self.width_px > 0 + && self.height_px > 0 } /// Begins a frame tick without clearing `pending_frame` until presentation succeeds. @@ -158,6 +221,7 @@ impl SurfaceLifecycleState { self.frame_count = self.frame_count.saturating_add(1); self.last_frame_nanos = frame_time_nanos; self.pending_frame = false; + self.needs_first_frame_after_recreate = false; true } Err(err) => { @@ -168,6 +232,7 @@ impl SurfaceLifecycleState { SurfacePresentError::SurfaceLost | SurfacePresentError::BackendUnavailable ) { self.backend = self.backend.downgrade(); + self.texture_generation = self.texture_generation.saturating_add(1); } false } @@ -281,4 +346,66 @@ mod tests { assert!(!surface.is_ready()); assert_eq!(surface.on_frame_tick(20_000), None); } + + #[test] + fn surface_recreation_and_vulkan_device_loss_preserve_viewport_dpi_and_scroll() { + let mut surface = SurfaceLifecycleState::new(); + assert_eq!( + surface.select_backend(true, true), + AndroidRenderBackend::Vulkan + ); + surface.set_density(3.0); + surface.set_scroll_offset(12.5, 420.0); + surface.on_created(true); + surface.on_changed(1, 1080, 2400); + assert!(surface.needs_first_frame_after_recreate); + assert_eq!(surface.recreation_count, 0); + assert_eq!(surface.texture_generation, 1); + + // First frame presented under Vulkan. + assert_eq!( + surface.on_frame_tick(16_000_000), + Some(DEFAULT_CLEAR_COLOR_ARGB) + ); + assert!(!surface.needs_first_frame_after_recreate); + + // Simulate Vulkan device loss -> downgrades to GLES3 while keeping state intact. + assert_eq!( + surface.report_vulkan_device_lost(), + AndroidRenderBackend::Gles3 + ); + assert!(surface.pending_frame); + assert!(surface.needs_first_frame_after_recreate); + assert_eq!(surface.texture_generation, 2); + assert_eq!(surface.density, 3.0); + assert_eq!(surface.scroll_offset_x, 12.5); + assert_eq!(surface.scroll_offset_y, 420.0); + + // Rotation / backgrounding -> surfaceDestroyed -> surfaceCreated -> surfaceChanged. + surface.on_destroyed(); + assert!(!surface.is_ready()); + assert_eq!(surface.density, 3.0); + assert_eq!(surface.scroll_offset_y, 420.0); + + surface.on_created(true); + assert_eq!(surface.generation, 2); + assert_eq!(surface.recreation_count, 1); + assert_eq!(surface.texture_generation, 3); + // Before surfaceChanged arrives for generation 2, is_ready() MUST be false even though + // previous width_px/height_px are remembered for layout, preventing 0x0 present failures. + assert!(!surface.is_ready()); + assert_eq!(surface.on_frame_tick(24_000_000), None); + assert_eq!(surface.present_failures, 1); + + surface.on_changed(1, 2400, 1080); + assert!(surface.is_ready()); + assert_eq!( + surface.on_frame_tick(32_000_000), + Some(DEFAULT_CLEAR_COLOR_ARGB) + ); + assert!(!surface.needs_first_frame_after_recreate); + assert_eq!(surface.backend, AndroidRenderBackend::Gles3); + assert_eq!(surface.density, 3.0); + assert_eq!(surface.scroll_offset_y, 420.0); + } } diff --git a/packages/frontend/hosts/android/src/text_layout.rs b/packages/frontend/hosts/android/src/text_layout.rs new file mode 100644 index 0000000000..daa7481aba --- /dev/null +++ b/packages/frontend/hosts/android/src/text_layout.rs @@ -0,0 +1,395 @@ +//! Pure-Rust fallback text layout (per-paragraph UAX #9 first-strong BiDi, +//! soft-wrapping, and proportional/measured glyph advances) used when Android +//! `StaticLayout` is unavailable (headless Rust tests and JVM-only parity checks). +//! On Android devices, `ShapedTextLayout` (`android.text.StaticLayout`) is the +//! single authoritative layout engine for handles, hit-testing, and the loupe. + +use crate::selection::TextDirection; + +/// Layout parameters in viewport pixel space. +#[derive(Debug, Clone, PartialEq)] +pub struct TextLayoutMetrics { + pub origin_x: f32, + pub origin_y: f32, + pub max_width: f32, + pub char_advance: f32, + pub line_height: f32, + /// Optional per-UTF-16-unit advance widths measured by Android `TextPaint.getTextWidths`. + pub measured_advances: Vec, +} + +impl Default for TextLayoutMetrics { + fn default() -> Self { + Self::for_viewport(1080.0, 3.0) + } +} + +impl TextLayoutMetrics { + /// Builds default viewport-scaled text metrics for a given width and density. + pub fn for_viewport(viewport_width: f32, density: f32) -> Self { + let d = if density.is_finite() && density > 0.0 { + density + } else { + 1.0 + }; + let pad = 24.0 * d; + let max_w = if viewport_width.is_finite() && viewport_width > pad * 2.0 { + viewport_width - pad * 2.0 + } else { + 320.0 * d + }; + Self { + origin_x: pad, + origin_y: 80.0 * d, + max_width: max_w, + char_advance: 12.0 * d, + line_height: 28.0 * d, + measured_advances: Vec::new(), + } + } + + /// Updates viewport-derived layout metrics while preserving any explicit `measured_advances`. + pub fn update_viewport(&mut self, viewport_width: f32, density: f32) { + let next = Self::for_viewport(viewport_width, density); + self.origin_x = next.origin_x; + self.origin_y = next.origin_y; + self.max_width = next.max_width; + self.char_advance = next.char_advance; + self.line_height = next.line_height; + } + + /// Replaces the optional measured advance table (sanitizing non-finite values). + pub fn set_measured_advances(&mut self, advances: Vec) { + self.measured_advances = advances + .into_iter() + .map(|w| if w.is_finite() && w >= 0.0 { w } else { 0.0 }) + .collect(); + } +} + +#[derive(Debug, Clone)] +struct VisualLine { + start_utf16: usize, + end_utf16: usize, + direction: TextDirection, + /// `(utf16_offset, step, x_offset_from_line_start, advance)` for each cluster on the line. + clusters: Vec<(usize, usize, f32, f32)>, + total_width: f32, +} + +/// Detects paragraph writing direction from the first strong directional scalar (UAX #9). +pub fn detect_writing_direction(utf16: &[u16]) -> TextDirection { + for ch in char::decode_utf16(utf16.iter().copied()).flatten() { + let cp = ch as u32; + if is_rtl_codepoint(cp) { + return TextDirection::Rtl; + } + if ch.is_alphabetic() { + return TextDirection::Ltr; + } + } + TextDirection::Ltr +} + +const fn is_rtl_codepoint(cp: u32) -> bool { + matches!( + cp, + 0x0590..=0x05FF + | 0x0600..=0x06FF + | 0x0750..=0x077F + | 0x08A0..=0x08FF + | 0x200F + | 0xFB50..=0xFDFF + | 0xFE70..=0xFEFF + ) +} + +/// Returns a proportional fallback glyph advance when `TextPaint` widths are not supplied. +pub fn proportional_char_advance(ch: char, base_advance: f32) -> f32 { + let base = base_advance.max(1.0); + let cp = ch as u32; + if matches!( + ch, + 'i' | 'l' | 'I' | '.' | ',' | ':' | ';' | '!' | '|' | '\'' | '`' + ) { + return base * 0.42; + } + if matches!( + ch, + ' ' | 'j' | 't' | 'f' | 'r' | '1' | '(' | ')' | '[' | ']' + ) { + return base * 0.58; + } + if matches!(ch, 'W' | 'M' | '@' | '%' | 'm' | 'w') { + return base * 1.38; + } + if cp >= 0x2E80 { + return base * 1.55; + } + base +} + +fn decode_cluster(utf16: &[u16], i: usize) -> (char, usize) { + let u = utf16[i]; + if (0xD800..=0xDBFF).contains(&u) + && i + 1 < utf16.len() + && (0xDC00..=0xDFFF).contains(&utf16[i + 1]) + { + let ch = char::decode_utf16([u, utf16[i + 1]]) + .next() + .and_then(Result::ok) + .unwrap_or('\u{FFFD}'); + (ch, 2) + } else { + let ch = char::from_u32(u32::from(u)).unwrap_or('\u{FFFD}'); + (ch, 1) + } +} + +fn cluster_advance( + utf16: &[u16], + i: usize, + step: usize, + ch: char, + metrics: &TextLayoutMetrics, +) -> f32 { + if metrics.measured_advances.len() == utf16.len() { + let sum: f32 = metrics.measured_advances[i..i + step].iter().copied().sum(); + if sum.is_finite() && sum >= 0.0 { + return sum; + } + } + proportional_char_advance(ch, metrics.char_advance) +} + +fn layout_lines(utf16: &[u16], metrics: &TextLayoutMetrics) -> Vec { + let max_w = metrics.max_width.max(metrics.char_advance.max(1.0)); + let mut lines = Vec::new(); + let mut para_start = 0usize; + + loop { + let mut para_end = para_start; + while para_end < utf16.len() && utf16[para_end] != b'\n' as u16 { + para_end += 1; + } + let para_dir = detect_writing_direction(&utf16[para_start..para_end]); + + let mut line_start = para_start; + let mut clusters = Vec::new(); + let mut line_w = 0.0_f32; + let mut i = para_start; + + while i < para_end { + let (ch, step) = decode_cluster(utf16, i); + let adv = cluster_advance(utf16, i, step, ch, metrics); + if !clusters.is_empty() && line_w + adv > max_w { + lines.push(VisualLine { + start_utf16: line_start, + end_utf16: i, + direction: para_dir, + clusters, + total_width: line_w, + }); + line_start = i; + clusters = Vec::new(); + line_w = 0.0; + } + clusters.push((i, step, line_w, adv)); + line_w += adv; + i += step; + } + + lines.push(VisualLine { + start_utf16: line_start, + end_utf16: para_end, + direction: para_dir, + clusters, + total_width: line_w, + }); + + if para_end >= utf16.len() { + break; + } + para_start = para_end + 1; + } + + lines +} + +fn find_line_for_offset(lines: &[VisualLine], clamped_offset: usize) -> usize { + for (idx, line) in lines.iter().enumerate() { + if clamped_offset < line.end_utf16 { + return idx; + } + if clamped_offset == line.end_utf16 { + // Soft-wrap boundary offsets belong to the start of the next visual line. + if let Some(next) = lines.get(idx + 1) + && next.start_utf16 == clamped_offset + { + return idx + 1; + } + return idx; + } + } + lines.len().saturating_sub(1) +} + +/// Returns the paragraph writing direction at UTF-16 `offset`. +pub fn detect_direction_at_offset( + utf16: &[u16], + offset: usize, + metrics: &TextLayoutMetrics, +) -> TextDirection { + let lines = layout_lines(utf16, metrics); + let idx = find_line_for_offset(&lines, offset.min(utf16.len())); + lines[idx].direction +} + +/// Computes the caret baseline `(x, y)` in viewport pixels for UTF-16 `offset`. +pub fn caret_position_for_offset( + utf16: &[u16], + offset: usize, + metrics: &TextLayoutMetrics, +) -> (f32, f32) { + let lines = layout_lines(utf16, metrics); + let clamped = offset.min(utf16.len()); + let line_idx = find_line_for_offset(&lines, clamped); + let line = &lines[line_idx]; + + let mut advance_x = line.total_width; + if clamped <= line.start_utf16 { + advance_x = 0.0; + } else { + for &(c_off, _step, c_x, _c_adv) in &line.clusters { + if c_off >= clamped { + advance_x = c_x; + break; + } + } + } + + let x = match line.direction { + TextDirection::Ltr => metrics.origin_x + advance_x, + TextDirection::Rtl => metrics.origin_x + metrics.max_width - advance_x, + }; + let y = metrics.origin_y + (line_idx as f32 + 1.0) * metrics.line_height; + (x, y) +} + +/// Resolves viewport pixel `(x, y)` to the closest UTF-16 scalar boundary offset. +pub fn closest_offset_for_position( + utf16: &[u16], + x: f32, + y: f32, + metrics: &TextLayoutMetrics, +) -> usize { + let lines = layout_lines(utf16, metrics); + let lh = metrics.line_height.max(1.0); + let rel_line = ((y - metrics.origin_y) / lh - 0.5).floor(); + let line_idx = if rel_line <= 0.0 { + 0 + } else { + (rel_line as usize).min(lines.len().saturating_sub(1)) + }; + let line = &lines[line_idx]; + let target_x = match line.direction { + TextDirection::Ltr => (x - metrics.origin_x).max(0.0), + TextDirection::Rtl => (metrics.origin_x + metrics.max_width - x).max(0.0), + }; + + let mut best_off = line.start_utf16; + let mut best_dist = target_x.abs(); + for &(c_off, step, c_x, c_adv) in &line.clusters { + let end_off = c_off + step; + let end_x = c_x + c_adv; + let dist = (target_x - end_x).abs(); + if dist < best_dist { + best_dist = dist; + best_off = end_off; + } + } + best_off +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn text_layout_handles_per_paragraph_bidi_and_proportional_widths() { + let metrics = TextLayoutMetrics::for_viewport(1080.0, 3.0); + + // 1. Per-paragraph BiDi ("A\nשלום"): line 0 is LTR (x increases), line 1 is RTL (x decreases). + let mixed: Vec = "A\nשלום".encode_utf16().collect(); + let (x0, y0) = caret_position_for_offset(&mixed, 0, &metrics); + let (x1, y1) = caret_position_for_offset(&mixed, 1, &metrics); + assert!(x1 > x0, "paragraph 0 ('A') must advance LTR"); + assert_eq!(y0, y1); + let (x2, y2) = caret_position_for_offset(&mixed, 2, &metrics); + let (x3, y3) = caret_position_for_offset(&mixed, 3, &metrics); + assert!(y2 > y0, "paragraph 1 must sit on second line"); + assert_eq!(y2, y3); + assert!(x3 < x2, "paragraph 1 ('שלום') must advance RTL"); + assert_eq!( + detect_direction_at_offset(&mixed, 0, &metrics), + TextDirection::Ltr + ); + assert_eq!( + detect_direction_at_offset(&mixed, 2, &metrics), + TextDirection::Rtl + ); + assert_eq!(closest_offset_for_position(&mixed, x3, y3, &metrics), 3); + + // 2. Proportional glyph widths: "WWWW" is strictly wider than "iiii". + let narrow: Vec = "iiii".encode_utf16().collect(); + let wide: Vec = "WWWW".encode_utf16().collect(); + let (nx_end, _) = caret_position_for_offset(&narrow, 4, &metrics); + let (wx_end, _) = caret_position_for_offset(&wide, 4, &metrics); + assert!( + wx_end > nx_end * 1.5, + "WWWW ({wx_end}) must be much wider than iiii ({nx_end})" + ); + + // 3. Explicit measured_advances preserve zero-advance combining marks (e\u{0301}) + // and survive update_viewport calls. + let combining: Vec = "e\u{0301}".encode_utf16().collect(); + let mut custom = metrics.clone(); + custom.set_measured_advances(vec![10.0, 0.0]); + let (c0, _) = caret_position_for_offset(&combining, 0, &custom); + let (c1, _) = caret_position_for_offset(&combining, 1, &custom); + let (c2, _) = caret_position_for_offset(&combining, 2, &custom); + assert!((c1 - c0 - 10.0).abs() < 1e-3); + assert!( + (c2 - c1).abs() < 1e-3, + "combining mark must keep 0.0 advance (got {})", + c2 - c1 + ); + custom.update_viewport(720.0, 2.0); + assert_eq!( + custom.measured_advances, + vec![10.0, 0.0], + "update_viewport must preserve measured_advances" + ); + + // 4. Soft-wrap boundary offset belongs to the start of the next visual line. + let mut wrap = TextLayoutMetrics { + origin_x: 0.0, + origin_y: 0.0, + max_width: 40.0, + char_advance: 10.0, + line_height: 20.0, + measured_advances: vec![10.0, 10.0, 10.0, 10.0, 10.0], + }; + let abcdz: Vec = "ABCDZ".encode_utf16().collect(); + let (wx4, wy4) = caret_position_for_offset(&abcdz, 4, &wrap); + assert!( + wx4.abs() < 1e-3 && (wy4 - 40.0).abs() < 1e-3, + "offset 4 in soft-wrapped 'ABCDZ' must land at line 1 start (got ({wx4}, {wy4}))" + ); + wrap.measured_advances.clear(); + assert_eq!( + detect_direction_at_offset(&abcdz, 4, &wrap), + TextDirection::Ltr + ); + } +} diff --git a/packages/frontend/hosts/android/tests/ImeHostParityCheck.kt b/packages/frontend/hosts/android/tests/ImeHostParityCheck.kt index 2af9e32ce7..d32e9b82e3 100644 --- a/packages/frontend/hosts/android/tests/ImeHostParityCheck.kt +++ b/packages/frontend/hosts/android/tests/ImeHostParityCheck.kt @@ -1,19 +1,31 @@ import android.view.inputmethod.InputConnection import app.affine.pro.host.AffineImeController import app.affine.pro.host.AffineSurfaceView +import app.affine.pro.host.AndroidAutofillController +import app.affine.pro.host.AndroidBackDispatcher import app.affine.pro.host.AndroidBootstrapCoordinator import app.affine.pro.host.AndroidCookieCleaner +import app.affine.pro.host.AndroidPdfPageRenderer +import app.affine.pro.host.AndroidSelectionCoordinator import app.affine.pro.host.AuthSessionStore import app.affine.pro.host.AuthTokenCipher +import app.affine.pro.host.AutofillPlatformBackend +import app.affine.pro.host.CaretBounds import app.affine.pro.host.CookieCleaner +import app.affine.pro.host.HostClipboard +import app.affine.pro.host.HostDocumentBufferController +import app.affine.pro.host.HostDocumentStore import app.affine.pro.host.HttpUrlConnectionRefreshTransport import app.affine.pro.host.InMemoryAesKeyProvider import app.affine.pro.host.LegacyLocalStorageProbe import app.affine.pro.host.NativeBridge +import app.affine.pro.host.PdfPageBackend import app.affine.pro.host.RefreshResult import app.affine.pro.host.RefreshTransport import app.affine.pro.host.Rfc4648Base64 +import app.affine.pro.host.SelectionGestureController import app.affine.pro.host.SessionPersistence +import app.affine.pro.host.TextLayoutAuthority import java.io.File import java.net.ServerSocket import java.nio.charset.StandardCharsets @@ -931,5 +943,933 @@ fun main() { tmpDir.deleteRecursively() } - println("Kotlin JNI AffineInputConnection + S2 Storage/DataStore/Probe real .so parity check passed (16/16 sequences)") + // 17. End-to-end Text <-> SelectionCoordinator/InputConnection: pure-Rust fallback layout + // (proportional widths & per-paragraph UAX #9 BiDi), grab-offset 0px drag, vertical drag + // beyond 0.5*line_height, slow drag across length==0 coincidence point (10->8->6->5->3), + // required HostClipboard Copy/Cut/Paste, InputConnection.performContextMenuAction(cut/paste), + // zero-alloc fillOverlayGeometry, and ACTION_CANCEL. + val selHandle = NativeBridge.nativeCreateHost() + try { + var overlayInvalidations = 0 + val ime = AffineImeController({ selHandle }, onMutated = { overlayInvalidations += 1 }) + val sel = AndroidSelectionCoordinator({ selHandle }, onMutated = { overlayInvalidations += 1 }) + sel.setViewport(1080f, 2400f, 3f) + + // Proportional fallback widths: "WWWW" is strictly wider than "iiii". + checkEq(ime.commitText("iiii", 1), true, "seq17 commit iiii") + checkEq(ime.setSelection(0, 4), true, "seq17 select iiii") + val narrowWidth = sel.overlayGeometry()!![9] - sel.overlayGeometry()!![3] + checkEq(ime.replaceText(0, ime.readText().length, "WWWW", 1), true, "seq17 replace with WWWW") + checkEq(ime.setSelection(0, 4), true, "seq17 select WWWW") + val wideWidth = sel.overlayGeometry()!![9] - sel.overlayGeometry()!![3] + checkEq(wideWidth > narrowWidth * 1.5f, true, "seq17 proportional fallback WWWW wider than iiii") + + // Insert "Hello world" and select [6, 11) ("world") -> handles & action menu auto-appear. + val invBefore = overlayInvalidations + checkEq(ime.replaceText(0, ime.readText().length, "Hello world", 1), true, "seq17 commit Hello world") + checkEq(ime.setSelection(6, 11), true, "seq17 select [6, 11)") + checkEq(overlayInvalidations > invBefore, true, "seq17 IME mutations trigger overlay invalidation") + checkEq(ime.getSelectedText(), "world", "seq17 initial selected text") + val g0 = sel.overlayGeometry()!! + checkEq(g0.size, 24, "seq17 fixed 24-float overlay geometry") + checkEq(g0[0], 1f, "seq17 has_selection=1") + checkEq(g0[1], 0f, "seq17 LTR direction=0") + checkEq(g0[19], 1f, "seq17 action menu visible before drag") + + // Grab End handle center and move 0px -> tip & selection stay identical. + val endCx = g0[11] + val endCy = g0[12] + val endTipX = g0[9] + checkEq(sel.beginDrag(endCx, endCy), 2, "seq17 hit End handle") + checkEq(sel.updateDrag(endCx, endCy), true, "seq17 0px drag succeeds") + checkEq(ime.getSelectedText(), "world", "seq17 0px drag preserves selection") + val gDragBuf = FloatArray(24) + checkEq(sel.fillOverlayGeometry(gDragBuf), true, "seq17 zero-alloc fillOverlayGeometry succeeds") + checkEq(gDragBuf[14], 1f, "seq17 magnifier visible during drag") + checkEq(gDragBuf[19], 0f, "seq17 action menu hidden during drag") + // Magnifier anchor_y must sit at the line vertical midpoint (strictly above tip_y). + checkEq(gDragBuf[16] < gDragBuf[10], true, "seq17 magnifier focus_y centered on line midpoint") + + // Vertical drag beyond 0.5*line_height on a single line must keep End active and magnifier at right end. + for (dy in listOf(-43f, -60f, -120f, 0f, 43f, 120f, 0f)) { + checkEq(sel.updateDrag(endCx, endCy + dy), true, "seq17 vertical drag dy=$dy") + checkEq(ime.selectionStart(), 6, "seq17 vertical drag dy=$dy keeps start=6") + checkEq(ime.selectionEnd(), 11, "seq17 vertical drag dy=$dy keeps end=11") + checkEq(sel.fillOverlayGeometry(gDragBuf), true, "seq17 fillOverlayGeometry at dy=$dy") + checkEq( + kotlin.math.abs(gDragBuf[15] - endTipX) < 0.01f, + true, + "seq17 magnifier anchor_x stays on right end at dy=$dy", + ) + } + + // Slow continuous drag across coincidence point (length==0) with +/-1px vertical jitter: + // offsets 10 -> 8 -> 6 (len=0) -> 5 -> 3 => final selection [3, 6) == "lo ". + for ((deltaX, jitterY) in listOf(-36f to 1f, -72f to -1f, -157.68f to 1f, -178.56f to -1f, -229.68f to 1f)) { + checkEq( + sel.updateDrag(endCx + deltaX, endCy + jitterY), + true, + "seq17 slow drag step dx=$deltaX", + ) + } + checkEq(ime.selectionStart(), 3, "seq17 inverted selection start=3") + checkEq(ime.selectionEnd(), 6, "seq17 inverted selection end=6") + checkEq(ime.getSelectedText(), "lo ", "seq17 inverted selection text == 'lo '") + checkEq(sel.endDrag(), true, "seq17 endDrag restores action menu") + + // Real HostClipboard integration: pre-seeded stale value replaced on Copy & Cut, + // failing clipboard aborts Cut before deleting text, Paste restores Cut text. + var clipboardStore: String? = "stale-clipboard" + val mockClipboard = object : HostClipboard { + override fun setPlainText(label: String, text: String): Boolean { + clipboardStore = text + return true + } + override fun getPlainText(): String? = clipboardStore + } + val failingClipboard = object : HostClipboard { + override fun setPlainText(label: String, text: String): Boolean = false + override fun getPlainText(): String? = null + } + checkEq(sel.performCopy(ime, mockClipboard), "lo ", "seq17 Copy returns 'lo '") + checkEq(clipboardStore, "lo ", "seq17 Copy wrote 'lo ' to HostClipboard") + + // ACTION_CANCEL hides magnifier cleanly. + val gBeforeCancel = sel.overlayGeometry()!! + checkEq(sel.beginDrag(gBeforeCancel[5], gBeforeCancel[6]) != 0, true, "seq17 begin drag before cancel") + checkEq(sel.overlayGeometry()!![14], 1f, "seq17 magnifier shown before cancel") + sel.cancelDrag() + checkEq(sel.overlayGeometry()!![14], 0f, "seq17 ACTION_CANCEL hides magnifier") + + // Cut with failing clipboard must NOT delete text; Cut with working clipboard writes BEFORE deleting. + checkEq(sel.performCut(ime, failingClipboard), null, "seq17 Cut aborts when clipboard write fails") + checkEq(ime.readText(), "Hello world", "seq17 text preserved when clipboard write fails") + clipboardStore = "stale-before-cut" + + // Real InputConnection.performContextMenuAction(cut / paste / selectAll) round-trip. + val ctxIc = AffineSurfaceView.createInputConnection( + handleProvider = { selHandle }, + onContextMenuAction = { actionId -> + sel.handleContextMenuAction(actionId, ime, mockClipboard) + }, + ) + checkEq(ctxIc.performContextMenuAction(android.R.id.cut), true, "seq17 IC performContextMenuAction(cut)") + checkEq(clipboardStore, "lo ", "seq17 IC cut wrote 'lo ' to HostClipboard") + checkEq(ime.readText(), "Helworld", "seq17 text after IC cut") + checkEq(sel.overlayGeometry()!![0], 0f, "seq17 collapsed selection auto-hides handles") + checkEq(ctxIc.performContextMenuAction(android.R.id.paste), true, "seq17 IC performContextMenuAction(paste)") + checkEq(ime.readText(), "Hello world", "seq17 IC paste restored exact original text") + checkEq(ime.selectionStart(), 6, "seq17 IC paste placed cursor at end of pasted span") + checkEq(ime.selectionEnd(), 6, "seq17 IC paste collapsed selection") + checkEq(ctxIc.performContextMenuAction(android.R.id.selectAll), true, "seq17 IC selectAll") + checkEq(ime.getSelectedText(), "Hello world", "seq17 IC selectAll selected full text") + + // Per-paragraph ("\n") UAX #9 BiDi: paragraph 0 ("A") is LTR, paragraph 1 ("שלום") is RTL. + checkEq(ime.replaceText(0, ime.readText().length, "A\nשלום", 1), true, "seq17 insert mixed BiDi paragraphs") + checkEq(ime.setSelection(0, 1), true, "seq17 select LTR paragraph 0") + checkEq(sel.overlayGeometry()!![1], 0f, "seq17 paragraph 0 ('A') is LTR") + checkEq(ime.setSelection(2, 6), true, "seq17 select RTL paragraph 1") + val gParaRtl = sel.overlayGeometry()!! + checkEq(gParaRtl[1], 1f, "seq17 paragraph 1 ('שלום') is RTL") + checkEq(gParaRtl[3] > gParaRtl[9], true, "seq17 paragraph 1 Start tip visually right of End tip") + + // Pure RTL ("שלום עולם"): direction=1, Start handle visually right of End handle, drag updates IME. + checkEq(ime.replaceText(0, ime.readText().length, "שלום עולם", 1), true, "seq17 insert RTL text") + checkEq(ime.setSelection(0, 4), true, "seq17 select RTL [0, 4)") + val gRtl = sel.overlayGeometry()!! + checkEq(gRtl[1], 1f, "seq17 RTL direction=1") + checkEq(gRtl[3] > gRtl[9], true, "seq17 RTL Start tip is visually right of End tip") + checkEq(sel.beginDrag(gRtl[11], gRtl[12]), 2, "seq17 hit RTL End handle") + checkEq(sel.updateDrag(gRtl[11] - 56.88f, gRtl[12]), true, "seq17 drag RTL End handle left by 2 chars") + checkEq(ime.selectionStart(), 0, "seq17 RTL selection start=0") + checkEq(ime.selectionEnd(), 6, "seq17 RTL selection end=6") + checkEq(sel.endDrag(), true, "seq17 RTL endDrag") + sel.clear() + checkEq(sel.overlayGeometry()!![0], 0f, "seq17 clear hides selection") + } finally { + NativeBridge.nativeDestroyHost(selHandle) + } + + // 18. Surface recreation state preservation (DPI, scroll, IME text, texture generation), + // nav-bar-deducted effective IME inset, cross-generation readiness guard, and Vulkan -> GLES3 recovery. + val recHandle = NativeBridge.nativeCreateHost() + try { + val ime = AffineImeController { recHandle } + checkEq(ime.commitText("persist-me", 1), true, "seq18 seed IME text") + NativeBridge.nativeOnSurfaceInsetsPx(recHandle, 120, 0, 72, 0, 900, 3.0f) + checkEq(NativeBridge.nativeGetSurfaceDensity(recHandle), 3.0f, "seq18 density preserved") + checkEq(NativeBridge.nativeGetEffectiveImeBottomDp(recHandle), 276.0f, "seq18 IME inset deducts nav bar bottom") + NativeBridge.nativeSetSurfaceScrollOffset(recHandle, 0f, 512.5f) + + // Select Vulkan (1), report Vulkan device loss -> downgrades seamlessly to GLES3 (2). + checkEq(NativeBridge.nativeSelectRenderBackend(recHandle, true, true), 1, "seq18 selected Vulkan") + checkEq(NativeBridge.nativeReportVulkanDeviceLost(recHandle), 2, "seq18 Vulkan device loss downgrades to GLES3") + checkEq(NativeBridge.nativeGetRenderBackend(recHandle), 2, "seq18 active backend is GLES3") + checkEq(NativeBridge.nativeGetTextureGeneration(recHandle) >= 1L, true, "seq18 texture generation advanced") + + // Background destroy & rotation size change preserve scroll, density, and IME text; + // before surfaceCreated + surfaceChanged pair completes, surface stays not ready. + NativeBridge.nativeOnSurfaceChanged(recHandle, 1, 1080, 2400) + NativeBridge.nativeOnSurfaceDestroyed(recHandle) + checkEq(NativeBridge.nativeIsSurfaceReady(recHandle), false, "seq18 destroyed surface not ready") + checkEq(NativeBridge.nativeOnFrameTick(recHandle, 20_000_000L), 0, "seq18 detached tick returns 0") + NativeBridge.nativeOnSurfaceChanged(recHandle, 1, 2400, 1080) + checkEq(NativeBridge.nativeHasPendingFrame(recHandle), true, "seq18 pending frame set after destroy") + checkEq(NativeBridge.nativeGetSurfaceScrollY(recHandle), 512.5f, "seq18 scroll offset preserved") + checkEq(NativeBridge.nativeGetSurfaceDensity(recHandle), 3.0f, "seq18 density preserved after destroy") + checkEq(ime.readText(), "persist-me", "seq18 IME text preserved across surface destroy") + } finally { + NativeBridge.nativeDestroyHost(recHandle) + } + + // 19. API 26+ AutofillManager virtual view structure bridge vs API 24/25 silent degradation, + // zero fake placeholders, IME write-back, and sensitive value wipe on commit/cancel. + for (legacySdk in listOf(24, 25)) { + val legacyAfHandle = NativeBridge.nativeCreateHost() + try { + val events = mutableListOf() + val mockBackend = object : AutofillPlatformBackend { + override fun notifyViewEntered(autofillId: Int, left: Int, top: Int, right: Int, bottom: Int) { + events.add("enter:$autofillId") + } + override fun notifyViewExited(autofillId: Int) { events.add("exit:$autofillId") } + override fun notifyValueChanged(autofillId: Int, text: String) { events.add("val:$autofillId") } + override fun commit() { events.add("commit") } + override fun cancel() { events.add("cancel") } + } + val af = AndroidAutofillController(legacySdk, { legacyAfHandle }, mockBackend) + checkEq(af.isEnabled, false, "seq19 API $legacySdk autofill disabled") + checkEq(af.registerField(101, 1, 10, 20, 400, 80, false, 0), false, "seq19 API $legacySdk register blocked") + af.onFieldFocusChanged(101) + checkEq(af.onAutofillValues(mapOf(101 to "a@b.com")), 0, "seq19 API $legacySdk autofill ignored") + checkEq(af.commit(), false, "seq19 API $legacySdk commit blocked") + checkEq(events.isEmpty(), true, "seq19 API $legacySdk zero platform AutofillManager calls") + checkEq(af.virtualNodesSnapshot().isEmpty(), true, "seq19 API $legacySdk empty virtual nodes") + } finally { + NativeBridge.nativeDestroyHost(legacyAfHandle) + } + } + val api26Handle = NativeBridge.nativeCreateHost() + try { + val events = mutableListOf() + val mockBackend = object : AutofillPlatformBackend { + override fun notifyViewEntered(autofillId: Int, left: Int, top: Int, right: Int, bottom: Int) { + events.add("enter:$autofillId:$left,$top,$right,$bottom") + } + override fun notifyViewExited(autofillId: Int) { events.add("exit:$autofillId") } + override fun notifyValueChanged(autofillId: Int, text: String) { events.add("val:$autofillId:$text") } + override fun commit() { events.add("commit") } + override fun cancel() { events.add("cancel") } + } + var syncingFocus = false + lateinit var af: AndroidAutofillController + val ime = AffineImeController( + handleProvider = { api26Handle }, + onMutated = {}, + onTextEdited = { edited -> + if (!syncingFocus) { + af.onFocusedTextEdited(edited) + } + }, + ) + val afIc = AffineSurfaceView.createInputConnection( + handleProvider = { api26Handle }, + onMutated = {}, + onTextEdited = { edited -> + if (!syncingFocus) { + af.onFocusedTextEdited(edited) + } + }, + ) + af = AndroidAutofillController( + sdkInt = 26, + handleProvider = { api26Handle }, + backend = mockBackend, + onValueCommitted = { id, text -> + if (af.focusedFieldId() == id) { + syncingFocus = true + try { + ime.replaceText(0, ime.readText().length, text, 1) + } finally { + syncingFocus = false + } + } + }, + onFocusedFieldTextSync = { _, text -> + syncingFocus = true + try { + ime.replaceText(0, ime.readText().length, text, 1) + } finally { + syncingFocus = false + } + }, + ) + checkEq(af.isEnabled, true, "seq19 API 26 autofill enabled") + checkEq(af.registerField(101, 1, 20, 100, 800, 180, false, 0), true, "seq19 register email field") + checkEq(af.registerField(102, 2, 20, 200, 800, 280, true, 8), true, "seq19 register password field") + checkEq(af.registerField(103, 3, 20, 300, 800, 380, false, 0), true, "seq19 register OTP field") + // Empty/unset fields MUST return null (never synthetic "********" or spaces). + checkEq(af.resolveVirtualFieldValueForStructure(102), null, "seq19 unset password emits null, never fake asterisks") + checkEq(af.virtualNodesSnapshot().size, 3, "seq19 3 virtual autofill nodes exposed") + + // Pure manual typing without any prior Autofill write-back: + // focus email (101) -> type "a@b.c" -> switch to password (102) -> switch back to email (101) => "a@b.c" preserved. + af.onFieldFocusChanged(101) + checkEq(afIc.commitText("a@b.c", 1), true, "seq19 manual type a@b.c without prior autofill") + checkEq(af.readFormValues()["email"], "a@b.c", "seq19 manual typed email stored in autofill state") + af.onFieldFocusChanged(102) + checkEq(ime.readText(), "", "seq19 switching to empty password clears IME") + af.onFieldFocusChanged(101) + checkEq(ime.readText(), "a@b.c", "seq19 returning to email restores manually typed a@b.c") + checkEq(af.readFormValues()["email"], "a@b.c", "seq19 form email remains a@b.c") + + // Matrix test: 2 focus targets (email vs password) x 2 batch orders ([email, password] vs [password, email]). + // IME must ALWAYS equal the currently focused field and NEVER be overwritten by another field's password. + val batchOrders = listOf( + "email_first" to linkedMapOf(101 to "darksky@affine.pro", 102 to "hunter2!"), + "password_first" to linkedMapOf(102 to "hunter2!", 101 to "darksky@affine.pro"), + ) + for ((focusId, expectedIme) in listOf(101 to "darksky@affine.pro", 102 to "hunter2!")) { + for ((orderName, batch) in batchOrders) { + af.onFieldFocusChanged(focusId) + checkEq( + AffineSurfaceView.dispatchAutofillBatch(af, batch), + 2, + "seq19 batch $orderName focus=$focusId applied 2 fields", + ) + checkEq( + ime.readText(), + expectedIme, + "seq19 batch $orderName focus=$focusId keeps IME strictly isolated to focused field", + ) + val form = af.readFormValues() + checkEq(form["email"], "darksky@affine.pro", "seq19 form email preserved ($orderName)") + checkEq(form["password"], "hunter2!", "seq19 form password preserved ($orderName)") + } + } + + // Manual IME edit round-trip: focus email (101) -> autofill A -> manual InputConnection edit to B -> + // switch focus to password (102) -> switch back to email (101) => both IME and form read B (never A). + af.onFieldFocusChanged(101) + checkEq(ime.readText(), "darksky@affine.pro", "seq19 email focused starts with autofilled A") + checkEq(afIc.deleteSurroundingText(18, 0), true, "seq19 manual deleteSurroundingText on email") + checkEq(afIc.commitText("edited@affine.pro", 1), true, "seq19 manual commitText B on email") + checkEq(ime.readText(), "edited@affine.pro", "seq19 IME now has manual edit B") + checkEq(af.readFormValues()["email"], "edited@affine.pro", "seq19 autofill store synced manual edit B") + af.onFieldFocusChanged(102) + checkEq(ime.readText(), "hunter2!", "seq19 switching to password loads password") + af.onFieldFocusChanged(101) + checkEq(ime.readText(), "edited@affine.pro", "seq19 returning to email preserves manual edit B (never clobbered by A)") + checkEq(af.readFormValues()["email"], "edited@affine.pro", "seq19 form email remains B after round-trip") + + // Clearing field text to "" must still notify AutofillManager. + checkEq(af.updateFieldText(102, ""), true, "seq19 clear password text") + checkEq(events.contains("val:102:"), true, "seq19 empty text still notifies notifyValueChanged") + checkEq(af.resolveVirtualFieldValueForStructure(102), null, "seq19 cleared password resolves to null") + + // Re-fill and verify structure JSON never leaks plaintext, then commit/cancel/clear wipe memory. + checkEq(af.updateFieldText(102, "hunter2!"), true, "seq19 restore password") + val structJson = af.virtualStructureJson() + checkEq(structJson.contains("\"emailAddress\""), true, "seq19 structure includes emailAddress") + checkEq(structJson.contains("\"password\""), true, "seq19 structure includes password") + checkEq(structJson.contains("\"smsOTPCode\""), true, "seq19 structure includes smsOTPCode") + checkEq(structJson.contains("hunter2!"), false, "seq19 structure JSON never leaks plaintext password") + checkEq(af.commit(), true, "seq19 autofill commit succeeded") + checkEq(af.resolveVirtualFieldValueForStructure(102), null, "seq19 commit wiped cached password") + checkEq(af.updateFieldText(102, "temp-secret"), true, "seq19 updateFieldText updates password") + checkEq(af.cancel(), true, "seq19 cancel wipes cached password") + checkEq(af.resolveVirtualFieldValueForStructure(102), null, "seq19 password wiped after cancel") + af.clearFields() + checkEq(af.virtualNodesSnapshot().isEmpty(), true, "seq19 clearFields removes all virtual nodes") + checkEq(events.contains("enter:101:20,100,800,180"), true, "seq19 notified enter 101") + checkEq(events.contains("exit:101"), true, "seq19 notified exit 101") + checkEq(events.contains("enter:102:20,200,800,280"), true, "seq19 notified enter 102") + checkEq(events.contains("commit"), true, "seq19 notified commit") + checkEq(events.contains("cancel"), true, "seq19 notified cancel") + } finally { + NativeBridge.nativeDestroyHost(api26Handle) + } + + // 20. Four-phase predictive back dispatcher across API levels (24, 33, 34) with real + // decrementing back_stack_depth, standalone API 34+ button-back, and re-entrancy guard. + val backCases = listOf( + Triple(24, 0, false), + Triple(32, 0, false), + Triple(33, 1, false), + Triple(34, 2, true), + Triple(35, 2, true), + ) + for ((sdk, expectedMode, supportsPredictive) in backCases) { + val backHandle = NativeBridge.nativeCreateHost() + try { + var exitCalls = 0 + var reentrantBlocked = false + var probeReentrantOnNextMutate = false + val visitedDestinations = mutableListOf() + val docStore = HostDocumentStore() + var switchingDoc = false + val navIme = AffineImeController( + handleProvider = { backHandle }, + onMutated = {}, + onTextEdited = { text -> + if (!switchingDoc) { + docStore.saveCurrent(text) + } + }, + ) + lateinit var dispatcher: AndroidBackDispatcher + dispatcher = AndroidBackDispatcher( + sdkInt = sdk, + handleProvider = { backHandle }, + onMutated = { + // Verify re-entrant commit inside Commit callback is blocked without double-popping. + if (probeReentrantOnNextMutate) { + probeReentrantOnNextMutate = false + if (supportsPredictive) { + if (!dispatcher.onBackInvoked()) reentrantBlocked = true + } else { + if (!dispatcher.onLegacyBackPressed()) reentrantBlocked = true + } + } + }, + onDestinationChanged = { dest -> + if (dest != null) { + visitedDestinations.add(dest) + if (docStore.activeDocumentId != dest) { + val targetText = docStore.switchTo(dest, navIme.currentText()) + switchingDoc = true + try { + navIme.replaceText(0, navIme.currentText().length, targetText, 1) + } finally { + switchingDoc = false + } + } + } + }, + onSystemExit = { exitCalls += 1 }, + ) + checkEq(dispatcher.dispatchMode, expectedMode, "seq20 API $sdk dispatchMode") + checkEq(dispatcher.currentDestination(), "workspace/home", "seq20 API $sdk starts on root destination") + + if (supportsPredictive) { + // Case A: 3-page real destination stack ("workspace/home" -> "doc/welcome" -> "doc/settings") + // driven via real host navigation entrypoints (navigateTo / openDocument), + // with two consecutive standalone button/key onBackInvoked() WITHOUT onBackStarted(). + checkEq(dispatcher.navigateTo("doc/welcome"), true, "seq20 API $sdk navigateTo doc/welcome") + checkEq(dispatcher.openDocument("settings"), true, "seq20 API $sdk openDocument settings") + checkEq(dispatcher.currentDestination(), "doc/settings", "seq20 API $sdk active route doc/settings") + probeReentrantOnNextMutate = true + checkEq(dispatcher.onBackInvoked(), true, "seq20 API $sdk standalone back #1 pops to doc/welcome") + checkEq(dispatcher.currentDestination(), "doc/welcome", "seq20 API $sdk route now doc/welcome") + checkEq(reentrantBlocked, true, "seq20 API $sdk re-entrant onBackInvoked blocked") + checkEq(dispatcher.onBackInvoked(), true, "seq20 API $sdk standalone back #2 pops to workspace/home") + checkEq(dispatcher.currentDestination(), "workspace/home", "seq20 API $sdk route now workspace/home") + checkEq(exitCalls, 0, "seq20 API $sdk no exit while popping stack") + checkEq(dispatcher.onBackInvoked(), false, "seq20 API $sdk standalone back #3 at root returns false") + checkEq(exitCalls, 1, "seq20 API $sdk root delegates to onSystemExit") + + // Case B: Real document content switch (Doc A -> Doc B): + // Gesture Cancel keeps "Doc B"; Gesture Commit restores "Doc A"; + // follow-up standalone button back pops to workspace/home; root exits. + checkEq(dispatcher.openDocument("doc-a"), true, "seq20 API $sdk openDocument doc-a") + checkEq(navIme.commitText("Doc A", 1), true, "seq20 API $sdk write Doc A") + checkEq(dispatcher.openDocument("doc-b"), true, "seq20 API $sdk openDocument doc-b") + checkEq(navIme.commitText("Doc B", 1), true, "seq20 API $sdk write Doc B") + checkEq(docStore.activeDocumentId, "doc/doc-b", "seq20 API $sdk active doc is doc/doc-b") + checkEq(navIme.currentText(), "Doc B", "seq20 API $sdk IME holds Doc B") + checkEq(dispatcher.onBackStarted(0f), true, "seq20 API $sdk gesture Start") + checkEq(dispatcher.onBackProgressed(0.5f), true, "seq20 API $sdk gesture Progress") + checkEq(dispatcher.onBackCancelled(), true, "seq20 API $sdk gesture Cancel") + checkEq(dispatcher.currentDestination(), "doc/doc-b", "seq20 API $sdk Cancel keeps doc/doc-b") + checkEq(navIme.currentText(), "Doc B", "seq20 API $sdk Cancel keeps Doc B content") + checkEq(dispatcher.onBackStarted(0f), true, "seq20 API $sdk second gesture Start") + checkEq(dispatcher.onBackProgressed(0.8f), true, "seq20 API $sdk second gesture Progress") + checkEq(dispatcher.onBackInvoked(), true, "seq20 API $sdk gesture Commit pops to doc/doc-a") + checkEq(dispatcher.currentDestination(), "doc/doc-a", "seq20 API $sdk route doc/doc-a after gesture") + checkEq(docStore.activeDocumentId, "doc/doc-a", "seq20 API $sdk activeDocumentId restored to doc/doc-a") + checkEq(navIme.currentText(), "Doc A", "seq20 API $sdk IME content restored to Doc A") + checkEq(dispatcher.onBackInvoked(), true, "seq20 API $sdk follow-up button back pops to workspace/home") + checkEq(dispatcher.currentDestination(), "workspace/home", "seq20 API $sdk route workspace/home after button") + checkEq(dispatcher.onBackInvoked(), false, "seq20 API $sdk root back returns false") + checkEq(exitCalls, 2, "seq20 API $sdk second root exit delegated") + checkEq(visitedDestinations.contains("doc/doc-a"), true, "seq20 API $sdk destination callback fired") + } else { + checkEq(dispatcher.navigateTo("doc/welcome"), true, "seq20 API $sdk navigateTo doc/welcome") + checkEq(dispatcher.openDocument("settings"), true, "seq20 API $sdk openDocument settings") + checkEq(dispatcher.onBackStarted(0f), false, "seq20 API $sdk predictive Start disabled") + probeReentrantOnNextMutate = true + checkEq(dispatcher.onLegacyBackPressed(), true, "seq20 API $sdk legacy #1 pops to doc/welcome") + checkEq(dispatcher.currentDestination(), "doc/welcome", "seq20 API $sdk legacy route doc/welcome") + checkEq(reentrantBlocked, true, "seq20 API $sdk re-entrant onLegacyBackPressed blocked") + checkEq(dispatcher.onLegacyBackPressed(), true, "seq20 API $sdk legacy #2 pops to workspace/home") + checkEq(dispatcher.currentDestination(), "workspace/home", "seq20 API $sdk legacy route workspace/home") + checkEq(exitCalls, 0, "seq20 API $sdk no exit while popping stack") + checkEq(dispatcher.onLegacyBackPressed(), false, "seq20 API $sdk legacy root returns false") + checkEq(exitCalls, 1, "seq20 API $sdk legacy root delegates to system exit") + } + } finally { + NativeBridge.nativeDestroyHost(backHandle) + } + } + + // 21. Native PdfRenderer page bridge: valid ARGB_8888 -> RGBA8, negative dpiBucket clamp, + // out-of-bounds & OOM cap rejection, and >4096-pixel multi-chunk streaming conversion. + var backendRenderCalls = 0 + val fakePdfBackend = object : PdfPageBackend { + override fun pageCount(): Int = 3 + override fun renderPageArgb(pageIndex: Int, widthPx: Int, heightPx: Int): IntArray { + backendRenderCalls += 1 + if (widthPx == 2 && heightPx == 2) { + return intArrayOf( + 0xFF112233.toInt(), + 0x80AABBCC.toInt(), + 0xFFFFFFFF.toInt(), + 0x00010203, + ) + } + return IntArray(widthPx * heightPx) { idx -> + if (idx % 2 == 0) 0xFF102030.toInt() else 0x80405060.toInt() + } + } + override fun close() {} + } + AndroidPdfPageRenderer("doc-pdf-1", fakePdfBackend).use { pdf -> + checkEq(pdf.renderPageRgba(-1, 2, 2), null, "seq21 negative page rejected") + checkEq(pdf.renderPageRgba(3, 2, 2), null, "seq21 out-of-bounds page rejected") + checkEq(pdf.renderPageRgba(0, 4097, 2), null, "seq21 OOM width > 4096 rejected") + checkEq(pdf.renderPageRgba(0, 0, 2), null, "seq21 zero width rejected") + checkEq(backendRenderCalls, 0, "seq21 invalid requests never invoke PdfRenderer backend") + + val page = pdf.renderPageRgba(1, 2, 2, dpiBucket = 320) + checkEq(page != null, true, "seq21 valid 2x2 page rendered") + checkEq(backendRenderCalls, 1, "seq21 backend invoked once for valid page") + checkEq(page!!.cacheKey, "pdf:doc-pdf-1:p1:2x2@320dpi", "seq21 deterministic cache key") + val expectedRgba = byteArrayOf( + 0x11, 0x22, 0x33, 0xFF.toByte(), + 0xAA.toByte(), 0xBB.toByte(), 0xCC.toByte(), 0x80.toByte(), + 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), + 0x01, 0x02, 0x03, 0x00, + ) + checkEq(page.rgbaBytes.contentEquals(expectedRgba), true, "seq21 exact ARGB_8888 -> RGBA8 conversion") + + // Negative dpiBucket clamps to 72dpi without NPE. + checkEq( + NativeBridge.nativePdfPageCacheKey("doc-pdf-1", 1, 2, 2, -100), + "pdf:doc-pdf-1:p1:2x2@72dpi", + "seq21 negative dpiBucket clamped to 72dpi without NPE", + ) + // Mismatched array length rejected before conversion. + checkEq( + NativeBridge.nativePdfConvertArgbToRgba(intArrayOf(1, 2, 3), 2, 2), + null, + "seq21 mismatched pixel array length returns null", + ) + // Multi-chunk streaming conversion (> 4096 pixels: 100 x 50 = 5000 pixels). + val largePage = pdf.renderPageRgba(2, 100, 50, dpiBucket = -5) + checkEq(largePage != null, true, "seq21 100x50 multi-chunk streaming page rendered") + checkEq(largePage!!.cacheKey, "pdf:doc-pdf-1:p2:100x50@72dpi", "seq21 negative dpi clamped via renderer") + checkEq(largePage.rgbaBytes.size, 5000 * 4, "seq21 5000-pixel RGBA8 byte length") + checkEq(largePage.rgbaBytes[0], 0x10.toByte(), "seq21 chunk 0 pixel 0 R") + checkEq(largePage.rgbaBytes[4999 * 4 + 3], 0x80.toByte(), "seq21 chunk 1 last pixel A") + } + + // 22. Authoritative TextLayoutAuthority selection parity (zero snap-back to Rust estimates on + // ACTION_UP/ACTION_CANCEL/selectAll), line-midpoint vertical grab probe on multi-line text, + // cross-anchor active_drag flip for loupe tracking, and strict Autofill/Document buffer isolation. + val layoutParityHandle = NativeBridge.nativeCreateHost() + try { + val narrowLayout = object : TextLayoutAuthority { + override var cachedText: String = "" + private val originX = 72f + private val originY = 240f + private val lineH = 60f + + private fun charWidth(c: Char): Float = when (c) { + 'i' -> 8f + ' ' -> 14f + else -> 30f + } + + override fun ensureLayoutReady(text: String, viewportWidthPx: Int, density: Float): Boolean { + cachedText = text + return true + } + + override fun caretBounds( + utf16Offset: Int, + isSelectionEnd: Boolean, + selStart: Int, + selEnd: Int, + ): CaretBounds { + val off = utf16Offset.coerceIn(0, cachedText.length) + var line = 0 + var x = originX + for (idx in 0 until off) { + val ch = cachedText[idx] + if (ch == '\n') { + line += 1 + x = originX + } else { + x += charWidth(ch) + } + } + val top = originY + line * lineH + return CaretBounds(x = x, top = top, bottom = top + lineH, lineIndex = line, isRtlParagraph = false) + } + + override fun selectionEndCarets(selStart: Int, selEnd: Int): Pair = + caretBounds(selStart, false, selStart, selEnd) to caretBounds(selEnd, true, selStart, selEnd) + + override fun closestOffset(x: Float, y: Float): Int { + val lines = cachedText.split('\n') + val targetLine = if (y < originY) 0 else ((y - originY) / lineH).toInt().coerceIn(0, lines.lastIndex) + var lineStartOff = 0 + for (l in 0 until targetLine) { + lineStartOff += lines[l].length + 1 + } + val lineText = lines[targetLine] + var bestOff = lineStartOff + var curX = originX + var bestDist = kotlin.math.abs(x - curX) + for (i in lineText.indices) { + curX += charWidth(lineText[i]) + val d = kotlin.math.abs(x - curX) + if (d < bestDist) { + bestDist = d + bestOff = lineStartOff + i + 1 + } + } + return bestOff + } + } + + val ime = AffineImeController { layoutParityHandle } + val sel = AndroidSelectionCoordinator({ layoutParityHandle }) + sel.setViewport(1080f, 2400f, 3f) + val gesture = SelectionGestureController( + coordinator = sel, + layoutAuthority = narrowLayout, + selectionStartProvider = { ime.selectionStart() }, + selectionEndProvider = { ime.selectionEnd() }, + onSelectionChanged = { lo, hi -> ime.setSelection(lo, hi) }, + ) + + // Part A: "iiiiiiiiii world" [11, 16) -> ACTION_DOWN -> ACTION_MOVE -> ACTION_UP & ACTION_CANCEL + // and performContextMenuAction(selectAll) must keep 0.0px error against TextLayoutAuthority. + checkEq(ime.commitText("iiiiiiiiii world", 1), true, "seq22 commit narrow-i string") + checkEq(ime.setSelection(11, 16), true, "seq22 select [11, 16) world") + gesture.syncSelectionFromLayout(ime.currentText(), 11, 16, 1080, 3f) + val expectedWorld = narrowLayout.selectionEndCarets(11, 16) + val gInit = sel.overlayGeometry()!! + checkEq(gInit[3], expectedWorld.first.x, "seq22 initial start tip matches authoritative layout") + checkEq(gInit[9], expectedWorld.second.x, "seq22 initial end tip matches authoritative layout") + checkEq(gesture.onDown(gInit[11], gInit[12], 3f), 2, "seq22 hit End handle on narrow-i string") + checkEq(gesture.onMove(gInit[11], gInit[12]), true, "seq22 0px drag on narrow-i string") + checkEq(gesture.onUp(1080, 3f), true, "seq22 ACTION_UP restores menu") + val gAfterUp = sel.overlayGeometry()!! + checkEq(gAfterUp[3], expectedWorld.first.x, "seq22 ACTION_UP start tip keeps 0px error (never snaps to Rust estimate)") + checkEq(gAfterUp[9], expectedWorld.second.x, "seq22 ACTION_UP end tip keeps 0px error (never snaps to Rust estimate)") + checkEq(gesture.onDown(gAfterUp[11], gAfterUp[12], 3f), 2, "seq22 hit End handle before cancel") + checkEq(gesture.onCancel(1080, 3f), true, "seq22 ACTION_CANCEL finishes cleanly") + val gAfterCancel = sel.overlayGeometry()!! + checkEq(gAfterCancel[3], expectedWorld.first.x, "seq22 ACTION_CANCEL start tip keeps 0px error") + checkEq(gAfterCancel[9], expectedWorld.second.x, "seq22 ACTION_CANCEL end tip keeps 0px error") + + val dummyClipboard = object : HostClipboard { + var data: String? = null + override fun setPlainText(label: String, text: String): Boolean { data = text; return true } + override fun getPlainText(): String? = data + } + val selectAllIc = AffineSurfaceView.createInputConnection( + handleProvider = { layoutParityHandle }, + onContextMenuAction = { id -> + val ok = sel.handleContextMenuAction(id, ime, dummyClipboard) + if (ok) gesture.syncSelectionFromLayout(ime.currentText(), ime.selectionStart(), ime.selectionEnd(), 1080, 3f) + ok + }, + ) + checkEq(selectAllIc.performContextMenuAction(android.R.id.selectAll), true, "seq22 IC selectAll") + val expectedAll = narrowLayout.selectionEndCarets(0, 16) + val gAll = sel.overlayGeometry()!! + checkEq(gAll[3], expectedAll.first.x, "seq22 selectAll start tip matches layout") + checkEq(gAll[9], expectedAll.second.x, "seq22 selectAll end tip matches layout") + + // Part B: Multi-line line-0 handle grab uses line midpoint (never jumps to line 1), + // and cross-anchor inversion flips Rust active_drag so magnifier follows moving left end. + checkEq(ime.replaceText(0, ime.currentText().length, "First line\nSecond line", 1), true, "seq22 seed 2-line text") + checkEq(ime.setSelection(6, 10), true, "seq22 select line-0 'line' [6, 10)") + gesture.syncSelectionFromLayout(ime.currentText(), 6, 10, 1080, 3f) + val gMulti = sel.overlayGeometry()!! + checkEq(gesture.onDown(gMulti[11], gMulti[12], 3f), 2, "seq22 grab line-0 End handle") + // Stationary / tiny horizontal move must stay on line 0 (never jump to line 1). + checkEq(gesture.onMove(gMulti[11], gMulti[12]), true, "seq22 stationary move on line 0") + checkEq(ime.selectionStart(), 6, "seq22 line-0 grab stayed on line 0 start=6") + checkEq(ime.selectionEnd(), 10, "seq22 line-0 grab stayed on line 0 end=10") + // Drag right handle left past fixed anchor (offset 6) to offset 2 -> active_drag flips to Start + // and magnifier.anchor_x tracks moving left end caret(2).x (NOT stationary right anchor caret(6).x). + val targetLeftX = narrowLayout.caretBounds(2).x + val endTipInitialX = narrowLayout.caretBounds(10).x + checkEq(gesture.onMove(gMulti[11] + (targetLeftX - endTipInitialX), gMulti[12]), true, "seq22 cross-anchor drag to offset 2") + checkEq(ime.selectionStart(), 2, "seq22 cross-anchor inverted start=2") + checkEq(ime.selectionEnd(), 6, "seq22 cross-anchor inverted end=6") + val gCross = sel.overlayGeometry()!! + checkEq(gCross[14], 1f, "seq22 magnifier visible during cross-anchor drag") + checkEq(kotlin.math.abs(gCross[15] - targetLeftX) < 0.01f, true, "seq22 magnifier anchor_x tracks moving left end") + checkEq(gesture.onUp(1080, 3f), true, "seq22 release after cross-anchor drag") + checkEq(ime.selectionStart(), 2, "seq22 post-release inverted start=2") + checkEq(ime.selectionEnd(), 6, "seq22 post-release inverted end=6") + + // Mixed-BiDi outward teardrop orientation: embedded LTR run ("12", start_x < end_x) inside RTL + // paragraph and embedded RTL run ("אב", start_x > end_x) inside LTR paragraph both lean outward. + sel.updateSelection(200f, 300f, 240f, 300f, 60f, rtl = true, hasSelection = true) + val gMixedLtrInRtl = sel.overlayGeometry()!! + checkEq(gMixedLtrInRtl[5] < gMixedLtrInRtl[3], true, "seq22 RTL-para LTR-run start bulb leans left") + checkEq(gMixedLtrInRtl[11] > gMixedLtrInRtl[9], true, "seq22 RTL-para LTR-run end bulb leans right") + checkEq(gMixedLtrInRtl[11] - gMixedLtrInRtl[5] > gMixedLtrInRtl[7] * 2f, true, "seq22 RTL-para LTR-run bulbs never overlap") + + sel.updateSelection(240f, 300f, 200f, 300f, 60f, rtl = false, hasSelection = true) + val gMixedRtlInLtr = sel.overlayGeometry()!! + checkEq(gMixedRtlInLtr[5] > gMixedRtlInLtr[3], true, "seq22 LTR-para RTL-run start bulb leans right") + checkEq(gMixedRtlInLtr[11] < gMixedRtlInLtr[9], true, "seq22 LTR-para RTL-run end bulb leans left") + checkEq(gMixedRtlInLtr[5] - gMixedRtlInLtr[11] > gMixedRtlInLtr[7] * 2f, true, "seq22 LTR-para RTL-run bulbs never overlap") + + // Part C: Strict Autofill vs Document buffer isolation across password fill, editing, and route switch. + val docStore = HostDocumentStore("doc/roadmap", "") + lateinit var afCtrl: AndroidAutofillController + lateinit var bufCtrl: HostDocumentBufferController + val docIme = AffineImeController( + handleProvider = { layoutParityHandle }, + onMutated = {}, + onTextEdited = { t -> bufCtrl.onImeTextEdited(t) }, + ) + afCtrl = AndroidAutofillController( + sdkInt = 26, + handleProvider = { layoutParityHandle }, + onValueCommitted = { id, text -> + if (afCtrl.focusedFieldId() == id) { + bufCtrl.applyAutofillTextToIme(text) + } + }, + onFocusedFieldTextSync = { _, text -> bufCtrl.applyAutofillTextToIme(text) }, + ) + bufCtrl = HostDocumentBufferController( + documentStore = docStore, + imeProvider = { docIme }, + autofillProvider = { afCtrl }, + ) + val nav = AndroidBackDispatcher( + sdkInt = 34, + handleProvider = { layoutParityHandle }, + onDestinationChanged = { dest -> if (dest != null) bufCtrl.onRouteChanged(dest) }, + ) + checkEq(nav.openDocument("roadmap"), true, "seq22 open doc/roadmap") + checkEq(docIme.replaceText(0, docIme.currentText().length, "Project roadmap", 1), true, "seq22 write roadmap text") + checkEq(bufCtrl.lastPreviewText, "Project roadmap", "seq22 preview shows Project roadmap") + + checkEq(afCtrl.registerField(202, 2, 20, 200, 800, 280, true, 0), true, "seq22 register password field") + bufCtrl.onAutofillFocusChanged(202) + checkEq(afCtrl.onAutofillValues(mapOf(202 to "s3cr3t!")), 1, "seq22 autofill password s3cr3t!") + checkEq(bufCtrl.lastPreviewText.contains("s3cr3t!"), false, "seq22 password NEVER leaks into HostTextPreviewView") + checkEq(bufCtrl.lastPreviewText, "Project roadmap", "seq22 preview stays Project roadmap while editing password") + checkEq(docStore.readDocument("doc/roadmap"), "Project roadmap", "seq22 documentStore stays Project roadmap") + + // Switch route to doc B while password was focused, then back to doc A -> roadmap intact, password intact. + checkEq(nav.openDocument("notes"), true, "seq22 navigate to doc/notes while password focused") + checkEq(docIme.commitText("Meeting notes", 1), true, "seq22 write notes doc") + checkEq(nav.onBackInvoked(), true, "seq22 back to doc/roadmap") + checkEq(docIme.currentText(), "Project roadmap", "seq22 doc/roadmap restored intact") + checkEq(bufCtrl.lastPreviewText, "Project roadmap", "seq22 preview restored to Project roadmap") + checkEq(afCtrl.readFormValues()["password"], "s3cr3t!", "seq22 autofill password preserved") + + // Part D: Autofill session exit via commitAutofillSession / cancelAutofillSession / clearAutofillFields + // must restore the document buffer immediately so subsequent typing and route switches never leak form text. + val exitModes = listOf("commit", "cancel", "clear") + for (mode in exitModes) { + checkEq(afCtrl.registerField(202, 2, 20, 200, 800, 280, true, 0), true, "seq22 ($mode) register password field") + checkEq(docIme.replaceText(0, docIme.currentText().length, "Doc-$mode", 1), true, "seq22 ($mode) seed doc text") + bufCtrl.recordDocumentSelection(0, 3) + bufCtrl.onAutofillFocusChanged(202) + checkEq(docIme.replaceText(0, docIme.currentText().length, "f0rm-secret-99", 1), true, "seq22 ($mode) type secret in form") + checkEq(docIme.setSelection(0, 6), true, "seq22 ($mode) select secret in form") + // Simulated surfaceChanged while Autofill focused must keep currentDocumentText() untouched. + checkEq(bufCtrl.isAutofillFocused(), true, "seq22 ($mode) autofill focused before resize") + checkEq(bufCtrl.currentDocumentText(), "Doc-$mode", "seq22 ($mode) currentDocumentText hides form secret") + checkEq(bufCtrl.lastPreviewText, "Doc-$mode", "seq22 ($mode) preview hides form secret") + when (mode) { + "commit" -> checkEq(bufCtrl.commitAutofillSession(), true, "seq22 commitAutofillSession") + "cancel" -> checkEq(bufCtrl.cancelAutofillSession(), true, "seq22 cancelAutofillSession") + "clear" -> bufCtrl.clearAutofillFields() + } + checkEq(bufCtrl.isAutofillFocused(), false, "seq22 ($mode) autofill unfocused after exit") + checkEq(docIme.currentText(), "Doc-$mode", "seq22 ($mode) IME immediately restored to doc text") + checkEq(docIme.setSelection(docIme.currentText().length, docIme.currentText().length), true, "seq22 ($mode) move caret to end") + checkEq(docIme.commitText("!", 1), true, "seq22 ($mode) first edit after exit appends to doc") + checkEq(docIme.currentText(), "Doc-$mode!", "seq22 ($mode) post-exit edit preserved doc without form text") + checkEq(docStore.readDocument("doc/roadmap"), "Doc-$mode!", "seq22 ($mode) store saved clean doc") + checkEq(nav.openDocument("scratch-$mode"), true, "seq22 ($mode) navigate away after exit") + checkEq(nav.onBackInvoked(), true, "seq22 ($mode) navigate back after exit") + checkEq(docIme.currentText(), "Doc-$mode!", "seq22 ($mode) roundtrip route switch kept clean doc") + checkEq(docIme.currentText().contains("f0rm-secret-99"), false, "seq22 ($mode) no form secret leaked") + } + + // Masked password field selection must clear document selection overlay while keeping form IME selection, + // and must block copy/cut from writing masked password plaintext to the system clipboard. + val maskedClipboard = object : HostClipboard { + var data: String? = "text copied elsewhere" + override fun setPlainText(label: String, text: String): Boolean { + data = text + return true + } + override fun getPlainText(): String? = data + } + val maskedSel = AndroidSelectionCoordinator({ layoutParityHandle }) + maskedSel.setViewport(1080f, 2400f, 3f) + checkEq(afCtrl.registerField(202, 2, 20, 200, 800, 280, true, 0), true, "seq22 masked register password field") + checkEq(docIme.replaceText(0, docIme.currentText().length, "Hello document", 1), true, "seq22 masked seed doc") + bufCtrl.onAutofillFocusChanged(202) + checkEq(bufCtrl.isFocusedAutofillFieldMasked(), true, "seq22 focused password field is masked") + checkEq(docIme.replaceText(0, docIme.currentText().length, "s3cr3t-pass", 1), true, "seq22 type masked password") + checkEq(docIme.setSelection(0, 6), true, "seq22 select [0, 6) inside masked password") + // Mirror MainActivity.onImeMutated suppression when Autofill is focused. + if (bufCtrl.isAutofillFocused()) { + maskedSel.clear() + } + checkEq(docIme.selectionStart(), 0, "seq22 masked form IME keeps selectionStart=0") + checkEq(docIme.selectionEnd(), 6, "seq22 masked form IME keeps selectionEnd=6") + val gMasked = maskedSel.overlayGeometry()!! + checkEq(gMasked[0], 0f, "seq22 masked password hides document overlay") + val maskedIc = AffineSurfaceView.createInputConnection( + handleProvider = { layoutParityHandle }, + onContextMenuAction = { actionId -> + if (bufCtrl.isAutofillFocused() && + (actionId == android.R.id.copy || actionId == android.R.id.cut) && + bufCtrl.isFocusedAutofillFieldMasked() + ) { + false + } else { + val ok = maskedSel.handleContextMenuAction(actionId, docIme, maskedClipboard) + if (bufCtrl.isAutofillFocused()) maskedSel.clear() + ok + } + }, + ) + checkEq(maskedIc.performContextMenuAction(android.R.id.copy), false, "seq22 masked copy blocked") + checkEq(maskedIc.performContextMenuAction(android.R.id.cut), false, "seq22 masked cut blocked") + checkEq(maskedClipboard.data, "text copied elsewhere", "seq22 clipboard untouched by masked copy/cut") + checkEq(bufCtrl.commitAutofillSession(), true, "seq22 exit masked autofill session") + checkEq(docIme.currentText(), "Hello document", "seq22 doc restored after masked autofill exit") + checkEq(docIme.setSelection(0, 5), true, "seq22 select [0, 5) in restored doc") + checkEq(maskedIc.performContextMenuAction(android.R.id.copy), true, "seq22 doc copy works after exit") + checkEq(maskedClipboard.data, "Hello", "seq22 doc copy wrote Hello to clipboard") + + // Part E: Mixed-direction run boundary disambiguation ("A אבג B") where RTL start offset 2 + // and LTR start offset 5 share one visual X coordinate. + val bidiBoundaryLayout = object : TextLayoutAuthority { + override var cachedText: String = "A \u05d0\u05d1\u05d2 B" + private val originX = 60f + private val originY = 200f + private val lineH = 56f + private val step = 28f + // Visual X positions for "A אבג B" (len 7): + // 0='A'[0..28], 1=' '[28..56], RTL run [2..5) occupies [56..140] (2->140, 3->112, 4->84, 5->56), + // LTR run [5..7) occupies [140..196] (5->140, 6->168, 7->196). + // Notice offset 2 (secondary) and offset 5 (primary) share visual X = originX + 140f! + private fun primX(off: Int): Float = when (off) { + 0 -> 0f + 1 -> step + 2 -> step * 2f + 3 -> step * 4f + 4 -> step * 3f + 5 -> step * 5f + 6 -> step * 6f + else -> step * 7f + } + private fun secX(off: Int): Float = when (off) { + 2 -> step * 5f + 5 -> step * 2f + else -> primX(off) + } + override fun ensureLayoutReady(text: String, viewportWidthPx: Int, density: Float): Boolean { + cachedText = text + return true + } + override fun caretBounds( + utf16Offset: Int, + isSelectionEnd: Boolean, + selStart: Int, + selEnd: Int, + ): CaretBounds { + val inRtlRun = if (selStart < selEnd) { + val idx = if (isSelectionEnd) (utf16Offset - 1).coerceIn(selStart, cachedText.length - 1) else utf16Offset + idx in 2..4 + } else { + false + } + val lx = if (inRtlRun) secX(utf16Offset) else primX(utf16Offset) + return CaretBounds(originX + lx, originY, originY + lineH, 0, false) + } + override fun selectionEndCarets(selStart: Int, selEnd: Int): Pair = + caretBounds(selStart, false, selStart, selEnd) to caretBounds(selEnd, true, selStart, selEnd) + override fun closestOffset(x: Float, y: Float): Int = closestOffset(x, y, -1) + override fun closestOffset(x: Float, y: Float, preferredOffset: Int): Int { + val localX = x - originX + val snapTol = minOf(6f, step * 0.35f) + if (preferredOffset in 0..cachedText.length) { + if (kotlin.math.abs(localX - primX(preferredOffset)) <= snapTol || + kotlin.math.abs(localX - secX(preferredOffset)) <= snapTol + ) { + return preferredOffset + } + } + // Ambiguous point at step*5 always returns 5 when preferredOffset is not matched. + return when { + localX < step * 0.5f -> 0 + localX < step * 1.5f -> 1 + localX < step * 2.5f -> 2 + localX < step * 3.5f -> 4 + localX < step * 4.5f -> 3 + localX < step * 5.5f -> 5 + localX < step * 6.5f -> 6 + else -> 7 + } + } + } + val bidiGesture = SelectionGestureController( + coordinator = sel, + layoutAuthority = bidiBoundaryLayout, + selectionStartProvider = { ime.selectionStart() }, + selectionEndProvider = { ime.selectionEnd() }, + onSelectionChanged = { lo, hi -> ime.setSelection(lo, hi) }, + ) + checkEq(ime.replaceText(0, ime.currentText().length, "A \u05d0\u05d1\u05d2 B", 1), true, "seq22 seed mixed BiDi boundary text") + // Case 1: [2, 5) start handle at shared boundary X -> stationary MOVE(0px) stays [2, 5), inward drag shrinks to [3, 5). + checkEq(ime.setSelection(2, 5), true, "seq22 select RTL [2, 5)") + bidiGesture.syncSelectionFromLayout(ime.currentText(), 2, 5, 1080, 3f) + val gRtl = sel.overlayGeometry()!! + checkEq(bidiGesture.onDown(gRtl[5], gRtl[6], 3f), 1, "seq22 hit RTL [2, 5) start handle") + checkEq(bidiGesture.onMove(gRtl[5], gRtl[6]), true, "seq22 RTL [2, 5) 0px move") + checkEq(ime.selectionStart(), 2, "seq22 RTL [2, 5) 0px move preserves start=2") + checkEq(ime.selectionEnd(), 5, "seq22 RTL [2, 5) 0px move preserves end=5") + checkEq(bidiGesture.onMove(gRtl[5] - 28f, gRtl[6]), true, "seq22 RTL [2, 5) inward 1-glyph drag") + checkEq(bidiGesture.onUp(1080, 3f), true, "seq22 RTL [2, 5) release") + checkEq(ime.selectionStart(), 3, "seq22 RTL [2, 5) inward drag shrinks to start=3") + checkEq(ime.selectionEnd(), 5, "seq22 RTL [2, 5) inward drag keeps end=5") + + // Case 2: [5, 7) start handle at shared boundary X -> stationary MOVE(0px) stays [5, 7), inward drag shrinks to [6, 7). + checkEq(ime.setSelection(5, 7), true, "seq22 select LTR [5, 7)") + bidiGesture.syncSelectionFromLayout(ime.currentText(), 5, 7, 1080, 3f) + val gLtr = sel.overlayGeometry()!! + checkEq(bidiGesture.onDown(gLtr[5], gLtr[6], 3f), 1, "seq22 hit LTR [5, 7) start handle") + checkEq(bidiGesture.onMove(gLtr[5], gLtr[6]), true, "seq22 LTR [5, 7) 0px move") + checkEq(ime.selectionStart(), 5, "seq22 LTR [5, 7) 0px move preserves start=5") + checkEq(ime.selectionEnd(), 7, "seq22 LTR [5, 7) 0px move preserves end=7") + checkEq(bidiGesture.onMove(gLtr[5] + 28f, gLtr[6]), true, "seq22 LTR [5, 7) inward 1-glyph drag") + checkEq(bidiGesture.onUp(1080, 3f), true, "seq22 LTR [5, 7) release") + checkEq(ime.selectionStart(), 6, "seq22 LTR [5, 7) inward drag shrinks to start=6") + checkEq(ime.selectionEnd(), 7, "seq22 LTR [5, 7) inward drag keeps end=7") + } finally { + NativeBridge.nativeDestroyHost(layoutParityHandle) + } + + println("Kotlin JNI Android host parity check passed (22/22 sequences)") }