Skip to main content

cranpose_app_shell/
placed_semantics.rs

1//! What a screen reader is told, and where each of those things actually is.
2//!
3//! [`build_semantics_tree_from_applier`] answers the first half and carries no
4//! geometry at all; a [`LayoutBox`] carries the geometry and knows nothing about
5//! semantics. Every question of the form "is this control big enough / on the
6//! display / where the label says it is" needs both halves joined, and the join
7//! existed in exactly one place: inside the desktop robot, behind an `AppShell`,
8//! a window and an event loop. A unit test that wants to audit a widget tree's
9//! touch targets could not reach it.
10//!
11//! This is that join, headless. One composition, one measure pass, and a tree of
12//! [`PlacedSemanticsNode`] carrying **two** boxes per node, because they are two
13//! different questions and a Wear scaling list is precisely where they diverge:
14//!
15//! - [`PlacedSemanticsNode::layout_bounds`] is the box the measure pass gave the
16//!   node — what the widget asked for and what an unscaled row occupies. This is
17//!   the box the desktop robot reports, and the one to assert a widget's own
18//!   declared minimum against.
19//! - [`PlacedSemanticsNode::touch_bounds`] is the axis-aligned box the renderer
20//!   draws and the hit test inverts, ancestor graphics layers included. A row
21//!   that a scaling ramp shrinks to 0.73 is only tappable where it is drawn
22//!   (`cranpose-render-common`'s `a_shrunken_row_is_only_tappable_where_it_is_drawn`
23//!   settles that), so this is the box a finger has to find. It is `None` for a
24//!   node the hit graph carries no region for — a label, a header, anything that
25//!   is described but not interactive. Gesture containers such as scrollable
26//!   lists are interactive even though they do not expose a click action.
27//!
28//! ## Every walk here reads the RETAINED tree, deliberately
29//!
30//! `compute_layout` returns a `LayoutTree` built from the `Placement`s a
31//! `MeasurePolicy` returned. The scene the
32//! renderer is handed is not: [`build_graph_from_applier`] walks the retained
33//! node state and drops any node whose `is_placed` is false, and `is_placed` is
34//! set by `placeable.place(x, y)` — *not* by pushing a `Placement` into a vec.
35//! The two disagreed once and a whole widget set laid out correctly in every
36//! assertion while reaching the device as an empty screen.
37//!
38//! So the layout boxes here come from [`build_layout_tree_from_applier`] and not
39//! from the tree `compute_layout` hands back. All three walks — layout,
40//! semantics, scene — then apply the same `is_placed` filter, and a node that
41//! one of them loses is lost by all of them. A caller cannot be handed bounds
42//! for a control the renderer never drew.
43
44use cranpose_core::{MemoryApplier, NodeError, NodeId, collections::map::HashMap};
45use cranpose_render_common::{
46    Renderer,
47    graph::{HitTestNode, ProjectiveTransform},
48    graph_scene::HitGeometry,
49    hit_graph::{HitGraphSink, collect_hits_from_graph},
50    scene_builder::build_graph_from_applier,
51};
52use cranpose_ui::{
53    LayoutBox, LayoutEngine, LayoutTree, Rect, SemanticsAction, SemanticsNode, SemanticsRole,
54    SemanticsWidgetRole, Size, build_layout_tree_from_applier, build_semantics_tree_from_applier,
55};
56
57use crate::AppShell;
58
59/// One semantics node, with the geometry it was placed and drawn at.
60///
61/// Field-for-field a subset of [`SemanticsNode`] plus the two boxes; the fields
62/// that are dropped are the ones a geometry audit has no use for (custom
63/// actions, text selection, the canvas children a drawn control publishes —
64/// those already carry their own bounds).
65#[derive(Clone, Debug, PartialEq)]
66pub struct PlacedSemanticsNode {
67    pub node_id: NodeId,
68    /// Where the node sits in the tree: layout, text, subcomposition …
69    pub role: SemanticsRole,
70    /// What a screen reader announces it as — Compose's `Role`.
71    pub widget_role: Option<SemanticsWidgetRole>,
72    /// The name a reader speaks, including merged text and excluding password values.
73    pub label: Option<String>,
74    pub state_description: Option<String>,
75    /// Whether the node carries a click action, which is what separates a
76    /// control from something merely described.
77    pub clickable: bool,
78    /// Whether the renderer carries any pointer-dispatch region for the node.
79    /// This also includes gesture-only containers such as scrollable lists.
80    pub interactive: bool,
81    pub toggled: Option<bool>,
82    pub selected: Option<bool>,
83    pub enabled: bool,
84    /// Whether a reader can type into the node.
85    pub editable_text: bool,
86    /// Whether Tab and a reader's focus reach the node.
87    pub focusable: bool,
88    /// Whether a reader skips the node and everything under it.
89    pub hidden: bool,
90    /// The title the node gives the screen, when it is the screen's root.
91    pub pane_title: Option<String>,
92    /// Where the app moved the node in the reading order; 0 leaves it be.
93    pub traversal_index: f32,
94    /// The name tests find the node by (`Modifier::test_tag`).
95    pub test_tag: Option<String>,
96    /// The place of a row among the rows of its list, counted from 1, when
97    /// the parent says it is a collection. A reader speaks it, so two rows
98    /// with one name are told apart.
99    pub list_position: Option<usize>,
100    /// The box the measure pass gave this node, in window coordinates.
101    pub layout_bounds: Rect,
102    /// The box the renderer draws and the hit test inverts, ancestor graphics
103    /// layers included. `None` when the hit graph carries no region for it.
104    pub touch_bounds: Option<Rect>,
105    pub children: Vec<PlacedSemanticsNode>,
106}
107
108impl PlacedSemanticsNode {
109    /// The box a finger has to find: the drawn quad where there is one, and the
110    /// layout box where the node is not a hit target at all.
111    pub fn target_bounds(&self) -> Rect {
112        self.touch_bounds.unwrap_or(self.layout_bounds)
113    }
114
115    /// Depth-first walk, self first.
116    pub fn visit(&self, visitor: &mut impl FnMut(&PlacedSemanticsNode)) {
117        visitor(self);
118        for child in &self.children {
119            child.visit(visitor);
120        }
121    }
122
123    /// Every node in the subtree, self first, in tree order.
124    pub fn flatten(&self) -> Vec<&PlacedSemanticsNode> {
125        let mut all = Vec::new();
126        self.collect(&mut all);
127        all
128    }
129
130    fn collect<'a>(&'a self, out: &mut Vec<&'a PlacedSemanticsNode>) {
131        out.push(self);
132        for child in &self.children {
133            child.collect(out);
134        }
135    }
136
137    /// The first node in the subtree, self first, that carries `tag`
138    /// (`Modifier::test_tag`).
139    pub fn find_by_tag(&self, tag: &str) -> Option<&PlacedSemanticsNode> {
140        if self.test_tag.as_deref() == Some(tag) {
141            return Some(self);
142        }
143        self.children
144            .iter()
145            .find_map(|child| child.find_by_tag(tag))
146    }
147
148    /// Every node a tap would do something to.
149    pub fn controls(&self) -> Vec<&PlacedSemanticsNode> {
150        self.flatten()
151            .into_iter()
152            .filter(|node| node.clickable)
153            .collect()
154    }
155
156    /// A name for an assertion message: the label if there is one, else the
157    /// role and the node id, which at least says which one it was.
158    pub fn describe(&self) -> String {
159        match &self.label {
160            Some(label) => format!("{label:?}"),
161            None => format!("{:?}#{}", self.role, self.node_id),
162        }
163    }
164}
165
166/// Lay `root` out at `size` and read back its semantics with geometry.
167///
168/// The applier must already be carrying a runtime handle
169/// (`MemoryApplier::set_runtime_handle`) — a subcomposing widget cannot be
170/// measured without one. `ComposeTestRule::placed_semantics` in cranpose-testing
171/// does that part; this is for a caller driving a `TestComposition` by hand.
172///
173/// `None` means the composition placed nothing at all, which for a root that
174/// composed content is itself the answer to a bug hunt.
175pub fn placed_semantics_from_applier(
176    applier: &mut MemoryApplier,
177    root: NodeId,
178    size: Size,
179) -> Result<Option<PlacedSemanticsNode>, NodeError> {
180    applier.compute_layout(root, size)?;
181
182    let Some(layout) = build_layout_tree_from_applier(applier, root)? else {
183        return Ok(None);
184    };
185    let Some(semantics) = build_semantics_tree_from_applier(applier, root)? else {
186        return Ok(None);
187    };
188
189    let mut layout_bounds = HashMap::default();
190    index_layout_bounds(layout.root(), &mut layout_bounds);
191
192    let mut touch_bounds = HashMap::default();
193    if let Some(graph) = build_graph_from_applier(applier, root, 1.0) {
194        let mut sink = TouchBoundsSink {
195            bounds: &mut touch_bounds,
196        };
197        collect_hits_from_graph(
198            &graph.root,
199            ProjectiveTransform::identity(),
200            &mut sink,
201            None,
202        );
203    }
204
205    join(semantics.root(), &layout_bounds, &touch_bounds).map(Some)
206}
207
208fn index_layout_bounds(layout_box: &LayoutBox, out: &mut HashMap<NodeId, Rect>) {
209    out.insert(layout_box.node_id, layout_box.rect);
210    for child in &layout_box.children {
211        index_layout_bounds(child, out);
212    }
213}
214
215struct TouchBoundsSink<'a> {
216    bounds: &'a mut HashMap<NodeId, Rect>,
217}
218
219impl HitGraphSink for TouchBoundsSink<'_> {
220    fn push_hit(
221        &mut self,
222        node_id: NodeId,
223        _capture_path: &[NodeId],
224        geometry: HitGeometry<'_>,
225        _hit: &HitTestNode,
226    ) {
227        self.bounds.entry(node_id).or_insert(geometry.rect);
228    }
229}
230
231/// Gives a row and everything inside it the place of the row, so that two
232/// rows with one name, and the controls inside them, are apart. A list inside
233/// a row keeps the places it gave its own rows.
234pub(crate) fn place_row(row: &mut PlacedSemanticsNode, position: usize) {
235    if row.list_position.is_some() {
236        return;
237    }
238    row.list_position = Some(position);
239    for child in &mut row.children {
240        place_row(child, position);
241    }
242}
243fn join(
244    node: &SemanticsNode,
245    layout_bounds: &HashMap<NodeId, Rect>,
246    touch_bounds: &HashMap<NodeId, Rect>,
247) -> Result<PlacedSemanticsNode, NodeError> {
248    let bounds = layout_bounds
249        .get(&node.node_id)
250        .copied()
251        .ok_or(NodeError::MissingContext {
252            id: node.node_id,
253            reason: "semantics node has no layout box: the semantics walk and the \
254                         layout walk disagree about what was placed",
255        })?;
256    let mut children = Vec::with_capacity(node.children.len());
257    for child in &node.children {
258        children.push(join(child, layout_bounds, touch_bounds)?);
259    }
260    let details = node.details();
261    if details.collection.is_some() {
262        for (child, position) in children.iter_mut().zip(1..) {
263            place_row(child, position);
264        }
265    }
266    Ok(PlacedSemanticsNode {
267        node_id: node.node_id,
268        role: node.role.clone(),
269        widget_role: node.widget_role,
270        label: node
271            .accessibility_label()
272            .map(std::borrow::Cow::into_owned)
273            .or_else(|| node.merges_accessibility_descendants().then(String::new)),
274        state_description: details.state_description.clone(),
275        clickable: node
276            .actions
277            .iter()
278            .any(|action| matches!(action, SemanticsAction::Click { .. })),
279        interactive: touch_bounds.contains_key(&node.node_id),
280        toggled: node.toggled,
281        selected: node.selected,
282        enabled: node.enabled,
283        editable_text: details.editable_text,
284        focusable: node.focusable,
285        hidden: node.hidden,
286        pane_title: details.pane_title.clone(),
287        traversal_index: node.traversal_index,
288        test_tag: details.test_tag.clone(),
289        list_position: None,
290        layout_bounds: bounds,
291        touch_bounds: touch_bounds.get(&node.node_id).copied(),
292        children,
293    })
294}
295
296/// The placed tree of a semantics tree and the layout it was measured in,
297/// without touch bounds: what a shell offers after a frame.
298pub fn placed_semantics_from_trees(
299    semantics: &SemanticsNode,
300    layout: &LayoutTree,
301) -> Result<PlacedSemanticsNode, NodeError> {
302    let mut layout_bounds = HashMap::default();
303    index_layout_bounds(layout.root(), &mut layout_bounds);
304    join(semantics, &layout_bounds, &HashMap::default())
305}
306
307/// The placed tree of what a shell shows right now. `None` before the first
308/// frame, or while the shell does not build semantics; turn them on with
309/// `set_semantics_enabled(true)` first.
310pub fn placed_semantics_from_shell<R>(shell: &mut AppShell<R>) -> Option<PlacedSemanticsNode>
311where
312    R: Renderer,
313    R::Error: std::fmt::Debug,
314{
315    let layout = shell.layout_tree()?.clone();
316    let semantics = shell.semantics_tree()?.root().clone();
317    placed_semantics_from_trees(&semantics, &layout).ok()
318}