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 place of a row among the rows of its list, counted from 1, when
95 /// the parent says it is a collection. A reader speaks it, so two rows
96 /// with one name are told apart.
97 pub list_position: Option<usize>,
98 /// The box the measure pass gave this node, in window coordinates.
99 pub layout_bounds: Rect,
100 /// The box the renderer draws and the hit test inverts, ancestor graphics
101 /// layers included. `None` when the hit graph carries no region for it.
102 pub touch_bounds: Option<Rect>,
103 pub children: Vec<PlacedSemanticsNode>,
104}
105
106impl PlacedSemanticsNode {
107 /// The box a finger has to find: the drawn quad where there is one, and the
108 /// layout box where the node is not a hit target at all.
109 pub fn target_bounds(&self) -> Rect {
110 self.touch_bounds.unwrap_or(self.layout_bounds)
111 }
112
113 /// Depth-first walk, self first.
114 pub fn visit(&self, visitor: &mut impl FnMut(&PlacedSemanticsNode)) {
115 visitor(self);
116 for child in &self.children {
117 child.visit(visitor);
118 }
119 }
120
121 /// Every node in the subtree, self first, in tree order.
122 pub fn flatten(&self) -> Vec<&PlacedSemanticsNode> {
123 let mut all = Vec::new();
124 self.collect(&mut all);
125 all
126 }
127
128 fn collect<'a>(&'a self, out: &mut Vec<&'a PlacedSemanticsNode>) {
129 out.push(self);
130 for child in &self.children {
131 child.collect(out);
132 }
133 }
134
135 /// Every node a tap would do something to.
136 pub fn controls(&self) -> Vec<&PlacedSemanticsNode> {
137 self.flatten()
138 .into_iter()
139 .filter(|node| node.clickable)
140 .collect()
141 }
142
143 /// A name for an assertion message: the label if there is one, else the
144 /// role and the node id, which at least says which one it was.
145 pub fn describe(&self) -> String {
146 match &self.label {
147 Some(label) => format!("{label:?}"),
148 None => format!("{:?}#{}", self.role, self.node_id),
149 }
150 }
151}
152
153/// Lay `root` out at `size` and read back its semantics with geometry.
154///
155/// The applier must already be carrying a runtime handle
156/// (`MemoryApplier::set_runtime_handle`) — a subcomposing widget cannot be
157/// measured without one. `ComposeTestRule::placed_semantics` in cranpose-testing
158/// does that part; this is for a caller driving a `TestComposition` by hand.
159///
160/// `None` means the composition placed nothing at all, which for a root that
161/// composed content is itself the answer to a bug hunt.
162pub fn placed_semantics_from_applier(
163 applier: &mut MemoryApplier,
164 root: NodeId,
165 size: Size,
166) -> Result<Option<PlacedSemanticsNode>, NodeError> {
167 applier.compute_layout(root, size)?;
168
169 let Some(layout) = build_layout_tree_from_applier(applier, root)? else {
170 return Ok(None);
171 };
172 let Some(semantics) = build_semantics_tree_from_applier(applier, root)? else {
173 return Ok(None);
174 };
175
176 let mut layout_bounds = HashMap::default();
177 index_layout_bounds(layout.root(), &mut layout_bounds);
178
179 let mut touch_bounds = HashMap::default();
180 if let Some(graph) = build_graph_from_applier(applier, root, 1.0) {
181 let mut sink = TouchBoundsSink {
182 bounds: &mut touch_bounds,
183 };
184 collect_hits_from_graph(
185 &graph.root,
186 ProjectiveTransform::identity(),
187 &mut sink,
188 None,
189 );
190 }
191
192 join(semantics.root(), &layout_bounds, &touch_bounds).map(Some)
193}
194
195fn index_layout_bounds(layout_box: &LayoutBox, out: &mut HashMap<NodeId, Rect>) {
196 out.insert(layout_box.node_id, layout_box.rect);
197 for child in &layout_box.children {
198 index_layout_bounds(child, out);
199 }
200}
201
202struct TouchBoundsSink<'a> {
203 bounds: &'a mut HashMap<NodeId, Rect>,
204}
205
206impl HitGraphSink for TouchBoundsSink<'_> {
207 fn push_hit(
208 &mut self,
209 node_id: NodeId,
210 _capture_path: &[NodeId],
211 geometry: HitGeometry<'_>,
212 _hit: &HitTestNode,
213 ) {
214 self.bounds.entry(node_id).or_insert(geometry.rect);
215 }
216}
217
218/// Gives a row and everything inside it the place of the row, so that two
219/// rows with one name, and the controls inside them, are apart. A list inside
220/// a row keeps the places it gave its own rows.
221pub(crate) fn place_row(row: &mut PlacedSemanticsNode, position: usize) {
222 if row.list_position.is_some() {
223 return;
224 }
225 row.list_position = Some(position);
226 for child in &mut row.children {
227 place_row(child, position);
228 }
229}
230fn join(
231 node: &SemanticsNode,
232 layout_bounds: &HashMap<NodeId, Rect>,
233 touch_bounds: &HashMap<NodeId, Rect>,
234) -> Result<PlacedSemanticsNode, NodeError> {
235 let bounds = layout_bounds
236 .get(&node.node_id)
237 .copied()
238 .ok_or(NodeError::MissingContext {
239 id: node.node_id,
240 reason: "semantics node has no layout box: the semantics walk and the \
241 layout walk disagree about what was placed",
242 })?;
243 let mut children = Vec::with_capacity(node.children.len());
244 for child in &node.children {
245 children.push(join(child, layout_bounds, touch_bounds)?);
246 }
247 let details = node.details();
248 if details.collection.is_some() {
249 for (child, position) in children.iter_mut().zip(1..) {
250 place_row(child, position);
251 }
252 }
253 Ok(PlacedSemanticsNode {
254 node_id: node.node_id,
255 role: node.role.clone(),
256 widget_role: node.widget_role,
257 label: node
258 .accessibility_label()
259 .map(std::borrow::Cow::into_owned)
260 .or_else(|| node.merges_accessibility_descendants().then(String::new)),
261 state_description: details.state_description.clone(),
262 clickable: node
263 .actions
264 .iter()
265 .any(|action| matches!(action, SemanticsAction::Click { .. })),
266 interactive: touch_bounds.contains_key(&node.node_id),
267 toggled: node.toggled,
268 selected: node.selected,
269 enabled: node.enabled,
270 editable_text: details.editable_text,
271 focusable: node.focusable,
272 hidden: node.hidden,
273 pane_title: details.pane_title.clone(),
274 traversal_index: node.traversal_index,
275 list_position: None,
276 layout_bounds: bounds,
277 touch_bounds: touch_bounds.get(&node.node_id).copied(),
278 children,
279 })
280}
281
282/// The placed tree of a semantics tree and the layout it was measured in,
283/// without touch bounds: what a shell offers after a frame.
284pub fn placed_semantics_from_trees(
285 semantics: &SemanticsNode,
286 layout: &LayoutTree,
287) -> Result<PlacedSemanticsNode, NodeError> {
288 let mut layout_bounds = HashMap::default();
289 index_layout_bounds(layout.root(), &mut layout_bounds);
290 join(semantics, &layout_bounds, &HashMap::default())
291}
292
293/// The placed tree of what a shell shows right now. `None` before the first
294/// frame, or while the shell does not build semantics; turn them on with
295/// `set_semantics_enabled(true)` first.
296pub fn placed_semantics_from_shell<R>(shell: &mut AppShell<R>) -> Option<PlacedSemanticsNode>
297where
298 R: Renderer,
299 R::Error: std::fmt::Debug,
300{
301 let layout = shell.layout_tree()?.clone();
302 let semantics = shell.semantics_tree()?.root().clone();
303 placed_semantics_from_trees(&semantics, &layout).ok()
304}