nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Close-request routing ([INV:close-request-single-path]): an `Escape` / `GoBack` key down that
//! no listener consumed closes the topmost open overlay that owns close requests.
//!
//! Walking the [`crate::TopLayerIndex::hoisted`] roots front-to-back (reverse paint order, the
//! published `NvOverlayItem` order) with their resolved flags, the first overlay that is modal
//! or has `CLOSE_ON_ESCAPE` owns the request. It receives a target-only
//! `Custom { name: "close" }` only when it has `CLOSE_ON_ESCAPE`; a non-escapable modal
//! (`closedby="none"`) swallows the request, so nothing beneath it closes — HTML close-watcher
//! semantics.
//!
//! [`CloseRequestAction`] is the built-in, statically ordered `DefaultAction` #0 of every host
//! that owns a scene; they dispatch through [`LaidOutScene::dispatch_routing_close_request`] (or
//! its fallible twin): the one funnel that dispatches a batch, then runs #0 on the close key the
//! dispatch reported unconsumed. The app reports a close request as one bit
//! (`DispatchResult::CLOSE_REQUEST`, the C ABI), so the funnel cuts the batch after every close
//! key: each part holds at most one, as its last event, and the bit names that key.

use std::convert::Infallible;

use nativeview_abi::DispatchResult;
use nativeview_engine::ext::input::{DefaultAction, Disposition};
use nativeview_store::{EventBatchBuf, EventFlags, NodeId, ValidatedEvent, ValidatedEvents};

use super::{LaidOutScene, close_request_owner};
use crate::StoreLayoutEngine;

/// Built-in default action #0: an unconsumed close-request key down writes one target-only
/// `close` to [`LaidOutScene::close_request_target`] into the context batch (cleared first) and
/// is consumed; anything else passes through. Zero allocations once the batch holds one custom
/// event.
pub struct CloseRequestAction<'s, L: StoreLayoutEngine>(pub &'s LaidOutScene<L>);

impl<L: StoreLayoutEngine> DefaultAction<EventBatchBuf> for CloseRequestAction<'_, L> {
    fn run(&mut self, ev: &ValidatedEvent<'_>, out: &mut EventBatchBuf) -> Disposition {
        out.clear();
        if !ev.is_close_request_key_down() {
            return Disposition::PassThrough;
        }
        let Some(target) = self.0.close_request_target() else {
            return Disposition::PassThrough;
        };
        out.push_custom_with_flags(ev.surface(), target, ev.timestamp(), "close", &[], EventFlags::NO_BUBBLE);
        Disposition::Consumed
    }
}

impl<L: StoreLayoutEngine> LaidOutScene<L> {
    /// The overlay an unconsumed close request closes (see the module docs). O(open overlays).
    #[inline]
    pub fn close_request_target(&self) -> Option<NodeId> {
        close_request_owner(self.open_overlays())
    }

    /// Dispatches `events` through `dispatch`, cut after every close key (a batch without one is
    /// one dispatch); when a part reports a close request, its close key is unconsumed. Then
    /// runs [`CloseRequestAction`] on the last unconsumed close key and dispatches its `close`
    /// through `dispatch` too (that dispatch's own close request is ignored: a `close` is no
    /// close key). One `close` per call: the scene is not laid out again in between, so a second
    /// would hit the same overlay. `batch` is the host's reused close batch. Returns whether any
    /// dispatch dirtied app state. Zero steady-state allocations.
    #[inline]
    pub fn dispatch_routing_close_request(
        &self,
        events: ValidatedEvents<'_>,
        batch: &mut EventBatchBuf,
        mut dispatch: impl FnMut(ValidatedEvents<'_>) -> DispatchResult,
    ) -> bool {
        let Ok(dirty) = self.try_dispatch_routing_close_request(events, batch, |ev| {
            Ok::<_, Infallible>(dispatch(ev))
        });
        dirty
    }

    /// [`Self::dispatch_routing_close_request`] for a fallible `dispatch` (e.g. a sandboxed
    /// plugin slot): the first error aborts and is returned.
    pub fn try_dispatch_routing_close_request<E>(
        &self,
        events: ValidatedEvents<'_>,
        batch: &mut EventBatchBuf,
        mut dispatch: impl FnMut(ValidatedEvents<'_>) -> Result<DispatchResult, E>,
    ) -> Result<bool, E> {
        let (mut dirty, mut trigger, mut rest) = (false, None, events);
        loop {
            let end = rest.iter().position(|ev| ev.is_close_request_key_down()).map_or(rest.len(), |i| i + 1);
            let (part, tail) = rest.split_at(end);
            let result = dispatch(part)?;
            dirty |= result.is_dirty();
            if result.is_close_request()
                && let Some(key) = end.checked_sub(1).and_then(|last| part.get(last))
                && key.is_close_request_key_down()
            {
                trigger = Some(key);
            }
            if tail.is_empty() {
                break;
            }
            rest = tail;
        }
        if let Some(trigger) = trigger
            && CloseRequestAction(self).run(&trigger, batch).is_consumed()
        {
            dirty |= dispatch(batch.as_validated())?.is_dirty();
        }
        Ok(dirty)
    }
}