cranpose 0.18.0

Build desktop, mobile and web apps with composable Rust functions
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
#![expect(unsafe_code, reason = "JNI and NDK calls into the Android system")]

use std::sync::Arc;

use jni::{
    Env, EnvUnowned, JavaVM, Outcome, jni_sig, jni_str,
    objects::{Global, JClass, JObject, JString},
    sys::{jfloat, jint, jlong},
};
use ndk::native_window::NativeWindow;

use super::overlay_window::{
    AndroidOverlayEventQueue, AndroidOverlayEventQueueHandle, AndroidOverlayPointerAction,
    AndroidOverlayWindowEvent,
};

pub(crate) fn with_android_activity_env<T, F>(
    app: &android_activity::AndroidApp,
    f: F,
) -> Result<T, String>
where
    F: for<'local> FnOnce(&mut Env<'local>, JObject<'local>) -> Result<T, String>,
{
    let vm = JavaVM::singleton()
        .map_err(|error| format!("Android JavaVM is not available on android_main: {error}"))?;
    vm.attach_current_thread(|env| -> jni::errors::Result<Result<T, String>> {
        let raw_activity_global = app.activity_as_ptr() as jni::sys::jobject;
        // SAFETY: android-activity owns this unowned global Activity reference for the
        // AndroidApp lifetime. The cast borrows it without taking deletion ownership;
        // new_local_ref creates the scoped local reference used by this JNI call chain.
        let activity_global = unsafe { env.as_cast_raw::<JObject>(&raw_activity_global)? };
        let activity = env.new_local_ref(activity_global.as_ref())?;
        Ok(f(env, activity))
    })
    .map_err(|error| format!("failed to access Android JNI environment: {error}"))?
}

/// Runs `run` with the activity and the Cranpose Java class `class_name`,
/// clearing any Java exception it leaves.
pub(crate) fn call_cranpose_class<T>(
    app: &android_activity::AndroidApp,
    class_name: &str,
    run: impl for<'local> FnOnce(
        &mut Env<'local>,
        &JObject<'local>,
        JClass<'local>,
    ) -> jni::errors::Result<T>,
) -> Result<T, String> {
    with_android_activity_env(app, |env, activity| {
        run_cranpose_class(env, &activity, class_name, run)
    })
}

fn run_cranpose_class<'local, T>(
    env: &mut Env<'local>,
    owner: &JObject<'local>,
    class_name: &str,
    run: impl FnOnce(&mut Env<'local>, &JObject<'local>, JClass<'local>) -> jni::errors::Result<T>,
) -> Result<T, String> {
    let class = load_cranpose_java_class(env, owner, class_name)?;
    run(env, owner, class).map_err(|error| {
        clear_pending_android_jni_exception(env);
        error.to_string()
    })
}

/// The application's `Context`, which outlives every activity and exists
/// also in a process the system started for a service, with no activity.
pub(crate) struct AndroidContext(Global<JObject<'static>>);

impl AndroidContext {
    /// Holds the application context that `context` belongs to.
    pub(crate) fn new(env: &mut Env<'_>, context: &JObject<'_>) -> Result<Self, String> {
        env.call_method(
            context,
            jni_str!("getApplicationContext"),
            jni_sig!("()Landroid/content/Context;"),
            &[],
        )
        .and_then(jni::JValueOwned::l)
        .and_then(|application| env.new_global_ref(application))
        .map(Self)
        .map_err(|error| {
            clear_pending_android_jni_exception(env);
            format!("the application context is not available: {error}")
        })
    }

    /// The JNI reference to the context, valid while `self` lives.
    pub(crate) fn raw(&self) -> jni::sys::jobject {
        self.0.as_raw()
    }

    /// Holds the application context of the activity `app` runs.
    pub(crate) fn of_activity(app: &android_activity::AndroidApp) -> Result<Self, String> {
        with_android_activity_env(app, |env, activity| Self::new(env, &activity))
    }

    /// Runs `run` with the context on this thread's JNI environment.
    pub(crate) fn with_env<T>(
        &self,
        run: impl for<'local> FnOnce(&mut Env<'local>, &JObject<'local>) -> Result<T, String>,
    ) -> Result<T, String> {
        JavaVM::singleton()
            .map_err(|error| format!("the Android JavaVM is not available: {error}"))?
            .attach_current_thread(|env| -> jni::errors::Result<Result<T, String>> {
                Ok(run(env, self.0.as_obj()))
            })
            .map_err(|error| format!("failed to access Android JNI environment: {error}"))?
    }

    /// Runs `run` with the context and the Cranpose Java class `class_name`,
    /// clearing any Java exception it leaves.
    pub(crate) fn call_class<T>(
        &self,
        class_name: &str,
        run: impl for<'local> FnOnce(
            &mut Env<'local>,
            &JObject<'local>,
            JClass<'local>,
        ) -> jni::errors::Result<T>,
    ) -> Result<T, String> {
        self.with_env(|env, context| run_cranpose_class(env, context, class_name, run))
    }
}

/// Calls the static method `name(Activity)` of the Cranpose Java class
/// `class_name`.
pub(crate) fn call_cranpose_activity_method(
    app: &android_activity::AndroidApp,
    class_name: &str,
    name: &'static jni::strings::JNIStr,
) -> Result<(), String> {
    call_cranpose_class(app, class_name, |env, activity, class| {
        env.call_static_method(
            class,
            name,
            jni::jni_sig!("(Landroid/app/Activity;)V"),
            &[jni::objects::JValue::Object(activity)],
        )
        .map(|_| ())
    })
}

pub(crate) fn decode_jni_string(env: &mut EnvUnowned<'_>, value: JString<'_>) -> Option<String> {
    match env
        .with_env(|env| -> jni::errors::Result<String> { value.try_to_string(env) })
        .into_outcome()
    {
        Outcome::Ok(text) => Some(text),
        Outcome::Err(_) | Outcome::Panic(_) => None,
    }
}

pub(crate) fn clear_pending_android_jni_exception(env: &mut Env<'_>) {
    if env.exception_check() {
        env.exception_describe();
        env.exception_clear();
    }
}

// The activity's resources and the configuration they currently follow.
// The configuration that android-activity reports comes from the
// AssetManager NativeActivity took at creation, and that one keeps the
// values of that moment: a night mode switch while the app runs, for one,
// shows only here.
pub(crate) fn activity_configuration<'local>(
    env: &mut Env<'local>,
    activity: &JObject<'local>,
) -> Result<(JObject<'local>, JObject<'local>), String> {
    let resources = env
        .call_method(
            activity,
            jni_str!("getResources"),
            jni_sig!("()Landroid/content/res/Resources;"),
            &[],
        )
        .and_then(jni::JValueOwned::l)
        .map_err(|error| jni_failure(env, "Activity.getResources", error))?;
    let configuration = env
        .call_method(
            &resources,
            jni_str!("getConfiguration"),
            jni_sig!("()Landroid/content/res/Configuration;"),
            &[],
        )
        .and_then(jni::JValueOwned::l)
        .map_err(|error| jni_failure(env, "Resources.getConfiguration", error))?;
    Ok((resources, configuration))
}

// Clears the Java exception that `what` left and names the failure.
pub(crate) fn jni_failure(env: &mut Env<'_>, what: &str, error: jni::errors::Error) -> String {
    clear_pending_android_jni_exception(env);
    format!("{what} failed: {error}")
}

pub(crate) fn load_cranpose_java_class<'local>(
    env: &mut Env<'local>,
    activity: &JObject<'local>,
    class_name: &str,
) -> Result<JClass<'local>, String> {
    use jni::objects::JValue;

    let class_name_string = env
        .new_string(class_name.replace('/', "."))
        .map_err(|error| {
            clear_pending_android_jni_exception(env);
            format!("failed to create Java class name for {class_name}: {error}")
        })?;
    let class_name_string = JObject::from(class_name_string);

    let class = env
        .call_method(
            activity,
            jni_str!("getClassLoader"),
            jni_sig!("()Ljava/lang/ClassLoader;"),
            &[],
        )
        .and_then(jni::JValueOwned::l)
        .and_then(|class_loader| {
            env.call_method(
                &class_loader,
                jni_str!("loadClass"),
                jni_sig!("(Ljava/lang/String;)Ljava/lang/Class;"),
                &[JValue::Object(&class_name_string)],
            )
            .and_then(jni::JValueOwned::l)
        })
        .map_err(|error| {
            clear_pending_android_jni_exception(env);
            format!(
                "failed to load Android helper class {class_name}; include cranpose/android/java in the Android source set: {error}"
            )
        })?;

    env.cast_local::<JClass>(class).map_err(|error| {
        clear_pending_android_jni_exception(env);
        format!("Android helper {class_name} did not resolve to a Java class: {error}")
    })
}

pub(crate) fn native_window_from_surface(
    env: &mut Env<'_>,
    surface: JObject<'_>,
) -> Result<NativeWindow, String> {
    // SAFETY: The Java overlay helper calls this with the current JNI
    // environment and a live android.view.Surface from SurfaceHolder.
    unsafe { NativeWindow::from_surface(env.get_raw().cast(), surface.as_raw()) }.ok_or_else(|| {
        clear_pending_android_jni_exception(env);
        "Android overlay Surface did not provide an ANativeWindow".to_string()
    })
}

pub(crate) fn release_android_overlay_event_queue_handle(handle: AndroidOverlayEventQueueHandle) {
    release_android_overlay_event_queue_handle_raw(handle.raw());
}

fn release_android_overlay_event_queue_handle_raw(handle: jlong) {
    if handle == 0 {
        return;
    }

    // SAFETY: AndroidOverlayEventQueueHandle values are created by
    // Arc::into_raw in android_overlay_window and released exactly once by the
    // Java overlay helper or by Rust when show() did not transfer ownership.
    unsafe {
        drop(Arc::from_raw(
            handle as usize as *const AndroidOverlayEventQueue,
        ));
    }
}

fn push_overlay_event_for_handle(handle: jlong, event: AndroidOverlayWindowEvent) {
    if handle == 0 {
        log::warn!(
            "dropped Android overlay event because the Java callback carried no queue handle"
        );
        return;
    }

    // SAFETY: The Java overlay helper stores a handle retained from an
    // Arc<AndroidOverlayEventQueue> and releases it only after the overlay is
    // disposed on the Android UI thread. Callbacks are ignored after disposal.
    let Some(queue) = (unsafe { (handle as usize as *const AndroidOverlayEventQueue).as_ref() })
    else {
        log::warn!("dropped Android overlay event because the queue handle was invalid");
        return;
    };
    queue.push(event);
}

#[doc(hidden)]
#[unsafe(no_mangle)]
pub(crate) extern "system" fn Java_dev_cranpose_android_CranposeOverlayWindow_nativeOverlayCreateFailed<
    'local,
>(
    mut env: EnvUnowned<'local>,
    _class: JClass<'local>,
    queue_handle: jlong,
    message: JString<'local>,
) {
    let message = match env
        .with_env(|env| -> jni::errors::Result<String> { message.try_to_string(env) })
        .into_outcome()
    {
        Outcome::Ok(message) => message,
        Outcome::Err(_) | Outcome::Panic(_) => "Android overlay window creation failed".to_string(),
    };
    push_overlay_event_for_handle(
        queue_handle,
        AndroidOverlayWindowEvent::CreateFailed(message),
    );
}

#[doc(hidden)]
#[unsafe(no_mangle)]
pub(crate) extern "system" fn Java_dev_cranpose_android_CranposeOverlayWindow_nativeOverlaySurfaceChanged<
    'local,
>(
    mut env: EnvUnowned<'local>,
    _class: JClass<'local>,
    queue_handle: jlong,
    surface: JObject<'local>,
    width: jint,
    height: jint,
) {
    match env
        .with_env(|env| -> jni::errors::Result<Result<NativeWindow, String>> {
            Ok(native_window_from_surface(env, surface))
        })
        .into_outcome()
    {
        Outcome::Ok(Ok(native_window)) if width > 0 && height > 0 => {
            push_overlay_event_for_handle(
                queue_handle,
                AndroidOverlayWindowEvent::SurfaceChanged {
                    native_window,
                    width: width as u32,
                    height: height as u32,
                },
            );
        }
        Outcome::Ok(Ok(_)) => {}
        Outcome::Ok(Err(message)) => {
            push_overlay_event_for_handle(
                queue_handle,
                AndroidOverlayWindowEvent::CreateFailed(message),
            );
        }
        Outcome::Err(error) => {
            push_overlay_event_for_handle(
                queue_handle,
                AndroidOverlayWindowEvent::CreateFailed(format!(
                    "failed to access Android overlay Surface: {error}"
                )),
            );
        }
        Outcome::Panic(_) => {
            push_overlay_event_for_handle(
                queue_handle,
                AndroidOverlayWindowEvent::CreateFailed(
                    "failed to access Android overlay Surface".to_string(),
                ),
            );
        }
    }
}

#[doc(hidden)]
#[unsafe(no_mangle)]
pub(crate) extern "system" fn Java_dev_cranpose_android_CranposeOverlayWindow_nativeOverlaySurfaceDestroyed(
    _env: EnvUnowned<'_>,
    _class: JClass<'_>,
    queue_handle: jlong,
) {
    push_overlay_event_for_handle(queue_handle, AndroidOverlayWindowEvent::SurfaceDestroyed);
}

#[doc(hidden)]
#[unsafe(no_mangle)]
pub(crate) extern "system" fn Java_dev_cranpose_android_CranposeOverlayWindow_nativeOverlayPointer(
    _env: EnvUnowned<'_>,
    _class: JClass<'_>,
    queue_handle: jlong,
    action: jint,
    x: jfloat,
    y: jfloat,
) {
    let action = match action {
        0 | 5 => AndroidOverlayPointerAction::Down,
        1 | 6 => AndroidOverlayPointerAction::Up,
        2 => AndroidOverlayPointerAction::Move,
        3 => AndroidOverlayPointerAction::Cancel,
        _ => return,
    };
    push_overlay_event_for_handle(
        queue_handle,
        AndroidOverlayWindowEvent::Pointer { action, x, y },
    );
}

#[doc(hidden)]
#[unsafe(no_mangle)]
pub(crate) extern "system" fn Java_dev_cranpose_android_CranposeOverlayWindow_nativeOverlayReleaseQueue(
    _env: EnvUnowned<'_>,
    _class: JClass<'_>,
    queue_handle: jlong,
) {
    release_android_overlay_event_queue_handle_raw(queue_handle);
}