1use std::any::Any;
9use std::cell::RefCell;
10
11use nativeview_abi::{
12 FrameId, HostServiceId, NvDirectHostEnv, NvGestureDisposition, NvHostCallbacks,
13 NvIntrinsicSize, NvPropsRef, NvSizeConstraints, SurfaceId, ValidatedEvents,
14};
15
16thread_local! {
17 static LAST_FFI_PANIC: RefCell<Option<String>> = const { RefCell::new(None) };
18}
19
20#[cold]
22#[inline(never)]
23#[expect(
24 clippy::disallowed_methods,
25 reason = "FFI catch_unwind panic payload boundary requires std::any::Any downcast"
26)]
27pub fn format_panic_payload(payload: &(dyn Any + Send)) -> String {
28 if let Some(s) = payload.downcast_ref::<&str>() {
29 (*s).to_owned()
30 } else if let Some(s) = payload.downcast_ref::<String>() {
31 s.clone()
32 } else {
33 "non-string panic payload".to_owned()
34 }
35}
36
37#[cold]
39#[inline(never)]
40#[doc(hidden)]
41pub fn record_ffi_panic(fn_name: &'static str, payload: Box<dyn Any + Send>) {
42 let detail = format_panic_payload(&*payload);
43 let msg = format!("{fn_name}: {detail}");
44 LAST_FFI_PANIC.with(|slot| {
45 *slot.borrow_mut() = Some(msg);
46 });
47}
48
49pub fn last_ffi_panic() -> Option<String> {
52 LAST_FFI_PANIC.with(|slot| slot.borrow().clone())
53}
54
55pub fn take_last_ffi_panic() -> Option<String> {
58 LAST_FFI_PANIC.with(|slot| slot.borrow_mut().take())
59}
60
61pub fn clear_last_ffi_panic() {
63 LAST_FFI_PANIC.with(|slot| {
64 let _ = slot.borrow_mut().take();
65 });
66}
67
68#[inline(always)]
74#[doc(hidden)]
75pub fn ffi_catch_unwind<T, F>(fn_name: &'static str, fallback: T, f: F) -> T
76where
77 F: FnOnce() -> T,
78{
79 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
80 Ok(val) => val,
81 Err(payload) => {
82 record_ffi_panic(fn_name, payload);
83 fallback
84 }
85 }
86}
87
88#[inline]
90pub fn default_measure_constraints(constraints: NvSizeConstraints) -> NvIntrinsicSize {
91 let w = if constraints.max_w.is_finite() {
92 constraints.max_w.max(constraints.min_w)
93 } else {
94 constraints.min_w
95 };
96 let h = if constraints.max_h.is_finite() {
97 constraints.max_h.max(constraints.min_h)
98 } else {
99 constraints.min_h
100 };
101 NvIntrinsicSize {
102 width: w,
103 height: h,
104 }
105}
106
107pub trait NvApp: Sized + 'static {
108 fn create(surface_id: SurfaceId) -> Self;
109
110 fn render(&mut self, frame_id: FrameId) -> &[u8];
112
113 fn dispatch_events(&mut self, events: ValidatedEvents<'_>) -> bool;
115
116 fn take_close_request(&mut self) -> bool {
120 false
121 }
122
123 fn take_unconsumed_key(&mut self) -> bool {
126 false
127 }
128
129 fn drain_pointer_capture_requests(
133 &mut self,
134 _sink: &mut dyn FnMut(crate::tracker::PointerCaptureRequest),
135 ) {
136 }
137
138 fn poll_work(&mut self, _waker: &core::task::Waker) -> bool {
141 false
142 }
143
144 fn measure(&mut self, constraints: NvSizeConstraints) -> NvIntrinsicSize {
146 default_measure_constraints(constraints)
147 }
148
149 fn hit_test(&mut self, _x: f32, _y: f32, _pointer_phase: u8) -> NvGestureDisposition {
151 NvGestureDisposition::PassThrough
152 }
153
154 fn set_props(&mut self, _props: NvPropsRef<'_>) -> bool {
156 false
157 }
158
159 fn drain_emitted_events(&mut self) -> ValidatedEvents<'_> {
161 ValidatedEvents::EMPTY
162 }
163
164 fn apply_hot_patch(&mut self, _patch: &crate::HotPatchMsg) -> bool {
167 false
168 }
169
170 fn snapshot_state(&mut self) -> &[u8] {
172 &[]
173 }
174
175 fn restore_state(&mut self, _state: &[u8]) {}
177
178 fn bind_host(&mut self, _callbacks: Option<NvHostCallbacks>) {}
181
182 fn dispatch_host_events(&mut self, _batch: &[u8]) -> bool {
185 false
186 }
187
188 fn bind_direct_host(&mut self, _env: Option<NvDirectHostEnv>) {}
190
191 fn dispatch_direct_completion(
193 &mut self,
194 _local_req_id: u64,
195 _status: i32,
196 _payload: &[u8],
197 ) -> bool {
198 false
199 }
200
201 fn dispatch_direct_event(
203 &mut self,
204 _service_id: HostServiceId,
205 _event_id: u32,
206 _flags: u32,
207 _payload: &[u8],
208 ) -> bool {
209 false
210 }
211}
212
213#[macro_export]
216macro_rules! export_nv_app {
217 ($app_ty:ty) => {
218 $crate::export_nv_app!($app_ty, symbol = nv_get_interface);
219 };
220 ($app_ty:ty, symbol = $symbol:ident) => {
221 #[allow(unsafe_code)]
222 const _: () = {
223 use ::std::ffi::c_void;
224 use $crate::abi::{
225 DispatchResult, FrameId, HostServiceId, InterfaceId, NvAppHandle, NvBufferSlice,
226 NvComponentApi,
227 NvDevApi, NvDirectHostApi, NvDirectHostEnv, NvEventBatch,
228 NvGestureDisposition, NvHostApi, NvHostCallbacks, NvIntrinsicSize,
229 NvLayoutApi, NvMapEntry, NvPointerApi, NvPointerCaptureRequest, NvPropsRef,
230 NvSizeConstraints, NvSurfaceApi, SurfaceId, ValidatedEvents, NV_IFACE_COMPONENT,
231 NV_IFACE_DEV, NV_IFACE_DIRECT_HOST, NV_IFACE_HOST, NV_IFACE_LAYOUT,
232 NV_IFACE_POINTER, NV_IFACE_SURFACE,
233 };
234 use $crate::NvApp;
235
236 unsafe extern "C" fn __nv_create(surface_id: SurfaceId) -> NvAppHandle {
237 $crate::app::ffi_catch_unwind(
238 "NvSurfaceApi::create",
239 ::std::ptr::null_mut(),
240 || {
241 let canonical = SurfaceId::from_raw_or_null(surface_id.raw());
242 let boxed = Box::new(<$app_ty as NvApp>::create(canonical));
243 Box::into_raw(boxed) as NvAppHandle
244 },
245 )
246 }
247
248 unsafe extern "C" fn __nv_destroy(handle: NvAppHandle) {
249 if handle.is_null() {
250 return;
251 }
252 $crate::app::ffi_catch_unwind("NvSurfaceApi::destroy", (), || {
253 unsafe { drop(Box::from_raw(handle as *mut $app_ty)) };
255 });
256 }
257
258 unsafe extern "C" fn __nv_render(
259 handle: NvAppHandle,
260 frame_id: FrameId,
261 ) -> NvBufferSlice {
262 if handle.is_null() {
263 return NvBufferSlice::EMPTY;
264 }
265 $crate::app::ffi_catch_unwind(
266 "NvSurfaceApi::render",
267 NvBufferSlice::EMPTY,
268 || {
269 let app = unsafe { &mut *(handle as *mut $app_ty) };
271 NvBufferSlice::from_slice(app.render(frame_id))
272 },
273 )
274 }
275
276 unsafe extern "C" fn __nv_dispatch_events(
277 handle: NvAppHandle,
278 batch: NvEventBatch,
279 ) -> u32 {
280 if handle.is_null() {
281 return 0;
282 }
283 $crate::app::ffi_catch_unwind("NvSurfaceApi::dispatch_events", 0, || {
284 let app = unsafe { &mut *(handle as *mut $app_ty) };
286 let Ok(events) = (unsafe { ValidatedEvents::try_from_raw(batch) }) else {
288 return 0;
289 };
290 let dirty = app.dispatch_events(events);
291 DispatchResult::from_parts(
292 dirty,
293 app.take_close_request(),
294 app.take_unconsumed_key(),
295 )
296 .bits()
297 })
298 }
299
300 unsafe extern "C" fn __nv_measure(
301 handle: NvAppHandle,
302 constraints: NvSizeConstraints,
303 ) -> NvIntrinsicSize {
304 if handle.is_null() {
305 return NvIntrinsicSize {
306 width: 0.0,
307 height: 0.0,
308 };
309 }
310 $crate::app::ffi_catch_unwind(
311 "NvLayoutApi::measure",
312 NvIntrinsicSize {
313 width: 0.0,
314 height: 0.0,
315 },
316 || {
317 let app = unsafe { &mut *(handle as *mut $app_ty) };
319 app.measure(constraints)
320 },
321 )
322 }
323
324 unsafe extern "C" fn __nv_hit_test(
325 handle: NvAppHandle,
326 x: f32,
327 y: f32,
328 pointer_phase: u8,
329 ) -> u8 {
330 if handle.is_null() {
331 return NvGestureDisposition::PassThrough as u8;
332 }
333 $crate::app::ffi_catch_unwind(
334 "NvLayoutApi::hit_test",
335 NvGestureDisposition::PassThrough as u8,
336 || {
337 let app = unsafe { &mut *(handle as *mut $app_ty) };
339 app.hit_test(x, y, pointer_phase) as u8
340 },
341 )
342 }
343
344 unsafe extern "C" fn __nv_set_props(
345 handle: NvAppHandle,
346 entries: *const NvMapEntry,
347 count: u32,
348 ) -> u32 {
349 if handle.is_null() {
350 return 0;
351 }
352 $crate::app::ffi_catch_unwind("NvComponentApi::set_props", 0, || {
353 let app = unsafe { &mut *(handle as *mut $app_ty) };
355 let props = unsafe { NvPropsRef::from_raw_parts(entries, count) };
357 u32::from(app.set_props(props))
358 })
359 }
360
361 unsafe extern "C" fn __nv_drain_emitted_events(
362 handle: NvAppHandle,
363 ) -> NvEventBatch {
364 if handle.is_null() {
365 return NvEventBatch::EMPTY;
366 }
367 $crate::app::ffi_catch_unwind(
368 "NvComponentApi::drain_emitted_events",
369 NvEventBatch::EMPTY,
370 || {
371 let app = unsafe { &mut *(handle as *mut $app_ty) };
373 app.drain_emitted_events().as_raw_batch()
374 },
375 )
376 }
377
378 unsafe extern "C" fn __nv_apply_hot_patch(
379 handle: NvAppHandle,
380 patch: NvBufferSlice,
381 ) -> u32 {
382 if handle.is_null() {
383 return 0;
384 }
385 $crate::app::ffi_catch_unwind("NvDevApi::apply_hot_patch", 0, || {
386 let app = unsafe { &mut *(handle as *mut $app_ty) };
388 let raw = unsafe { patch.as_slice() };
390 let Ok(msg) = $crate::HotPatchMsg::from_bytes(raw)
391 else {
392 return 0;
393 };
394 u32::from(app.apply_hot_patch(&msg))
395 })
396 }
397
398 unsafe extern "C" fn __nv_snapshot_state(handle: NvAppHandle) -> NvBufferSlice {
399 if handle.is_null() {
400 return NvBufferSlice::EMPTY;
401 }
402 $crate::app::ffi_catch_unwind(
403 "NvDevApi::snapshot_state",
404 NvBufferSlice::EMPTY,
405 || {
406 let app = unsafe { &mut *(handle as *mut $app_ty) };
408 NvBufferSlice::from_slice(app.snapshot_state())
409 },
410 )
411 }
412
413 unsafe extern "C" fn __nv_restore_state(
414 handle: NvAppHandle,
415 state: NvBufferSlice,
416 ) {
417 if handle.is_null() {
418 return;
419 }
420 $crate::app::ffi_catch_unwind("NvDevApi::restore_state", (), || {
421 let app = unsafe { &mut *(handle as *mut $app_ty) };
423 let bytes = unsafe { state.as_slice() };
425 app.restore_state(bytes);
426 });
427 }
428
429 unsafe extern "C" fn __nv_bind_host(
430 handle: NvAppHandle,
431 callbacks: *const NvHostCallbacks,
432 ) {
433 if handle.is_null() {
434 return;
435 }
436 $crate::app::ffi_catch_unwind("NvHostApi::bind_host", (), || {
437 let app = unsafe { &mut *(handle as *mut $app_ty) };
439 let bound = if callbacks.is_null() {
440 None
441 } else {
442 Some(unsafe { *callbacks })
444 };
445 app.bind_host(bound);
446 });
447 }
448
449 unsafe extern "C" fn __nv_dispatch_host_events(
450 handle: NvAppHandle,
451 batch: NvBufferSlice,
452 ) -> u32 {
453 if handle.is_null() {
454 return 0;
455 }
456 $crate::app::ffi_catch_unwind("NvHostApi::dispatch_host_events", 0, || {
457 let app = unsafe { &mut *(handle as *mut $app_ty) };
459 let bytes = unsafe { batch.as_slice() };
461 u32::from(app.dispatch_host_events(bytes))
462 })
463 }
464
465 unsafe extern "C" fn __nv_bind_direct_host(
466 handle: NvAppHandle,
467 env: *const NvDirectHostEnv,
468 ) {
469 if handle.is_null() {
470 return;
471 }
472 $crate::app::ffi_catch_unwind("NvDirectHostApi::bind_direct_host", (), || {
473 let app = unsafe { &mut *(handle as *mut $app_ty) };
475 let bound = unsafe { NvDirectHostEnv::from_raw_checked(env) };
478 app.bind_direct_host(bound);
479 });
480 }
481
482 unsafe extern "C" fn __nv_dispatch_direct_completion(
483 handle: NvAppHandle,
484 local_req_id: u64,
485 status: i32,
486 ptr: *const u8,
487 len: usize,
488 ) -> u32 {
489 if handle.is_null() {
490 return 0;
491 }
492 $crate::app::ffi_catch_unwind(
493 "NvDirectHostApi::dispatch_direct_completion",
494 0,
495 || {
496 let app = unsafe { &mut *(handle as *mut $app_ty) };
498 let Some(bytes) = (unsafe { $crate::abi::sink_bytes(ptr, len) }) else {
500 return u32::from(app.dispatch_direct_completion(
501 local_req_id,
502 $crate::abi::NvModStatus::Codec.as_i32(),
503 &[],
504 ));
505 };
506 u32::from(app.dispatch_direct_completion(local_req_id, status, bytes))
507 },
508 )
509 }
510
511 unsafe extern "C" fn __nv_dispatch_direct_event(
512 handle: NvAppHandle,
513 service_id: HostServiceId,
514 event_id: u32,
515 flags: u32,
516 ptr: *const u8,
517 len: usize,
518 ) -> u32 {
519 if handle.is_null() {
520 return 0;
521 }
522 $crate::app::ffi_catch_unwind("NvDirectHostApi::dispatch_direct_event", 0, || {
523 let app = unsafe { &mut *(handle as *mut $app_ty) };
525 let Some(bytes) = (unsafe { $crate::abi::sink_bytes(ptr, len) }) else {
527 return 0;
528 };
529 u32::from(app.dispatch_direct_event(service_id, event_id, flags, bytes))
530 })
531 }
532
533 unsafe extern "C" fn __nv_drain_capture_requests(
534 handle: NvAppHandle,
535 out: *mut NvPointerCaptureRequest,
536 cap: u32,
537 ) -> u32 {
538 if handle.is_null() {
539 return 0;
540 }
541 $crate::app::ffi_catch_unwind("NvPointerApi::drain_capture_requests", 0, || {
542 let app = unsafe { &mut *(handle as *mut $app_ty) };
544 unsafe { $crate::app::pointer::write_capture_requests(app, out, cap) }
546 })
547 }
548
549 static __NV_POINTER_API: NvPointerApi = NvPointerApi {
550 drain_capture_requests: __nv_drain_capture_requests,
551 };
552
553 static __NV_SURFACE_API: NvSurfaceApi = NvSurfaceApi {
554 create: __nv_create,
555 destroy: __nv_destroy,
556 render: __nv_render,
557 dispatch_events: __nv_dispatch_events,
558 };
559
560 static __NV_LAYOUT_API: NvLayoutApi = NvLayoutApi {
561 measure: __nv_measure,
562 hit_test: __nv_hit_test,
563 };
564
565 static __NV_COMPONENT_API: NvComponentApi = NvComponentApi {
566 set_props: __nv_set_props,
567 drain_emitted_events: __nv_drain_emitted_events,
568 };
569
570 static __NV_DEV_API: NvDevApi = NvDevApi {
571 apply_hot_patch: __nv_apply_hot_patch,
572 snapshot_state: __nv_snapshot_state,
573 restore_state: __nv_restore_state,
574 };
575
576 static __NV_HOST_API: NvHostApi = NvHostApi {
577 bind_host: __nv_bind_host,
578 dispatch_host_events: __nv_dispatch_host_events,
579 };
580
581 static __NV_DIRECT_HOST_API: NvDirectHostApi = NvDirectHostApi {
582 bind_direct_host: __nv_bind_direct_host,
583 dispatch_direct_completion: __nv_dispatch_direct_completion,
584 dispatch_direct_event: __nv_dispatch_direct_event,
585 };
586
587 #[unsafe(no_mangle)]
588 pub unsafe extern "C" fn $symbol(interface_id: InterfaceId) -> *const c_void {
589 match interface_id {
590 NV_IFACE_SURFACE => &__NV_SURFACE_API as *const NvSurfaceApi as *const c_void,
591 NV_IFACE_LAYOUT => &__NV_LAYOUT_API as *const NvLayoutApi as *const c_void,
592 NV_IFACE_COMPONENT => {
593 &__NV_COMPONENT_API as *const NvComponentApi as *const c_void
594 }
595 NV_IFACE_DEV => &__NV_DEV_API as *const NvDevApi as *const c_void,
596 NV_IFACE_HOST => &__NV_HOST_API as *const NvHostApi as *const c_void,
597 NV_IFACE_DIRECT_HOST => {
598 &__NV_DIRECT_HOST_API as *const NvDirectHostApi as *const c_void
599 }
600 NV_IFACE_POINTER => &__NV_POINTER_API as *const NvPointerApi as *const c_void,
601 _ => ::std::ptr::null(),
602 }
603 }
604 };
605 };
606}
607
608pub mod module;
609pub mod pointer;
610
611#[cfg(test)]
612mod tests;