waterui-ffi 0.3.0

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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
use core::fmt;
use core::ops::Deref;

#[cfg(feature = "c-api")]
use crate::WuiAnyView;
use crate::array::WuiArray;
use crate::components::text::WuiStyledStr;
use crate::{IntoFFI, IntoRust, OpaqueType, WuiStr};
use alloc::boxed::Box;
use alloc::rc::Rc;
use alloc::vec::Vec;
#[cfg(feature = "c-api")]
use nami::watcher::WatcherGuard;
use nami::watcher::{Context, Watcher};
use nami::{Computed, Signal, watcher};
#[cfg(feature = "c-api")]
use waterui::AnyView;
use waterui::Str;
use waterui::reactive::watcher::BoxWatcherGuard;
use waterui::reactive::watcher::Metadata;
use waterui_text::styled::StyledStr;
opaque!(WuiWatcherMetadata, Metadata, watcher_metadata, any());

opaque!(WuiWatcherGuard, BoxWatcherGuard, box_watcher_guard, any());

/// FFI-owned wrapper around a [`waterui::Computed`] signal.
///
/// Opaque to native code; accessed only through the `waterui_read_computed_*`,
/// `waterui_watch_computed_*`, and `waterui_drop_computed_*` functions generated
/// by the `ffi_computed!` macro.
#[repr(transparent)]
pub struct WuiComputed<T>(pub(crate) waterui::Computed<T>);

impl<T> fmt::Debug for WuiComputed<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // `waterui::Computed` is a boxed `dyn` signal with no meaningful Debug
        // representation, so only the wrapper's identity is reported.
        f.debug_struct("WuiComputed").finish_non_exhaustive()
    }
}

impl<T> WuiComputed<T>
where
    T: IntoFFI,
    T::FFI: IntoRust<Rust = T>,
{
    /// Creates a new FFI-computed signal using native callbacks.
    ///
    /// # Safety
    /// The caller must ensure that the provided function pointers are valid and adhere to the expected signatures
    pub unsafe fn new(
        data: *mut (),
        get: unsafe extern "C" fn(*const ()) -> T::FFI,
        watch: unsafe extern "C" fn(*const (), *mut WuiWatcher<T>) -> *mut WuiWatcherGuard,
        drop: unsafe extern "C" fn(*mut ()),
    ) -> Self
    where
        T: IntoFFI + 'static,
    {
        // SAFETY: the caller contract requires `data` and the three function pointers
        // to be one registration from the backend, which is what `FFIComputed` calls
        // them as.
        unsafe { Self(Computed::new(FFIComputed::new(data, get, watch, drop))) }
    }
}

struct FFIComputed<T: IntoFFI> {
    data: Rc<NativeComputedData>,
    get: unsafe extern "C" fn(*const ()) -> T::FFI,
    watch: unsafe extern "C" fn(*const (), *mut WuiWatcher<T>) -> *mut WuiWatcherGuard,
}

struct NativeComputedData {
    ptr: *mut (),
    drop: unsafe extern "C" fn(*mut ()),
}

impl Drop for NativeComputedData {
    fn drop(&mut self) {
        // SAFETY: `drop` and `ptr` come from the same registration, and `Drop` runs
        // once, so the backend's destructor sees its pointer exactly once.
        unsafe { (self.drop)(self.ptr) };
    }
}

impl<T: IntoFFI> Signal for FFIComputed<T>
where
    T::FFI: IntoRust<Rust = T>,
{
    type Output = T;
    type Guard = BoxWatcherGuard;
    fn get(&self) -> Self::Output {
        // SAFETY: `get` and `data.ptr` come from the same registration, and `&self`
        // proves it has not been dropped; `get` hands back an owning value.
        unsafe { (self.get)(self.data.ptr.cast_const()).into_rust() }
    }

    fn watch(&self, watcher: impl Fn(Context<Self::Output>) + 'static) -> Self::Guard {
        let watcher: Watcher<Self::Output> = Rc::new(watcher);
        let watcher = watcher.into_ffi();

        // SAFETY: `watch` belongs to the same registration as `data.ptr`, and it
        // returns an owning guard pointer that this call takes responsibility for.
        unsafe {
            let guard_ptr = (self.watch)(self.data.ptr.cast_const(), watcher);
            let guard = Box::from_raw(guard_ptr);
            let WuiWatcherGuard(guard) = *guard;
            guard
        }
    }
}

impl<T: IntoFFI> FFIComputed<T> {
    pub unsafe fn new(
        data: *mut (),
        get: unsafe extern "C" fn(*const ()) -> T::FFI,
        watch: unsafe extern "C" fn(*const (), *mut WuiWatcher<T>) -> *mut WuiWatcherGuard,
        drop: unsafe extern "C" fn(*mut ()),
    ) -> Self {
        Self {
            data: Rc::new(NativeComputedData { ptr: data, drop }),
            get,
            watch,
        }
    }
}

impl<T: IntoFFI> Clone for FFIComputed<T> {
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            get: self.get,
            watch: self.watch,
        }
    }
}

impl<T: 'static> IntoFFI for waterui::Computed<T> {
    type FFI = *mut WuiComputed<T>;

    fn into_ffi(self) -> Self::FFI {
        Box::into_raw(Box::new(WuiComputed(self)))
    }
}

impl<T: 'static> IntoFFI for Option<waterui::Computed<T>> {
    type FFI = *mut WuiComputed<T>;

    fn into_ffi(self) -> Self::FFI {
        self.map_or(core::ptr::null_mut(), super::super::IntoFFI::into_ffi)
    }
}

impl<T> IntoFFI for waterui::Binding<T> {
    type FFI = *mut WuiBinding<T>;

    fn into_ffi(self) -> Self::FFI {
        Box::into_raw(Box::new(WuiBinding(self)))
    }
}

impl<T: 'static> OpaqueType for WuiComputed<T> {}

impl<T> Deref for WuiComputed<T> {
    type Target = waterui::Computed<T>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> Deref for WuiBinding<T> {
    type Target = waterui::Binding<T>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// FFI-owned wrapper around a [`waterui::Binding`] signal.
///
/// Opaque to native code; accessed only through the `waterui_read_binding_*`,
/// `waterui_set_binding_*`, `waterui_watch_binding_*`, and
/// `waterui_drop_binding_*` functions generated by the `ffi_binding!` macro.
#[repr(transparent)]
pub struct WuiBinding<T: 'static>(pub(crate) waterui::Binding<T>);

impl<T> fmt::Debug for WuiBinding<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // `waterui::Binding` is a boxed `dyn` signal with no meaningful Debug
        // representation, so only the wrapper's identity is reported.
        f.debug_struct("WuiBinding").finish_non_exhaustive()
    }
}

impl<T> OpaqueType for WuiBinding<T> {}

/// Generates the C constructor for a native watcher.
///
/// Invoke this directly for binding-only types. [`ffi_computed!`](crate::ffi_computed) invokes it
/// automatically for computed types.
#[macro_export]
macro_rules! ffi_watcher {
    ($ty:ty, $ffi:ty, $ident:tt) => {
        pastey::paste! {
            #[cfg(feature = "c-api")]
            /// Creates a watcher from native callbacks.
            ///
            /// # Safety
            ///
            /// All function pointers must be valid and `data` must remain valid
            /// until `drop` is called exactly once.
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn [<waterui_new_watcher_ $ident>](
                data: *mut (),
                call: unsafe extern "C" fn(
                    *mut (),
                    $ffi,
                    *mut $crate::reactive::WuiWatcherMetadata,
                ),
                drop: unsafe extern "C" fn(*mut ()),
            ) -> *mut $crate::reactive::WuiWatcher<$ty>
            where
                $ty: $crate::IntoFFI + 'static,
            {
                // SAFETY: the caller contract requires `data`, `call` and `drop` to be
                // one registration from the backend.
                let watcher = unsafe {
                    $crate::reactive::WuiWatcher::<$ty>::new(data, call, drop)
                };
                alloc::boxed::Box::into_raw(alloc::boxed::Box::new(watcher))
            }
        }
    };

    ($ty:ty, $ffi:ty) => {
        pastey::paste! {
            $crate::ffi_watcher!($ty, $ffi, [<$ty:snake>]);
        }
    };
}

/// Generates the notify/release pair a native-controlled signal needs.
///
/// [`ffi_watcher!`] lets a backend *create* a watcher; these let it drive one.
/// `waterui_call_watcher_{ident}` delivers a new value to a watcher `WaterUI`
/// handed the backend, and `waterui_drop_watcher_{ident}` releases it when the
/// backend's signal loses its last subscriber. Only types a backend actually
/// publishes need them, so this is a separate macro rather than part of
/// [`ffi_computed!`](crate::ffi_computed), which every reactive type invokes.
#[macro_export]
macro_rules! ffi_watcher_notify {
    ($ty:ty, $ffi:ty, $ident:tt) => {
        pastey::paste! {
            #[doc = concat!("Delivers `value` to a `", stringify!($ty), "` watcher.")]
            ///
            /// # Safety
            /// The watcher pointer must be a valid handle that is alive for this
            /// call.
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn [<waterui_call_watcher_ $ident>](
                watcher: *const $crate::reactive::WuiWatcher<$ty>,
                value: $ffi,
            ) {
                // SAFETY: the caller contract requires `watcher` to be a valid handle
                // alive for this call; it is only borrowed.
                unsafe {
                    let watcher = $crate::borrow_ffi(watcher);
                    let value = $crate::IntoRust::into_rust(value);
                    watcher.call(value, waterui::reactive::watcher::Metadata::default());
                }
            }

            #[doc = concat!("Releases a `", stringify!($ty), "` watcher.")]
            ///
            /// # Safety
            /// The watcher pointer must be an owning pointer from the matching
            /// constructor that has not already been dropped.
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn [<waterui_drop_watcher_ $ident>](
                watcher: *mut $crate::reactive::WuiWatcher<$ty>,
            ) {
                // SAFETY: the caller contract makes `watcher` an owning pointer from the
                // matching constructor that has not been dropped.
                unsafe {
                    drop(alloc::boxed::Box::from_raw(watcher));
                }
            }
        }
    };
}

/// Generates computed FFI support for read-only reactive types.
///
/// When `c-api` feature is enabled, generates C FFI functions.
/// When `android-jni` feature is enabled, generates JNI functions.
///
/// # Generated Functions (C-API)
/// - `waterui_read_computed_{ident}` - read current value
/// - `waterui_watch_computed_{ident}` - subscribe to changes
/// - `waterui_drop_computed_{ident}` - cleanup
/// - `waterui_new_watcher_{ident}` - create watcher
///
/// For types that also need native-controlled signal constructors,
/// additionally invoke `ffi_computed_ctor!`.
#[macro_export]
macro_rules! ffi_computed {
    ($ty:ty,$ffi:ty, $ident:tt) => {
        pastey::paste!{
            // ========== C-API (for Apple/GTK backends) ==========
            #[cfg(feature = "c-api")]
            /// Reads the current value from a computed
            /// # Safety
            /// The computed pointer must be valid and point to a properly initialized computed object.
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn [< waterui_read_computed_ $ident >](computed: *const $crate::reactive::WuiComputed<$ty>) -> $ffi {
                use waterui::Signal;
                // SAFETY: the caller contract requires `computed` to be a valid handle
                // alive for this call; it is only borrowed.
                unsafe { $crate::IntoFFI::into_ffi((&(*computed)).get()) }
            }

            #[cfg(feature = "c-api")]
            /// Watches for changes in a computed
            /// # Safety
            /// The computed pointer must be valid and point to a properly initialized computed object.
            /// The watcher pointer will be consumed and freed when the returned guard is dropped.
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn [< waterui_watch_computed_ $ident >](
                computed: *const $crate::reactive::WuiComputed<$ty>,
                watcher: *mut $crate::reactive::WuiWatcher<$ty>,
            ) -> *mut $crate::reactive::WuiWatcherGuard {
                use waterui::Signal;
                // SAFETY: the caller contract makes `watcher` an owning pointer from
                // the matching constructor, consumed here, and `computed` a valid handle
                // that is only borrowed.
                unsafe {
                    let watcher = (*alloc::boxed::Box::from_raw(watcher)).into_inner();
                    let guard = (&*computed).watch(move |ctx| {
                        let metadata: waterui::reactive::watcher::Metadata = ctx.metadata().clone();
                        let value = ctx.into_value();
                        let callback = alloc::rc::Rc::clone(&watcher);
                        callback(nami::watcher::Context::new(value, metadata));
                    });
                    $crate::IntoFFI::into_ffi(guard)
                }
            }

            #[cfg(feature = "c-api")]
            /// Drops a computed
            /// # Safety
            /// The caller must ensure that `computed` is a valid pointer.
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn [< waterui_drop_computed_ $ident >](computed: *mut $crate::reactive::WuiComputed<$ty>) {
                // SAFETY: the caller contract makes `computed` an owning pointer
                // from the matching FFI constructor, so reclaiming the box
                // frees it exactly once.
                unsafe { drop(alloc::boxed::Box::from_raw(computed)); }
            }

            // ========== Android JNI ==========
            #[cfg(feature = "android-jni")]
            /// JNI: Drops a computed
            #[unsafe(no_mangle)]
            extern "system" fn [<Java_dev_waterui_android_ffi_WatcherJni_dropComputed $ident:camel>]<'local>(
                _env: $crate::jni::JNIEnv<'local>,
                _class: $crate::jni::JClass<'local>,
                computed_ptr: $crate::jni::jlong,
            ) {
                unsafe { drop(alloc::boxed::Box::from_raw(computed_ptr as *mut $crate::reactive::WuiComputed<$ty>)) };
            }

            #[cfg(feature = "android-jni")]
            /// JNI: Watches for changes in a computed
            #[unsafe(no_mangle)]
            extern "system" fn [<Java_dev_waterui_android_ffi_WatcherJni_watchComputed $ident:camel>]<'local>(
                mut env: $crate::jni::JNIEnv<'local>,
                _class: $crate::jni::JClass<'local>,
                computed_ptr: $crate::jni::jlong,
                watcher: $crate::jni::JObject<'local>,
            ) -> $crate::jni::jlong {
                use waterui::Signal;
                use alloc::boxed::Box;
                use alloc::rc::Rc;
                use $crate::IntoFFI;

                $crate::jni::with_env(&mut env, |env| {
                let (data_ptr, call_ptr, drop_ptr) = $crate::jni::extract_watcher_struct(env, &watcher);

                // Cast function pointers
                let call_fn: unsafe extern "C" fn(*mut (), $ffi, *mut $crate::reactive::WuiWatcherMetadata) =
                    unsafe { core::mem::transmute(call_ptr as *const ()) };
                let drop_fn: unsafe extern "C" fn(*mut ()) =
                    unsafe { core::mem::transmute(drop_ptr as *const ()) };

                // Get the computed reference
                let computed = unsafe { &*(computed_ptr as *const $crate::reactive::WuiComputed<$ty>) };

                // Create a cleaner to ensure drop_fn is called when the watcher is dropped
                struct Cleaner {
                    data: *mut (),
                    drop_fn: unsafe extern "C" fn(*mut ()),
                }
                impl Drop for Cleaner {
                    fn drop(&mut self) {
                        unsafe { (self.drop_fn)(self.data) }
                    }
                }
                let cleaner = Rc::new(Cleaner {
                    data: data_ptr as *mut (),
                    drop_fn,
                });
                let cleaner_clone = cleaner.clone();

                // Register the watcher with the computed
                let guard = computed.watch(move |ctx: nami::watcher::Context<$ty>| {
                    let cleaner = Rc::clone(&cleaner_clone);
                    let metadata: waterui::reactive::watcher::Metadata = ctx.metadata().clone();
                    let value: $ty = ctx.into_value();
                    unsafe {
                        call_fn(cleaner.data, value.into_ffi(), metadata.into_ffi());
                    }
                });

                // Return the guard as a pointer
                let guard_box = Box::new($crate::reactive::WuiWatcherGuard(Box::new(guard)));
                Box::into_raw(guard_box) as $crate::jni::jlong
                })
            }

            $crate::ffi_watcher!($ty, $ffi, $ident);

            // ========== Android JNI ==========
            // Note: JNI reactive bindings require more complex struct conversions
            // and are implemented in ffi/src/jni/reactive.rs with helper functions.
            // The macros here generate stub functions that delegate to those helpers.
        }
    };

    ($ty:ty,$ffi:ty) => {
        pastey::paste! {
            $crate::ffi_computed!($ty, $ffi, [<$ty:snake>]);
        }
    }
}

/// Generates the native-controlled computed constructor.
///
/// Generates `waterui_new_computed_{ident}` for creating signals from native callbacks.
/// Requires the FFI type to implement `IntoRust`.
///
/// Only generated for `c-api` feature - JNI uses a different approach.
#[macro_export]
macro_rules! ffi_computed_ctor {
    ($ty:ty,$ffi:ty, $ident:tt) => {
        pastey::paste!{
            #[cfg(feature = "c-api")]
            /// Creates a computed signal from native callbacks.
            /// # Safety
            /// All function pointers must be valid and follow the expected calling conventions.
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn [< waterui_new_computed_ $ident >](
                data: *mut (),
                get: unsafe extern "C" fn(*const ()) -> $ffi,
                watch: unsafe extern "C" fn(*const (), *mut $crate::reactive::WuiWatcher<$ty>) -> *mut $crate::reactive::WuiWatcherGuard,
                drop: unsafe extern "C" fn(*mut ()),
            ) -> *mut $crate::reactive::WuiComputed<$ty>
            where
                $ty: $crate::IntoFFI + 'static,
                <$ty as $crate::IntoFFI>::FFI: $crate::IntoRust<Rust = $ty>,
            {
                // SAFETY: the caller contract requires these four to be one
                // registration from the backend.
                let computed = unsafe { $crate::reactive::WuiComputed::new(data, get, watch, drop) };
                alloc::boxed::Box::into_raw(alloc::boxed::Box::new(computed))
            }
        }
    };

    ($ty:ty,$ffi:ty) => {
        pastey::paste! {
            $crate::ffi_computed_ctor!($ty, $ffi, [<$ty:snake>]);
        }
    }
}

/// Generates binding FFI support for mutable reactive types.
///
/// When `c-api` feature is enabled, generates C FFI functions.
/// When `android-jni` feature is enabled, generates JNI functions.
///
/// # Generated Functions (C-API)
/// - `waterui_read_binding_{ident}` - read current value
/// - `waterui_set_binding_{ident}` - set value
/// - `waterui_watch_binding_{ident}` - subscribe to changes
/// - `waterui_drop_binding_{ident}` - cleanup
#[macro_export]
macro_rules! ffi_binding {
    ($ty:ty,$ffi:ty, $ident:tt) => {
        pastey::paste!{
            // ========== C-API (for Apple/GTK backends) ==========
            #[cfg(feature = "c-api")]
            /// Reads the current value from a binding
            /// # Safety
            /// The binding pointer must be valid and point to a properly initialized binding object.
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn [< waterui_read_binding_ $ident >](binding: *const $crate::reactive::WuiBinding<$ty>) -> $ffi {
                // SAFETY: the caller contract requires `binding` to be a valid handle
                // alive for this call; it is only borrowed.
                unsafe { (*binding).get().into_ffi() }
            }

            #[cfg(feature = "c-api")]
            /// Sets the value of a binding
            /// # Safety
            /// The binding pointer must be valid and point to a properly initialized binding object.
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn [< waterui_set_binding_ $ident >](binding: *mut $crate::reactive::WuiBinding<$ty>, value: $ffi) {
                // SAFETY: the caller contract requires `binding` to be a valid handle
                // and `value` an owning handle, consumed by the set.
                unsafe {
                    (*binding).set($crate::IntoRust::into_rust(value));
                }
            }

            #[cfg(feature = "c-api")]
            /// Watches for changes in a binding
            /// # Safety
            /// The binding pointer must be valid and point to a properly initialized binding object.
            /// The watcher pointer will be consumed and freed when the returned guard is dropped.
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn [< waterui_watch_binding_ $ident >](
                binding: *const $crate::reactive::WuiBinding<$ty>,
                watcher: *mut $crate::reactive::WuiWatcher<$ty>,
            ) -> *mut $crate::reactive::WuiWatcherGuard {
                use waterui::Signal;

                // SAFETY: as for the computed watch — `watcher` is owned and consumed,
                // `binding` is a valid handle that is only borrowed.
                unsafe {
                    let watcher = (*alloc::boxed::Box::from_raw(watcher)).into_inner();
                    let guard = (*binding).watch(move |ctx| {
                        let metadata: waterui::reactive::watcher::Metadata = ctx.metadata().clone();
                        let value = ctx.into_value();
                        let callback = alloc::rc::Rc::clone(&watcher);
                        callback(nami::watcher::Context::new(value, metadata));
                    });
                    guard.into_ffi()
                }
            }

            #[cfg(feature = "c-api")]
            /// Drops a binding
            /// # Safety
            /// The caller must ensure that `binding` is a valid pointer obtained from the corresponding FFI function.
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn [< waterui_drop_binding_ $ident >](binding: *mut $crate::reactive::WuiBinding<$ty>) {
                // SAFETY: the caller contract makes `binding` an owning pointer from
                // the matching constructor that has not been dropped.
                unsafe {
                    drop(alloc::boxed::Box::from_raw(binding));
                }
            }

            // ========== Android JNI ==========
            #[cfg(feature = "android-jni")]
            /// JNI: Drops a binding
            #[unsafe(no_mangle)]
            extern "system" fn [<Java_dev_waterui_android_ffi_WatcherJni_dropBinding $ident:camel>]<'local>(
                _env: $crate::jni::JNIEnv<'local>,
                _class: $crate::jni::JClass<'local>,
                binding_ptr: $crate::jni::jlong,
            ) {
                unsafe { drop(alloc::boxed::Box::from_raw(binding_ptr as *mut $crate::reactive::WuiBinding<$ty>)) };
            }

            #[cfg(feature = "android-jni")]
            /// JNI: Watches for changes in a binding
            #[unsafe(no_mangle)]
            extern "system" fn [<Java_dev_waterui_android_ffi_WatcherJni_watchBinding $ident:camel>]<'local>(
                mut env: $crate::jni::JNIEnv<'local>,
                _class: $crate::jni::JClass<'local>,
                binding_ptr: $crate::jni::jlong,
                watcher: $crate::jni::JObject<'local>,
            ) -> $crate::jni::jlong {
                use waterui::Signal;
                use alloc::boxed::Box;
                use alloc::rc::Rc;
                use $crate::IntoFFI;

                $crate::jni::with_env(&mut env, |env| {
                let (data_ptr, call_ptr, drop_ptr) = $crate::jni::extract_watcher_struct(env, &watcher);

                // Cast function pointers
                let call_fn: unsafe extern "C" fn(*mut (), $ffi, *mut $crate::reactive::WuiWatcherMetadata) =
                    unsafe { core::mem::transmute(call_ptr as *const ()) };
                let drop_fn: unsafe extern "C" fn(*mut ()) =
                    unsafe { core::mem::transmute(drop_ptr as *const ()) };

                // Get the binding reference
                let binding = unsafe { &*(binding_ptr as *const $crate::reactive::WuiBinding<$ty>) };

                // Create a cleaner to ensure drop_fn is called when the watcher is dropped
                struct Cleaner {
                    data: *mut (),
                    drop_fn: unsafe extern "C" fn(*mut ()),
                }
                impl Drop for Cleaner {
                    fn drop(&mut self) {
                        unsafe { (self.drop_fn)(self.data) }
                    }
                }
                let cleaner = Rc::new(Cleaner {
                    data: data_ptr as *mut (),
                    drop_fn,
                });
                let cleaner_clone = cleaner.clone();

                // Register the watcher with the binding
                let guard = binding.watch(move |ctx: nami::watcher::Context<$ty>| {
                    let cleaner = Rc::clone(&cleaner_clone);
                    let metadata: waterui::reactive::watcher::Metadata = ctx.metadata().clone();
                    let value: $ty = ctx.into_value();
                    unsafe {
                        call_fn(cleaner.data, value.into_ffi(), metadata.into_ffi());
                    }
                });

                // Return the guard as a pointer
                let guard_box = Box::new($crate::reactive::WuiWatcherGuard(Box::new(guard)));
                Box::into_raw(guard_box) as $crate::jni::jlong
                })
            }
        }
    };

    ($ty:ty,$ffi:ty) =>{
        pastey::paste!{
            $crate::ffi_binding!($ty,$ffi,[<$ty:snake>]);
        }
    }
}

/// Generates both binding and computed FFI support.
///
/// Use this for types that need two-way reactive binding support.
#[macro_export]
macro_rules! ffi_reactive {
    ($ty:ty,$ffi:ty, $ident:tt) => {
        $crate::ffi_binding!($ty, $ffi, $ident);
        $crate::ffi_computed!($ty, $ffi, $ident);
    };

    ($ty:ty,$ffi:ty) => {
        pastey::paste! {
            $crate::ffi_reactive!($ty, $ffi, [<$ty:snake>]);
        }
    };
}

ffi_binding!(Str, WuiStr);
#[cfg(feature = "c-api")]
ffi_computed!(Str, WuiStr);
ffi_binding!(StyledStr, WuiStyledStr, styled_str);

#[cfg(feature = "c-api")]
/// Sets a `Binding<StyledStr>` using borrowed UTF-8 bytes.
///
/// Native text controls can pass their current editor string without first
/// constructing an owned FFI `WuiStr`.
///
/// # Panics
/// Panics if `bytes` is null while `len` is non-zero.
///
/// # Safety
/// `binding` must be a valid pointer to `WuiBinding<StyledStr>`. `bytes` must
/// point to `len` valid UTF-8 bytes unless `len` is zero.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_set_binding_styled_str_utf8(
    binding: *mut WuiBinding<StyledStr>,
    bytes: *const u8,
    len: usize,
) {
    assert!(
        len == 0 || !bytes.is_null(),
        "waterui_set_binding_styled_str_utf8 received null bytes with non-zero length"
    );
    let bytes = if len == 0 {
        &[]
    } else {
        // SAFETY: the caller contract requires `bytes` to point at `len` initialized
        // bytes that stay alive for this call.
        unsafe { core::slice::from_raw_parts(bytes, len) }
    };
    // SAFETY: the caller contract requires those bytes to be valid UTF-8.
    let plain = unsafe { Str::from_utf8_unchecked(bytes.to_vec()) };
    // SAFETY: the caller contract requires `binding` to be a valid handle alive for
    // this call; it is only borrowed.
    unsafe { (*binding).set(StyledStr::plain(plain)) };
}

#[cfg(feature = "c-api")]
ffi_watcher!(AnyView, *mut WuiAnyView, any_view);

#[cfg(feature = "android-jni")]
ffi_binding!(i32, i32, int);
ffi_computed!(i32, i32, i32);

ffi_reactive!(bool, bool);

ffi_computed!(f32, f32, f32);

#[cfg(feature = "android-jni")]
ffi_binding!(f64, f64, double);
ffi_computed!(f64, f64, f64);

// The C ABI uses Rust primitive names consistently.
#[cfg(feature = "c-api")]
ffi_binding!(i32, i32, i32);
#[cfg(feature = "c-api")]
ffi_binding!(f32, f32, f32);
#[cfg(feature = "c-api")]
ffi_binding!(f64, f64, f64);

// ============================================================================
// JNI Primitive Reactive Macros
// ============================================================================
//
// The `JniPrimitive` trait is defined in `jni/convert.rs` and re-exported via `jni` module.
// These macros generate read/set functions for types implementing that trait.

/// Generates JNI read/set functions for primitive binding types.
///
/// Uses the `JniPrimitive` trait (from `jni::convert`) for type-safe conversion.
#[macro_export]
macro_rules! jni_binding_primitive {
    ($rust_ty:ty, $binding_name:tt) => {
        pastey::paste! {
            #[cfg(feature = "android-jni")]
            #[unsafe(no_mangle)]
            extern "system" fn [<Java_dev_waterui_android_ffi_WatcherJni_readBinding $binding_name:camel>]<'local>(
                _env: $crate::jni::JNIEnv<'local>,
                _class: $crate::jni::JClass<'local>,
                binding_ptr: $crate::jni::jlong,
            ) -> <$rust_ty as $crate::jni::JniPrimitive>::Jni {
                use $crate::jni::JniPrimitive;
                let binding = unsafe { &*(binding_ptr as *const $crate::reactive::WuiBinding<$rust_ty>) };
                binding.get().to_jni()
            }

            #[cfg(feature = "android-jni")]
            #[unsafe(no_mangle)]
            extern "system" fn [<Java_dev_waterui_android_ffi_WatcherJni_setBinding $binding_name:camel>]<'local>(
                _env: $crate::jni::JNIEnv<'local>,
                _class: $crate::jni::JClass<'local>,
                binding_ptr: $crate::jni::jlong,
                value: <$rust_ty as $crate::jni::JniPrimitive>::Jni,
            ) {
                use $crate::jni::JniPrimitive;
                let binding = unsafe { &*(binding_ptr as *const $crate::reactive::WuiBinding<$rust_ty>) };
                binding.set(<$rust_ty>::from_jni(value));
            }
        }
    };
}

/// Generates JNI read functions for primitive computed types.
#[macro_export]
macro_rules! jni_computed_primitive {
    ($rust_ty:ty, $computed_name:tt) => {
        pastey::paste! {
            #[cfg(feature = "android-jni")]
            #[unsafe(no_mangle)]
            extern "system" fn [<Java_dev_waterui_android_ffi_WatcherJni_readComputed $computed_name:camel>]<'local>(
                _env: $crate::jni::JNIEnv<'local>,
                _class: $crate::jni::JClass<'local>,
                computed_ptr: $crate::jni::jlong,
            ) -> <$rust_ty as $crate::jni::JniPrimitive>::Jni {
                use waterui::Signal;
                use $crate::jni::JniPrimitive;
                let computed = unsafe { &*(computed_ptr as *const $crate::reactive::WuiComputed<$rust_ty>) };
                computed.get().to_jni()
            }
        }
    };
}

// Generate JNI read/set for primitive bindings
// Note: Kotlin naming convention differs - Binding uses Java names (Int, Double, Float)
jni_binding_primitive!(bool, bool);
jni_binding_primitive!(i32, int);
jni_binding_primitive!(f64, double);

// Generate JNI read for primitive computed
// Note: Kotlin naming convention differs - Computed uses Rust names (I32, F64, F32)
jni_computed_primitive!(bool, bool);
jni_computed_primitive!(i32, i32);
jni_computed_primitive!(f32, f32);
jni_computed_primitive!(f64, f64);

// Date reactive bindings (using WuiDate FFI representation)
use crate::components::form::{WuiDate, WuiDateTime};
use jiff::civil::{Date, DateTime};
ffi_binding!(DateTime, WuiDateTime, date_time);
#[cfg(feature = "c-api")]
ffi_watcher!(DateTime, WuiDateTime, date_time);
ffi_reactive!(Vec<Date>, WuiArray<WuiDate>, date_vec);

/// FFI-owned wrapper around a native watcher callback.
///
/// Bridges a C function pointer pair (`call`/`drop`) into a Rust [`Watcher`]
/// that can be registered with a [`WuiComputed`] or [`WuiBinding`].
pub struct WuiWatcher<T: IntoFFI>(watcher::Watcher<T>);

impl<T: IntoFFI> fmt::Debug for WuiWatcher<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The inner `Watcher` is a reference-counted `dyn Fn` with no meaningful
        // Debug representation, so only the wrapper's identity is reported.
        f.debug_struct("WuiWatcher").finish_non_exhaustive()
    }
}

impl<T: IntoFFI> WuiWatcher<T> {
    /// Creates a new FFI watcher using C-style function pointers.
    ///
    /// # Safety
    /// The caller must ensure that the provided function pointers are valid and adhere to the expected signatures
    pub unsafe fn new(
        data: *mut (),
        call: unsafe extern "C" fn(*mut (), T::FFI, *mut WuiWatcherMetadata),
        drop: unsafe extern "C" fn(*mut ()),
    ) -> Self {
        struct Cleaner {
            data: *mut (),
            drop: unsafe extern "C" fn(*mut ()),
        }

        impl Drop for Cleaner {
            fn drop(&mut self) {
                // SAFETY: `drop` and `data` are one registration, and `Drop` runs
                // once.
                unsafe { (self.drop)(self.data) }
            }
        }
        let cleaner = Rc::new(Cleaner { data, drop });
        Self(Rc::new(move |ctx| {
            let cleaner = Rc::clone(&cleaner);
            let metadata: waterui::reactive::watcher::Metadata = ctx.metadata().clone();
            let value = ctx.into_value();
            // SAFETY: `call` and `cleaner.data` are one registration, and the `Rc`
            // captured here keeps the cleaner (and therefore the data) alive for every
            // invocation.
            unsafe {
                call(cleaner.data, value.into_ffi(), metadata.into_ffi());
            }
        }))
    }

    pub(crate) fn into_inner(self) -> Watcher<T> {
        self.0
    }

    pub(crate) fn call(&self, value: T, metadata: Metadata) {
        let watcher = Rc::clone(&self.0);
        watcher(Context::new(value, metadata));
    }
}

impl<T: IntoFFI> IntoFFI for Watcher<T> {
    type FFI = *mut WuiWatcher<T>;
    fn into_ffi(self) -> Self::FFI {
        Box::into_raw(Box::new(WuiWatcher(self)))
    }
}

/// Creates a new watcher guard from raw data and a drop function.
///
/// # Safety
/// The caller must ensure that the provided data pointer and drop function are valid.
#[cfg(feature = "c-api")]
#[unsafe(no_mangle)]
pub extern "C" fn waterui_new_watcher_guard(
    data: *mut (),
    drop: unsafe extern "C" fn(*mut ()),
) -> *mut WuiWatcherGuard {
    struct Cleaner {
        data: *mut (),
        drop: unsafe extern "C" fn(*mut ()),
    }

    impl Drop for Cleaner {
        fn drop(&mut self) {
            // SAFETY: `drop` and `data` are one registration, and `Drop` runs once.
            unsafe { (self.drop)(self.data) }
        }
    }

    impl WatcherGuard for Cleaner {}

    let cleaner = Cleaner { data, drop };
    Box::into_raw(Box::new(WuiWatcherGuard(Box::new(cleaner))))
}

// Custom Secure binding implementation
// Secure uses WuiStr for FFI, but converts to/from Secure on the Rust side
#[cfg(feature = "c-api")]
use waterui_form::secure::Secure;

/// Reads the current value from a Secure binding
/// # Safety
/// The binding pointer must be valid and point to a properly initialized binding object.
#[cfg(feature = "c-api")]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_read_binding_secure(binding: *const WuiBinding<Secure>) -> WuiStr {
    use alloc::string::String;
    // SAFETY: the caller contract requires `binding` to be a valid handle alive for
    // this call; it is only borrowed.
    unsafe {
        let secure = (*binding).get();
        // Create an owned String, then convert to Str
        let owned_string = String::from(secure.expose());
        Str::from(owned_string).into_ffi()
    }
}

/// Sets the value of a Secure binding
/// # Safety
/// The binding pointer must be valid and point to a properly initialized binding object.
#[cfg(feature = "c-api")]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_set_binding_secure(
    binding: *mut WuiBinding<Secure>,
    value: WuiStr,
) {
    // SAFETY: the caller contract requires `binding` to be a valid handle and `value`
    // an owning string handle, consumed here.
    unsafe {
        let str_value: Str = value.into_rust();
        (*binding).set(Secure::new(str_value.into_string()));
    }
}

/// Watches for changes in a Secure binding
/// # Safety
/// The binding pointer must be valid and point to a properly initialized binding object.
/// The watcher pointer will be consumed and freed when the returned guard is dropped.
#[cfg(feature = "c-api")]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_watch_binding_secure(
    binding: *const WuiBinding<Secure>,
    watcher: *mut WuiWatcher<Secure>,
) -> *mut WuiWatcherGuard {
    use waterui::Signal;

    // SAFETY: the caller contract makes `watcher` an owning pointer consumed here and
    // `binding` a valid handle that is only borrowed.
    unsafe {
        let watcher = (*Box::from_raw(watcher)).into_inner();
        let guard = (*binding).watch(move |ctx| {
            let metadata: waterui::reactive::watcher::Metadata = ctx.metadata().clone();
            let value = ctx.into_value();
            let callback = Rc::clone(&watcher);
            callback(Context::new(value, metadata));
        });
        guard.into_ffi()
    }
}

/// Drops a Secure binding
/// # Safety
/// The caller must ensure that `binding` is a valid pointer obtained from the corresponding FFI function.
#[cfg(feature = "c-api")]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_drop_binding_secure(binding: *mut WuiBinding<Secure>) {
    // SAFETY: the caller contract makes `binding` an owning pointer from the matching
    // constructor that has not been dropped.
    unsafe {
        drop(alloc::boxed::Box::from_raw(binding));
    }
}

/// Creates a watcher from native callbacks for Secure
/// # Safety
/// All function pointers must be valid.
#[cfg(feature = "c-api")]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_new_watcher_secure(
    data: *mut (),
    call: unsafe extern "C" fn(*mut (), WuiStr, *mut WuiWatcherMetadata),
    drop: unsafe extern "C" fn(*mut ()),
) -> *mut WuiWatcher<Secure> {
    use alloc::boxed::Box;
    // SAFETY: the caller contract requires `data`, `call` and `drop` to be one
    // registration from the backend.
    let watcher = unsafe { WuiWatcher::new(data, call, drop) };
    Box::into_raw(Box::new(watcher))
}

#[cfg(test)]
mod tests {
    use super::{WuiWatcher, WuiWatcherMetadata};
    use alloc::boxed::Box;
    use alloc::rc::Rc;
    use alloc::vec::Vec;
    use core::cell::RefCell;
    use nami::watcher::{Context, Metadata};

    struct NativeWatcherData {
        events: Rc<RefCell<Vec<&'static str>>>,
    }

    unsafe extern "C" fn record_call(
        data: *mut (),
        _value: u32,
        metadata: *mut WuiWatcherMetadata,
    ) {
        // SAFETY: the test registers this callback with a pointer to its own live
        // `NativeWatcherData`.
        let data = unsafe { &*data.cast::<NativeWatcherData>() };
        data.events.borrow_mut().push("call");
        // SAFETY: the watcher hands the callback an owning metadata handle to release.
        unsafe { super::waterui_drop_watcher_metadata(metadata) };
    }

    unsafe extern "C" fn record_drop(data: *mut ()) {
        // SAFETY: `data` is the boxed `NativeWatcherData` this drop entry was
        // registered with, and the watcher invokes it once.
        let data = unsafe { Box::from_raw(data.cast::<NativeWatcherData>()) };
        data.events.borrow_mut().push("drop");
    }

    #[test]
    fn native_watcher_data_lives_until_the_last_callback_owner_drops() {
        let events = Rc::new(RefCell::new(Vec::new()));
        let data = Box::into_raw(Box::new(NativeWatcherData {
            events: Rc::clone(&events),
        }))
        .cast();

        // SAFETY: `data` is the boxed test payload above, paired with the two entries
        // written for it.
        let watcher = unsafe { WuiWatcher::<u32>::new(data, record_call, record_drop) };
        let callback = watcher.into_inner();

        callback(Context::new(42, Metadata::new()));
        assert_eq!(&*events.borrow(), &["call"]);

        drop(callback);
        assert_eq!(&*events.borrow(), &["call", "drop"]);
    }
}