Skip to main content

nativeview_abi/
ffi.rs

1//! Modular zero-cost C ABI (`nv_get_interface`) shared between Rust (`nativeview-engine`),
2//! `libnv_runtime` (which attaches app modules to its surfaces), ObjC++ (`hosts/apple-common`),
3//! Kotlin/JNI (`hosts/android-shell`, `packages/backends/{android,compose}`), Dart FFI (`packages/backends/flutter`),
4//! Swift (`hosts/swiftui-kit`), and Tier-2 hot-swappable app `cdylib`s.
5//!
6//! Instead of a monolithic vtable that grows on every feature, each NV module exports ONE
7//! entry point `nv_get_interface(uint32_t interface_id) -> *const c_void`. Hosts query the
8//! small 2–4 function `const` interface tables they need once at load time and call them directly
9//! in CPU registers (~1–2 ns overhead for scalar ops like `measure`/`hit_test`, and single-slice
10//! batched `CommandBuffer` / `EventRing` transfers for bulk per-frame tree mutations).
11
12use std::ffi::c_void;
13
14use nativeview_abi_macros::{NvAbi, ReprEnum};
15
16use crate::event::NvEventBatch;
17use crate::id::{FrameId, InterfaceId, NodeId, SurfaceId};
18use crate::value::{NvMapEntry, NvValueTag};
19
20/// Compile-time XXH64 schema fingerprint for NV's Core C ABI, derived directly from
21/// `crate::schema::core_abi_descriptor()` (zero hardcoded hex literals).
22pub const NV_CORE_ABI_SCHEMA_HASH: u64 = crate::schema::compute_core_abi_schema_hash();
23
24nativeview_abi_macros::abi_consts! {
25    pub(crate) const FFI_ABI_CONSTS;
26
27    /// Wire magic bytes (`"NV02"` little-endian).
28    #[nativeview_abi(hex)]
29    pub const NV_ABI_MAGIC: u32 = u32::from_le_bytes(*b"NV02");
30    /// Binary `NV02` wire protocol version.
31    pub const NV_ABI_VERSION: u32 = 1;
32    /// `NvSurfaceApi::dispatch_events` result bit: app state changed; render a new frame.
33    pub const NV_DISPATCH_RESULT_DIRTY: u32 = 1 << 0;
34    /// `NvSurfaceApi::dispatch_events` result bit: the batch carried a close request (an
35    /// `Escape` / `GoBack` key down no listener consumed); the runtime routes it to the topmost
36    /// open overlay that owns close requests.
37    pub const NV_DISPATCH_RESULT_CLOSE_REQUEST: u32 = 1 << 1;
38    /// `NvSurfaceApi::dispatch_events` result bit: the batch carried a `KeyDown` no app listener
39    /// consumed, making it eligible for post-dispatch runtime `DefaultAction`s.
40    pub const NV_DISPATCH_RESULT_UNCONSUMED_KEY: u32 = 1 << 2;
41}
42
43crate::define_bitflags! {
44    /// Typed `NvSurfaceApi::dispatch_events` result (`NV_DISPATCH_RESULT_*` bits).
45    #[derive(Default)]
46    pub struct DispatchResult(u32) {
47        /// App state changed; render a new frame.
48        const DIRTY = NV_DISPATCH_RESULT_DIRTY;
49        /// Unconsumed close request ([INV:close-request-single-path]).
50        const CLOSE_REQUEST = NV_DISPATCH_RESULT_CLOSE_REQUEST;
51        /// Unconsumed `KeyDown` eligible for post-dispatch `DefaultAction`s.
52        const UNCONSUMED_KEY = NV_DISPATCH_RESULT_UNCONSUMED_KEY;
53    }
54}
55
56impl DispatchResult {
57    /// Encodes one `NvApp` / `RuntimeApp` dispatch outcome (`dirty`, `close_request`).
58    #[inline]
59    pub const fn new(dirty: bool, close_request: bool) -> Self {
60        Self::from_parts(dirty, close_request, false)
61    }
62
63    /// Encodes one `NvApp` / `RuntimeApp` dispatch outcome including `unconsumed_key`.
64    #[inline]
65    pub const fn from_parts(dirty: bool, close_request: bool, unconsumed_key: bool) -> Self {
66        Self(
67            ((dirty as u32) * NV_DISPATCH_RESULT_DIRTY)
68                | ((close_request as u32) * NV_DISPATCH_RESULT_CLOSE_REQUEST)
69                | ((unconsumed_key as u32) * NV_DISPATCH_RESULT_UNCONSUMED_KEY),
70        )
71    }
72
73    #[inline]
74    pub const fn is_dirty(self) -> bool {
75        self.contains(Self::DIRTY)
76    }
77
78    #[inline]
79    pub const fn is_close_request(self) -> bool {
80        self.contains(Self::CLOSE_REQUEST)
81    }
82
83    #[inline]
84    pub const fn is_unconsumed_key(self) -> bool {
85        self.contains(Self::UNCONSUMED_KEY)
86    }
87}
88
89pub const NV_IFACE_SURFACE: InterfaceId = InterfaceId(1);
90pub const NV_IFACE_LAYOUT: InterfaceId = InterfaceId(2);
91pub const NV_IFACE_COMPONENT: InterfaceId = InterfaceId(3);
92pub const NV_IFACE_DEV: InterfaceId = InterfaceId(4);
93pub const NV_IFACE_HOST: InterfaceId = InterfaceId(5);
94/// Optional pointer interface ([`NvPointerApi`]; `6` is `NV_IFACE_DIRECT_HOST`).
95pub const NV_IFACE_POINTER: InterfaceId = InterfaceId(7);
96
97/// Pointer of a borrowed slab published across the C ABI: NULL when empty (every zero-count slab
98/// is published as NULL, never as a dangling non-null pointer).
99#[inline]
100pub fn slab_ptr<T>(slab: &[T]) -> *const T {
101    if slab.is_empty() {
102        core::ptr::null()
103    } else {
104        slab.as_ptr()
105    }
106}
107
108/// Borrowed immutable byte slice across the C ABI.
109#[repr(C)]
110#[derive(Debug, Clone, Copy, NvAbi)]
111#[nativeview_abi(size_64 = 16)]
112pub struct NvBufferSlice {
113    pub ptr: *const u8,
114    pub len: usize,
115}
116
117impl NvBufferSlice {
118    pub const EMPTY: Self = Self {
119        ptr: std::ptr::null(),
120        len: 0,
121    };
122
123    /// Borrows `s`; empty slices are `EMPTY` (NULL pointer, never a dangling one).
124    pub fn from_slice(s: &[u8]) -> Self {
125        if s.is_empty() {
126            return Self::EMPTY;
127        }
128        Self {
129            ptr: s.as_ptr(),
130            len: s.len(),
131        }
132    }
133
134    /// Validated raw-slice view returning `None` on a null pointer with `len > 0` or on
135    /// `len > isize::MAX`.
136    ///
137    /// # Safety
138    /// Caller must ensure `ptr` is valid for `len` bytes for the returned lifetime when `len > 0`.
139    #[inline]
140    pub unsafe fn try_as_slice<'a>(self) -> Option<&'a [u8]> {
141        // SAFETY: Caller guarantees `self.ptr` is valid for `self.len` bytes for `'a`.
142        unsafe { crate::value::guarded_slice(self.ptr, self.len) }
143    }
144
145    /// [`Self::try_as_slice`], with an invalid slice read as empty.
146    ///
147    /// # Safety
148    /// Caller must ensure `ptr` is valid for `len` bytes for the returned lifetime.
149    #[inline]
150    pub unsafe fn as_slice<'a>(self) -> &'a [u8] {
151        // SAFETY: Forwarded caller contract.
152        unsafe { self.try_as_slice() }.unwrap_or(&[])
153    }
154}
155
156/// Box layout constraints passed to `NvLayoutApi::measure`.
157#[repr(C)]
158#[derive(Debug, Clone, Copy, PartialEq, NvAbi)]
159#[nativeview_abi(size = 16)]
160pub struct NvSizeConstraints {
161    #[nativeview_abi(offset = 0)]
162    pub min_w: f32,
163    #[nativeview_abi(offset = 4)]
164    pub min_h: f32,
165    #[nativeview_abi(offset = 8)]
166    pub max_w: f32,
167    #[nativeview_abi(offset = 12)]
168    pub max_h: f32,
169}
170
171impl NvSizeConstraints {
172    pub const fn loose(max_w: f32, max_h: f32) -> Self {
173        Self {
174            min_w: 0.0,
175            min_h: 0.0,
176            max_w,
177            max_h,
178        }
179    }
180}
181
182/// Measured intrinsic dimensions returned by `NvLayoutApi::measure`.
183#[repr(C)]
184#[derive(Debug, Clone, Copy, PartialEq, Default, NvAbi)]
185#[nativeview_abi(size = 8)]
186pub struct NvIntrinsicSize {
187    #[nativeview_abi(offset = 0)]
188    pub width: f32,
189    #[nativeview_abi(offset = 4)]
190    pub height: f32,
191}
192
193
194/// Gesture arbitration disposition returned by `NvLayoutApi::hit_test`.
195#[repr(u8)]
196#[derive(Debug, Clone, Copy, PartialEq, Eq, NvAbi, ReprEnum)]
197#[nativeview_abi(c_prefix = "NV_GESTURE_", dart_fallback = "PassThrough")]
198#[repr_enum(fallback = PassThrough)]
199pub enum NvGestureDisposition {
200    Claim = 1,
201    PassThrough = 2,
202    DeferToParent = 3,
203}
204
205/// Validation / decoding errors shared across zero-copy FFI views and binary wire codecs.
206#[derive(Debug, Clone, PartialEq, Eq)]
207pub enum DecodeError {
208    Truncated,
209    InvalidMagic(u32),
210    UnsupportedVersion(u16),
211    UnknownOpcode(u8),
212    InvalidEnum(&'static str, u32),
213    InvalidUtf8,
214    TrailingBytes(usize),
215    MaxDepthExceeded,
216    /// A value's wire tag differs from the tag its declared type requires (`found` is the raw tag).
217    UnexpectedTag { expected: NvValueTag, found: u32 },
218    /// An integer does not fit the named declared type.
219    OutOfRange(&'static str),
220    /// A required struct field is absent.
221    MissingField(&'static str),
222    /// A string, byte run, container payload, or element count exceeds the wire format's `u32`.
223    TooLarge,
224    InvalidEvent(crate::event::EventValidationError),
225}
226
227impl std::fmt::Display for DecodeError {
228    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
229        write!(f, "{self:?}")
230    }
231}
232
233impl std::error::Error for DecodeError {}
234
235nativeview_abi_macros::abi_aliases! {
236    pub(crate) const FFI_ABI_ALIASES;
237
238    /// Opaque handle to an instantiated NV app/component.
239    pub type NvAppHandle = *mut c_void;
240}
241
242nativeview_abi_macros::abi_callbacks! {
243    pub(crate) const FFI_ABI_CALLBACKS;
244
245    /// Single exported entry point per NV module (`nv_get_interface`).
246    pub type NvGetInterfaceFn = unsafe extern "C" fn(interface_id: InterfaceId) -> *const c_void;
247}
248
249/// Required core surface interface (`NV_IFACE_SURFACE = 1`).
250#[repr(C)]
251#[derive(Debug, Clone, Copy, NvAbi)]
252#[nativeview_abi(interface = NV_IFACE_SURFACE)]
253pub struct NvSurfaceApi {
254    pub create: unsafe extern "C" fn(surface_id: SurfaceId) -> NvAppHandle,
255    pub destroy: unsafe extern "C" fn(handle: NvAppHandle),
256    pub render: unsafe extern "C" fn(handle: NvAppHandle, frame_id: FrameId) -> NvBufferSlice,
257    pub dispatch_events: unsafe extern "C" fn(handle: NvAppHandle, batch: NvEventBatch) -> u32,
258}
259
260/// Optional layout & gesture interface (`NV_IFACE_LAYOUT = 2`). Zero-serialization register calls.
261#[repr(C)]
262#[derive(Debug, Clone, Copy, NvAbi)]
263#[nativeview_abi(interface = NV_IFACE_LAYOUT)]
264pub struct NvLayoutApi {
265    pub measure:
266        unsafe extern "C" fn(handle: NvAppHandle, constraints: NvSizeConstraints) -> NvIntrinsicSize,
267    pub hit_test: unsafe extern "C" fn(
268        handle: NvAppHandle,
269        x: f32,
270        y: f32,
271        pointer_phase: u8,
272    ) -> u8,
273}
274
275/// Optional embedded component props & outbound event interface (`NV_IFACE_COMPONENT = 3`).
276#[repr(C)]
277#[derive(Debug, Clone, Copy, NvAbi)]
278#[nativeview_abi(interface = NV_IFACE_COMPONENT)]
279pub struct NvComponentApi {
280    pub set_props:
281        unsafe extern "C" fn(handle: NvAppHandle, entries: *const NvMapEntry, count: u32) -> u32,
282    pub drain_emitted_events: unsafe extern "C" fn(handle: NvAppHandle) -> NvEventBatch,
283}
284
285/// Optional dev / 2-tier hot-reload interface (`NV_IFACE_DEV = 4`, may be NULL in release builds).
286#[repr(C)]
287#[derive(Debug, Clone, Copy, NvAbi)]
288#[nativeview_abi(interface = NV_IFACE_DEV)]
289pub struct NvDevApi {
290    /// Applies one binary `NV_HOT_PATCH` `HotPatchMsg` frame exactly as broadcast by `nv dev`
291    /// (returns 1 when the app changed; 0 for non-template or malformed frames).
292    pub apply_hot_patch:
293        unsafe extern "C" fn(handle: NvAppHandle, patch: NvBufferSlice) -> u32,
294    pub snapshot_state: unsafe extern "C" fn(handle: NvAppHandle) -> NvBufferSlice,
295    pub restore_state: unsafe extern "C" fn(handle: NvAppHandle, state: NvBufferSlice),
296}
297
298/// One W3C `setPointerCapture` (`capture = 1`) / `releasePointerCapture` (`capture = 0`) call
299/// of an app listener: pointer `(kind: NV_POINTER_TYPE_*, id)` to / from `node`.
300#[repr(C)]
301#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, NvAbi)]
302#[nativeview_abi(size = 12)]
303pub struct NvPointerCaptureRequest {
304    #[nativeview_abi(offset = 0)]
305    pub node: NodeId,
306    #[nativeview_abi(offset = 4)]
307    pub id: u32,
308    #[nativeview_abi(offset = 8)]
309    pub kind: u8,
310    #[nativeview_abi(offset = 9)]
311    pub capture: u8,
312    #[nativeview_abi(offset = 10)]
313    pub _pad: u16,
314}
315
316/// Optional pointer interface (`NV_IFACE_POINTER = 7`): carries app pointer-capture requests
317/// out of a `cdylib` app.
318#[repr(C)]
319#[derive(Debug, Clone, Copy, NvAbi)]
320#[nativeview_abi(interface = NV_IFACE_POINTER)]
321pub struct NvPointerApi {
322    /// Moves up to `cap` capture requests of the last `dispatch_events` into `out` (oldest
323    /// first) and returns how many it wrote; the rest are dropped.
324    pub drain_capture_requests:
325        unsafe extern "C" fn(handle: NvAppHandle, out: *mut NvPointerCaptureRequest, cap: u32) -> u32,
326}
327
328#[cfg(test)]
329mod tests {
330    use std::path::Path;
331
332    use super::*;
333
334    #[test]
335    fn core_c_header_matches_compile_time_schema_hash_when_present() {
336        assert_ne!(NV_CORE_ABI_SCHEMA_HASH, 0);
337        let header_path = Path::new(env!("CARGO_MANIFEST_DIR"))
338            .join("../host-cxx/include/nv/generated/nv_abi.generated.h");
339        if !header_path.is_file() {
340            return;
341        }
342        let content = std::fs::read_to_string(&header_path)
343            .expect("read generated host-cxx nv_abi.generated.h");
344        let expected_macro = format!("0x{NV_CORE_ABI_SCHEMA_HASH:016X}ULL");
345        assert!(
346            content.contains(&expected_macro),
347            "nv_abi.generated.h schema hash drift! Expected {expected_macro} in {}",
348            header_path.display()
349        );
350    }
351}