nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
//! Framework-agnostic host-runtime application and per-frame tick hook contracts.
//!
//! Defined in `nativeview-engine` so frontend adapters (such as `nativeview-app::ReactiveRuntimeApp`) implement
//! [`RuntimeApp`] without depending on the native host runtime (`nativeview-runtime`, layout engines, or
//! network wire transports). Re-exported identically from `nativeview-runtime`.

use std::sync::Arc;

use nativeview_abi::{
    FrameId, HostServiceId, NvDirectHostEnv, NvHostCallbacks, NvPropsRef, NvSizeConstraints,
    NvSurfaceMeasure, ValidatedEvents,
};
use nativeview_store::{ChangeSet, NodeStore};

pub use crate::ext::frame::FrameTickHook;
use crate::tracker::PointerCaptureRequest;
use crate::HotPatchMsg;
use crate::wake::WakeBridge;

/// Output of one [`RuntimeApp::render_frame`] pass.
pub enum AppFrame<'a> {
    /// No new tree changes were produced this frame.
    Clean,
    /// In-process zero-serialization `ChangeSet` against [`RuntimeApp::direct_store`] (e.g. `ReactiveRuntimeApp`).
    Direct { changes: &'a ChangeSet },
    /// Cross-boundary binary `NV02` delta/keyframe slice (e.g. `NvApp`, `cdylib`, or remote wire).
    Wire(&'a [u8]),
}

/// The attached app does not implement an optional [`RuntimeApp`] capability (embedded props,
/// outbound events, state snapshots, or hot patching).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CapabilityUnsupported;

/// Framework-agnostic application contract hosted by `nv_runtime::SurfaceRuntime`.
///
/// Implementations may either own a `NodeStore` directly (zero wire encode/decode via
/// [`AppFrame::Direct`]) or emit binary `NV02` frames ([`AppFrame::Wire`]).
pub trait RuntimeApp {
    /// Produces the next frame's changes (`Direct`, `Wire`, or `Clean`).
    fn render_frame(&mut self, frame_id: FrameId) -> AppFrame<'_>;

    /// Dispatches a direct typed event batch into the application. Returns `true` when the app
    /// dirtied state and needs a re-render.
    fn dispatch_events(&mut self, events: ValidatedEvents<'_>) -> bool;

    /// Takes the close request of the last [`Self::dispatch_events`]: an `Escape` / `GoBack` key
    /// down no listener consumed. `nv_runtime::SurfaceRuntime` routes it to
    /// `LaidOutScene::close_request_target` ([INV:close-request-single-path]).
    fn take_close_request(&mut self) -> bool {
        false
    }

    /// Takes whether the last `KeyDown` of [`Self::dispatch_events`] went unconsumed by app
    /// listeners (eligible for post-dispatch runtime `DefaultAction`s).
    fn take_unconsumed_key(&mut self) -> bool {
        false
    }

    /// Drains the W3C pointer capture requests (`setPointerCapture` / `releasePointerCapture`)
    /// listeners made during the last [`Self::dispatch_events`] into `sink`; the runtime applies
    /// them as pending captures before each pointer's next sample.
    fn drain_pointer_capture_requests(&mut self, _sink: &mut dyn FnMut(PointerCaptureRequest)) {}

    /// Borrows the app's authoritative `NodeStore` when running in zero-copy direct mode.
    fn direct_store(&self) -> Option<&NodeStore> {
        None
    }

    /// Mutably borrows the app's authoritative `NodeStore` (for [`FrameTickHook`]s in direct mode).
    fn direct_store_mut(&mut self) -> Option<&mut NodeStore> {
        None
    }

    /// Polls any pending async work (e.g. reactive tasks or background streams) and arms the
    /// installed [`WakeBridge`] waker on newly spawned pending futures. Returns `true` when new
    /// work became ready and a render should follow.
    fn poll_async_work(&mut self) -> bool {
        false
    }

    /// Installs the runtime's single coalesced [`WakeBridge`] so async tasks wake the host loop
    /// directly without double-layered wake latches.
    ///
    /// Returns `true` if the app had a pending wake prior to installation; callers trigger the
    /// newly installed bridge *after* releasing any surface write lock.
    fn install_wake_bridge(&mut self, _wake: Arc<WakeBridge>) -> bool {
        false
    }

    /// Applies a Tier-1 binary hot-reload patch payload. `Ok(true)` when the surface dirtied.
    fn apply_hot_patch(&mut self, _patch: &HotPatchMsg) -> Result<bool, CapabilityUnsupported> {
        Err(CapabilityUnsupported)
    }

    /// Applies embedding-host props (RN / SwiftUI / Compose / Flutter widget props). `Ok(true)`
    /// when the app needs a re-render.
    fn set_props(&mut self, _props: NvPropsRef<'_>) -> Result<bool, CapabilityUnsupported> {
        Err(CapabilityUnsupported)
    }

    /// Drains component-emitted outbound events, borrowed until the next call on `self`.
    fn drain_emitted_events(&mut self) -> Result<ValidatedEvents<'_>, CapabilityUnsupported> {
        Err(CapabilityUnsupported)
    }

    /// `true` when [`Self::snapshot_state`] / [`Self::restore_state`] are supported: lets the
    /// runtime check the capability before touching state files, without serializing state.
    fn supports_state(&self) -> bool {
        false
    }

    /// Serializes app state (instant boot / Tier-2 hot swap), borrowed until the next call on `self`.
    fn snapshot_state(&mut self) -> Result<&[u8], CapabilityUnsupported> {
        Err(CapabilityUnsupported)
    }

    /// Restores state produced by [`Self::snapshot_state`]; the runtime re-renders afterwards.
    fn restore_state(&mut self, _state: &[u8]) -> Result<(), CapabilityUnsupported> {
        Err(CapabilityUnsupported)
    }

    /// Measures the surface under `constraints` and `NV_MEASURE_FLAG_*` bits.
    ///
    /// Returning `Some(measure)` delegates sizing to the app (e.g. `NV_IFACE_LAYOUT = 2`);
    /// returning `None` falls back to the runtime's `StoreLayoutEngine::measure_root`.
    fn measure_surface(
        &mut self,
        _constraints: NvSizeConstraints,
        _flags: u32,
    ) -> Option<NvSurfaceMeasure> {
        None
    }

    /// Binds or unbinds the runtime's `NV_IFACE_HOST = 5` callbacks. Called automatically on
    /// attach (`Some(callbacks)`) and before reload, detach, or drop (`None`).
    fn bind_host(&mut self, _callbacks: Option<NvHostCallbacks>) {}

    /// Delivers one canonical `NVHB` v1 host event batch drained from `RuntimeHostRouter`.
    /// Returns `true` when the app dirtied state and needs a re-render.
    fn dispatch_host_events(&mut self, _batch: &[u8]) -> bool {
        false
    }

    /// Binds or unbinds the runtime's `NV_IFACE_DIRECT_HOST = 6` environment (`NvDirectHostEnv`).
    /// Called on attach (`Some(env)`) and before reload, detach, or drop (`None`).
    fn bind_direct_host(&mut self, _env: Option<NvDirectHostEnv>) {}

    /// Delivers one completed direct-FFI async response on the owner thread (`NV_IFACE_DIRECT_HOST = 6`).
    /// Returns `true` when the app dirtied state and needs a re-render.
    fn dispatch_direct_completion(
        &mut self,
        _local_req_id: u64,
        _status: i32,
        _payload: &[u8],
    ) -> bool {
        false
    }

    /// Delivers one direct-FFI push event on the owner thread (`NV_IFACE_DIRECT_HOST = 6`).
    /// Returns `true` when the app dirtied state and needs a re-render.
    fn dispatch_direct_event(
        &mut self,
        _service_id: HostServiceId,
        _event_id: u32,
        _flags: u32,
        _payload: &[u8],
    ) -> bool {
        false
    }
}