nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
//! Core framework-agnostic runtime: `StoreBackend` trait, `SurfaceRunner`
//! coordinator, `StoreWireReplica` for cross-boundary `NV02` frames, 6-stage `FrameProfiler` with
//! Perfetto/Chrome trace export, and 2-tier hot-reload spine.

#![cfg_attr(doctest, doc = include_str!("../README.md"))]

pub mod app;
pub use app::module as app_module;
pub mod drag;
pub mod editing;
pub mod ext;
pub mod focus;
pub mod focus_query;
pub mod hotreload;
#[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
pub mod loader;
pub mod persistence;
pub mod profiler;
pub mod runtime_app;
pub mod store_backend;
pub mod wake;
pub mod tracker;

pub use nativeview_abi as abi;
use nativeview_abi::{DecodeError, DurationUs, FrameId, NodeId, SurfaceId};
use nativeview_store::{ChangeSet, NodeStore};

pub use app::{
    clear_last_ffi_panic, default_measure_constraints, last_ffi_panic, take_last_ffi_panic, NvApp,
};
pub use app_module::NvAppModule;
pub use ext::frame::{
    FrameTickHook, FrameTickRegistry, FrameWaker, SlotWaker, TickDemand, TickHookId, TickPriority,
    WallClock,
};
pub use ext::vsync::{
    interval_us_from_millihertz, sanitize_refresh_rate_millihertz, ManualVsyncHandle,
    ManualVsyncPacer, TimerVsyncPacer, VsyncPacer, DEFAULT_REFRESH_RATE_MILLIHERTZ,
};
pub use runtime_app::{AppFrame, CapabilityUnsupported, RuntimeApp};
pub use store_backend::{StoreBackend, StoreWireReplica};
pub use wake::{AppWake, WakeBridge, WakeCallback, WakeDeferGuard, WakeToken};
pub use focus::{
    first_focusable_in_subtree, first_matching_in_subtree, is_composite_aria_group,
    is_focusable_node, is_focusable_self, is_subtree_closed_overlay, is_subtree_disabled,
    is_tabbable_self, is_text_entry_node, is_within_subtree, resolve_focus_recovery,
    snapshot_focus_anchor, topmost_open_modal, FocusAnchor, FocusRecoveryResult,
};
pub use focus_query::press_focus_target;
pub use tracker::InteractionTracker;

pub use hotreload::{
    HotPatchDecodeError, HotPatchMsg, HOT_PATCH_VERSION,
    HOT_PATCH_WIRE_MAGIC,
};
pub use persistence::{
    write_file_atomic, AppBuildId, Frame0File, Frame0Footer, Frame0Meta, Frame0Miss,
    PersistenceError, StateByteLen, StateFile, StateRecoveryStats, StateSaveOutcome,
    DEFAULT_FRAME0_FILE_NAME, DEFAULT_STATE_FILE_NAME, FRAME0_FOOTER_SIZE, MAX_FRAME0_FILE_BYTES,
    MAX_STATE_FILE_BYTES, STATE_FILE_HEADER_SIZE, STATE_FILE_MAGIC,
};
pub use profiler::{FrameProfiler, FrameTiming};

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Viewport {
    pub width: f32,
    pub height: f32,
    pub scale_factor: f32,
}

impl Default for Viewport {
    fn default() -> Self {
        Self {
            width: 393.0,
            height: 852.0,
            scale_factor: 3.0,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct LayoutRect {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

#[derive(Debug, Clone, Copy, Default)]
pub struct BackendApplyStats {
    pub op_count: u32,
    pub mutation_count: u32,
    pub decode_us: DurationUs,
    pub layout_us: DurationUs,
    pub diff_us: DurationUs,
    pub mount_us: DurationUs,
}

#[derive(Debug)]
pub enum BackendError {
    Decode(DecodeError),
    Wire(nativeview_store::wire::WireError),
    /// Replica hit a mid-frame wire failure and reset; deltas are rejected until a `frame == 1` keyframe arrives.
    NeedsKeyframe(Option<nativeview_store::wire::WireError>),
    InvalidNode(NodeId),
    Internal(String),
}

impl From<DecodeError> for BackendError {
    fn from(e: DecodeError) -> Self {
        Self::Decode(e)
    }
}

impl From<nativeview_store::wire::WireError> for BackendError {
    fn from(e: nativeview_store::wire::WireError) -> Self {
        Self::Wire(e)
    }
}

impl std::fmt::Display for BackendError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}

impl std::error::Error for BackendError {}

/// Manages frame sequencing and stage profiling for one rendered surface backed by a [`StoreBackend`].
pub struct SurfaceRunner<B: StoreBackend> {
    surface_id: SurfaceId,
    next_frame_id: FrameId,
    backend: B,
    profiler: FrameProfiler,
}

impl<B: StoreBackend> SurfaceRunner<B> {
    pub fn new(surface_id: SurfaceId, viewport: Viewport, mut backend: B) -> Self {
        backend.set_viewport(surface_id, viewport);
        Self {
            surface_id,
            next_frame_id: FrameId(1),
            backend,
            profiler: FrameProfiler::new(512),
        }
    }

    pub fn surface_id(&self) -> SurfaceId {
        self.surface_id
    }

    pub fn backend(&self) -> &B {
        &self.backend
    }

    pub fn backend_mut(&mut self) -> &mut B {
        &mut self.backend
    }

    pub fn profiler(&self) -> &FrameProfiler {
        &self.profiler
    }

    pub fn next_frame_id(&mut self) -> FrameId {
        let id = self.next_frame_id;
        self.next_frame_id = self.next_frame_id.next();
        id
    }

    /// Commits one already-committed `(&NodeStore, &ChangeSet)` directly into the backend with
    /// zero wire serialization or copying, recording exact `FrameTiming` in `profiler`.
    pub fn commit_store(
        &mut self,
        frame_id: FrameId,
        reconcile_us: u64,
        store: &NodeStore,
        changes: &ChangeSet,
    ) -> Result<FrameTiming, BackendError> {
        let stats = self.backend.commit(store, changes)?;
        let timing = FrameTiming {
            frame_id,
            op_count: stats.op_count,
            mutation_count: stats.mutation_count,
            reconcile_us: DurationUs(reconcile_us),
            encode_us: DurationUs(0),
            decode_us: stats.decode_us,
            layout_us: stats.layout_us,
            diff_us: stats.diff_us,
            mount_us: stats.mount_us,
        };
        self.profiler.record(timing);
        Ok(timing)
    }

    /// Runs a timed producer/commit closure against the backend and records exact `FrameTiming`.
    pub fn commit_with<F>(&mut self, flush: F) -> Result<FrameTiming, BackendError>
    where
        F: FnOnce(FrameId, &mut B) -> Result<(u64, BackendApplyStats), BackendError>,
    {
        let frame_id = self.next_frame_id();
        let (reconcile_us, stats) = flush(frame_id, &mut self.backend)?;
        let timing = FrameTiming {
            frame_id,
            op_count: stats.op_count,
            mutation_count: stats.mutation_count,
            reconcile_us: DurationUs(reconcile_us),
            encode_us: DurationUs(0),
            decode_us: stats.decode_us,
            layout_us: stats.layout_us,
            diff_us: stats.diff_us,
            mount_us: stats.mount_us,
        };
        self.profiler.record(timing);
        Ok(timing)
    }
}