Skip to main content

cranpose_ui/layout/
layout_node_data.rs

1//! What a layout box keeps of its node: the node's slices, semantics and
2//! kind, and its modifier where inspection is built in, read from the
3//! applier when the box is made.
4
5use std::{cell::RefCell, fmt, rc::Rc};
6
7use cranpose_core::{MemoryApplier, NodeError, NodeId};
8use cranpose_foundation::SemanticsConfiguration;
9use cranpose_ui_graphics::{ProjectiveTransform, layer_transform::laid_out_transform_to_window};
10
11use super::{SemanticsRole, SemanticsText};
12#[cfg(feature = "inspection")]
13use crate::modifier::Modifier;
14use crate::{
15    modifier::{ModifierNodeSlices, Point, ResolvedModifiers, Size},
16    subcompose_layout::SubcomposeLayoutNode,
17    widgets::nodes::{LayoutNode, LayoutState},
18};
19
20/// Snapshot of the data required to render a layout node.
21#[derive(Debug, Clone)]
22pub struct LayoutNodeData {
23    /// Composable origins retained by an inspection-enabled layout node.
24    #[cfg(feature = "inspection")]
25    pub source_trace: Rc<[cranpose_core::source_trace::SourceLocation]>,
26    /// The modifier of the node, kept where inspection is built in, which
27    /// reads it.
28    #[cfg(feature = "inspection")]
29    pub modifier: Modifier,
30    /// Padding, layout properties and offset that the modifier chain resolved to.
31    pub resolved_modifiers: ResolvedModifiers,
32    /// Draw commands, pointer input handlers, text and graphics layer data collected from the
33    /// modifier nodes.
34    pub modifier_slices: Rc<ModifierNodeSlices>,
35    /// Semantics that the modifier chain reported, if any.
36    pub semantics: Option<Rc<SemanticsConfiguration>>,
37    /// What kind of node this is.
38    pub kind: LayoutNodeKind,
39    /// Where the node draws among its siblings: its `Modifier::z_index`
40    /// plus the z index its parent placed it with.
41    pub z_index: f32,
42}
43
44impl LayoutNodeData {
45    /// Creates node data from its parts.
46    pub fn new(
47        resolved_modifiers: ResolvedModifiers,
48        modifier_slices: Rc<ModifierNodeSlices>,
49        semantics: Option<Rc<SemanticsConfiguration>>,
50        kind: LayoutNodeKind,
51    ) -> Self {
52        Self {
53            #[cfg(feature = "inspection")]
54            source_trace: Rc::default(),
55            #[cfg(feature = "inspection")]
56            modifier: Modifier::empty(),
57            resolved_modifiers,
58            modifier_slices,
59            semantics,
60            kind,
61            z_index: 0.0,
62        }
63    }
64
65    /// Reads the resolved modifiers, the modifier slices and the semantics
66    /// again from node `node_id` of `applier`, and the modifier where
67    /// inspection is built in. Data of a node that is neither a layout node
68    /// nor a subcompose node stays as it was.
69    pub fn refresh(&mut self, applier: &mut MemoryApplier, node_id: NodeId) {
70        let Some(info) = runtime_metadata_for(applier, node_id) else {
71            return;
72        };
73        #[cfg(feature = "inspection")]
74        {
75            self.modifier = info.modifier;
76        }
77        self.resolved_modifiers = info.resolved_modifiers;
78        self.modifier_slices = info.modifier_slices;
79        self.semantics = info.semantics;
80    }
81
82    /// Semantics the node's live modifier chain reported when the snapshot
83    /// was taken.
84    pub fn semantics(&self) -> Option<&SemanticsConfiguration> {
85        self.semantics.as_deref()
86    }
87
88    /// Returns the padding, layout properties and offset that the modifier chain resolved to.
89    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
90        self.resolved_modifiers
91    }
92
93    /// Returns the draw, pointer input, text and graphics layer data collected from the modifier
94    /// nodes.
95    pub fn modifier_slices(&self) -> &ModifierNodeSlices {
96        &self.modifier_slices
97    }
98}
99
100/// Classification of the node captured inside a [`LayoutBox`](super::LayoutBox).
101///
102/// Note: Text content is no longer represented as a distinct LayoutNodeKind.
103/// Text nodes now use `LayoutNodeKind::Layout` with their content stored in
104/// `modifier_slices.text_content()` via TextModifierNode, following Jetpack
105/// Compose's pattern where text is a modifier node capability.
106#[derive(Clone)]
107pub enum LayoutNodeKind {
108    /// A node that measures and places its children.
109    Layout,
110    /// A subcomposition boundary, such as a lazy list or a `SubcomposeLayout`.
111    Subcompose,
112    /// A non-interactive spacer.
113    Spacer,
114    /// A button node.
115    Button {
116        /// Handler that runs when the button is clicked.
117        on_click: Rc<RefCell<dyn FnMut()>>,
118    },
119    /// A node that fits no other kind.
120    Unknown,
121}
122
123impl fmt::Debug for LayoutNodeKind {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        match self {
126            Self::Layout => f.write_str("Layout"),
127            Self::Subcompose => f.write_str("Subcompose"),
128            Self::Spacer => f.write_str("Spacer"),
129            Self::Button { .. } => f.write_str("Button"),
130            Self::Unknown => f.write_str("Unknown"),
131        }
132    }
133}
134
135pub(super) fn snapshot_node_data(
136    applier: &mut MemoryApplier,
137    node_id: NodeId,
138    top_left: Point,
139    size: Size,
140    parent_transform: Option<ProjectiveTransform>,
141) -> Result<(LayoutNodeData, Option<ProjectiveTransform>), NodeError> {
142    let info = runtime_metadata_for(applier, node_id).unwrap_or_default();
143    let kind = layout_kind_from_metadata(node_id, &info);
144    let RuntimeNodeMetadata {
145        #[cfg(feature = "inspection")]
146        modifier,
147        resolved_modifiers,
148        modifier_slices,
149        semantics,
150        z_index,
151        ..
152    } = info;
153
154    let window_transform = modifier_slices
155        .graphics_layer()
156        .map_or(parent_transform, |layer| {
157            laid_out_transform_to_window(
158                parent_transform,
159                top_left,
160                modifier_slices.layer_bounds(size),
161                &layer,
162            )
163        });
164    modifier_slices.publish_window_geometry(top_left, window_transform, size);
165
166    let data = LayoutNodeData {
167        #[cfg(feature = "inspection")]
168        source_trace: applier
169            .with_node::<LayoutNode, _>(node_id, |node| Rc::clone(&node.source_trace))
170            .unwrap_or_default(),
171        #[cfg(feature = "inspection")]
172        modifier,
173        resolved_modifiers,
174        modifier_slices,
175        semantics,
176        kind,
177        z_index,
178    };
179    Ok((data, window_transform))
180}
181
182#[derive(Clone)]
183struct RuntimeNodeMetadata {
184    #[cfg(feature = "inspection")]
185    modifier: Modifier,
186    resolved_modifiers: ResolvedModifiers,
187    modifier_slices: Rc<ModifierNodeSlices>,
188    semantics: Option<Rc<SemanticsConfiguration>>,
189    role: SemanticsRole,
190    // The node's `Modifier::z_index` plus its placement's.
191    z_index: f32,
192    button_handler: Option<Rc<RefCell<dyn FnMut()>>>,
193}
194
195impl Default for RuntimeNodeMetadata {
196    fn default() -> Self {
197        Self {
198            #[cfg(feature = "inspection")]
199            modifier: Modifier::empty(),
200            resolved_modifiers: ResolvedModifiers::default(),
201            modifier_slices: Rc::default(),
202            semantics: None,
203            role: SemanticsRole::Unknown,
204            button_handler: None,
205            z_index: 0.0,
206        }
207    }
208}
209
210pub(super) fn role_from_modifier_slices(modifier_slices: &ModifierNodeSlices) -> SemanticsRole {
211    modifier_slices
212        .annotated_text()
213        .map_or(SemanticsRole::Layout, |text| SemanticsRole::Text {
214            value: SemanticsText(text.clone()),
215        })
216}
217
218// What node `node_id` of `applier` shows a layout box; `None` for a node
219// that is neither a layout node nor a subcompose node.
220fn runtime_metadata_for(
221    applier: &mut MemoryApplier,
222    node_id: NodeId,
223) -> Option<RuntimeNodeMetadata> {
224    if let Ok(meta) = applier.with_node::<LayoutNode, _>(node_id, |layout| {
225        let resolved_modifiers = layout.resolved_modifiers();
226        let modifier_slices = layout.modifier_slices_snapshot();
227        let role = role_from_modifier_slices(&modifier_slices);
228        let z_index = modifier_slices.z_index() + layout.with_layout_state(LayoutState::z_index);
229
230        RuntimeNodeMetadata {
231            #[cfg(feature = "inspection")]
232            modifier: layout.modifier(),
233            resolved_modifiers,
234            modifier_slices,
235            semantics: layout.semantics_configuration().map(Rc::new),
236            role,
237            button_handler: None,
238            z_index,
239        }
240    }) {
241        return Some(meta);
242    }
243    applier
244        .with_node::<SubcomposeLayoutNode, _>(node_id, |node| {
245            let modifier_slices = node.modifier_slices_snapshot();
246            let placed = node.layout_parts().layout_state().z_index();
247            RuntimeNodeMetadata {
248                #[cfg(feature = "inspection")]
249                modifier: node.modifier(),
250                resolved_modifiers: node.resolved_modifiers(),
251                z_index: modifier_slices.z_index() + placed,
252                modifier_slices,
253                semantics: node.semantics_configuration().map(Rc::new),
254                role: SemanticsRole::Subcompose,
255                button_handler: None,
256            }
257        })
258        .ok()
259}
260
261fn layout_kind_from_metadata(_node_id: NodeId, info: &RuntimeNodeMetadata) -> LayoutNodeKind {
262    match &info.role {
263        SemanticsRole::Layout => LayoutNodeKind::Layout,
264        SemanticsRole::Subcompose => LayoutNodeKind::Subcompose,
265        SemanticsRole::Text { .. } => LayoutNodeKind::Layout,
266        SemanticsRole::Spacer => LayoutNodeKind::Spacer,
267        SemanticsRole::Button => {
268            let handler = info
269                .button_handler
270                .as_ref()
271                .cloned()
272                .unwrap_or_else(|| Rc::new(RefCell::new(|| {})));
273            LayoutNodeKind::Button { on_click: handler }
274        }
275        SemanticsRole::Unknown => LayoutNodeKind::Unknown,
276    }
277}