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.
This commit is contained in:
DarkSky committed 2026-11-27 06:55:48 +09:00
1 parent 5fc9486baf
commit 71697c42ce
12 files changed
+6534 -57

No files matched your search

+12 -3
View File
@@ -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 `<filesDir>/datastore/auth-sessions.preferences_pb` using `v1:<base64_iv>:<base64_ct_tag>` 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 \
File diff suppressed because it is too large. Load diff
@@ -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<u8>,
}
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<Self> {
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<i32>,
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<i32, AutofillFieldNode>,
filled_values: BTreeMap<i32, ZeroizingString>,
focused_id: Option<i32>,
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<i32> {
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<i32>) -> Vec<AutofillEvent> {
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<AutofillValue>)`.
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\":[]"));
}
}
}
+109
View File
@@ -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 {
@@ -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,
);
}
});
}
@@ -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<i32>,
output_bytes: Vec<u8>,
pending_exception: bool,
fail_get_region_on_call: Option<usize>,
fail_set_region_on_call: Option<usize>,
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);
}
}
+258 -6
View File
@@ -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<String>,
}
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<String>) -> 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<String> {
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<usize>,
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<String>) -> 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<u16> = "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
);
}
}
}
+243
View File
@@ -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<usize, PdfRenderError> {
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<Vec<u8>, 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<u8>) {
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<u32>` copy.
pub fn argb8888_i32_to_rgba8(
argb_pixels: &[i32],
width_px: u32,
height_px: u32,
) -> Result<Vec<u8>, 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,
})
);
}
}
@@ -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<RectF>,
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<RectF> {
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
);
}
}
+137 -10
View File
@@ -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);
}
}
@@ -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<f32>,
}
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<f32>) {
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<VisualLine> {
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<u16> = "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<u16> = "iiii".encode_utf16().collect();
let wide: Vec<u16> = "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<u16> = "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<u16> = "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
);
}
}
@@ -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<String>()
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<String>()
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<String>()
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, CaretBounds> =
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, CaretBounds> =
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)")
}