euv-core 0.47.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Runs `operation` with `ctx` bound as the active ambient `Context`, restoring any previous context on exit.
///
/// # Arguments
///
/// - `Context` - Framework context to bind during `operation`.
/// - `F` - Closure executing declarative UI construction (`view!` or components).
///
/// # Returns
///
/// - `R` - Value returned by `operation`.
pub fn with_context<F, R>(ctx: Context, operation: F) -> R
where
    F: FnOnce() -> R,
{
    let previous: Option<Context> =
        ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| slot.borrow_mut().replace(ctx));
    let _guard: ContextGuard = ContextGuard::new(previous);
    operation()
}

/// Borrows the active ambient `Context` without cloning its 216-byte struct or bumping its `Rc` handles.
///
/// # Arguments
///
/// - `F` - Closure receiving a borrowed `&Context` reference.
///
/// # Returns
///
/// - `R` - Value returned by `operation`.
pub fn with_current_context<F, R>(operation: F) -> R
where
    F: FnOnce(&Context) -> R,
{
    ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
        let borrowed: Ref<'_, Option<Context>> = slot.borrow();
        if let Some(ctx) = borrowed.as_ref() {
            operation(ctx)
        } else {
            drop(borrowed);
            let fallback: Context = Context::new(SceneHandle::new_tree(), PlatformKind::Headless);
            operation(&fallback)
        }
    })
}

/// Returns a cloned handle to the active ambient `Context`.
///
/// # Returns
///
/// - `Context` - Currently bound ambient framework context.
#[must_use]
pub fn current_context() -> Context {
    ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
        slot.borrow()
            .clone()
            .unwrap_or_else(|| Context::new(SceneHandle::new_tree(), PlatformKind::Headless))
    })
}

/// Returns `true` when an ambient `Context` is currently bound on this thread.
///
/// # Returns
///
/// - `bool` - Whether `with_context` or `App::mount` is active.
#[must_use]
pub fn has_context() -> bool {
    ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| slot.borrow().is_some())
}

/// Returns the active `PlatformKind` from the ambient `Context`.
///
/// # Returns
///
/// - `PlatformKind` - Execution platform kind.
#[must_use]
pub fn current_platform() -> PlatformKind {
    with_current_context(|ctx: &Context| ctx.get_platform())
}

/// Mounts a reactive `Text` node in the ambient `Context` without cloning the full `Context` struct.
///
/// # Arguments
///
/// - `Style` - Initial text style.
/// - `F` - Reactive text producer closure.
///
/// # Returns
///
/// - `NodeId` - Created reactive text node handle.
pub fn mount_reactive_text<F>(style: Style, producer: F) -> NodeId
where
    F: FnMut() -> String + 'static,
{
    let handle: SceneHandle = with_current_context(|ctx: &Context| ctx.get_scene().clone());
    let node_id: NodeId = handle.with_write(
        |tree: &mut SceneTree| tree.create_text(String::new(), style),
        NodeId::default(),
    );
    let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| handle.bind_text(node_id, producer));
    handle.mutate(move |tree: &mut SceneTree| {
        tree.attach_scope(node_id, scope);
    });
    node_id
}

/// Binds a reactive `Style` closure onto `node_id` in the ambient `Context` without cloning `Context`.
///
/// # Arguments
///
/// - `NodeId` - Target scene node handle.
/// - `F` - Reactive `Style` producer closure.
pub fn bind_style_current<F>(node_id: NodeId, producer: F)
where
    F: FnMut() -> Style + 'static,
{
    let handle: SceneHandle = with_current_context(|ctx: &Context| ctx.get_scene().clone());
    let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| handle.bind_style(node_id, producer));
    handle.mutate(move |tree: &mut SceneTree| {
        tree.attach_scope(node_id, scope);
    });
}

/// Mounts a reactive child builder onto `host` using the ambient `Context`.
///
/// # Arguments
///
/// - `NodeId` - Host container node handle.
/// - `F` - Reactive child builder returning ordered `NodeId` values.
pub fn bind_children_current<F>(host: NodeId, builder: F)
where
    F: FnMut() -> Vec<NodeId> + 'static,
{
    let mut ctx: Context = current_context();
    ctx.bind_children(host, builder);
}

/// Converts any string-like value into an owned `String` for declarative `view!` macro expansion.
///
/// # Arguments
///
/// - `T` - String-like text value implementing `Into<String>`.
///
/// # Returns
///
/// - `String` - Owned UTF-8 text string.
#[must_use]
pub fn into_text<T>(value: T) -> String
where
    T: Into<String>,
{
    value.into()
}

/// Registers a zero-allocation platform frame-wakeup callback invoked whenever reactive or scene state dirties an idle frame loop.
///
/// # Arguments
///
/// - `fn()` - Wakeup callback requesting the next host VSync or `requestAnimationFrame` presentation.
pub fn register_frame_wakeup(hook: fn()) {
    FRAME_WAKEUP_HOOK.store(hook as *mut (), Ordering::Release);
    if FRAME_NEEDED.load(Ordering::Acquire) {
        hook();
    }
}

/// Unregisters any active platform frame-wakeup callback.
pub fn clear_frame_wakeup() {
    FRAME_WAKEUP_HOOK.store(null_mut(), Ordering::Release);
}

/// Marks that pending reactive or scene updates require presentation and invokes the registered wakeup hook on idle-to-dirty edges.
#[inline(always)]
pub fn notify_frame_needed() {
    if !FRAME_NEEDED.load(Ordering::Relaxed) && !FRAME_NEEDED.swap(true, Ordering::AcqRel) {
        let raw: *mut () = FRAME_WAKEUP_HOOK.load(Ordering::Acquire);
        if !raw.is_null() {
            // SAFETY: `raw` is stored exclusively via `register_frame_wakeup` from a valid `fn()` pointer.
            let hook: fn() = unsafe { transmute::<*mut (), fn()>(raw) };
            hook();
        }
    }
}

/// Atomically consumes and clears the pending frame-wakeup flag before rendering a frame.
///
/// # Returns
///
/// - `bool` - `true` when at least one reactive or scene invalidation occurred since the previous take.
#[must_use]
#[inline(always)]
pub fn take_frame_needed() -> bool {
    FRAME_NEEDED.swap(false, Ordering::AcqRel)
}

/// Returns whether a reactive or scene invalidation has marked a new frame as needed without consuming the flag.
///
/// # Returns
///
/// - `bool` - `true` when a new frame presentation has been requested.
#[must_use]
#[inline(always)]
pub fn is_frame_needed() -> bool {
    FRAME_NEEDED.load(Ordering::Acquire)
}

/// Returns `true` when any `SceneTree` borrow is currently active on the current thread.
///
/// # Returns
///
/// - `bool` - Whether a `SceneTree` read or write guard is active on this thread.
#[must_use]
#[inline(always)]
pub(crate) fn is_scene_borrowed() -> bool {
    SCENE_BORROW_DEPTH
        .try_with(|depth: &Cell<u32>| depth.get() > 0)
        .unwrap_or(false)
}

/// Records that `flush_effects` deferred effect execution until the active `SceneTree` borrow exits.
#[inline(always)]
pub(crate) fn defer_effect_flush_while_borrowed() {
    let _: Result<(), _> = DEFERRED_EFFECT_FLUSH.try_with(|flag: &Cell<bool>| {
        flag.set(true);
    });
    notify_frame_needed();
}

/// Returns `true` when a deferred reactive effect flush is queued for the current thread without clearing it.
///
/// # Returns
///
/// - `bool` - Whether deferred reactive effects are waiting for the outer scene borrow to drop.
#[must_use]
#[inline(always)]
pub(crate) fn has_deferred_effect_flush() -> bool {
    DEFERRED_EFFECT_FLUSH.try_with(Cell::get).unwrap_or(false)
}

/// Consumes and clears the thread-local deferred reactive effect flush flag.
///
/// # Returns
///
/// - `bool` - `true` when effects were deferred while a `SceneTree` borrow was active.
#[must_use]
#[inline(always)]
pub(crate) fn take_deferred_effect_flush() -> bool {
    DEFERRED_EFFECT_FLUSH
        .try_with(|flag: &Cell<bool>| flag.replace(false))
        .unwrap_or(false)
}

/// Resets thread-local scene borrow-depth tracking and deferred flush state during runtime resets.
pub(crate) fn reset_scene_borrow_state() {
    let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
        depth.set(0);
    });
    let _: Result<(), _> = DEFERRED_EFFECT_FLUSH.try_with(|flag: &Cell<bool>| {
        flag.set(false);
    });
    FRAME_NEEDED.store(false, Ordering::Release);
}