use std::any::Any;
use std::cell::RefCell;
use nativeview_abi::{
FrameId, HostServiceId, NvDirectHostEnv, NvGestureDisposition, NvHostCallbacks,
NvIntrinsicSize, NvPropsRef, NvSizeConstraints, SurfaceId, ValidatedEvents,
};
thread_local! {
static LAST_FFI_PANIC: RefCell<Option<String>> = const { RefCell::new(None) };
}
#[cold]
#[inline(never)]
#[expect(
clippy::disallowed_methods,
reason = "FFI catch_unwind panic payload boundary requires std::any::Any downcast"
)]
pub fn format_panic_payload(payload: &(dyn Any + Send)) -> String {
if let Some(s) = payload.downcast_ref::<&str>() {
(*s).to_owned()
} else if let Some(s) = payload.downcast_ref::<String>() {
s.clone()
} else {
"non-string panic payload".to_owned()
}
}
#[cold]
#[inline(never)]
#[doc(hidden)]
pub fn record_ffi_panic(fn_name: &'static str, payload: Box<dyn Any + Send>) {
let detail = format_panic_payload(&*payload);
let msg = format!("{fn_name}: {detail}");
LAST_FFI_PANIC.with(|slot| {
*slot.borrow_mut() = Some(msg);
});
}
pub fn last_ffi_panic() -> Option<String> {
LAST_FFI_PANIC.with(|slot| slot.borrow().clone())
}
pub fn take_last_ffi_panic() -> Option<String> {
LAST_FFI_PANIC.with(|slot| slot.borrow_mut().take())
}
pub fn clear_last_ffi_panic() {
LAST_FFI_PANIC.with(|slot| {
let _ = slot.borrow_mut().take();
});
}
#[inline(always)]
#[doc(hidden)]
pub fn ffi_catch_unwind<T, F>(fn_name: &'static str, fallback: T, f: F) -> T
where
F: FnOnce() -> T,
{
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
Ok(val) => val,
Err(payload) => {
record_ffi_panic(fn_name, payload);
fallback
}
}
}
#[inline]
pub fn default_measure_constraints(constraints: NvSizeConstraints) -> NvIntrinsicSize {
let w = if constraints.max_w.is_finite() {
constraints.max_w.max(constraints.min_w)
} else {
constraints.min_w
};
let h = if constraints.max_h.is_finite() {
constraints.max_h.max(constraints.min_h)
} else {
constraints.min_h
};
NvIntrinsicSize {
width: w,
height: h,
}
}
pub trait NvApp: Sized + 'static {
fn create(surface_id: SurfaceId) -> Self;
fn render(&mut self, frame_id: FrameId) -> &[u8];
fn dispatch_events(&mut self, events: ValidatedEvents<'_>) -> bool;
fn take_close_request(&mut self) -> bool {
false
}
fn take_unconsumed_key(&mut self) -> bool {
false
}
fn drain_pointer_capture_requests(
&mut self,
_sink: &mut dyn FnMut(crate::tracker::PointerCaptureRequest),
) {
}
fn poll_work(&mut self, _waker: &core::task::Waker) -> bool {
false
}
fn measure(&mut self, constraints: NvSizeConstraints) -> NvIntrinsicSize {
default_measure_constraints(constraints)
}
fn hit_test(&mut self, _x: f32, _y: f32, _pointer_phase: u8) -> NvGestureDisposition {
NvGestureDisposition::PassThrough
}
fn set_props(&mut self, _props: NvPropsRef<'_>) -> bool {
false
}
fn drain_emitted_events(&mut self) -> ValidatedEvents<'_> {
ValidatedEvents::EMPTY
}
fn apply_hot_patch(&mut self, _patch: &crate::HotPatchMsg) -> bool {
false
}
fn snapshot_state(&mut self) -> &[u8] {
&[]
}
fn restore_state(&mut self, _state: &[u8]) {}
fn bind_host(&mut self, _callbacks: Option<NvHostCallbacks>) {}
fn dispatch_host_events(&mut self, _batch: &[u8]) -> bool {
false
}
fn bind_direct_host(&mut self, _env: Option<NvDirectHostEnv>) {}
fn dispatch_direct_completion(
&mut self,
_local_req_id: u64,
_status: i32,
_payload: &[u8],
) -> bool {
false
}
fn dispatch_direct_event(
&mut self,
_service_id: HostServiceId,
_event_id: u32,
_flags: u32,
_payload: &[u8],
) -> bool {
false
}
}
#[macro_export]
macro_rules! export_nv_app {
($app_ty:ty) => {
$crate::export_nv_app!($app_ty, symbol = nv_get_interface);
};
($app_ty:ty, symbol = $symbol:ident) => {
#[allow(unsafe_code)]
const _: () = {
use ::std::ffi::c_void;
use $crate::abi::{
DispatchResult, FrameId, HostServiceId, InterfaceId, NvAppHandle, NvBufferSlice,
NvComponentApi,
NvDevApi, NvDirectHostApi, NvDirectHostEnv, NvEventBatch,
NvGestureDisposition, NvHostApi, NvHostCallbacks, NvIntrinsicSize,
NvLayoutApi, NvMapEntry, NvPointerApi, NvPointerCaptureRequest, NvPropsRef,
NvSizeConstraints, NvSurfaceApi, SurfaceId, ValidatedEvents, NV_IFACE_COMPONENT,
NV_IFACE_DEV, NV_IFACE_DIRECT_HOST, NV_IFACE_HOST, NV_IFACE_LAYOUT,
NV_IFACE_POINTER, NV_IFACE_SURFACE,
};
use $crate::NvApp;
unsafe extern "C" fn __nv_create(surface_id: SurfaceId) -> NvAppHandle {
$crate::app::ffi_catch_unwind(
"NvSurfaceApi::create",
::std::ptr::null_mut(),
|| {
let canonical = SurfaceId::from_raw_or_null(surface_id.raw());
let boxed = Box::new(<$app_ty as NvApp>::create(canonical));
Box::into_raw(boxed) as NvAppHandle
},
)
}
unsafe extern "C" fn __nv_destroy(handle: NvAppHandle) {
if handle.is_null() {
return;
}
$crate::app::ffi_catch_unwind("NvSurfaceApi::destroy", (), || {
unsafe { drop(Box::from_raw(handle as *mut $app_ty)) };
});
}
unsafe extern "C" fn __nv_render(
handle: NvAppHandle,
frame_id: FrameId,
) -> NvBufferSlice {
if handle.is_null() {
return NvBufferSlice::EMPTY;
}
$crate::app::ffi_catch_unwind(
"NvSurfaceApi::render",
NvBufferSlice::EMPTY,
|| {
let app = unsafe { &mut *(handle as *mut $app_ty) };
NvBufferSlice::from_slice(app.render(frame_id))
},
)
}
unsafe extern "C" fn __nv_dispatch_events(
handle: NvAppHandle,
batch: NvEventBatch,
) -> u32 {
if handle.is_null() {
return 0;
}
$crate::app::ffi_catch_unwind("NvSurfaceApi::dispatch_events", 0, || {
let app = unsafe { &mut *(handle as *mut $app_ty) };
let Ok(events) = (unsafe { ValidatedEvents::try_from_raw(batch) }) else {
return 0;
};
let dirty = app.dispatch_events(events);
DispatchResult::from_parts(
dirty,
app.take_close_request(),
app.take_unconsumed_key(),
)
.bits()
})
}
unsafe extern "C" fn __nv_measure(
handle: NvAppHandle,
constraints: NvSizeConstraints,
) -> NvIntrinsicSize {
if handle.is_null() {
return NvIntrinsicSize {
width: 0.0,
height: 0.0,
};
}
$crate::app::ffi_catch_unwind(
"NvLayoutApi::measure",
NvIntrinsicSize {
width: 0.0,
height: 0.0,
},
|| {
let app = unsafe { &mut *(handle as *mut $app_ty) };
app.measure(constraints)
},
)
}
unsafe extern "C" fn __nv_hit_test(
handle: NvAppHandle,
x: f32,
y: f32,
pointer_phase: u8,
) -> u8 {
if handle.is_null() {
return NvGestureDisposition::PassThrough as u8;
}
$crate::app::ffi_catch_unwind(
"NvLayoutApi::hit_test",
NvGestureDisposition::PassThrough as u8,
|| {
let app = unsafe { &mut *(handle as *mut $app_ty) };
app.hit_test(x, y, pointer_phase) as u8
},
)
}
unsafe extern "C" fn __nv_set_props(
handle: NvAppHandle,
entries: *const NvMapEntry,
count: u32,
) -> u32 {
if handle.is_null() {
return 0;
}
$crate::app::ffi_catch_unwind("NvComponentApi::set_props", 0, || {
let app = unsafe { &mut *(handle as *mut $app_ty) };
let props = unsafe { NvPropsRef::from_raw_parts(entries, count) };
u32::from(app.set_props(props))
})
}
unsafe extern "C" fn __nv_drain_emitted_events(
handle: NvAppHandle,
) -> NvEventBatch {
if handle.is_null() {
return NvEventBatch::EMPTY;
}
$crate::app::ffi_catch_unwind(
"NvComponentApi::drain_emitted_events",
NvEventBatch::EMPTY,
|| {
let app = unsafe { &mut *(handle as *mut $app_ty) };
app.drain_emitted_events().as_raw_batch()
},
)
}
unsafe extern "C" fn __nv_apply_hot_patch(
handle: NvAppHandle,
patch: NvBufferSlice,
) -> u32 {
if handle.is_null() {
return 0;
}
$crate::app::ffi_catch_unwind("NvDevApi::apply_hot_patch", 0, || {
let app = unsafe { &mut *(handle as *mut $app_ty) };
let raw = unsafe { patch.as_slice() };
let Ok(msg) = $crate::HotPatchMsg::from_bytes(raw)
else {
return 0;
};
u32::from(app.apply_hot_patch(&msg))
})
}
unsafe extern "C" fn __nv_snapshot_state(handle: NvAppHandle) -> NvBufferSlice {
if handle.is_null() {
return NvBufferSlice::EMPTY;
}
$crate::app::ffi_catch_unwind(
"NvDevApi::snapshot_state",
NvBufferSlice::EMPTY,
|| {
let app = unsafe { &mut *(handle as *mut $app_ty) };
NvBufferSlice::from_slice(app.snapshot_state())
},
)
}
unsafe extern "C" fn __nv_restore_state(
handle: NvAppHandle,
state: NvBufferSlice,
) {
if handle.is_null() {
return;
}
$crate::app::ffi_catch_unwind("NvDevApi::restore_state", (), || {
let app = unsafe { &mut *(handle as *mut $app_ty) };
let bytes = unsafe { state.as_slice() };
app.restore_state(bytes);
});
}
unsafe extern "C" fn __nv_bind_host(
handle: NvAppHandle,
callbacks: *const NvHostCallbacks,
) {
if handle.is_null() {
return;
}
$crate::app::ffi_catch_unwind("NvHostApi::bind_host", (), || {
let app = unsafe { &mut *(handle as *mut $app_ty) };
let bound = if callbacks.is_null() {
None
} else {
Some(unsafe { *callbacks })
};
app.bind_host(bound);
});
}
unsafe extern "C" fn __nv_dispatch_host_events(
handle: NvAppHandle,
batch: NvBufferSlice,
) -> u32 {
if handle.is_null() {
return 0;
}
$crate::app::ffi_catch_unwind("NvHostApi::dispatch_host_events", 0, || {
let app = unsafe { &mut *(handle as *mut $app_ty) };
let bytes = unsafe { batch.as_slice() };
u32::from(app.dispatch_host_events(bytes))
})
}
unsafe extern "C" fn __nv_bind_direct_host(
handle: NvAppHandle,
env: *const NvDirectHostEnv,
) {
if handle.is_null() {
return;
}
$crate::app::ffi_catch_unwind("NvDirectHostApi::bind_direct_host", (), || {
let app = unsafe { &mut *(handle as *mut $app_ty) };
let bound = unsafe { NvDirectHostEnv::from_raw_checked(env) };
app.bind_direct_host(bound);
});
}
unsafe extern "C" fn __nv_dispatch_direct_completion(
handle: NvAppHandle,
local_req_id: u64,
status: i32,
ptr: *const u8,
len: usize,
) -> u32 {
if handle.is_null() {
return 0;
}
$crate::app::ffi_catch_unwind(
"NvDirectHostApi::dispatch_direct_completion",
0,
|| {
let app = unsafe { &mut *(handle as *mut $app_ty) };
let Some(bytes) = (unsafe { $crate::abi::sink_bytes(ptr, len) }) else {
return u32::from(app.dispatch_direct_completion(
local_req_id,
$crate::abi::NvModStatus::Codec.as_i32(),
&[],
));
};
u32::from(app.dispatch_direct_completion(local_req_id, status, bytes))
},
)
}
unsafe extern "C" fn __nv_dispatch_direct_event(
handle: NvAppHandle,
service_id: HostServiceId,
event_id: u32,
flags: u32,
ptr: *const u8,
len: usize,
) -> u32 {
if handle.is_null() {
return 0;
}
$crate::app::ffi_catch_unwind("NvDirectHostApi::dispatch_direct_event", 0, || {
let app = unsafe { &mut *(handle as *mut $app_ty) };
let Some(bytes) = (unsafe { $crate::abi::sink_bytes(ptr, len) }) else {
return 0;
};
u32::from(app.dispatch_direct_event(service_id, event_id, flags, bytes))
})
}
unsafe extern "C" fn __nv_drain_capture_requests(
handle: NvAppHandle,
out: *mut NvPointerCaptureRequest,
cap: u32,
) -> u32 {
if handle.is_null() {
return 0;
}
$crate::app::ffi_catch_unwind("NvPointerApi::drain_capture_requests", 0, || {
let app = unsafe { &mut *(handle as *mut $app_ty) };
unsafe { $crate::app::pointer::write_capture_requests(app, out, cap) }
})
}
static __NV_POINTER_API: NvPointerApi = NvPointerApi {
drain_capture_requests: __nv_drain_capture_requests,
};
static __NV_SURFACE_API: NvSurfaceApi = NvSurfaceApi {
create: __nv_create,
destroy: __nv_destroy,
render: __nv_render,
dispatch_events: __nv_dispatch_events,
};
static __NV_LAYOUT_API: NvLayoutApi = NvLayoutApi {
measure: __nv_measure,
hit_test: __nv_hit_test,
};
static __NV_COMPONENT_API: NvComponentApi = NvComponentApi {
set_props: __nv_set_props,
drain_emitted_events: __nv_drain_emitted_events,
};
static __NV_DEV_API: NvDevApi = NvDevApi {
apply_hot_patch: __nv_apply_hot_patch,
snapshot_state: __nv_snapshot_state,
restore_state: __nv_restore_state,
};
static __NV_HOST_API: NvHostApi = NvHostApi {
bind_host: __nv_bind_host,
dispatch_host_events: __nv_dispatch_host_events,
};
static __NV_DIRECT_HOST_API: NvDirectHostApi = NvDirectHostApi {
bind_direct_host: __nv_bind_direct_host,
dispatch_direct_completion: __nv_dispatch_direct_completion,
dispatch_direct_event: __nv_dispatch_direct_event,
};
#[unsafe(no_mangle)]
pub unsafe extern "C" fn $symbol(interface_id: InterfaceId) -> *const c_void {
match interface_id {
NV_IFACE_SURFACE => &__NV_SURFACE_API as *const NvSurfaceApi as *const c_void,
NV_IFACE_LAYOUT => &__NV_LAYOUT_API as *const NvLayoutApi as *const c_void,
NV_IFACE_COMPONENT => {
&__NV_COMPONENT_API as *const NvComponentApi as *const c_void
}
NV_IFACE_DEV => &__NV_DEV_API as *const NvDevApi as *const c_void,
NV_IFACE_HOST => &__NV_HOST_API as *const NvHostApi as *const c_void,
NV_IFACE_DIRECT_HOST => {
&__NV_DIRECT_HOST_API as *const NvDirectHostApi as *const c_void
}
NV_IFACE_POINTER => &__NV_POINTER_API as *const NvPointerApi as *const c_void,
_ => ::std::ptr::null(),
}
}
};
};
}
pub mod module;
pub mod pointer;
#[cfg(test)]
mod tests;