waterui-ffi 0.3.1

FFI bindings for the WaterUI cross-platform UI framework
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
//! JNI bridge for Android `WebView` integration.
//!
//! This module provides:
//! - A native `WebView` handle implementation (function pointers) for `WaterUI`'s
//!   `WebViewController`
//! - JNI callbacks invoked by Kotlin `WebView` wrappers (events, JS messaging, JS results)

extern crate alloc;
extern crate std;

use alloc::boxed::Box;
use alloc::rc::Rc;
use alloc::string::String;
use alloc::string::ToString;

use jni::objects::{Global, JObject, JString, JValue};
use jni::sys::{jboolean, jfloat, jint, jlong, jobject};
use jni::{Env, EnvUnowned, JavaVM, jni_sig, jni_str};

use crate::closure::WuiFn;
use crate::components::webview::{
    FfiWebViewHandle, WuiJsCallback, WuiJsReplyKind, WuiScriptInjectionTime, WuiStringCallback,
    WuiWebViewEvent, WuiWebViewEventType, WuiWebViewHandle, WuiWebViewMessage, WuiWebViewReply,
};
use crate::reactive::WuiComputed;
use crate::{IntoFFI, IntoRust, WuiStr};
use base64::Engine as _;
use waterui_webview::{CustomWebViewController, WebViewController, WebViewHandle, bridge};

use std::{collections::HashMap, sync::Arc};

struct AndroidWebViewHandle {
    jvm: Arc<JavaVM>,
    wrapper: Global<JObject<'static>>,
    event_callback: Option<Rc<WuiFn<WuiWebViewEvent>>>,
    handlers: HashMap<String, Rc<WuiFn<WuiWebViewMessage>>>,
}

impl AndroidWebViewHandle {
    fn with_env<R>(&self, f: impl FnOnce(&mut Env) -> R) -> R {
        super::with_attached_env(&self.jvm, f)
            .expect("AndroidWebViewHandle failed to attach its JVM thread")
    }
}

struct AndroidWebViewFactory {
    jvm: Arc<JavaVM>,
    factory: Global<JObject<'static>>,
}

impl AndroidWebViewFactory {
    fn with_env<R>(&self, f: impl FnOnce(&mut Env) -> R) -> R {
        super::with_attached_env(&self.jvm, f)
            .expect("AndroidWebViewFactory failed to attach its JVM thread")
    }

    fn create_webview(&self) -> WuiWebViewHandle {
        self.with_env(|env| {
            let wrapper_obj = env
                .call_method(
                    &self.factory,
                    jni_str!("create"),
                    jni_sig!("()Ldev/waterui/android/components/WebViewWrapper;"),
                    &[],
                )
                .expect("Android WebViewFactory.create failed")
                .l()
                .expect("Android WebViewFactory.create did not return a WebViewWrapper");

            let wrapper_ref = env
                .new_global_ref(wrapper_obj)
                .expect("Failed to retain WebViewWrapper");

            let handle = Box::new(AndroidWebViewHandle {
                jvm: Arc::clone(&self.jvm),
                wrapper: wrapper_ref,
                event_callback: None,
                handlers: HashMap::new(),
            });
            let handle_ptr = Box::into_raw(handle).cast::<()>();

            WuiWebViewHandle {
                data: handle_ptr,
                go_back: webview_go_back,
                go_forward: webview_go_forward,
                go_to: webview_go_to,
                stop: webview_stop,
                refresh: webview_refresh,
                can_go_back: webview_can_go_back,
                can_go_forward: webview_can_go_forward,
                set_user_agent: webview_set_user_agent,
                set_redirects_enabled: webview_set_redirects_enabled,
                inject_script: webview_inject_script,
                watch: webview_watch,
                add_handler: Some(webview_add_handler),
                remove_handler: Some(webview_remove_handler),
                set_bridge_origins: Some(webview_set_bridge_origins),
                set_cookie: Some(webview_set_cookie),
                get_cookies: Some(webview_get_cookies),
                run_javascript: webview_run_javascript,
                call_async_javascript: webview_call_async_javascript,
                drop: webview_drop,
            }
        })
    }
}

impl CustomWebViewController for AndroidWebViewFactory {
    fn open(&self) -> impl WebViewHandle {
        FfiWebViewHandle::new(self.create_webview())
    }
}

fn wui_str_to_string(s: WuiStr) -> String {
    // SAFETY: every `WuiStr` reaching this module was produced by the matching
    // `into_ffi`, and each one arrives once, as an owned argument.
    let s: waterui::Str = unsafe { s.into_rust() };
    s.as_str().to_string()
}

/// Hands a native callback entry point to Kotlin as the `long` it passes back.
fn entry_point_to_jlong(entry_point: usize) -> jlong {
    jlong::try_from(entry_point).expect("callback entry point address must fit a Java long")
}

fn java_string<'local>(env: &mut Env<'local>, s: &str) -> JString<'local> {
    env.new_string(s).expect("Failed to create Java string")
}

// =============================================================================
// WebView handle vtable (called from Rust via FFI)
// =============================================================================

unsafe extern "C" fn webview_go_back(data: *mut ()) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`, and it stays live until `webview_drop` reclaims it.
    let handle = unsafe { &*data.cast::<AndroidWebViewHandle>() };
    handle.with_env(|env| {
        env.call_method(&handle.wrapper, jni_str!("goBack"), jni_sig!("()V"), &[])
            .expect("webview_go_back: failed to call WebViewWrapper.goBack()");
    });
}

unsafe extern "C" fn webview_go_forward(data: *mut ()) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`, and it stays live until `webview_drop` reclaims it.
    let handle = unsafe { &*data.cast::<AndroidWebViewHandle>() };
    handle.with_env(|env| {
        env.call_method(&handle.wrapper, jni_str!("goForward"), jni_sig!("()V"), &[])
            .expect("webview_go_forward: failed to call WebViewWrapper.goForward()");
    });
}

unsafe extern "C" fn webview_go_to(data: *mut (), url: WuiStr) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`, and it stays live until `webview_drop` reclaims it.
    let handle = unsafe { &*data.cast::<AndroidWebViewHandle>() };
    let url = wui_str_to_string(url);
    handle.with_env(|env| {
        let jurl = java_string(env, &url);
        env.call_method(
            &handle.wrapper,
            jni_str!("goTo"),
            jni_sig!("(Ljava/lang/String;)V"),
            &[JValue::Object(&jurl)],
        )
        .expect("webview_go_to: failed to call WebViewWrapper.goTo(String)");
    });
}

unsafe extern "C" fn webview_stop(data: *mut ()) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`, and it stays live until `webview_drop` reclaims it.
    let handle = unsafe { &*data.cast::<AndroidWebViewHandle>() };
    handle.with_env(|env| {
        env.call_method(&handle.wrapper, jni_str!("stop"), jni_sig!("()V"), &[])
            .expect("webview_stop: failed to call WebViewWrapper.stop()");
    });
}

unsafe extern "C" fn webview_refresh(data: *mut ()) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`, and it stays live until `webview_drop` reclaims it.
    let handle = unsafe { &*data.cast::<AndroidWebViewHandle>() };
    handle.with_env(|env| {
        env.call_method(&handle.wrapper, jni_str!("refresh"), jni_sig!("()V"), &[])
            .expect("webview_refresh: failed to call WebViewWrapper.refresh()");
    });
}

unsafe extern "C" fn webview_can_go_back(data: *const ()) -> bool {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`, and it stays live until `webview_drop` reclaims it.
    let handle = unsafe { &*data.cast::<AndroidWebViewHandle>() };
    handle.with_env(|env| {
        env.call_method(&handle.wrapper, jni_str!("canGoBack"), jni_sig!("()Z"), &[])
            .expect("webview_can_go_back: failed to call WebViewWrapper.canGoBack()")
            .z()
            .expect("webview_can_go_back: canGoBack() did not return boolean")
    })
}

unsafe extern "C" fn webview_can_go_forward(data: *const ()) -> bool {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`, and it stays live until `webview_drop` reclaims it.
    let handle = unsafe { &*data.cast::<AndroidWebViewHandle>() };
    handle.with_env(|env| {
        env.call_method(
            &handle.wrapper,
            jni_str!("canGoForward"),
            jni_sig!("()Z"),
            &[],
        )
        .expect("webview_can_go_forward: failed to call WebViewWrapper.canGoForward()")
        .z()
        .expect("webview_can_go_forward: canGoForward() did not return boolean")
    })
}

unsafe extern "C" fn webview_set_user_agent(data: *mut (), user_agent: WuiStr) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`, and it stays live until `webview_drop` reclaims it.
    let handle = unsafe { &*data.cast::<AndroidWebViewHandle>() };
    let ua = wui_str_to_string(user_agent);
    handle.with_env(|env| {
        let jua = java_string(env, &ua);
        env.call_method(
            &handle.wrapper,
            jni_str!("setUserAgent"),
            jni_sig!("(Ljava/lang/String;)V"),
            &[JValue::Object(&jua)],
        )
        .expect("webview_set_user_agent: failed to call WebViewWrapper.setUserAgent(String)");
    });
}

unsafe extern "C" fn webview_set_redirects_enabled(data: *mut (), enabled: *mut WuiComputed<bool>) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`, and it stays live until `webview_drop` reclaims it.
    let handle = unsafe { &*data.cast::<AndroidWebViewHandle>() };
    handle.with_env(|env| {
        env.call_method(
            &handle.wrapper,
            jni_str!("setRedirectsEnabled"),
            jni_sig!("(J)V"),
            &[JValue::Long(enabled as jlong)],
        )
        .expect(
            "webview_set_redirects_enabled: failed to transfer redirect signal to WebViewWrapper",
        );
    });
}

unsafe extern "C" fn webview_inject_script(
    data: *mut (),
    key: WuiStr,
    script: WuiStr,
    time: WuiScriptInjectionTime,
) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`, and it stays live until `webview_drop` reclaims it.
    let handle = unsafe { &*data.cast::<AndroidWebViewHandle>() };
    let key = wui_str_to_string(key);
    let script = wui_str_to_string(script);
    handle.with_env(|env| {
        let jkey = java_string(env, &key);
        let jscript = java_string(env, &script);
        env.call_method(
            &handle.wrapper,
            jni_str!("injectScript"),
            jni_sig!("(Ljava/lang/String;Ljava/lang/String;I)V"),
            &[
                JValue::Object(&jkey),
                JValue::Object(&jscript),
                JValue::Int(time as jint),
            ],
        )
        .expect(
            "webview_inject_script: failed to call WebViewWrapper.injectScript(String, String, int)",
        );
    });
}

unsafe extern "C" fn webview_watch(data: *mut (), callback: WuiFn<WuiWebViewEvent>) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`; the controller calls one entry at a time, so this exclusive
    // borrow is the only live reference to it.
    let handle = unsafe { &mut *data.cast::<AndroidWebViewHandle>() };
    handle.event_callback = Some(Rc::new(callback));
    let handle_ptr = core::ptr::from_mut(handle) as jlong;

    handle.with_env(|env| {
        let cb_class = env
            .find_class(jni_str!(
                "dev/waterui/android/components/NativeWebViewEventCallback"
            ))
            .expect("NativeWebViewEventCallback class not found");
        let cb_obj = env
            .new_object(cb_class, jni_sig!("(J)V"), &[JValue::Long(handle_ptr)])
            .expect("Failed to create NativeWebViewEventCallback");

        env.call_method(
            &handle.wrapper,
            jni_str!("setEventCallback"),
            jni_sig!("(Ldev/waterui/android/components/WebViewEventCallback;)V"),
            &[JValue::Object(&cb_obj)],
        )
        .expect("webview_watch: failed to call WebViewWrapper.setEventCallback(callback)");
    });
}

unsafe extern "C" fn webview_add_handler(
    data: *mut (),
    name: WuiStr,
    handler: WuiFn<WuiWebViewMessage>,
) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`; the controller calls one entry at a time, so this exclusive
    // borrow is the only live reference to it.
    let handle = unsafe { &mut *data.cast::<AndroidWebViewHandle>() };
    let name = wui_str_to_string(name);
    handle.handlers.insert(name.clone(), Rc::new(handler));
    let handle_ptr = core::ptr::from_mut(handle) as jlong;

    handle.with_env(|env| {
        let jname = java_string(env, &name);
        env.call_method(
            &handle.wrapper,
            jni_str!("addHandler"),
            jni_sig!("(Ljava/lang/String;J)V"),
            &[JValue::Object(&jname), JValue::Long(handle_ptr)],
        )
        .expect("webview_add_handler: failed to call WebViewWrapper.addHandler(String, long)");
    });
}

unsafe extern "C" fn webview_remove_handler(data: *mut (), name: WuiStr) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`; the controller calls one entry at a time, so this exclusive
    // borrow is the only live reference to it.
    let handle = unsafe { &mut *data.cast::<AndroidWebViewHandle>() };
    let name = wui_str_to_string(name);

    handle.with_env(|env| {
        let jname = java_string(env, &name);
        env.call_method(
            &handle.wrapper,
            jni_str!("removeHandler"),
            jni_sig!("(Ljava/lang/String;)V"),
            &[JValue::Object(&jname)],
        )
        .expect("webview_remove_handler: failed to call WebViewWrapper.removeHandler(String)");
    });

    handle.handlers.remove(&name);
}

unsafe extern "C" fn webview_set_bridge_origins(data: *mut (), patterns: WuiStr) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`, and it stays live until `webview_drop` reclaims it.
    let handle = unsafe { &*data.cast::<AndroidWebViewHandle>() };
    let patterns = wui_str_to_string(patterns);
    handle.with_env(|env| {
        let jpatterns = java_string(env, &patterns);
        env.call_method(
            &handle.wrapper,
            jni_str!("setBridgeOrigins"),
            jni_sig!("(Ljava/lang/String;)V"),
            &[JValue::Object(&jpatterns)],
        )
        .expect("webview_set_bridge_origins: failed to call WebViewWrapper.setBridgeOrigins");
    });
}

unsafe extern "C" fn webview_set_cookie(data: *mut (), cookie: WuiStr) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`, and it stays live until `webview_drop` reclaims it.
    let handle = unsafe { &*data.cast::<AndroidWebViewHandle>() };
    let cookie = wui_str_to_string(cookie);
    handle.with_env(|env| {
        let jcookie = java_string(env, &cookie);
        env.call_method(
            &handle.wrapper,
            jni_str!("setCookie"),
            jni_sig!("(Ljava/lang/String;)V"),
            &[JValue::Object(&jcookie)],
        )
        .expect("webview_set_cookie: failed to call WebViewWrapper.setCookie(String)");
    });
}

unsafe extern "C" fn webview_get_cookies(data: *const (), callback: WuiStringCallback) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`, and it stays live until `webview_drop` reclaims it.
    let handle = unsafe { &*data.cast::<AndroidWebViewHandle>() };
    let call_ptr = entry_point_to_jlong(callback.call as usize);
    handle.with_env(|env| {
        env.call_method(
            &handle.wrapper,
            jni_str!("getCookies"),
            jni_sig!("(JJ)V"),
            &[JValue::Long(callback.data as jlong), JValue::Long(call_ptr)],
        )
        .expect("webview_get_cookies: failed to call getCookies(callback)");
    });
}

unsafe extern "C" fn webview_run_javascript(
    data: *mut (),
    script: WuiStr,
    callback: WuiJsCallback,
) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`, and it stays live until `webview_drop` reclaims it.
    let handle = unsafe { &*data.cast::<AndroidWebViewHandle>() };
    let script = wui_str_to_string(script);
    let call_ptr = entry_point_to_jlong(callback.call as usize);
    handle.with_env(|env| {
        let jscript = java_string(env, &script);
        env.call_method(
            &handle.wrapper,
            jni_str!("runJavaScript"),
            jni_sig!("(Ljava/lang/String;JJ)V"),
            &[
                JValue::Object(&jscript),
                JValue::Long(callback.data as jlong),
                JValue::Long(call_ptr),
            ],
        )
        .expect("webview_run_javascript: failed to call WebViewWrapper.runJavaScript");
    });
}

/// Runs an async function body and awaits the promise it returns.
///
/// Android's `WebView.evaluateJavascript` has no awaiting form, so the Kotlin
/// side resolves the promise in JavaScript and reports the settled value back
/// through this same callback. Without it the shared wrapper's promise crossed
/// unresolved and every typed evaluation — including every mirrored-state push
/// — failed to decode.
unsafe extern "C" fn webview_call_async_javascript(
    data: *mut (),
    body: WuiStr,
    callback: WuiJsCallback,
) {
    // SAFETY: `data` is the handle pointer this vtable entry was registered with in
    // `create_webview`, and it stays live until `webview_drop` reclaims it.
    let handle = unsafe { &*data.cast::<AndroidWebViewHandle>() };
    let body = wui_str_to_string(body);
    let call_ptr = entry_point_to_jlong(callback.call as usize);
    handle.with_env(|env| {
        let jbody = java_string(env, &body);
        env.call_method(
            &handle.wrapper,
            jni_str!("callAsyncJavaScript"),
            jni_sig!("(Ljava/lang/String;JJ)V"),
            &[
                JValue::Object(&jbody),
                JValue::Long(callback.data as jlong),
                JValue::Long(call_ptr),
            ],
        )
        .expect("webview_call_async_javascript: failed to call WebViewWrapper.callAsyncJavaScript");
    });
}

unsafe extern "C" fn webview_drop(data: *mut ()) {
    // SAFETY: `data` is the handle pointer `create_webview` boxed for this vtable, and
    // the controller drops each handle once, after its last other entry point call.
    let mut handle = unsafe { Box::from_raw(data.cast::<AndroidWebViewHandle>()) };

    handle.with_env(|env| {
        env.call_method(
            &handle.wrapper,
            jni_str!("setEventCallback"),
            jni_sig!("(Ldev/waterui/android/components/WebViewEventCallback;)V"),
            &[JValue::Object(&JObject::null())],
        )
        .expect("webview_drop: failed to clear WebViewWrapper event callback");
        env.call_method(&handle.wrapper, jni_str!("release"), jni_sig!("()V"), &[])
            .expect("webview_drop: failed to call WebViewWrapper.release()");
    });

    // Drop callbacks.
    handle.event_callback.take();
    handle.handlers.clear();
}

/// Installs an Android `WebView` controller that owns its Java VM capability.
///
/// # Panics
///
/// Panics when the JVM will not hand out its `JavaVM` capability or retain the
/// Java factory, neither of which a running Android app can fail.
///
/// # Safety
///
/// `wui_env` must point to a live `WaterUI` environment owned by the caller.
pub unsafe fn install_android_webview_controller(
    env: &Env,
    wui_env: *mut crate::WuiEnv,
    factory: JObject,
) {
    let controller = WebViewController::new(AndroidWebViewFactory {
        jvm: Arc::new(
            env.get_java_vm()
                .expect("WebView factory installation failed to access JavaVM"),
        ),
        factory: env
            .new_global_ref(factory)
            .expect("WebView factory installation failed to retain Java factory"),
    });
    // SAFETY: the caller contract above makes `wui_env` a live environment, borrowed
    // only for this insertion.
    let env = unsafe { crate::borrow_ffi_mut(wui_env) };
    env.0.insert(controller);
}

pub(crate) fn webview_native_view(env: &mut Env<'_>, handle_ptr: jlong) -> jobject {
    // SAFETY: Kotlin passes back the handle pointer `create_webview` gave it, which is
    // live until the controller drops the web view.
    let handle = unsafe { &*(handle_ptr as *const AndroidWebViewHandle) };
    env.call_method(
        &handle.wrapper,
        jni_str!("getWebView"),
        jni_sig!("()Landroid/webkit/WebView;"),
        &[],
    )
    .expect("webview_native_view: failed to call WebViewWrapper.getWebView()")
    .l()
    .expect("webview_native_view: getWebView() did not return an object")
    .into_raw()
}

// =============================================================================
// Kotlin -> Rust callback trampolines
// =============================================================================

type JsCallbackFn = unsafe extern "C" fn(*mut (), bool, WuiStr);
type StringCallbackFn = unsafe extern "C" fn(*mut (), WuiStr);

#[unsafe(no_mangle)]
extern "system" fn Java_dev_waterui_android_components_WebViewWrapper_nativeCompleteCookies<
    'local,
>(
    mut env: EnvUnowned<'local>,
    _this: JObject<'local>,
    callback_data: jlong,
    callback_fn: jlong,
    result: JString<'local>,
) {
    // SAFETY: Kotlin passes back the two `long`s `webview_get_cookies` handed it, so
    // `callback_fn` is that `WuiStringCallback`'s own `call` entry point.
    let call: StringCallbackFn = unsafe {
        core::mem::transmute::<usize, StringCallbackFn>(
            usize::try_from(callback_fn)
                .expect("cookie callback entry point must be a valid address"),
        )
    };
    super::with_env(&mut env, |env| {
        let text = result
            .try_to_string(env)
            .expect("WebViewWrapper.nativeCompleteCookies: result");
        // SAFETY: `callback_data` is the payload registered with the entry point above,
        // and the wrapper completes each request once.
        unsafe {
            call(
                callback_data as *mut (),
                waterui::Str::from(text).into_ffi(),
            );
        }
    });
}

#[unsafe(no_mangle)]
extern "system" fn Java_dev_waterui_android_components_WebViewWrapper_nativeCompleteJsResult<
    'local,
>(
    mut env: EnvUnowned<'local>,
    _this: JObject<'local>,
    callback_data: jlong,
    callback_fn: jlong,
    success: jboolean,
    result: JString<'local>,
) {
    // SAFETY: Kotlin passes back the two `long`s `webview_run_javascript` or
    // `webview_call_async_javascript` handed it, so `callback_fn` is that
    // `WuiJsCallback`'s own `call` entry point.
    let call: JsCallbackFn = unsafe {
        core::mem::transmute::<usize, JsCallbackFn>(
            usize::try_from(callback_fn).expect("JS callback entry point must be a valid address"),
        )
    };

    super::with_env(&mut env, |env| {
        let text = result
            .try_to_string(env)
            .expect("WebViewWrapper.nativeCompleteJsResult: result");
        let wui_str = waterui::Str::from(text).into_ffi();
        // SAFETY: `callback_data` is the payload registered with the entry point above,
        // and the wrapper completes each evaluation once.
        unsafe {
            call(callback_data as *mut (), success, wui_str);
        }
    });
}

struct ReplyCtx {
    jvm: Arc<JavaVM>,
    wrapper: Global<JObject<'static>>,
    request_id: u64,
}

/// Completes one bridge call.
///
/// The reply script is rendered here rather than in Kotlin so the envelope format
/// lives in exactly one place: `waterui_webview::bridge`.
unsafe extern "C" fn reply_call(
    data: *mut (),
    success: bool,
    kind: WuiJsReplyKind,
    payload_b64: WuiStr,
) {
    // SAFETY: `data` is the `ReplyCtx` boxed for this one bridge call in
    // `nativeOnBridgeMessage`, and a `WuiWebViewReply` is answered exactly once.
    let ctx = unsafe { Box::from_raw(data.cast::<ReplyCtx>()) };
    // SAFETY: `payload_b64` is an owned `WuiStr` the handler produced for this reply.
    let payload: waterui::Str = unsafe { payload_b64.into_rust() };

    let reply = if success {
        match base64::engine::general_purpose::STANDARD.decode(payload.as_str()) {
            Ok(bytes) => match kind {
                WuiJsReplyKind::Json => bridge::Reply::Json(bytes),
                WuiJsReplyKind::Bytes => bridge::Reply::Bytes(bytes),
            },
            Err(error) => bridge::Reply::failure(&error),
        }
    } else {
        bridge::Reply::failure(&payload.as_str())
    };
    let script = reply.resolve_script(ctx.request_id);

    super::with_attached_env(&ctx.jvm, |env| {
        let jscript = java_string(env, &script);
        env.call_method(
            &ctx.wrapper,
            jni_str!("evaluateBridgeScript"),
            jni_sig!("(Ljava/lang/String;)V"),
            &[JValue::Object(&jscript)],
        )
        .expect("reply_call: failed to call WebViewWrapper.evaluateBridgeScript(String)");
    })
    .expect("WebView reply failed to attach its JVM thread");
}

/// Returns the shared bridge script for the Kotlin side to inject.
#[unsafe(no_mangle)]
extern "system" fn Java_dev_waterui_android_components_WebViewWrapper_nativeBridgeScript<'local>(
    mut env: EnvUnowned<'local>,
    _this: JObject<'local>,
) -> jobject {
    super::with_env(&mut env, |env| {
        java_string(env, waterui_webview::DOCUMENT_START_SCRIPT).into_raw()
    })
}

/// Receives one `waterui.invoke(...)` envelope from page script.
///
/// Page script reaches this transport directly, so a malformed envelope or an
/// unknown handler name is rejected back to JavaScript rather than aborting the
/// application.
#[unsafe(no_mangle)]
extern "system" fn Java_dev_waterui_android_components_WebViewWrapper_nativeOnBridgeMessage<
    'local,
>(
    mut env: EnvUnowned<'local>,
    _this: JObject<'local>,
    native_ptr: jlong,
    envelope: JString<'local>,
) {
    super::with_env(&mut env, |env| {
        let Ok(envelope) = envelope.try_to_string(env) else {
            tracing::warn!("WaterUI bridge received a non-UTF-8 envelope; ignoring");
            return;
        };
        // SAFETY: Kotlin passes back the handle pointer `webview_add_handler` gave it,
        // which is live until the controller drops the web view.
        let handle = unsafe { &*(native_ptr as *const AndroidWebViewHandle) };
        let request = match bridge::Request::parse(&envelope) {
            Ok(request) => request,
            Err(error) => {
                tracing::warn!(%error, "page script sent a malformed WaterUI bridge request");
                return;
            }
        };

        let mut reply_to_page = |reply: &bridge::Reply| {
            let script = reply.resolve_script(request.id);
            let jscript = java_string(env, &script);
            env.call_method(
                &handle.wrapper,
                jni_str!("evaluateBridgeScript"),
                jni_sig!("(Ljava/lang/String;)V"),
                &[JValue::Object(&jscript)],
            )
            .expect("failed to call WebViewWrapper.evaluateBridgeScript(String)");
        };

        let Some(handler) = handle.handlers.get(&request.name).map(Rc::clone) else {
            tracing::warn!(
                handler = %request.name,
                "page script called a WaterUI handler that is not registered"
            );
            reply_to_page(&bridge::Reply::failure(&format!(
                "no WaterUI handler named `{}`",
                request.name
            )));
            return;
        };

        let reply_ctx = Box::new(ReplyCtx {
            jvm: Arc::clone(&handle.jvm),
            wrapper: env
                .new_global_ref(handle.wrapper.as_obj())
                .expect("failed to clone the WebViewWrapper reference"),
            request_id: request.id,
        });
        let msg = WuiWebViewMessage {
            payload_base64: waterui::Str::from(
                base64::engine::general_purpose::STANDARD.encode(&request.payload),
            )
            .into_ffi(),
            reply: WuiWebViewReply {
                data: Box::into_raw(reply_ctx).cast::<()>(),
                call: reply_call,
            },
        };
        handler.call(msg);
    });
}

/// Transfers one required Java string field of an event into an owned `WuiStr`.
fn take_java_string(env: &mut Env, value: &JString, field: &'static str) -> *mut WuiStr {
    let value = value
        .try_to_string(env)
        .unwrap_or_else(|_| panic!("webview.native_on_event requires {field}"));
    Box::into_raw(Box::new(waterui::Str::from(value).into_ffi()))
}

#[unsafe(no_mangle)]
extern "system" fn Java_dev_waterui_android_components_NativeWebViewEventCallback_nativeOnEvent<
    'local,
>(
    mut env: EnvUnowned<'local>,
    _this: JObject<'local>,
    native_ptr: jlong,
    event_type: jint,
    url: JString<'local>,
    url2: JString<'local>,
    message: JString<'local>,
    progress: jfloat,
    can_go_back: jboolean,
    can_go_forward: jboolean,
) {
    // SAFETY: Kotlin passes back the handle pointer `webview_watch` gave it, which is
    // live until the controller drops the web view.
    let callback = unsafe { &*(native_ptr as *const AndroidWebViewHandle) }
        .event_callback
        .clone()
        .expect("webview.native_on_event missing registered Rust callback");

    let event_type = match event_type {
        1 => WuiWebViewEventType::WillNavigate,
        2 => WuiWebViewEventType::Loading,
        3 => WuiWebViewEventType::Loaded,
        4 => WuiWebViewEventType::Redirect,
        5 => WuiWebViewEventType::SslError,
        6 => WuiWebViewEventType::Error,
        7 => WuiWebViewEventType::StateChanged,
        _ => panic!("webview.native_on_event received unknown event type {event_type}"),
    };

    super::with_env(&mut env, |env| {
        let (url, url2, message) = match event_type {
            WuiWebViewEventType::WillNavigate => (
                take_java_string(env, &url, "url"),
                core::ptr::null_mut(),
                core::ptr::null_mut(),
            ),
            WuiWebViewEventType::Redirect => (
                take_java_string(env, &url, "url"),
                take_java_string(env, &url2, "url2"),
                core::ptr::null_mut(),
            ),
            WuiWebViewEventType::SslError => (
                take_java_string(env, &url, "url"),
                core::ptr::null_mut(),
                take_java_string(env, &message, "message"),
            ),
            WuiWebViewEventType::Error => (
                core::ptr::null_mut(),
                core::ptr::null_mut(),
                take_java_string(env, &message, "message"),
            ),
            WuiWebViewEventType::Loading
            | WuiWebViewEventType::Loaded
            | WuiWebViewEventType::StateChanged => (
                core::ptr::null_mut(),
                core::ptr::null_mut(),
                core::ptr::null_mut(),
            ),
        };

        let event = WuiWebViewEvent {
            event_type,
            url,
            url2,
            message,
            progress,
            can_go_back,
            can_go_forward,
        };

        callback.call(event);
    });
}