nativeview-cli 0.1.0-rc.1

Developer CLI (`nv`) for Native View Engine: dev hot-reload, builds, pairing, SDK management, app scaffolding, and docs.
Documentation
//! [`PairedApp`] abstraction and [`PairedHotApp`] dynamic `cdylib` implementation for `nv pair`.

use std::borrow::Cow;
use std::path::Path;

use nativeview_abi::{DispatchResult, FrameId, NvMapEntry, SurfaceId, SurfaceToken, ValidatedEvents};
use nativeview_engine::loader::HotAppInstance;
use nv_runtime::{
    next_global_reload_gen, DirectDrainScratch, DirectSurfaceBinding, WakeBridge,
};

/// Runtime abstraction over a live NV app hosted by [`crate::pair::PairSession`].
pub(crate) trait PairedApp {
    fn render(&mut self, frame_id: FrameId) -> Cow<'_, [u8]>;
    /// The app's full dispatch outcome. [`PairSession`] renders on [`DispatchResult::is_dirty`]
    /// and never routes the close request: the paired host owns the scene, and the Web pair
    /// client's browser close watchers close the overlay natively, reporting the bridged `close`
    /// upstream ([INV:close-request-single-path]).
    fn dispatch_events(&mut self, events: ValidatedEvents<'_>) -> DispatchResult;
    fn set_props(&mut self, _entries: &[NvMapEntry]) -> bool {
        false
    }
    fn apply_hot_patch(&mut self, _patch: &[u8]) -> bool {
        false
    }
    fn reload(&mut self, _dylib_path: &Path) -> Result<u64, String> {
        Ok(1)
    }
    fn drain_direct_events(&mut self) -> bool {
        false
    }
}

pub(crate) struct PairedHotApp {
    instance: HotAppInstance,
    direct_binding: DirectSurfaceBinding,
    direct_scratch: DirectDrainScratch,
}

impl PairedHotApp {
    pub(crate) fn load(dylib_path: &Path, surface_id: SurfaceId) -> Result<Self, String> {
        let mut instance = HotAppInstance::load(dylib_path, surface_id, 1, None)
            .map_err(|e| format!("load {}: {e}", dylib_path.display()))?;
        let wake = std::sync::Arc::new(WakeBridge::new());
        let token = SurfaceToken::new(surface_id, next_global_reload_gen());
        let (direct_binding, _) = DirectSurfaceBinding::new(token, wake);
        instance.bind_direct_host(Some(direct_binding.env()));
        Ok(Self {
            instance,
            direct_binding,
            direct_scratch: DirectDrainScratch::default(),
        })
    }
}

impl Drop for PairedHotApp {
    fn drop(&mut self) {
        self.direct_binding.deactivate_and_invalidate();
        self.instance.bind_direct_host(None);
    }
}

impl PairedApp for PairedHotApp {
    fn render(&mut self, frame_id: FrameId) -> Cow<'_, [u8]> {
        Cow::Borrowed(self.instance.render(frame_id))
    }
    fn dispatch_events(&mut self, events: ValidatedEvents<'_>) -> DispatchResult {
        let dirty = self.instance.dispatch_events(events);
        DispatchResult::new(dirty, self.instance.take_close_request())
    }
    fn set_props(&mut self, entries: &[NvMapEntry]) -> bool {
        self.instance.set_props(entries)
    }
    fn apply_hot_patch(&mut self, patch: &[u8]) -> bool {
        self.instance.apply_hot_patch(patch)
    }
    fn reload(&mut self, dylib_path: &Path) -> Result<u64, String> {
        let prior = self.instance.snapshot_state().to_vec();
        let prior_slice = (!prior.is_empty()).then_some(prior.as_slice());
        let next_token = SurfaceToken::new(self.instance.surface_id(), next_global_reload_gen());
        let (next_binding, _) =
            DirectSurfaceBinding::new(next_token, std::sync::Arc::new(WakeBridge::new()));
        let next_env = next_binding.env();
        let old_binding = &mut self.direct_binding;
        let outcome = self
            .instance
            .reload_with_hosts_and_state(
                dylib_path,
                None,
                Some(next_env),
                prior_slice,
                || {
                    old_binding.deactivate_and_invalidate();
                },
                || {},
            )
            .map_err(|e| format!("cdylib hot-swap failed: {e}"))?;
        self.direct_binding = next_binding;
        Ok(outcome.generation)
    }
    fn drain_direct_events(&mut self) -> bool {
        let (dirty, _) = self.direct_binding.queue().drain_with(
            &mut self.direct_scratch,
            &mut self.instance,
            |app, req_id, st, payload| app.dispatch_direct_completion(req_id, st, payload),
            |app, svc, ev_id, flags, payload| app.dispatch_direct_event(svc, ev_id, flags, payload),
        );
        dirty
    }
}