nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
//! Shared, ref-counted app module handle ([`NvAppModule`]) for multi-surface execution.
//!
//! Opening N surfaces for the same app `cdylib` stages and `dlopen`s the library **once per reload
//! generation** (`staged_loads == 1`) so every surface shares the exact same Rust `static`s,
//! `SharedAtom<T>`s, and allocator while unloading cleanly once the last surface detaches.

#[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
use std::path::Path;
#[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
use std::sync::Arc;

use nativeview_abi::NvGetInterfaceFn;

#[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
use crate::loader::{LoaderError, StagedDylib};

#[derive(Clone)]
enum ModuleBacking {
    #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
    Dylib(Arc<StagedDylib>),
    Static(NvGetInterfaceFn),
}

/// Ref-counted handle to one loaded app module generation (`Arc<StagedDylib>` or static
/// `NvGetInterfaceFn`).
///
/// Cloning is an O(1) atomic refcount bump that shares the single mapped `cdylib` across all
/// surfaces attached to the same generation (`[INV:multi-surface-shared-dylib]`).
#[derive(Clone)]
pub struct NvAppModule {
    backing: ModuleBacking,
    generation: u64,
    staged_loads: u64,
}

impl NvAppModule {
    /// Stages and `dlopen`s `dylib_path` **once** (generation 1) into a shared [`NvAppModule`].
    #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
    pub fn load(dylib_path: &Path, subdir: &str, label: &str) -> Result<Self, LoaderError> {
        let staged = StagedDylib::load(dylib_path, subdir, label)?;
        Ok(Self::from_staged_dylib(Arc::new(staged), 1))
    }

    /// Stages and `dlopen`s `dylib_path` **once** for reload `generation` into a shared
    /// [`NvAppModule`].
    #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
    pub fn load_generation(
        dylib_path: &Path,
        subdir: &str,
        generation: u64,
    ) -> Result<Self, LoaderError> {
        let staged = StagedDylib::load(dylib_path, subdir, &format!("gen{generation}"))?;
        Ok(Self::from_staged_dylib(Arc::new(staged), generation))
    }

    /// Wraps an already-loaded [`StagedDylib`] as generation `generation` (`staged_loads == 1`).
    #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
    pub fn from_staged_dylib(staged: Arc<StagedDylib>, generation: u64) -> Self {
        Self {
            backing: ModuleBacking::Dylib(staged),
            generation,
            staged_loads: 1,
        }
    }

    /// Wraps a statically linked or in-process `nv_get_interface` entry point (zero dylib
    /// staging; works on every target including `wasm32`).
    #[inline]
    pub fn from_get_interface(get_interface: NvGetInterfaceFn) -> Self {
        Self::from_get_interface_generation(get_interface, 1)
    }

    /// Wraps a statically linked `nv_get_interface` entry point tagged with `generation`.
    #[inline]
    pub fn from_get_interface_generation(
        get_interface: NvGetInterfaceFn,
        generation: u64,
    ) -> Self {
        Self {
            backing: ModuleBacking::Static(get_interface),
            generation,
            staged_loads: 0,
        }
    }

    /// Returns the resolved `nv_get_interface` entry point backed by this module.
    #[inline]
    pub fn get_interface(&self) -> NvGetInterfaceFn {
        match &self.backing {
            #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
            ModuleBacking::Dylib(staged) => staged.get_interface(),
            ModuleBacking::Static(f) => *f,
        }
    }

    /// Reload generation of this module (`1` for initial load, incremented per atomic reload).
    #[inline]
    pub fn generation(&self) -> u64 {
        self.generation
    }

    /// Number of staged `cdylib` loads performed to produce this generation (`1` for dylib loads,
    /// `0` for statically linked `nv_get_interface`).
    #[inline]
    pub fn staged_loads(&self) -> u64 {
        self.staged_loads
    }

    /// Path of the private staged copy (or resolved in-place file on mobile), or `None` for
    /// statically linked modules.
    #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
    pub fn loaded_copy_path(&self) -> Option<&Path> {
        match &self.backing {
            ModuleBacking::Dylib(staged) => Some(staged.loaded_copy_path()),
            ModuleBacking::Static(_) => None,
        }
    }

    /// Strong reference count of the underlying `Arc<StagedDylib>` (`1` for static modules).
    #[inline]
    pub fn strong_count(&self) -> usize {
        match &self.backing {
            #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
            ModuleBacking::Dylib(staged) => Arc::strong_count(staged),
            ModuleBacking::Static(_) => 1,
        }
    }

    /// Returns `true` when both handles share the exact same underlying mapped `StagedDylib`
    /// allocation (or identical static `nv_get_interface` function pointer).
    #[inline]
    pub fn same_backing(&self, other: &Self) -> bool {
        match (&self.backing, &other.backing) {
            #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
            (ModuleBacking::Dylib(a), ModuleBacking::Dylib(b)) => Arc::ptr_eq(a, b),
            (ModuleBacking::Static(a), ModuleBacking::Static(b)) => {
                std::ptr::fn_addr_eq(*a, *b)
            }
            #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
            _ => false,
        }
    }
}

impl std::fmt::Debug for NvAppModule {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("NvAppModule");
        s.field("generation", &self.generation)
            .field("staged_loads", &self.staged_loads)
            .field("strong_count", &self.strong_count());
        #[cfg(all(not(target_arch = "wasm32"), feature = "dynamic-loader"))]
        s.field("loaded_copy_path", &self.loaded_copy_path());
        s.finish()
    }
}