nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
use std::cell::Cell;
use std::ffi::c_void;

use nativeview_abi::{
    EventBatchBuf, InterfaceId, NodeId, NvBufferSlice, NvComponentApi, NvDevApi, NvEventBatch,
    NvGestureDisposition, NvHostApi, NvHostCallbacks, NvIntrinsicSize, NvLayoutApi,
    NvMapEntry, NvPropsRef, NvSizeConstraints, NvSurfaceApi, NvValue, TimestampUs,
    ValidatedEvents, NV_IFACE_COMPONENT, NV_IFACE_DEV, NV_IFACE_HOST, NV_IFACE_LAYOUT,
    NV_IFACE_SURFACE,
};

use super::*;

#[derive(Clone, Copy, PartialEq, Eq)]
enum PanicTarget {
    None,
    Create,
    Render,
    DispatchEvents,
    Measure,
    HitTest,
    SetProps,
    DrainEmittedEvents,
    ApplyHotPatch,
    SnapshotState,
    RestoreState,
    BindHost,
    DispatchHostEvents,
    Destroy,
    NonStringPayload,
}

thread_local! {
    static PANIC_TARGET: Cell<PanicTarget> = const { Cell::new(PanicTarget::None) };
}

fn set_panic_target(target: PanicTarget) {
    PANIC_TARGET.with(|cell| cell.set(target));
}

fn current_panic_target() -> PanicTarget {
    PANIC_TARGET.with(Cell::get)
}

struct PanickingTestApp {
    surface_id: SurfaceId,
    frame_buf: Vec<u8>,
    emitted_buf: EventBatchBuf,
    state_buf: Vec<u8>,
}

impl Drop for PanickingTestApp {
    fn drop(&mut self) {
        if current_panic_target() == PanicTarget::Destroy {
            panic!("boom in destroy for {}", self.surface_id);
        }
    }
}

impl NvApp for PanickingTestApp {
    fn create(surface_id: SurfaceId) -> Self {
        match current_panic_target() {
            PanicTarget::Create => panic!("boom in create"),
            PanicTarget::NonStringPayload => std::panic::panic_any(404u32),
            _ => {
                let mut emitted_buf = EventBatchBuf::new();
                emitted_buf.push_press(surface_id, NodeId::ROOT, TimestampUs(10), 1.0, 2.0);
                Self {
                    surface_id,
                    frame_buf: vec![0xAA, 0xBB],
                    emitted_buf,
                    state_buf: vec![1, 2, 3],
                }
            }
        }
    }

    fn render(&mut self, frame_id: FrameId) -> &[u8] {
        if current_panic_target() == PanicTarget::Render {
            panic!("boom in render frame {frame_id}");
        }
        &self.frame_buf
    }

    fn dispatch_events(&mut self, _events: ValidatedEvents<'_>) -> bool {
        if current_panic_target() == PanicTarget::DispatchEvents {
            panic!("boom in dispatch_events");
        }
        true
    }

    fn measure(&mut self, _constraints: NvSizeConstraints) -> NvIntrinsicSize {
        if current_panic_target() == PanicTarget::Measure {
            panic!("boom in measure");
        }
        NvIntrinsicSize {
            width: 123.0,
            height: 45.0,
        }
    }

    fn hit_test(&mut self, _x: f32, _y: f32, _pointer_phase: u8) -> NvGestureDisposition {
        if current_panic_target() == PanicTarget::HitTest {
            panic!("boom in hit_test");
        }
        NvGestureDisposition::Claim
    }

    fn set_props(&mut self, _props: NvPropsRef<'_>) -> bool {
        if current_panic_target() == PanicTarget::SetProps {
            panic!("boom in set_props");
        }
        true
    }

    fn drain_emitted_events(&mut self) -> ValidatedEvents<'_> {
        if current_panic_target() == PanicTarget::DrainEmittedEvents {
            panic!("boom in drain_emitted_events");
        }
        self.emitted_buf.as_validated()
    }

    fn apply_hot_patch(&mut self, _patch: &crate::HotPatchMsg) -> bool {
        if current_panic_target() == PanicTarget::ApplyHotPatch {
            panic!("boom in apply_hot_patch");
        }
        true
    }

    fn snapshot_state(&mut self) -> &[u8] {
        if current_panic_target() == PanicTarget::SnapshotState {
            panic!("boom in snapshot_state");
        }
        &self.state_buf
    }

    fn restore_state(&mut self, state: &[u8]) {
        if current_panic_target() == PanicTarget::RestoreState {
            panic!("boom in restore_state");
        }
        self.state_buf = state.to_vec();
    }

    fn bind_host(&mut self, _callbacks: Option<NvHostCallbacks>) {
        if current_panic_target() == PanicTarget::BindHost {
            panic!("boom in bind_host");
        }
    }

    fn dispatch_host_events(&mut self, _batch: &[u8]) -> bool {
        if current_panic_target() == PanicTarget::DispatchHostEvents {
            panic!("boom in dispatch_host_events");
        }
        true
    }
}

crate::export_nv_app!(PanickingTestApp, symbol = test_panicking_app_get_interface);

unsafe extern "C" {
    fn test_panicking_app_get_interface(interface_id: InterfaceId) -> *const c_void;
}

#[test]
fn export_nv_app_catches_panics_across_all_12_shims_and_null_handles() {
    clear_last_ffi_panic();
    set_panic_target(PanicTarget::None);

    // SAFETY: Tests the locally exported `export_nv_app!` C ABI tables, panic catch-unwind
    // boundaries, null-handle guards, and balanced create/destroy lifecycle.
    unsafe {
        let surface =
            &*(test_panicking_app_get_interface(NV_IFACE_SURFACE) as *const NvSurfaceApi);
        let layout =
            &*(test_panicking_app_get_interface(NV_IFACE_LAYOUT) as *const NvLayoutApi);
        let component =
            &*(test_panicking_app_get_interface(NV_IFACE_COMPONENT) as *const NvComponentApi);
        let dev = &*(test_panicking_app_get_interface(NV_IFACE_DEV) as *const NvDevApi);
        let host = &*(test_panicking_app_get_interface(NV_IFACE_HOST) as *const NvHostApi);

        // 0. Null handle guards across all 12 handle-taking shims (no dereference, no panic).
        let null_h = std::ptr::null_mut();
        assert_eq!((surface.render)(null_h, FrameId(1)).len, 0);
        assert_eq!((surface.dispatch_events)(null_h, NvEventBatch::EMPTY), 0);
        assert_eq!(
            (layout.measure)(null_h, NvSizeConstraints::loose(100.0, 100.0)),
            NvIntrinsicSize {
                width: 0.0,
                height: 0.0
            }
        );
        assert_eq!(
            (layout.hit_test)(null_h, 0.0, 0.0, 0),
            NvGestureDisposition::PassThrough as u8
        );
        assert_eq!((component.set_props)(null_h, std::ptr::null(), 0), 0);
        assert_eq!((component.drain_emitted_events)(null_h).event_count, 0);
        assert_eq!((dev.apply_hot_patch)(null_h, NvBufferSlice::EMPTY), 0);
        assert_eq!((dev.snapshot_state)(null_h).len, 0);
        (dev.restore_state)(null_h, NvBufferSlice::EMPTY);
        (host.bind_host)(null_h, std::ptr::null());
        assert_eq!((host.dispatch_host_events)(null_h, NvBufferSlice::EMPTY), 0);
        (surface.destroy)(null_h);
        assert_eq!(last_ffi_panic(), None);

        // 1. Panicking `create` returns null and records message; non-string payloads also work.
        set_panic_target(PanicTarget::Create);
        let h_fail = (surface.create)(SurfaceId::new(7, 0));
        assert!(h_fail.is_null());
        let peeked = last_ffi_panic().expect("create panic recorded");
        assert!(peeked.contains("NvSurfaceApi::create"));
        assert!(peeked.contains("boom in create"));
        assert_eq!(take_last_ffi_panic(), Some(peeked));
        assert_eq!(last_ffi_panic(), None);

        set_panic_target(PanicTarget::NonStringPayload);
        let h_non_str = (surface.create)(SurfaceId::new(8, 0));
        assert!(h_non_str.is_null());
        let non_str_msg = take_last_ffi_panic().expect("non-string panic recorded");
        assert!(non_str_msg.contains("non-string panic payload"));

        // 2. Normal create + verify happy path does not record any panic, AND verify non-canonical
        // index-0 SurfaceId from C PODs is canonicalized to `SurfaceId::NULL` at FFI ingress.
        set_panic_target(PanicTarget::None);
        // SAFETY: `SurfaceId` is `#[repr(transparent)]` over `u32`; simulating raw C POD bits.
        let non_canonical_sid = core::mem::transmute::<u32, SurfaceId>(0x0500_0000);
        let h_canon = (surface.create)(non_canonical_sid);
        assert!(!h_canon.is_null());
        assert_eq!((*(h_canon as *const PanickingTestApp)).surface_id, SurfaceId::NULL);
        (surface.destroy)(h_canon);

        let handle = (surface.create)(SurfaceId::new(42, 0));
        assert!(!handle.is_null());
        assert_eq!((surface.render)(handle, FrameId(1)).as_slice(), &[0xAA, 0xBB]);
        assert_eq!(
            (layout.measure)(handle, NvSizeConstraints::loose(300.0, 200.0)),
            NvIntrinsicSize {
                width: 123.0,
                height: 45.0
            }
        );
        assert_eq!(
            (layout.hit_test)(handle, 1.0, 2.0, 0),
            NvGestureDisposition::Claim as u8
        );
        assert_eq!(last_ffi_panic(), None);

        // 3. Verify every remaining shim survives panics and returns its exact sentinel.
        set_panic_target(PanicTarget::Render);
        let r = (surface.render)(handle, FrameId(99));
        assert!(r.ptr.is_null() && r.len == 0);
        let msg = take_last_ffi_panic().unwrap();
        assert!(msg.contains("NvSurfaceApi::render") && msg.contains("boom in render frame 99"));

        set_panic_target(PanicTarget::DispatchEvents);
        let mut ev_buf = EventBatchBuf::new();
        ev_buf.push_press(SurfaceId::new(42, 0), NodeId::new(2, 0), TimestampUs(100), 1.0, 2.0);
        assert_eq!((surface.dispatch_events)(handle, ev_buf.as_raw_batch()), 0);
        let msg = take_last_ffi_panic().unwrap();
        assert!(
            msg.contains("NvSurfaceApi::dispatch_events")
                && msg.contains("boom in dispatch_events")
        );

        set_panic_target(PanicTarget::Measure);
        assert_eq!(
            (layout.measure)(handle, NvSizeConstraints::loose(100.0, 100.0)),
            NvIntrinsicSize {
                width: 0.0,
                height: 0.0
            }
        );
        let msg = take_last_ffi_panic().unwrap();
        assert!(msg.contains("NvLayoutApi::measure") && msg.contains("boom in measure"));

        set_panic_target(PanicTarget::HitTest);
        assert_eq!(
            (layout.hit_test)(handle, 5.0, 6.0, 1),
            NvGestureDisposition::PassThrough as u8
        );
        let msg = take_last_ffi_panic().unwrap();
        assert!(msg.contains("NvLayoutApi::hit_test") && msg.contains("boom in hit_test"));

        set_panic_target(PanicTarget::SetProps);
        let entries = [NvMapEntry::new("k", NvValue::i64(1))];
        assert_eq!(
            (component.set_props)(handle, entries.as_ptr(), entries.len() as u32),
            0
        );
        let msg = take_last_ffi_panic().unwrap();
        assert!(msg.contains("NvComponentApi::set_props") && msg.contains("boom in set_props"));

        set_panic_target(PanicTarget::DrainEmittedEvents);
        let drained = (component.drain_emitted_events)(handle);
        assert!(drained.events.is_null() && drained.event_count == 0);
        let msg = take_last_ffi_panic().unwrap();
        assert!(
            msg.contains("NvComponentApi::drain_emitted_events")
                && msg.contains("boom in drain_emitted_events")
        );

        set_panic_target(PanicTarget::ApplyHotPatch);
        let patch = crate::HotPatchMsg::DevStatus {
            message: "x".into(),
            latency_ms: 0,
        }
        .to_bytes()
        .unwrap();
        assert_eq!(
            (dev.apply_hot_patch)(handle, NvBufferSlice::from_slice(&patch)),
            0
        );
        let msg = take_last_ffi_panic().unwrap();
        assert!(
            msg.contains("NvDevApi::apply_hot_patch") && msg.contains("boom in apply_hot_patch")
        );

        set_panic_target(PanicTarget::SnapshotState);
        let snap = (dev.snapshot_state)(handle);
        assert!(snap.ptr.is_null() && snap.len == 0);
        let msg = take_last_ffi_panic().unwrap();
        assert!(
            msg.contains("NvDevApi::snapshot_state") && msg.contains("boom in snapshot_state")
        );

        set_panic_target(PanicTarget::RestoreState);
        (dev.restore_state)(handle, NvBufferSlice::from_slice(&[9, 8, 7]));
        let msg = take_last_ffi_panic().unwrap();
        assert!(msg.contains("NvDevApi::restore_state") && msg.contains("boom in restore_state"));

        set_panic_target(PanicTarget::BindHost);
        let empty_cb = NvHostCallbacks::EMPTY;
        (host.bind_host)(handle, &empty_cb);
        let msg = take_last_ffi_panic().unwrap();
        assert!(msg.contains("NvHostApi::bind_host") && msg.contains("boom in bind_host"));

        set_panic_target(PanicTarget::DispatchHostEvents);
        assert_eq!(
            (host.dispatch_host_events)(handle, NvBufferSlice::from_slice(b"host")),
            0
        );
        let msg = take_last_ffi_panic().unwrap();
        assert!(
            msg.contains("NvHostApi::dispatch_host_events")
                && msg.contains("boom in dispatch_host_events")
        );

        // 4. Panicking `destroy` (Drop) survives without aborting and records the message.
        set_panic_target(PanicTarget::Destroy);
        (surface.destroy)(handle);
        let msg = take_last_ffi_panic().unwrap();
        assert!(
            msg.contains("NvSurfaceApi::destroy")
                && msg.contains("boom in destroy for surface(42,0)")
        );
        set_panic_target(PanicTarget::None);
        assert_eq!(last_ffi_panic(), None);
    }
}

#[derive(Default)]
struct DirectOnlyPropsApp {
    count: i64,
    route: String,
    nested_flag: bool,
    tag_count: usize,
}

impl NvApp for DirectOnlyPropsApp {
    fn create(_surface_id: SurfaceId) -> Self {
        Self::default()
    }

    fn render(&mut self, _frame_id: FrameId) -> &[u8] {
        &[]
    }

    fn dispatch_events(&mut self, _events: ValidatedEvents<'_>) -> bool {
        false
    }

    fn set_props(&mut self, props: NvPropsRef<'_>) -> bool {
        let mut changed = false;
        if let Some(c) = props.get("count").and_then(|v| v.as_i64()) {
            self.count = c;
            changed = true;
        }
        if let Some(r) = props.get("route").and_then(|v| v.as_str()) {
            self.route = r.to_owned();
            changed = true;
        }
        if let Some(flag) = props
            .get("meta")
            .and_then(|m| m.get("active"))
            .and_then(|v| v.as_bool())
        {
            self.nested_flag = flag;
            changed = true;
        }
        if let Some(tags) = props.get("tags").and_then(|v| v.as_array()) {
            self.tag_count = tags.len();
            changed = true;
        }
        changed
    }
}

#[test]
fn direct_set_props_reads_nested_maps_and_arrays_zero_copy() {
    let mut app = DirectOnlyPropsApp::create(SurfaceId::ROOT);
    let nested_entries = [NvMapEntry::new("active", NvValue::bool(true))];
    let tag_elems = [NvValue::from_str("a"), NvValue::from_str("b")];
    let entries = [
        NvMapEntry::new("count", NvValue::i64(77)),
        NvMapEntry::new("route", NvValue::from_str("/docs/abi")),
        NvMapEntry::new("meta", NvValue::map(&nested_entries)),
        NvMapEntry::new("tags", NvValue::array(&tag_elems)),
    ];

    // SAFETY: `entries` and its nested backing slices outlive the synchronous `set_props` call.
    assert!(app.set_props(unsafe { NvPropsRef::from_slice(&entries) }));
    assert_eq!(app.count, 77);
    assert_eq!(app.route, "/docs/abi");
    assert!(app.nested_flag);
    assert_eq!(app.tag_count, 2);
    assert!(!app.set_props(NvPropsRef::EMPTY));
}

#[deny(unsafe_code)]
mod deny_unsafe_export_smoke {
    use nativeview_abi::{FrameId, SurfaceId, ValidatedEvents};

    use crate::NvApp;

    struct SafeOnlyApp;

    impl NvApp for SafeOnlyApp {
        fn create(_surface_id: SurfaceId) -> Self {
            Self
        }

        fn render(&mut self, _frame_id: FrameId) -> &[u8] {
            &[]
        }

        fn dispatch_events(&mut self, _events: ValidatedEvents<'_>) -> bool {
            false
        }
    }

    crate::export_nv_app!(SafeOnlyApp, symbol = test_safe_only_app_get_interface);
}