Skip to main content

cranpose_ui/layout/
semantics_tree.rs

1use cranpose_core::NodeId;
2use cranpose_foundation::{SemanticsCustomAction, SemanticsWidgetRole};
3
4use super::{GeometryRect, LayoutState, Point, SemanticsDetails, Size};
5
6/// Discrete event callback reference produced during semantics extraction.
7#[derive(Clone, Debug, PartialEq, Eq)]
8pub struct SemanticsCallback {
9    pub(super) node_id: NodeId,
10}
11
12impl SemanticsCallback {
13    /// Creates a callback that targets the node with `node_id`.
14    pub fn new(node_id: NodeId) -> Self {
15        Self { node_id }
16    }
17
18    /// Returns the id of the node whose action this callback triggers.
19    pub fn node_id(&self) -> NodeId {
20        self.node_id
21    }
22}
23
24/// Semantics action exposed to the input system.
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub enum SemanticsAction {
27    /// Activates the node, as a tap or a keyboard or assistive technology click does.
28    Click {
29        /// Callback that identifies the node to activate.
30        handler: SemanticsCallback,
31    },
32}
33
34/// A text node's text in the semantics tree, shared with the node's modifier
35/// slices rather than copied out of them.
36#[derive(Clone, Debug)]
37pub struct SemanticsText(pub(super) crate::text::AnnotatedString);
38
39impl SemanticsText {
40    /// The text the node shows.
41    pub fn as_str(&self) -> &str {
42        self.0.text()
43    }
44}
45
46impl PartialEq for SemanticsText {
47    fn eq(&self, other: &Self) -> bool {
48        self.as_str() == other.as_str()
49    }
50}
51
52impl Eq for SemanticsText {}
53
54impl From<&str> for SemanticsText {
55    fn from(text: &str) -> Self {
56        Self(crate::text::AnnotatedString::from(text))
57    }
58}
59
60/// Semantic role describing how a node should participate in accessibility and hit testing.
61/// Roles are now derived from SemanticsConfiguration rather than widget types.
62#[derive(Clone, Debug, PartialEq, Eq)]
63pub enum SemanticsRole {
64    /// Generic container or layout node
65    Layout,
66    /// Subcomposition boundary
67    Subcompose,
68    /// Text content derived from the text node semantics payload.
69    Text {
70        /// The text the node shows.
71        value: SemanticsText,
72    },
73    /// Spacer (non-interactive)
74    Spacer,
75    /// Button (derived from the semantics `role`)
76    Button,
77    /// Unknown or unspecified role
78    Unknown,
79}
80
81/// A single node within the semantics tree.
82///
83/// Not `Eq`: a node now carries drawn-control bounds, which are floats. The
84/// tree is compared for "did anything a screen reader can see change", and
85/// that comparison is `PartialEq` everywhere else on the accessibility path
86/// (`AccessibilityRect`, `AccessibilityElement`) for the same reason.
87#[derive(Clone, Debug, PartialEq)]
88pub struct SemanticsNode {
89    /// Id of the runtime node this semantics node describes.
90    pub node_id: NodeId,
91    /// Where the node lies in the root's coordinates: its layout rect,
92    /// before graphics-layer transforms, as [`LayoutBox::rect`](super::LayoutBox::rect) holds it.
93    pub bounds: GeometryRect,
94    /// Where layout put the node inside its parent's content, from which a
95    /// tree update moves a node that did not change along with its parent.
96    pub placement: SemanticsPlacement,
97    /// Incarnation of the runtime node, incremented when its storage is recycled.
98    pub node_generation: u32,
99    /// Where this node sits in the tree (layout, text, subcomposition …).
100    pub role: SemanticsRole,
101    /// What kind of control this node is, as a screen reader announces it —
102    /// Compose's `Role`. Separate from [`SemanticsNode::role`] because a
103    /// clickable `Row` is structurally a layout node and semantically a button.
104    pub widget_role: Option<SemanticsWidgetRole>,
105    /// Actions that the input system and assistive technology can invoke on this node.
106    pub actions: Vec<SemanticsAction>,
107    /// Child semantics nodes, in layout order.
108    pub children: Vec<Self>,
109    /// Content description that a screen reader announces for the node, if one was set.
110    pub description: Option<String>,
111    /// Direct activation callback for keyboard and assistive technology.
112    pub on_click: Option<SemanticsCustomAction>,
113    /// Selection state, or `None` if the node is not selectable.
114    pub selected: Option<bool>,
115    /// Checked state, or `None` if the node is not a toggleable control.
116    pub toggled: Option<cranpose_foundation::ToggleableState>,
117    /// Whether the node accepts user interaction. `true` unless the node was disabled.
118    pub enabled: bool,
119    /// Whether a screen reader skips this node and everything under it.
120    pub hidden: bool,
121    /// Whether a screen reader takes this node and the text under it as one
122    /// stop.
123    pub merge_descendants: bool,
124    /// Where a screen reader visits this node among the ones beside it.
125    pub traversal_index: f32,
126    /// The text an editable field holds.
127    pub text: Option<String>,
128    /// Whether this node registered a focus target, so focus can land on it.
129    /// Compose's `SemanticsProperties.Focused` companion.
130    pub focusable: bool,
131    /// Whether focus sits on this node right now.
132    pub focused: bool,
133    /// The properties few nodes set, held only when the node sets one: read
134    /// them through [`SemanticsNode::details`] and write them through
135    /// [`SemanticsNode::set_details`].
136    pub details: Option<Box<SemanticsDetails>>,
137}
138
139impl Default for SemanticsNode {
140    fn default() -> Self {
141        Self {
142            node_id: NodeId::default(),
143            bounds: GeometryRect::EMPTY,
144            placement: SemanticsPlacement::default(),
145            node_generation: 0,
146            role: SemanticsRole::Unknown,
147            widget_role: None,
148            actions: Vec::new(),
149            children: Vec::new(),
150            description: None,
151            on_click: None,
152            selected: None,
153            toggled: None,
154            enabled: true,
155            hidden: false,
156            merge_descendants: false,
157            traversal_index: 0.0,
158            text: None,
159            focusable: false,
160            focused: false,
161            details: None,
162        }
163    }
164}
165
166/// Where layout put a semantics node: its offset inside its parent's
167/// content and where its own content starts inside it.
168#[derive(Clone, Copy, Debug, Default, PartialEq)]
169pub struct SemanticsPlacement {
170    pub(super) position: Point,
171    pub(super) content_offset: Point,
172}
173
174impl SemanticsPlacement {
175    pub(super) fn of(state: &LayoutState) -> Self {
176        Self {
177            position: state.position(),
178            content_offset: state.content_offset(),
179        }
180    }
181
182    pub(super) fn place(self, origin: Point) -> (Point, Point) {
183        let top_left = Point {
184            x: origin.x + self.position.x,
185            y: origin.y + self.position.y,
186        };
187        let content = Point {
188            x: top_left.x + self.content_offset.x,
189            y: top_left.y + self.content_offset.y,
190        };
191        (top_left, content)
192    }
193}
194
195/// Rooted semantics tree extracted after layout.
196///
197/// Two trees are equal when they hold the same nodes; what a tree keeps to
198/// bring itself up to date is not compared.
199#[derive(Clone, Debug)]
200pub struct SemanticsTree {
201    pub(super) full: SemanticsNode,
202    pub(super) modal: Option<Vec<usize>>,
203    pub(super) tracking: super::semantics_update::SemanticsTracking,
204}
205
206impl PartialEq for SemanticsTree {
207    fn eq(&self, other: &Self) -> bool {
208        self.full == other.full && self.modal == other.modal
209    }
210}
211
212impl SemanticsTree {
213    pub(super) fn new(full: SemanticsNode) -> Self {
214        let modal = top_modal_path(&full);
215        Self {
216            full,
217            modal,
218            tracking: super::semantics_update::SemanticsTracking::default(),
219        }
220    }
221
222    /// Returns the top visible modal subtree, or the full root when no modal is open.
223    pub fn root(&self) -> &SemanticsNode {
224        self.modal.as_deref().map_or(&self.full, |path| {
225            path.iter()
226                .try_fold(&self.full, |node, &index| node.children.get(index))
227                .unwrap_or(&self.full)
228        })
229    }
230}
231
232/// Whether a modal of `size` takes space; a zero-sized modal hides nothing.
233pub(super) fn modal_takes_space(size: Size) -> bool {
234    size.width > 0.0 && size.height > 0.0 && size.width.is_finite() && size.height.is_finite()
235}
236
237/// The path to the modal drawn on top: the last visible modal in document
238/// order, a modal inside another preferred to it.
239pub(super) fn top_modal_path(root: &SemanticsNode) -> Option<Vec<usize>> {
240    pub(super) fn search(node: &SemanticsNode, path: &mut Vec<usize>) -> bool {
241        if node.hidden {
242            return false;
243        }
244        for (index, child) in node.children.iter().enumerate().rev() {
245            path.push(index);
246            if search(child, path) {
247                return true;
248            }
249            path.pop();
250        }
251        node.details().is_modal
252    }
253    let mut path = Vec::new();
254    search(root, &mut path).then_some(path)
255}