nativeview_engine/runtime_app.rs
1//! Framework-agnostic host-runtime application and per-frame tick hook contracts.
2//!
3//! Defined in `nativeview-engine` so frontend adapters (such as `nativeview-app::ReactiveRuntimeApp`) implement
4//! [`RuntimeApp`] without depending on the native host runtime (`nativeview-runtime`, layout engines, or
5//! network wire transports). Re-exported identically from `nativeview-runtime`.
6
7use std::sync::Arc;
8
9use nativeview_abi::{
10 FrameId, HostServiceId, NvDirectHostEnv, NvHostCallbacks, NvPropsRef, NvSizeConstraints,
11 NvSurfaceMeasure, ValidatedEvents,
12};
13use nativeview_store::{ChangeSet, NodeStore};
14
15pub use crate::ext::frame::FrameTickHook;
16use crate::tracker::PointerCaptureRequest;
17use crate::HotPatchMsg;
18use crate::wake::WakeBridge;
19
20/// Output of one [`RuntimeApp::render_frame`] pass.
21pub enum AppFrame<'a> {
22 /// No new tree changes were produced this frame.
23 Clean,
24 /// In-process zero-serialization `ChangeSet` against [`RuntimeApp::direct_store`] (e.g. `ReactiveRuntimeApp`).
25 Direct { changes: &'a ChangeSet },
26 /// Cross-boundary binary `NV02` delta/keyframe slice (e.g. `NvApp`, `cdylib`, or remote wire).
27 Wire(&'a [u8]),
28}
29
30/// The attached app does not implement an optional [`RuntimeApp`] capability (embedded props,
31/// outbound events, state snapshots, or hot patching).
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct CapabilityUnsupported;
34
35/// Framework-agnostic application contract hosted by `nv_runtime::SurfaceRuntime`.
36///
37/// Implementations may either own a `NodeStore` directly (zero wire encode/decode via
38/// [`AppFrame::Direct`]) or emit binary `NV02` frames ([`AppFrame::Wire`]).
39pub trait RuntimeApp {
40 /// Produces the next frame's changes (`Direct`, `Wire`, or `Clean`).
41 fn render_frame(&mut self, frame_id: FrameId) -> AppFrame<'_>;
42
43 /// Dispatches a direct typed event batch into the application. Returns `true` when the app
44 /// dirtied state and needs a re-render.
45 fn dispatch_events(&mut self, events: ValidatedEvents<'_>) -> bool;
46
47 /// Takes the close request of the last [`Self::dispatch_events`]: an `Escape` / `GoBack` key
48 /// down no listener consumed. `nv_runtime::SurfaceRuntime` routes it to
49 /// `LaidOutScene::close_request_target` ([INV:close-request-single-path]).
50 fn take_close_request(&mut self) -> bool {
51 false
52 }
53
54 /// Takes whether the last `KeyDown` of [`Self::dispatch_events`] went unconsumed by app
55 /// listeners (eligible for post-dispatch runtime `DefaultAction`s).
56 fn take_unconsumed_key(&mut self) -> bool {
57 false
58 }
59
60 /// Drains the W3C pointer capture requests (`setPointerCapture` / `releasePointerCapture`)
61 /// listeners made during the last [`Self::dispatch_events`] into `sink`; the runtime applies
62 /// them as pending captures before each pointer's next sample.
63 fn drain_pointer_capture_requests(&mut self, _sink: &mut dyn FnMut(PointerCaptureRequest)) {}
64
65 /// Borrows the app's authoritative `NodeStore` when running in zero-copy direct mode.
66 fn direct_store(&self) -> Option<&NodeStore> {
67 None
68 }
69
70 /// Mutably borrows the app's authoritative `NodeStore` (for [`FrameTickHook`]s in direct mode).
71 fn direct_store_mut(&mut self) -> Option<&mut NodeStore> {
72 None
73 }
74
75 /// Polls any pending async work (e.g. reactive tasks or background streams) and arms the
76 /// installed [`WakeBridge`] waker on newly spawned pending futures. Returns `true` when new
77 /// work became ready and a render should follow.
78 fn poll_async_work(&mut self) -> bool {
79 false
80 }
81
82 /// Installs the runtime's single coalesced [`WakeBridge`] so async tasks wake the host loop
83 /// directly without double-layered wake latches.
84 ///
85 /// Returns `true` if the app had a pending wake prior to installation; callers trigger the
86 /// newly installed bridge *after* releasing any surface write lock.
87 fn install_wake_bridge(&mut self, _wake: Arc<WakeBridge>) -> bool {
88 false
89 }
90
91 /// Applies a Tier-1 binary hot-reload patch payload. `Ok(true)` when the surface dirtied.
92 fn apply_hot_patch(&mut self, _patch: &HotPatchMsg) -> Result<bool, CapabilityUnsupported> {
93 Err(CapabilityUnsupported)
94 }
95
96 /// Applies embedding-host props (RN / SwiftUI / Compose / Flutter widget props). `Ok(true)`
97 /// when the app needs a re-render.
98 fn set_props(&mut self, _props: NvPropsRef<'_>) -> Result<bool, CapabilityUnsupported> {
99 Err(CapabilityUnsupported)
100 }
101
102 /// Drains component-emitted outbound events, borrowed until the next call on `self`.
103 fn drain_emitted_events(&mut self) -> Result<ValidatedEvents<'_>, CapabilityUnsupported> {
104 Err(CapabilityUnsupported)
105 }
106
107 /// `true` when [`Self::snapshot_state`] / [`Self::restore_state`] are supported: lets the
108 /// runtime check the capability before touching state files, without serializing state.
109 fn supports_state(&self) -> bool {
110 false
111 }
112
113 /// Serializes app state (instant boot / Tier-2 hot swap), borrowed until the next call on `self`.
114 fn snapshot_state(&mut self) -> Result<&[u8], CapabilityUnsupported> {
115 Err(CapabilityUnsupported)
116 }
117
118 /// Restores state produced by [`Self::snapshot_state`]; the runtime re-renders afterwards.
119 fn restore_state(&mut self, _state: &[u8]) -> Result<(), CapabilityUnsupported> {
120 Err(CapabilityUnsupported)
121 }
122
123 /// Measures the surface under `constraints` and `NV_MEASURE_FLAG_*` bits.
124 ///
125 /// Returning `Some(measure)` delegates sizing to the app (e.g. `NV_IFACE_LAYOUT = 2`);
126 /// returning `None` falls back to the runtime's `StoreLayoutEngine::measure_root`.
127 fn measure_surface(
128 &mut self,
129 _constraints: NvSizeConstraints,
130 _flags: u32,
131 ) -> Option<NvSurfaceMeasure> {
132 None
133 }
134
135 /// Binds or unbinds the runtime's `NV_IFACE_HOST = 5` callbacks. Called automatically on
136 /// attach (`Some(callbacks)`) and before reload, detach, or drop (`None`).
137 fn bind_host(&mut self, _callbacks: Option<NvHostCallbacks>) {}
138
139 /// Delivers one canonical `NVHB` v1 host event batch drained from `RuntimeHostRouter`.
140 /// Returns `true` when the app dirtied state and needs a re-render.
141 fn dispatch_host_events(&mut self, _batch: &[u8]) -> bool {
142 false
143 }
144
145 /// Binds or unbinds the runtime's `NV_IFACE_DIRECT_HOST = 6` environment (`NvDirectHostEnv`).
146 /// Called on attach (`Some(env)`) and before reload, detach, or drop (`None`).
147 fn bind_direct_host(&mut self, _env: Option<NvDirectHostEnv>) {}
148
149 /// Delivers one completed direct-FFI async response on the owner thread (`NV_IFACE_DIRECT_HOST = 6`).
150 /// Returns `true` when the app dirtied state and needs a re-render.
151 fn dispatch_direct_completion(
152 &mut self,
153 _local_req_id: u64,
154 _status: i32,
155 _payload: &[u8],
156 ) -> bool {
157 false
158 }
159
160 /// Delivers one direct-FFI push event on the owner thread (`NV_IFACE_DIRECT_HOST = 6`).
161 /// Returns `true` when the app dirtied state and needs a re-render.
162 fn dispatch_direct_event(
163 &mut self,
164 _service_id: HostServiceId,
165 _event_id: u32,
166 _flags: u32,
167 _payload: &[u8],
168 ) -> bool {
169 false
170 }
171}