frus-shell 0.3.0

frus — the platform layer: window + event loop (Milestone 0)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! The **Android input bridge** (§6, tier 2) — the `InputConnection` NativeActivity
//! lacks.
//!
//! Without one, IMEs run in a degraded mode (`TYPE_NULL`): Latin keys only, with no
//! composition, no swipe, no suggestions and no CJK. The way out is a Java `View`
//! that supplies a real `InputConnection` wired to the engine, and we take that route
//! without Gradle:
//!
//! 1. `FrusTextBridge.java` — a 1×1 View plus a `BaseInputConnection` — is
//!    precompiled into a **bundled dex** (`assets/frus_input.dex`, built by
//!    scripts/build-input-dex.sh);
//! 2. at startup the dex is loaded through `InMemoryDexClassLoader`, the `native*`
//!    methods are wired up by `RegisterNatives`, and the view is added to the
//!    activity;
//! 3. every IME operation — commit, composition, deletion, action — arrives on the
//!    Java UI thread → is pushed onto a shared **queue** and the winit loop is woken
//!    (`AndroidAppWaker`) → the shell drains it in `new_events` and applies it to the
//!    focused field.
//!
//! IME focus, meaning opening and closing the keyboard, goes through
//! [`start_input`]/[`stop_input`]: the bridge view takes Java focus, the IME talks to
//! it, and the native content keeps receiving touch.

use std::sync::{Mutex, OnceLock};

use jni::objects::{GlobalRef, JClass, JObject, JString, JValue};
use jni::sys::{jboolean, jint, JNI_TRUE};
use jni::{JNIEnv, JavaVM};
use winit::platform::android::activity::AndroidApp;

/// The operations, and what each does to a field, live in `crate::ime`, where they can
/// be tested away from a device.
pub(crate) use crate::ime::ImeEvent;

/// The operation queue, filled on the Java UI thread and drained by the shell.
static QUEUE: Mutex<Vec<ImeEvent>> = Mutex::new(Vec::new());
/// Wakes the winit loop when the queue fills.
static WAKER: OnceLock<Mutex<winit::platform::android::activity::AndroidAppWaker>> =
    OnceLock::new();
/// What it takes to cross over: the VM and the bridge class, as global refs, for
/// start and stop.
static BRIDGE: OnceLock<Bridge> = OnceLock::new();

struct Bridge {
    vm: JavaVM,
    class: GlobalRef,
    activity: GlobalRef,
}

// SAFETY: JavaVM and the GlobalRefs are shareable across threads, per the JNI contract.
unsafe impl Send for Bridge {}
unsafe impl Sync for Bridge {}

/// A snapshot of the focused field's editing state — the context the IME queries:
/// the text before and after the cursor, and the selection. Written by the shell,
/// read by the natives on the Java UI thread.
#[derive(Default)]
struct EditorState {
    /// The field's characters; indices count **characters**, not bytes.
    chars: Vec<char>,
    cursor: usize,
    selection: Option<(usize, usize)>,
}

static EDITOR: Mutex<Option<EditorState>> = Mutex::new(None);

/// Pushes the focused field's editing state, called by the shell on every change.
/// It is the context the IME's suggestions draw on.
pub(crate) fn set_editor_state(text: &str, cursor: usize, selection: Option<(usize, usize)>) {
    let chars: Vec<char> = text.chars().collect();
    let cursor = cursor.min(chars.len());
    *EDITOR.lock().unwrap() = Some(EditorState {
        chars,
        cursor,
        selection,
    });
}

/// Clears the context, focus having left the text fields.
pub(crate) fn clear_editor_state() {
    *EDITOR.lock().unwrap() = None;
}

/// The bridge's dex, built by `scripts/build-input-dex.sh` and kept in the repo.
static BRIDGE_DEX: &[u8] = include_bytes!("../assets/frus_input.dex");

/// Installs the bridge: loads the dex, wires the natives, adds the view. A failing
/// step leaves everything untouched, with a log line, and the shell then falls back
/// to `TYPE_NULL` mode, Latin keys only.
pub(crate) fn install(app: &AndroidApp) {
    if BRIDGE.get().is_some() {
        return;
    }
    match try_install(app) {
        Ok(bridge) => {
            let _ = BRIDGE.set(bridge);
            let _ = WAKER.set(Mutex::new(app.create_waker()));
            log::info!("input bridge installed (a real InputConnection)");
        }
        Err(err) => log::warn!("input bridge unavailable ({err}) — falling back to key mode"),
    }
}

fn try_install(app: &AndroidApp) -> Result<Bridge, jni::errors::Error> {
    let vm = unsafe { JavaVM::from_raw(app.vm_as_ptr() as *mut jni::sys::JavaVM) }?;
    let mut env = vm.attach_current_thread_permanently()?;
    let activity = unsafe { JObject::from_raw(app.activity_as_ptr() as jni::sys::jobject) };

    // 1. Load the bundled dex into an in-memory class loader.
    let buffer =
        unsafe { env.new_direct_byte_buffer(BRIDGE_DEX.as_ptr() as *mut u8, BRIDGE_DEX.len()) }?;
    let parent = env
        .call_method(
            &activity,
            "getClassLoader",
            "()Ljava/lang/ClassLoader;",
            &[],
        )?
        .l()?;
    let loader = env.new_object(
        "dalvik/system/InMemoryDexClassLoader",
        "(Ljava/nio/ByteBuffer;Ljava/lang/ClassLoader;)V",
        &[JValue::Object(&buffer), JValue::Object(&parent)],
    )?;
    // The same dex carries the system bars' half (#46). Loaded through the same loader, and
    // on its own terms: a failure there must not cost the keyboard.
    crate::android_system_bars::install(&mut env, &loader, &activity);
    // And the clipboard (#22), on the same terms.
    crate::android_clipboard::install(&mut env, &loader, &activity);

    let name = env.new_string("dev.frus.input.FrusTextBridge")?;
    let class_obj = env
        .call_method(
            &loader,
            "loadClass",
            "(Ljava/lang/String;)Ljava/lang/Class;",
            &[JValue::Object(&name)],
        )?
        .l()?;
    let class: JClass = class_obj.into();

    // 2. Wire up the bridge class's native methods.
    use jni::NativeMethod;
    let method = |name: &str, sig: &str, ptr: *mut std::ffi::c_void| NativeMethod {
        name: name.into(),
        sig: sig.into(),
        fn_ptr: ptr,
    };
    env.register_native_methods(
        &class,
        &[
            method(
                "nativeCommit",
                "(Ljava/lang/String;)V",
                native_commit as *mut _,
            ),
            method(
                "nativeSetComposing",
                "(Ljava/lang/String;)V",
                native_set_composing as *mut _,
            ),
            method(
                "nativeSetComposingRegion",
                "(II)V",
                native_set_composing_region as *mut _,
            ),
            method(
                "nativeFinishComposing",
                "()V",
                native_finish_composing as *mut _,
            ),
            method("nativeDelete", "(II)V", native_delete as *mut _),
            method("nativeEditorAction", "(I)V", native_editor_action as *mut _),
            method("nativeKey", "(IZII)Z", native_key as *mut _),
            method(
                "nativeTextBeforeCursor",
                "(I)Ljava/lang/String;",
                native_text_before as *mut _,
            ),
            method(
                "nativeTextAfterCursor",
                "(I)Ljava/lang/String;",
                native_text_after as *mut _,
            ),
            method(
                "nativeSelectedText",
                "()Ljava/lang/String;",
                native_selected_text as *mut _,
            ),
            method(
                "nativeAutofill",
                "(ILjava/lang/String;)V",
                crate::android_autofill::native_autofill as *mut _,
            ),
        ],
    )?;

    // 3. Add the bridge view to the activity, posted on the Java UI thread.
    env.call_static_method(
        &class,
        "install",
        "(Landroid/app/Activity;)V",
        &[JValue::Object(&activity)],
    )?;

    let class_ref = env.new_global_ref(&class)?;
    let activity_ref = env.new_global_ref(&activity)?;
    Ok(Bridge {
        vm,
        class: class_ref,
        activity: activity_ref,
    })
}

/// Is the bridge operational?
pub(crate) fn installed() -> bool {
    BRIDGE.get().is_some()
}

/// Runs `call` against the bridge's class and activity — the way in for the other
/// halves that live in the same Java class (autofill, milestone 512). Nothing happens
/// when the bridge is not installed; a failure is logged, and the Java exception it left
/// pending is cleared, or the next call across would abort the process.
pub(crate) fn with_bridge(
    what: &str,
    call: impl FnOnce(&mut JNIEnv, &JClass, &JObject) -> jni::errors::Result<()>,
) {
    let Some(bridge) = BRIDGE.get() else {
        return;
    };
    let Ok(mut env) = bridge.vm.attach_current_thread_permanently() else {
        return;
    };
    let class: &JClass = bridge.class.as_obj().into();
    if let Err(err) = call(&mut env, class, bridge.activity.as_obj()) {
        let _ = env.exception_clear();
        log::warn!("input bridge: {what} failed ({err})");
    }
}

/// Wakes the event loop for something queued on the Java UI thread — by asking for a frame.
///
/// A bare wake of the looper is not enough. winit takes a wake with no redraw requested and
/// no message of its own queued for a false one and goes back to sleep
/// (`platform_impl/android`, `PollEvent::Wake`), so the operation waited for whatever woke
/// the loop next: on the device, the demo's stopwatch ticking once a second, and a letter
/// took up to a second to appear (milestone 513). A redraw request is a reason winit
/// honours, and the frame is wanted anyway — it is what shows the letter.
pub(crate) fn wake() {
    if let Some(window) = WINDOW.lock().unwrap().as_ref() {
        window.request_redraw();
    } else if let Some(waker) = WAKER.get() {
        waker.lock().unwrap().wake();
    }
}

/// The window a wake asks a frame of, while there is one.
static WINDOW: Mutex<Option<std::sync::Arc<winit::window::Window>>> = Mutex::new(None);

/// Hands the bridge the window its wakes ask frames of — or takes it away, with the surface.
pub(crate) fn set_window(window: Option<std::sync::Arc<winit::window::Window>>) {
    *WINDOW.lock().unwrap() = window;
}

/// Native focus enters a text field: the bridge view captures the IME, told what
/// kind of field it is.
///
/// The two numbers are computed on this side rather than chosen on the Java one, and
/// that is the point: the bridge's dex is **checked in**, so rebuilding it needs the
/// Android SDK. A Java file that only ever sets two integers on the `EditorInfo` never
/// has to be rebuilt again for a keyboard type we have not thought of yet.
pub(crate) fn start_input(ime: frus_widgets::Ime) {
    let Some(bridge) = BRIDGE.get() else {
        return;
    };
    let input_type = ime.android_input_type();
    let ime_options = ime.action.android_ime_options();
    let result = bridge
        .vm
        .attach_current_thread_permanently()
        .and_then(|mut env| {
            let class: &JClass = bridge.class.as_obj().into();
            env.call_static_method(
                class,
                "startInput",
                "(Landroid/app/Activity;II)V",
                &[
                    JValue::Object(bridge.activity.as_obj()),
                    JValue::Int(input_type),
                    JValue::Int(ime_options),
                ],
            )
            .map(|_| ())
        });
    if let Err(err) = result {
        log::warn!("input bridge: startInput failed ({err})");
    }
}

/// Tells the keyboard where the caret, the selection and the composition now are, in
/// UTF-16 units: what an Android editor reports on every change, and what a keyboard
/// that predicts needs to stay in step with a field (milestone 510). `-1` is no
/// composition.
pub(crate) fn update_selection(sel_start: i32, sel_end: i32, cand_start: i32, cand_end: i32) {
    let Some(bridge) = BRIDGE.get() else {
        return;
    };
    let result = bridge
        .vm
        .attach_current_thread_permanently()
        .and_then(|mut env| {
            let class: &JClass = bridge.class.as_obj().into();
            env.call_static_method(
                class,
                "updateSelection",
                "(Landroid/app/Activity;IIII)V",
                &[
                    JValue::Object(bridge.activity.as_obj()),
                    JValue::Int(sel_start),
                    JValue::Int(sel_end),
                    JValue::Int(cand_start),
                    JValue::Int(cand_end),
                ],
            )
            .map(|_| ())
        });
    if let Err(err) = result {
        log::warn!("input bridge: updateSelection failed ({err})");
    }
}

/// Native focus leaves the text fields, and the IME closes.
pub(crate) fn stop_input() {
    call_bridge("stopInput");
}

fn call_bridge(method: &str) {
    let Some(bridge) = BRIDGE.get() else {
        return;
    };
    let result = bridge
        .vm
        .attach_current_thread_permanently()
        .and_then(|mut env| {
            let class: &JClass = bridge.class.as_obj().into();
            env.call_static_method(
                class,
                method,
                "(Landroid/app/Activity;)V",
                &[JValue::Object(bridge.activity.as_obj())],
            )
            .map(|_| ())
        });
    if let Err(err) = result {
        log::warn!("input bridge: {method} failed ({err})");
    }
}

/// Drains the pending operations, in arrival order.
pub(crate) fn drain() -> Vec<ImeEvent> {
    std::mem::take(&mut QUEUE.lock().unwrap())
}

fn push(event: ImeEvent) {
    QUEUE.lock().unwrap().push(event);
    wake();
}

// --- Natives, called on the Java UI thread -----------------------------------

fn jstring_to_string(env: &mut JNIEnv, text: &JString) -> String {
    env.get_string(text).map(Into::into).unwrap_or_default()
}

extern "system" fn native_commit(mut env: JNIEnv, _class: JClass, text: JString) {
    let text = jstring_to_string(&mut env, &text);
    push(ImeEvent::Commit(text));
}

extern "system" fn native_set_composing(mut env: JNIEnv, _class: JClass, text: JString) {
    let text = jstring_to_string(&mut env, &text);
    push(ImeEvent::Composing(text));
}

extern "system" fn native_set_composing_region(
    _env: JNIEnv,
    _class: JClass,
    start: jint,
    end: jint,
) {
    push(ImeEvent::ComposingRegion {
        start: start.max(0) as u32,
        end: end.max(0) as u32,
    });
}

extern "system" fn native_finish_composing(_env: JNIEnv, _class: JClass) {
    push(ImeEvent::FinishComposing);
}

extern "system" fn native_delete(_env: JNIEnv, _class: JClass, before: jint, after: jint) {
    push(ImeEvent::Delete {
        before: before.max(0) as u32,
        after: after.max(0) as u32,
    });
}

extern "system" fn native_editor_action(_env: JNIEnv, _class: JClass, _action: jint) {
    push(ImeEvent::Action);
}

/// A synchronous filter: `true` means an editing key was consumed and queued,
/// `false` means the key follows the default path — Back, navigation, and so on.
extern "system" fn native_key(
    _env: JNIEnv,
    _class: JClass,
    code: jint,
    down: jboolean,
    unicode: jint,
    _meta: jint,
) -> jboolean {
    const KEYCODE_ENTER: jint = 66;
    const KEYCODE_DEL: jint = 67;
    if down != JNI_TRUE {
        // The releases of consumed keys are consumed too, for symmetry.
        return matches!(code, KEYCODE_ENTER | KEYCODE_DEL) as jboolean | (unicode > 0) as jboolean;
    }
    let handled = matches!(code, KEYCODE_ENTER | KEYCODE_DEL) || unicode > 0;
    if handled {
        push(ImeEvent::Key {
            code,
            unicode: unicode.max(0) as u32,
        });
    }
    handled as jboolean
}

// --- The input context, read by the IME through the InputConnection ----------

/// Returns a Java `jstring`, or an empty string, without propagating an error.
fn to_jstring(env: &JNIEnv, text: &str) -> jni::sys::jstring {
    env.new_string(text)
        .map(|s| s.into_raw())
        .unwrap_or(std::ptr::null_mut())
}

extern "system" fn native_text_before(env: JNIEnv, _class: JClass, n: jint) -> jni::sys::jstring {
    let guard = EDITOR.lock().unwrap();
    let text = guard
        .as_ref()
        .map(|s| {
            let n = (n.max(0) as usize).min(s.cursor);
            s.chars[s.cursor - n..s.cursor].iter().collect::<String>()
        })
        .unwrap_or_default();
    to_jstring(&env, &text)
}

extern "system" fn native_text_after(env: JNIEnv, _class: JClass, n: jint) -> jni::sys::jstring {
    let guard = EDITOR.lock().unwrap();
    let text = guard
        .as_ref()
        .map(|s| {
            let end = (s.cursor + n.max(0) as usize).min(s.chars.len());
            s.chars[s.cursor..end].iter().collect::<String>()
        })
        .unwrap_or_default();
    to_jstring(&env, &text)
}

extern "system" fn native_selected_text(env: JNIEnv, _class: JClass) -> jni::sys::jstring {
    let guard = EDITOR.lock().unwrap();
    let text = guard
        .as_ref()
        .and_then(|s| {
            let (a, b) = s.selection?;
            let (a, b) = (a.min(s.chars.len()), b.min(s.chars.len()));
            (a < b).then(|| s.chars[a..b].iter().collect::<String>())
        })
        .unwrap_or_default();
    to_jstring(&env, &text)
}