nativeview-codegen 0.1.0-rc.1

Multi-language ABI, policy, flat-op codec, and hybrid Direct-FFI code generator for Native View Engine.
Documentation
//! Top-layer policy conformance vectors ([INV:top-layer-policy-conformance]): the pointer-down
//! "hide popovers until" cases and the close-key probes, with the verdicts the Rust reference
//! computed, rendered for the C++, Swift, Java, Dart and TS host suites. The caller (`nativeview-cli`)
//! evaluates the reference (`nativeview_layout::scene::top_layer_conformance`) and passes plain data, so
//! this crate stays layout-free.

use askama::Template;
use nativeview_abi::{NodeId, NvOverlayItem};

use super::{CXX, DART, JAVA, SWIFT, TS, render_with_cap};
use crate::error::CodegenError;
use crate::schema::export::GeneratedFile;

/// The reference-computed vectors.
#[derive(Debug, Clone, Default)]
pub struct TopLayerVectors {
    /// Scene trees as `(node, parent)` pairs (`NodeId::NULL` parents a root), shared by cases.
    pub trees: Vec<Vec<(NodeId, NodeId)>>,
    pub press: Vec<PressVector>,
    /// `(key, is_close_request_key)`.
    pub close_keys: Vec<(&'static str, bool)>,
}

/// One pointer-down case and its verdict.
#[derive(Debug, Clone)]
pub struct PressVector {
    pub name: &'static str,
    /// Index into [`TopLayerVectors::trees`].
    pub tree: usize,
    /// Open overlays, back to front, as published.
    pub overlays: Vec<NvOverlayItem>,
    pub x: f32,
    pub y: f32,
    /// Hit node (`NULL`: none).
    pub hit: NodeId,
    /// The `topmost_modal` scene fact input (`NULL`: none), authoritative over the MODAL flags.
    pub topmost_modal: NodeId,
    /// `PressOutcome` variant name (`LightDismiss`).
    pub outcome: String,
    pub modal_barrier: bool,
    /// The backmost overlay closed (`NULL` unless light dismiss).
    pub until: NodeId,
    /// Overlays closed, front to back.
    pub dismissed: Vec<NodeId>,
}

/// An `f32` spelled as a literal of each host language (non-finite values included).
#[derive(Debug, Clone, Copy)]
pub struct F(pub f32);

impl F {
    fn finite(self) -> Option<String> {
        self.0.is_finite().then(|| format!("{:?}", self.0))
    }
    fn spell(self, suffix: &str, nan: &str, inf: &str) -> String {
        match self.finite() {
            Some(v) => format!("{v}{suffix}"),
            None if self.0.is_nan() => nan.to_owned(),
            None if self.0 > 0.0 => inf.to_owned(),
            None => format!("-{inf}"),
        }
    }
    pub fn c(&self) -> String {
        self.spell("f", "std::numeric_limits<float>::quiet_NaN()", "std::numeric_limits<float>::infinity()")
    }
    pub fn swift(&self) -> String {
        self.spell("", "Float.nan", "Float.infinity")
    }
    pub fn java(&self) -> String {
        self.spell("f", "Float.NaN", "Float.POSITIVE_INFINITY")
    }
    pub fn dart(&self) -> String {
        self.spell("", "double.nan", "double.infinity")
    }
    pub fn ts(&self) -> String {
        self.spell("", "NaN", "Infinity")
    }
}

/// One overlay item as the templates see it.
pub struct ItemView {
    pub node: NodeId,
    pub x: F,
    pub y: F,
    pub width: F,
    pub height: F,
    pub flags: u16,
    pub layer: u8,
    pub color: u32,
    pub anchor: NodeId,
}

impl ItemView {
    /// RGBA8888 as hex (a valid `int` literal in Java even with the top bit set).
    pub fn color_hex(&self) -> String {
        format!("0x{:08X}", self.color)
    }
}

/// One case as the templates see it.
pub struct CaseView<'a> {
    pub v: &'a PressVector,
    pub items: Vec<ItemView>,
    pub x: F,
    pub y: F,
    /// `lightDismiss`.
    pub camel: String,
    /// `LIGHT_DISMISS`.
    pub screaming: String,
}

impl<'a> CaseView<'a> {
    fn new(v: &'a PressVector) -> Self {
        let items = v
            .overlays
            .iter()
            .map(|o| ItemView {
                node: o.node_id,
                x: F(o.x),
                y: F(o.y),
                width: F(o.width),
                height: F(o.height),
                flags: o.flags.bits(),
                layer: o.layer.raw(),
                color: o.backdrop_color,
                anchor: o.anchor_node_id,
            })
            .collect();
        let mut camel = v.outcome.clone();
        camel[..1].make_ascii_lowercase();
        Self {
            v,
            items,
            x: F(v.x),
            y: F(v.y),
            camel,
            screaming: super::spell::screaming(&v.outcome),
        }
    }
}

macro_rules! vector_templates {
    ($($name:ident: $path:literal;)*) => {$(
        #[derive(Template)]
        #[template(path = $path, escape = "none")]
        struct $name<'a> {
            trees: &'a [Vec<(NodeId, NodeId)>],
            cases: &'a [CaseView<'a>],
            keys: &'a [(&'static str, bool)],
        }
    )*};
}

vector_templates! {
    CxxTopLayer: "c/top_layer_vectors.hpp";
    SwiftTopLayer: "swift/TopLayerVectors.swift";
    JavaTopLayer: "java/TopLayerVectors.java";
    DartTopLayer: "dart/top_layer_vectors.dart";
    TsTopLayer: "ts/top_layer_vectors.ts";
}

/// The five host suites' vector files.
pub fn generate_top_layer_vector_files(v: &TopLayerVectors) -> Result<Vec<GeneratedFile>, CodegenError> {
    let plain = |s: &str| s.bytes().all(|b| (b' '..=b'~').contains(&b) && !matches!(b, b'"' | b'\'' | b'\\' | b'$'));
    if let Some(bad) = v
        .press
        .iter()
        .find(|c| c.tree >= v.trees.len() || c.outcome.is_empty() || !plain(c.name))
    {
        return Err(CodegenError::validation(format!("top-layer vector `{}` is malformed", bad.name)));
    }
    if let Some((bad, _)) = v.close_keys.iter().find(|(k, _)| !plain(k)) {
        return Err(CodegenError::validation(format!("close-key probe `{bad}` needs escaping")));
    }
    let cases: Vec<CaseView<'_>> = v.press.iter().map(CaseView::new).collect();
    let (trees, cases, keys) = (v.trees.as_slice(), cases.as_slice(), v.close_keys.as_slice());
    const CAP: usize = 64 * 1024;
    Ok(vec![
        render_with_cap(
            &CxxTopLayer { trees, cases, keys },
            format!("{CXX}/tests/top_layer_vectors.generated.hpp"),
            CAP,
        )?,
        render_with_cap(
            &SwiftTopLayer { trees, cases, keys },
            format!("{SWIFT}/Tests/NativeViewHostTests/TopLayerVectors.generated.swift"),
            CAP,
        )?,
        render_with_cap(
            &JavaTopLayer { trees, cases, keys },
            format!("{JAVA}/test/java/io/github/nativeview/host/generated/TopLayerVectors.java"),
            CAP,
        )?,
        render_with_cap(
            &DartTopLayer { trees, cases, keys },
            format!("{DART}/test/src/top_layer_vectors.generated.dart"),
            CAP,
        )?,
        render_with_cap(
            &TsTopLayer { trees, cases, keys },
            format!("{TS}/test/top_layer_vectors.generated.ts"),
            CAP,
        )?,
    ])
}