Skip to main content

nativeview_codegen/abi/
top_layer_vectors.rs

1//! Top-layer policy conformance vectors ([INV:top-layer-policy-conformance]): the pointer-down
2//! "hide popovers until" cases and the close-key probes, with the verdicts the Rust reference
3//! computed, rendered for the C++, Swift, Java, Dart and TS host suites. The caller (`nativeview-cli`)
4//! evaluates the reference (`nativeview_layout::scene::top_layer_conformance`) and passes plain data, so
5//! this crate stays layout-free.
6
7use askama::Template;
8use nativeview_abi::{NodeId, NvOverlayItem};
9
10use super::{CXX, DART, JAVA, SWIFT, TS, render_with_cap};
11use crate::error::CodegenError;
12use crate::schema::export::GeneratedFile;
13
14/// The reference-computed vectors.
15#[derive(Debug, Clone, Default)]
16pub struct TopLayerVectors {
17    /// Scene trees as `(node, parent)` pairs (`NodeId::NULL` parents a root), shared by cases.
18    pub trees: Vec<Vec<(NodeId, NodeId)>>,
19    pub press: Vec<PressVector>,
20    /// `(key, is_close_request_key)`.
21    pub close_keys: Vec<(&'static str, bool)>,
22}
23
24/// One pointer-down case and its verdict.
25#[derive(Debug, Clone)]
26pub struct PressVector {
27    pub name: &'static str,
28    /// Index into [`TopLayerVectors::trees`].
29    pub tree: usize,
30    /// Open overlays, back to front, as published.
31    pub overlays: Vec<NvOverlayItem>,
32    pub x: f32,
33    pub y: f32,
34    /// Hit node (`NULL`: none).
35    pub hit: NodeId,
36    /// The `topmost_modal` scene fact input (`NULL`: none), authoritative over the MODAL flags.
37    pub topmost_modal: NodeId,
38    /// `PressOutcome` variant name (`LightDismiss`).
39    pub outcome: String,
40    pub modal_barrier: bool,
41    /// The backmost overlay closed (`NULL` unless light dismiss).
42    pub until: NodeId,
43    /// Overlays closed, front to back.
44    pub dismissed: Vec<NodeId>,
45}
46
47/// An `f32` spelled as a literal of each host language (non-finite values included).
48#[derive(Debug, Clone, Copy)]
49pub struct F(pub f32);
50
51impl F {
52    fn finite(self) -> Option<String> {
53        self.0.is_finite().then(|| format!("{:?}", self.0))
54    }
55    fn spell(self, suffix: &str, nan: &str, inf: &str) -> String {
56        match self.finite() {
57            Some(v) => format!("{v}{suffix}"),
58            None if self.0.is_nan() => nan.to_owned(),
59            None if self.0 > 0.0 => inf.to_owned(),
60            None => format!("-{inf}"),
61        }
62    }
63    pub fn c(&self) -> String {
64        self.spell("f", "std::numeric_limits<float>::quiet_NaN()", "std::numeric_limits<float>::infinity()")
65    }
66    pub fn swift(&self) -> String {
67        self.spell("", "Float.nan", "Float.infinity")
68    }
69    pub fn java(&self) -> String {
70        self.spell("f", "Float.NaN", "Float.POSITIVE_INFINITY")
71    }
72    pub fn dart(&self) -> String {
73        self.spell("", "double.nan", "double.infinity")
74    }
75    pub fn ts(&self) -> String {
76        self.spell("", "NaN", "Infinity")
77    }
78}
79
80/// One overlay item as the templates see it.
81pub struct ItemView {
82    pub node: NodeId,
83    pub x: F,
84    pub y: F,
85    pub width: F,
86    pub height: F,
87    pub flags: u16,
88    pub layer: u8,
89    pub color: u32,
90    pub anchor: NodeId,
91}
92
93impl ItemView {
94    /// RGBA8888 as hex (a valid `int` literal in Java even with the top bit set).
95    pub fn color_hex(&self) -> String {
96        format!("0x{:08X}", self.color)
97    }
98}
99
100/// One case as the templates see it.
101pub struct CaseView<'a> {
102    pub v: &'a PressVector,
103    pub items: Vec<ItemView>,
104    pub x: F,
105    pub y: F,
106    /// `lightDismiss`.
107    pub camel: String,
108    /// `LIGHT_DISMISS`.
109    pub screaming: String,
110}
111
112impl<'a> CaseView<'a> {
113    fn new(v: &'a PressVector) -> Self {
114        let items = v
115            .overlays
116            .iter()
117            .map(|o| ItemView {
118                node: o.node_id,
119                x: F(o.x),
120                y: F(o.y),
121                width: F(o.width),
122                height: F(o.height),
123                flags: o.flags.bits(),
124                layer: o.layer.raw(),
125                color: o.backdrop_color,
126                anchor: o.anchor_node_id,
127            })
128            .collect();
129        let mut camel = v.outcome.clone();
130        camel[..1].make_ascii_lowercase();
131        Self {
132            v,
133            items,
134            x: F(v.x),
135            y: F(v.y),
136            camel,
137            screaming: super::spell::screaming(&v.outcome),
138        }
139    }
140}
141
142macro_rules! vector_templates {
143    ($($name:ident: $path:literal;)*) => {$(
144        #[derive(Template)]
145        #[template(path = $path, escape = "none")]
146        struct $name<'a> {
147            trees: &'a [Vec<(NodeId, NodeId)>],
148            cases: &'a [CaseView<'a>],
149            keys: &'a [(&'static str, bool)],
150        }
151    )*};
152}
153
154vector_templates! {
155    CxxTopLayer: "c/top_layer_vectors.hpp";
156    SwiftTopLayer: "swift/TopLayerVectors.swift";
157    JavaTopLayer: "java/TopLayerVectors.java";
158    DartTopLayer: "dart/top_layer_vectors.dart";
159    TsTopLayer: "ts/top_layer_vectors.ts";
160}
161
162/// The five host suites' vector files.
163pub fn generate_top_layer_vector_files(v: &TopLayerVectors) -> Result<Vec<GeneratedFile>, CodegenError> {
164    let plain = |s: &str| s.bytes().all(|b| (b' '..=b'~').contains(&b) && !matches!(b, b'"' | b'\'' | b'\\' | b'$'));
165    if let Some(bad) = v
166        .press
167        .iter()
168        .find(|c| c.tree >= v.trees.len() || c.outcome.is_empty() || !plain(c.name))
169    {
170        return Err(CodegenError::validation(format!("top-layer vector `{}` is malformed", bad.name)));
171    }
172    if let Some((bad, _)) = v.close_keys.iter().find(|(k, _)| !plain(k)) {
173        return Err(CodegenError::validation(format!("close-key probe `{bad}` needs escaping")));
174    }
175    let cases: Vec<CaseView<'_>> = v.press.iter().map(CaseView::new).collect();
176    let (trees, cases, keys) = (v.trees.as_slice(), cases.as_slice(), v.close_keys.as_slice());
177    const CAP: usize = 64 * 1024;
178    Ok(vec![
179        render_with_cap(
180            &CxxTopLayer { trees, cases, keys },
181            format!("{CXX}/tests/top_layer_vectors.generated.hpp"),
182            CAP,
183        )?,
184        render_with_cap(
185            &SwiftTopLayer { trees, cases, keys },
186            format!("{SWIFT}/Tests/NativeViewHostTests/TopLayerVectors.generated.swift"),
187            CAP,
188        )?,
189        render_with_cap(
190            &JavaTopLayer { trees, cases, keys },
191            format!("{JAVA}/test/java/io/github/nativeview/host/generated/TopLayerVectors.java"),
192            CAP,
193        )?,
194        render_with_cap(
195            &DartTopLayer { trees, cases, keys },
196            format!("{DART}/test/src/top_layer_vectors.generated.dart"),
197            CAP,
198        )?,
199        render_with_cap(
200            &TsTopLayer { trees, cases, keys },
201            format!("{TS}/test/top_layer_vectors.generated.ts"),
202            CAP,
203        )?,
204    ])
205}