Skip to main content

nativeview_engine/app/
pointer.rs

1//! `NvPointerApi` (`NV_IFACE_POINTER`): app pointer-capture requests across the `cdylib` C ABI.
2//! [`write_capture_requests`] is the `export_nv_app!` side, [`drain_capture_requests`] the
3//! loader / runtime side; both bounded by [`MAX_ACTIVE_POINTERS`] with no allocation.
4
5use nativeview_abi::{NvAppHandle, NvPointerApi, NvPointerCaptureRequest};
6
7use crate::tracker::{PointerCaptureRequest, MAX_ACTIVE_POINTERS};
8use crate::NvApp;
9
10/// Drains `app`'s capture requests into `out[..cap]`, returning how many it wrote.
11///
12/// # Safety
13/// `out` must be NULL or writable for `cap` records.
14pub unsafe fn write_capture_requests<A: NvApp>(
15    app: &mut A,
16    out: *mut NvPointerCaptureRequest,
17    cap: u32,
18) -> u32 {
19    let mut n = 0u32;
20    app.drain_pointer_capture_requests(&mut |r| {
21        if !out.is_null() && n < cap {
22            // SAFETY: `n < cap` and the caller guarantees `out` is writable for `cap` records.
23            unsafe { out.add(n as usize).write(r.to_abi()) };
24            n += 1;
25        }
26    });
27    n
28}
29
30/// Drains the capture requests of `api`'s app `handle` into `sink`, dropping malformed records.
31///
32/// # Safety
33/// `handle` must be the live app handle of the module `api` was resolved from.
34pub unsafe fn drain_capture_requests(
35    api: NvPointerApi,
36    handle: NvAppHandle,
37    sink: &mut dyn FnMut(PointerCaptureRequest),
38) {
39    let mut out = [NvPointerCaptureRequest::default(); MAX_ACTIVE_POINTERS];
40    // SAFETY: `out` is writable for `MAX_ACTIVE_POINTERS` records; the caller guarantees `handle`.
41    let n = unsafe { (api.drain_capture_requests)(handle, out.as_mut_ptr(), out.len() as u32) };
42    for r in out.iter().take(n as usize) {
43        if let Some(r) = PointerCaptureRequest::from_abi(*r) {
44            sink(r);
45        }
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use std::ffi::c_void;
52
53    use nativeview_abi::{
54        FrameId, InterfaceId, NodeId, NvPointerApi, NvPointerCaptureRequest, NvSurfaceApi, SurfaceId,
55        ValidatedEvents, NV_IFACE_POINTER, NV_IFACE_SURFACE,
56    };
57
58    use super::*;
59    use crate::tracker::{PointerKey, PointerType};
60
61    /// Queues one request per pointer `0..12` (more than `MAX_ACTIVE_POINTERS`) on each dispatch.
62    struct CaptureApp(Vec<PointerCaptureRequest>);
63
64    fn request(id: u32) -> PointerCaptureRequest {
65        PointerCaptureRequest {
66            key: PointerKey::new(PointerType::Touch, id),
67            node: NodeId::from_raw_or_null(id + 1),
68            capture: id.is_multiple_of(2),
69        }
70    }
71
72    impl NvApp for CaptureApp {
73        fn create(_: SurfaceId) -> Self {
74            Self(Vec::new())
75        }
76        fn render(&mut self, _: FrameId) -> &[u8] {
77            &[]
78        }
79        fn dispatch_events(&mut self, _: ValidatedEvents<'_>) -> bool {
80            self.0 = (0..12).map(request).collect();
81            false
82        }
83        fn drain_pointer_capture_requests(&mut self, sink: &mut dyn FnMut(PointerCaptureRequest)) {
84            self.0.drain(..).for_each(sink);
85        }
86    }
87
88    crate::export_nv_app!(CaptureApp, symbol = test_capture_app_get_interface);
89
90    unsafe extern "C" {
91        fn test_capture_app_get_interface(interface_id: InterfaceId) -> *const c_void;
92    }
93
94    #[test]
95    fn capture_requests_cross_the_cdylib_abi_bounded_and_validated() {
96        // SAFETY: The locally exported `export_nv_app!` tables; the handle is destroyed below.
97        unsafe {
98            let surface = *(test_capture_app_get_interface(NV_IFACE_SURFACE) as *const NvSurfaceApi);
99            let api = *(test_capture_app_get_interface(NV_IFACE_POINTER) as *const NvPointerApi);
100            let mut out = [NvPointerCaptureRequest::default(); 4];
101            assert_eq!((api.drain_capture_requests)(core::ptr::null_mut(), out.as_mut_ptr(), 4), 0);
102
103            let handle = (surface.create)(SurfaceId::new(1, 0));
104            let dispatch = |h| (surface.dispatch_events)(h, nativeview_abi::NvEventBatch::EMPTY);
105            let _ = dispatch(handle);
106            // The loader side keeps the first `MAX_ACTIVE_POINTERS` (oldest first), drops the rest.
107            let mut got = Vec::new();
108            drain_capture_requests(api, handle, &mut |r| got.push(r));
109            assert_eq!(got, (0..MAX_ACTIVE_POINTERS as u32).map(request).collect::<Vec<_>>());
110            // Drained: nothing left. A small `cap` and a NULL `out` write at most `cap` / nothing.
111            assert_eq!((api.drain_capture_requests)(handle, out.as_mut_ptr(), 4), 0);
112            let _ = dispatch(handle);
113            assert_eq!((api.drain_capture_requests)(handle, out.as_mut_ptr(), 2), 2);
114            assert_eq!(out[..2], [request(0).to_abi(), request(1).to_abi()]);
115            let _ = dispatch(handle);
116            assert_eq!((api.drain_capture_requests)(handle, core::ptr::null_mut(), 4), 0);
117            (surface.destroy)(handle);
118        }
119        // Malformed records from a foreign module are dropped, valid ones round-trip.
120        let ok = request(3).to_abi();
121        assert_eq!(PointerCaptureRequest::from_abi(ok), Some(request(3)));
122        for bad in [
123            NvPointerCaptureRequest { kind: 9, ..ok },
124            NvPointerCaptureRequest { capture: 2, ..ok },
125            NvPointerCaptureRequest { _pad: 1, ..ok },
126        ] {
127            assert_eq!(PointerCaptureRequest::from_abi(bad), None);
128        }
129    }
130}