cranpose 0.1.133

Cranpose runtime and UI facade
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
#![allow(unsafe_code)]

use std::sync::{
    Mutex, OnceLock,
    atomic::{AtomicBool, Ordering},
};

use cranpose_app_shell::AppShell;
use cranpose_render_wgpu::WgpuRenderer;
use jni::{
    EnvUnowned, Outcome, jni_sig, jni_str,
    objects::{JClass, JObject, JString, JValue},
    sys::{jboolean, jfloat, jint},
};

use crate::{
    accessibility::{self, AccessibilityElement},
    accessibility_publish_policy::AccessibilityPublishPolicy,
    android_accessibility_wire::encode_elements,
    android_jni::{clear_pending_android_jni_exception, with_android_activity_env},
};

static ACTIVATIONS: OnceLock<Mutex<Vec<(f32, f32)>>> = OnceLock::new();
static CUSTOM_ACTIONS: OnceLock<Mutex<Vec<(i32, usize)>>> = OnceLock::new();
static FOCUS_REQUESTS: OnceLock<Mutex<Vec<i32>>> = OnceLock::new();
static VALUE_REQUESTS: OnceLock<Mutex<Vec<(i32, f32)>>> = OnceLock::new();
static TEXT_REQUESTS: OnceLock<Mutex<Vec<(i32, String)>>> = OnceLock::new();
static SCROLL_REQUESTS: OnceLock<Mutex<Vec<(i32, bool)>>> = OnceLock::new();
static EXPAND_REQUESTS: OnceLock<Mutex<Vec<(i32, bool)>>> = OnceLock::new();
static LONG_CLICK_REQUESTS: OnceLock<Mutex<Vec<i32>>> = OnceLock::new();
static DISMISS_REQUESTS: OnceLock<Mutex<Vec<i32>>> = OnceLock::new();
static JUMP_REQUESTS: OnceLock<Mutex<Vec<(i32, usize)>>> = OnceLock::new();
static LOOP_WAKER: Mutex<Option<android_activity::AndroidAppWaker>> = Mutex::new(None);
static PLATFORM_ACCESSIBILITY_ENABLED: AtomicBool = AtomicBool::new(false);

fn accessibility_sync_override() -> Option<bool> {
    static OVERRIDE: OnceLock<Option<bool>> = OnceLock::new();
    *OVERRIDE.get_or_init(|| match std::env::var("CRANPOSE_A11Y_SYNC").as_deref() {
        Ok("0") | Ok("false") | Ok("off") => Some(false),
        Ok("1") | Ok("true") | Ok("on") => Some(true),
        _ => None,
    })
}

fn accessibility_bridge_enabled() -> bool {
    accessibility_sync_override()
        .unwrap_or_else(|| PLATFORM_ACCESSIBILITY_ENABLED.load(Ordering::Relaxed))
}

pub(crate) fn set_waker(waker: android_activity::AndroidAppWaker) {
    *LOOP_WAKER
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(waker);
}

fn wake_loop() {
    let waker = LOOP_WAKER
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .clone();
    if let Some(waker) = waker {
        waker.wake();
    }
}

fn activations() -> &'static Mutex<Vec<(f32, f32)>> {
    ACTIVATIONS.get_or_init(|| Mutex::new(Vec::new()))
}

fn custom_actions() -> &'static Mutex<Vec<(i32, usize)>> {
    CUSTOM_ACTIONS.get_or_init(|| Mutex::new(Vec::new()))
}

fn focus_requests() -> &'static Mutex<Vec<i32>> {
    FOCUS_REQUESTS.get_or_init(|| Mutex::new(Vec::new()))
}

fn value_requests() -> &'static Mutex<Vec<(i32, f32)>> {
    VALUE_REQUESTS.get_or_init(|| Mutex::new(Vec::new()))
}

fn text_requests() -> &'static Mutex<Vec<(i32, String)>> {
    TEXT_REQUESTS.get_or_init(|| Mutex::new(Vec::new()))
}

fn scroll_requests() -> &'static Mutex<Vec<(i32, bool)>> {
    SCROLL_REQUESTS.get_or_init(|| Mutex::new(Vec::new()))
}

fn expand_requests() -> &'static Mutex<Vec<(i32, bool)>> {
    EXPAND_REQUESTS.get_or_init(|| Mutex::new(Vec::new()))
}

fn long_click_requests() -> &'static Mutex<Vec<i32>> {
    LONG_CLICK_REQUESTS.get_or_init(|| Mutex::new(Vec::new()))
}

fn dismiss_requests() -> &'static Mutex<Vec<i32>> {
    DISMISS_REQUESTS.get_or_init(|| Mutex::new(Vec::new()))
}

fn jump_requests() -> &'static Mutex<Vec<(i32, usize)>> {
    JUMP_REQUESTS.get_or_init(|| Mutex::new(Vec::new()))
}

pub(crate) fn drain_activations() -> Vec<(f32, f32)> {
    std::mem::take(
        &mut *activations()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()),
    )
}

pub(crate) fn drain_custom_actions() -> Vec<(i32, usize)> {
    std::mem::take(
        &mut *custom_actions()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()),
    )
}

/// The virtual view ids TalkBack put its cursor on since the last frame.
pub(crate) fn drain_focus_requests() -> Vec<i32> {
    std::mem::take(
        &mut *focus_requests()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()),
    )
}

/// Values TalkBack asked adjustable controls to take, as virtual view ids.
pub(crate) fn drain_value_requests() -> Vec<(i32, f32)> {
    std::mem::take(
        &mut *value_requests()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()),
    )
}

/// Text TalkBack or a voice tool handed to text fields, as virtual view ids.
pub(crate) fn drain_text_requests() -> Vec<(i32, String)> {
    std::mem::take(
        &mut *text_requests()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()),
    )
}

/// Containers TalkBack asked to page, as virtual view ids, and which way.
pub(crate) fn drain_scroll_requests() -> Vec<(i32, bool)> {
    std::mem::take(
        &mut *scroll_requests()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()),
    )
}

/// Controls TalkBack asked to open or to close, as virtual view ids.
pub(crate) fn drain_expand_requests() -> Vec<(i32, bool)> {
    std::mem::take(
        &mut *expand_requests()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()),
    )
}

/// Controls TalkBack asked for a long press on, as virtual view ids.
pub(crate) fn drain_long_click_requests() -> Vec<i32> {
    std::mem::take(
        &mut *long_click_requests()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()),
    )
}

/// Controls TalkBack asked to send away, as virtual view ids.
pub(crate) fn drain_dismiss_requests() -> Vec<i32> {
    std::mem::take(
        &mut *dismiss_requests()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()),
    )
}

/// Rows TalkBack asked a list for by number, as virtual view ids and the row
/// counted from zero.
pub(crate) fn drain_jump_requests() -> Vec<(i32, usize)> {
    std::mem::take(
        &mut *jump_requests()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()),
    )
}

/// Hands TalkBack text to read out at once, with no control to move to.
/// Android reads a live region set on a virtual view only through its host, so
/// a live region change reaches the user the same way an app announcement
/// does: as one spoken line.
fn speak(
    app: &android_activity::AndroidApp,
    announcements: Vec<cranpose_ui::Announcement>,
) -> Result<(), String> {
    if announcements.is_empty() {
        return Ok(());
    }
    let text = announcements
        .into_iter()
        .map(|announcement| announcement.text)
        .collect::<Vec<_>>()
        .join(". ");
    with_android_activity_env(app, |env, activity| {
        let text = env.new_string(text).map_err(|error| {
            clear_pending_android_jni_exception(env);
            format!("failed to encode an accessibility announcement: {error}")
        })?;
        let text = JObject::from(text);
        env.call_method(
            &activity,
            jni_str!("cranposeAnnounceForAccessibility"),
            jni_sig!("(Ljava/lang/String;)V"),
            &[JValue::Object(&text)],
        )
        .map_err(|error| {
            clear_pending_android_jni_exception(env);
            format!("failed to read out an accessibility announcement: {error}")
        })?;
        Ok(())
    })
}

pub(crate) fn sync(
    app: &android_activity::AndroidApp,
    shell: &mut AppShell<WgpuRenderer>,
    density: f32,
    previous: &mut Vec<AccessibilityElement>,
    seen_revision: &mut Option<u64>,
    policy: &mut AccessibilityPublishPolicy,
) -> Result<(), String> {
    if policy.update_enabled(accessibility_bridge_enabled()) {
        *seen_revision = None;
    }
    let mut announcements = accessibility::drain_app_announcements();
    let now = std::time::Instant::now();
    let elements = if policy.try_begin_publish(now) {
        accessibility::snapshot_if_changed(shell, seen_revision)
    } else {
        None
    };
    let elements = elements.filter(|elements| elements != previous);
    if let Some(elements) = &elements {
        announcements.extend(accessibility::live_region_announcements(previous, elements));
        announcements.extend(accessibility::pane_title_announcements(previous, elements));
    }
    speak(app, announcements)?;
    let Some(elements) = elements else {
        return Ok(());
    };
    let changed = accessibility::spoken_changes(previous, &elements);
    *previous = elements;
    let payload = encode_elements(previous, &changed, density);
    with_android_activity_env(app, |env, activity| {
        let payload = env.new_string(payload).map_err(|error| {
            clear_pending_android_jni_exception(env);
            format!("failed to encode Android accessibility tree: {error}")
        })?;
        let payload = JObject::from(payload);
        env.call_method(
            &activity,
            jni_str!("cranposeSetAccessibilityElements"),
            jni_sig!("(Ljava/lang/String;)V"),
            &[JValue::Object(&payload)],
        )
        .map_err(|error| {
            clear_pending_android_jni_exception(env);
            format!("failed to publish Android accessibility tree: {error}")
        })?;
        Ok(())
    })
}

#[doc(hidden)]
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_cranpose_android_CranposeActivity_nativeOnAccessibilityActivate(
    _env: EnvUnowned<'_>,
    _class: JClass<'_>,
    x: jfloat,
    y: jfloat,
) {
    activations()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .push((x, y));
    wake_loop();
}

#[doc(hidden)]
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_cranpose_android_CranposeActivity_nativeOnAccessibilityStateChanged(
    _env: EnvUnowned<'_>,
    _class: JClass<'_>,
    enabled: jboolean,
) {
    let previous = PLATFORM_ACCESSIBILITY_ENABLED.swap(enabled, Ordering::Relaxed);
    if previous != enabled {
        wake_loop();
    }
}

/// TalkBack landed its cursor on a virtual view; the frame loop moves app
/// focus to match, so the reader and the app agree on what holds focus.
#[doc(hidden)]
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_cranpose_android_CranposeActivity_nativeOnAccessibilityFocus(
    _env: EnvUnowned<'_>,
    _class: JClass<'_>,
    virtual_id: jint,
) {
    focus_requests()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .push(virtual_id);
    wake_loop();
}

#[doc(hidden)]
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_cranpose_android_CranposeActivity_nativeOnAccessibilityCustomAction(
    _env: EnvUnowned<'_>,
    _class: JClass<'_>,
    virtual_id: jint,
    action_index: jint,
) {
    if action_index < 0 {
        return;
    }
    custom_actions()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .push((virtual_id, action_index as usize));
    wake_loop();
}

/// TalkBack moved the value of an adjustable control. Only the identity and
/// the value cross back; the frame loop resolves the control against the live
/// semantics tree, as a custom action does.
#[doc(hidden)]
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_cranpose_android_CranposeActivity_nativeOnAccessibilitySetProgress(
    _env: EnvUnowned<'_>,
    _class: JClass<'_>,
    virtual_id: jint,
    value: jfloat,
) {
    value_requests()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .push((virtual_id, value));
    wake_loop();
}

/// TalkBack or a voice tool handed a text field new text. The frame loop
/// resolves the field against the live semantics tree.
#[doc(hidden)]
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_cranpose_android_CranposeActivity_nativeOnAccessibilitySetText(
    mut env: EnvUnowned<'_>,
    _class: JClass<'_>,
    virtual_id: jint,
    text: JString<'_>,
) {
    let Outcome::Ok(text) = env
        .with_env(|env| -> jni::errors::Result<String> { text.try_to_string(env) })
        .into_outcome()
    else {
        return;
    };
    text_requests()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .push((virtual_id, text));
    wake_loop();
}

/// TalkBack asked a container for its next or previous page. The frame loop
/// resolves the container against the live semantics tree and pages it.
#[doc(hidden)]
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_cranpose_android_CranposeActivity_nativeOnAccessibilityScroll(
    _env: EnvUnowned<'_>,
    _class: JClass<'_>,
    virtual_id: jint,
    forward: jboolean,
) {
    scroll_requests()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .push((virtual_id, forward));
    wake_loop();
}

/// TalkBack asked a list for the row at a number, through Android's
/// scroll-to-position action. The frame loop resolves the list against the
/// live semantics tree and puts that row in view.
#[doc(hidden)]
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_cranpose_android_CranposeActivity_nativeOnAccessibilityScrollToIndex(
    _env: EnvUnowned<'_>,
    _class: JClass<'_>,
    virtual_id: jint,
    index: jint,
) {
    if index < 0 {
        return;
    }
    jump_requests()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .push((virtual_id, index as usize));
    wake_loop();
}

/// TalkBack asked a control to open or to close. The frame loop resolves the
/// control against the live semantics tree, as a custom action does.
#[doc(hidden)]
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_cranpose_android_CranposeActivity_nativeOnAccessibilityExpand(
    _env: EnvUnowned<'_>,
    _class: JClass<'_>,
    virtual_id: jint,
    open: jboolean,
) {
    expand_requests()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .push((virtual_id, open));
    wake_loop();
}

/// TalkBack asked a control for its long press. The frame loop resolves the
/// control against the live semantics tree, as a custom action does.
#[doc(hidden)]
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_cranpose_android_CranposeActivity_nativeOnAccessibilityLongClick(
    _env: EnvUnowned<'_>,
    _class: JClass<'_>,
    virtual_id: jint,
) {
    long_click_requests()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .push(virtual_id);
    wake_loop();
}

/// TalkBack asked a control to go away. The frame loop resolves the control
/// against the live semantics tree, as a custom action does.
#[doc(hidden)]
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_cranpose_android_CranposeActivity_nativeOnAccessibilityDismiss(
    _env: EnvUnowned<'_>,
    _class: JClass<'_>,
    virtual_id: jint,
) {
    dismiss_requests()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .push(virtual_id);
    wake_loop();
}