Skip to main content

cranpose_ui/widgets/
layout.rs

1//! Generic Layout widget and SubcomposeLayout
2
3#![allow(non_snake_case)]
4
5use std::{cell::RefCell, rc::Rc};
6
7use cranpose_core::{NodeId, SlotId};
8use cranpose_ui_graphics::Size;
9use cranpose_ui_layout::{MeasurePolicy, Placement};
10
11use super::{nodes::LayoutNode, scopes::BoxWithConstraintsScopeImpl};
12use crate::{
13    composable,
14    modifier::Modifier,
15    subcompose_layout::{
16        Constraints, MeasurePolicy as SubcomposeMeasurePolicy, MeasureResult, SubcomposeLayoutNode,
17        SubcomposeLayoutScope, SubcomposeMeasureScope, SubcomposeMeasureScopeImpl,
18    },
19};
20
21struct RetainedMeasurePolicy<P> {
22    value: P,
23    policy: Rc<dyn MeasurePolicy>,
24}
25
26#[composable]
27pub fn Layout<F, P>(modifier: Modifier, measure_policy: P, mut content: F) -> NodeId
28where
29    F: FnMut() + 'static,
30    P: MeasurePolicy + Clone + PartialEq + 'static,
31{
32    let policy_holder = cranpose_core::remember({
33        let measure_policy = measure_policy.clone();
34        move || {
35            Rc::new(RefCell::new(RetainedMeasurePolicy {
36                value: measure_policy.clone(),
37                policy: Rc::new(measure_policy),
38            }))
39        }
40    })
41    .with(|holder| holder.clone());
42    let policy = {
43        let mut holder = policy_holder.borrow_mut();
44        if holder.value != measure_policy {
45            holder.value = measure_policy.clone();
46            holder.policy = Rc::new(measure_policy);
47        }
48        Rc::clone(&holder.policy)
49    };
50    let modifier_for_reset = modifier.clone();
51    let policy_for_reset = Rc::clone(&policy);
52    let id = cranpose_core::with_current_composer(|composer| {
53        composer.emit_recyclable_node(
54            || LayoutNode::new(modifier.clone(), Rc::clone(&policy)),
55            move |node| {
56                *node = LayoutNode::new(modifier_for_reset.clone(), Rc::clone(&policy_for_reset));
57            },
58        )
59    });
60    // Read while the composition is still running: measurement happens after it
61    // and cannot reach a composition local. Reading here also subscribes, so a
62    // subtree given a different grid recomposes and re-captures.
63    let composed_density = crate::density::density();
64    if let Err(err) = cranpose_core::with_node_mut(id, |node: &mut LayoutNode| {
65        node.set_modifier(modifier.clone());
66        node.set_measure_policy(Rc::clone(&policy));
67        node.set_density(composed_density);
68    }) {
69        debug_assert!(false, "failed to update Layout node: {err}");
70    }
71    cranpose_core::push_parent(id);
72    content();
73    cranpose_core::pop_parent();
74    id
75}
76
77#[composable]
78pub fn SubcomposeLayout(
79    modifier: Modifier,
80    measure_policy: impl for<'scope> Fn(&mut SubcomposeMeasureScopeImpl<'scope>, Constraints) -> MeasureResult
81        + 'static,
82) -> NodeId {
83    cranpose_core::debug_label_current_scope("SubcomposeLayout");
84    let policy_cell =
85        cranpose_core::remember(|| Rc::new(RefCell::new(None::<Rc<SubcomposeMeasurePolicy>>)))
86            .with(|cell| cell.clone());
87    let current_policy: Rc<SubcomposeMeasurePolicy> = Rc::new(measure_policy);
88    let policy_captures_changed = {
89        let mut policy_cell_ref = policy_cell.borrow_mut();
90        let changed = policy_cell_ref
91            .as_ref()
92            .is_none_or(|previous| !Rc::ptr_eq(previous, &current_policy));
93        *policy_cell_ref = Some(current_policy);
94        changed
95    };
96    let policy: Rc<SubcomposeMeasurePolicy> = cranpose_core::remember(move || {
97        let policy_cell = policy_cell.clone();
98        let policy: Rc<SubcomposeMeasurePolicy> =
99            Rc::new(
100                move |scope, constraints| match policy_cell.borrow().as_ref().cloned() {
101                    Some(current) => current(scope, constraints),
102                    None => empty_subcompose_measure_result(constraints),
103                },
104            );
105        policy
106    })
107    .with(|policy| policy.clone());
108    let id = cranpose_core::with_current_composer(|composer| {
109        composer.emit_node(|| SubcomposeLayoutNode::new(modifier.clone(), Rc::clone(&policy)))
110    });
111    // Measure-time composition inherits both locals and the source scope. The
112    // ownership link prevents secondary-host callbacks from outliving this
113    // composition while preserving the call-site local providers.
114    let captured_context =
115        cranpose_core::with_current_composer(|composer| composer.capture_composition_context());
116    // Read while the composition is still running, same as `Layout`: measurement
117    // happens after it and cannot reach a composition local. Reading here also
118    // subscribes, so a subtree given a different grid recomposes and re-captures.
119    let composed_density = crate::density::density();
120    if let Err(err) = cranpose_core::with_node_mut(id, |node: &mut SubcomposeLayoutNode| {
121        node.set_modifier(modifier.clone());
122        node.set_measure_policy(Rc::clone(&policy));
123        node.set_captured_context(captured_context.clone());
124        node.set_density(composed_density);
125        if policy_captures_changed {
126            node.request_measure_recompose();
127        }
128    }) {
129        debug_assert!(false, "failed to update SubcomposeLayout node: {err}");
130    }
131    id
132}
133
134fn empty_subcompose_measure_result(constraints: Constraints) -> MeasureResult {
135    let (width, height) = constraints.constrain(0.0, 0.0);
136    MeasureResult::new(Size { width, height }, Vec::new())
137}
138
139#[composable(no_skip)]
140pub fn BoxWithConstraints<F>(modifier: Modifier, content: F) -> NodeId
141where
142    F: FnMut(BoxWithConstraintsScopeImpl) + 'static,
143{
144    let content_ref: Rc<RefCell<F>> = Rc::new(RefCell::new(content));
145    SubcomposeLayout(modifier, move |scope, constraints| {
146        let scope_impl = BoxWithConstraintsScopeImpl::new(constraints);
147        let scope_for_content = scope_impl;
148        let measurables = {
149            let content_ref = Rc::clone(&content_ref);
150            scope.subcompose(SlotId::new(0), move || {
151                cranpose_core::debug_label_current_scope("BoxWithConstraints.slot(0)");
152                let mut content = content_ref.borrow_mut();
153                content(scope_for_content);
154            })
155        };
156        let child_constraints = Constraints {
157            min_width: 0.0,
158            max_width: constraints.max_width,
159            min_height: 0.0,
160            max_height: constraints.max_height,
161        };
162
163        let mut width = 0.0_f32;
164        let mut height = 0.0_f32;
165        let mut placements = Vec::with_capacity(measurables.len());
166
167        for measurable in measurables {
168            let placeable = scope.measure(measurable, child_constraints);
169            width = width.max(placeable.width());
170            height = height.max(placeable.height());
171            placeable.place(0.0, 0.0);
172            placements.push(Placement::new(placeable.node_id(), 0.0, 0.0, 0));
173        }
174
175        width = width.clamp(constraints.min_width, constraints.max_width);
176        height = height.clamp(constraints.min_height, constraints.max_height);
177        scope.layout(width, height, placements)
178    })
179}
180
181#[cfg(test)]
182mod tests {
183    use std::cell::Cell;
184
185    use cranpose_core::{location_key, Composition, MemoryApplier, MutableState};
186
187    use super::*;
188
189    #[test]
190    fn layout_recomposes_when_content_reads_state() {
191        let _app_context = crate::render_state::app_context_test_scope();
192        thread_local! {
193            static INVOCATIONS: Cell<usize> = const { Cell::new(0) };
194        }
195
196        let mut composition = Composition::new(MemoryApplier::new());
197        let runtime = composition.runtime_handle();
198        let state = MutableState::with_runtime(0_i32, runtime);
199
200        composition
201            .render(location_key(file!(), line!(), column!()), {
202                let observed_state = state;
203                move || {
204                    Layout(
205                        Modifier::empty(),
206                        crate::layout::policies::EmptyMeasurePolicy,
207                        {
208                            let observed_state = observed_state;
209                            move || {
210                                let _ = observed_state.value();
211                                INVOCATIONS.with(|calls| calls.set(calls.get() + 1));
212                            }
213                        },
214                    );
215                }
216            })
217            .expect("initial layout render");
218
219        INVOCATIONS.with(|calls| assert_eq!(calls.get(), 1));
220
221        state.set_value(1);
222        composition
223            .process_invalid_scopes()
224            .expect("layout content recomposition");
225
226        INVOCATIONS.with(|calls| assert_eq!(calls.get(), 2));
227    }
228
229    #[test]
230    fn subcompose_missing_policy_cell_measures_empty_layout() {
231        let result = empty_subcompose_measure_result(Constraints {
232            min_width: 12.0,
233            max_width: 120.0,
234            min_height: 8.0,
235            max_height: 90.0,
236        });
237
238        assert_eq!(result.size.width, 12.0);
239        assert_eq!(result.size.height, 8.0);
240        assert!(result.placements.is_empty());
241    }
242}