Skip to main content

cranpose_ui/widgets/
layout.rs

1//! Generic Layout widget and SubcomposeLayout
2
3use std::{cell::RefCell, rc::Rc};
4
5use cranpose_core::{NodeId, SlotId};
6use cranpose_ui_graphics::Size;
7use cranpose_ui_layout::{MeasurePolicy, Placement};
8
9use super::{nodes::LayoutNode, scopes::BoxWithConstraintsScopeImpl};
10use crate::{
11    composable,
12    modifier::Modifier,
13    subcompose_layout::{
14        Constraints, MeasurePolicy as SubcomposeMeasurePolicy, MeasureResult, SubcomposeLayoutNode,
15        SubcomposeLayoutScope, SubcomposeMeasureScope, SubcomposeMeasureScopeImpl,
16    },
17};
18
19pub(crate) fn caller_modifier_changed(modifier: &Modifier) -> bool {
20    cranpose_core::remember(|| RefCell::new(modifier.clone())).with(|last| {
21        let changed = *last.borrow() != *modifier;
22        if changed {
23            last.replace(modifier.clone());
24        }
25        changed
26    })
27}
28
29struct RetainedMeasurePolicy<P> {
30    value: P,
31    policy: Rc<dyn MeasurePolicy>,
32}
33
34#[composable]
35pub fn Layout<F, P>(modifier: Modifier, measure_policy: P, content: F) -> NodeId
36where
37    F: FnMut() + 'static,
38    P: MeasurePolicy + Clone + PartialEq + 'static,
39{
40    compose_layout(modifier, measure_policy, crate::density::density(), content)
41}
42
43/// Emits a layout node in the calling composable's group, so a widget that
44/// is one layout composes in one group rather than its own and `Layout`'s.
45pub(crate) fn compose_layout<F, P>(
46    modifier: Modifier,
47    measure_policy: P,
48    composed_density: crate::density::Density,
49    mut content: F,
50) -> NodeId
51where
52    F: FnMut() + 'static,
53    P: MeasurePolicy + Clone + PartialEq + 'static,
54{
55    let policy_holder = cranpose_core::remember({
56        let measure_policy = measure_policy.clone();
57        move || {
58            Rc::new(RefCell::new(RetainedMeasurePolicy {
59                value: measure_policy.clone(),
60                policy: Rc::new(measure_policy),
61            }))
62        }
63    })
64    .with(Rc::clone);
65    let policy = {
66        let mut holder = policy_holder.borrow_mut();
67        if holder.value != measure_policy {
68            holder.value = measure_policy.clone();
69            holder.policy = Rc::new(measure_policy);
70        }
71        Rc::clone(&holder.policy)
72    };
73    let id = cranpose_core::with_current_composer(|composer| {
74        composer.emit_recyclable_node(
75            || LayoutNode::new(modifier.clone(), Rc::clone(&policy)),
76            |node| *node = LayoutNode::new(modifier.clone(), Rc::clone(&policy)),
77        )
78    });
79    let provided = modifier.provided_composition_locals();
80    let direction = crate::layout_direction();
81    if let Err(err) = cranpose_core::with_node_mut(id, |node: &mut LayoutNode| {
82        node.set_modifier(modifier);
83        node.set_measure_policy(policy);
84        node.set_density(composed_density);
85        node.set_layout_direction(direction);
86    }) {
87        debug_assert!(false, "failed to update Layout node: {err}");
88    }
89    cranpose_core::push_parent(id);
90    compose_under_locals(provided, &mut content);
91    cranpose_core::pop_parent();
92    id
93}
94
95fn compose_under_locals(provided: Vec<cranpose_core::ProvidedValue>, content: &mut dyn FnMut()) {
96    if provided.is_empty() {
97        content();
98        return;
99    }
100    cranpose_core::CompositionLocalProvider(provided, content);
101}
102
103#[composable]
104pub fn SubcomposeLayout(
105    modifier: Modifier,
106    measure_policy: impl for<'scope> Fn(
107        &mut SubcomposeMeasureScopeImpl<'scope>,
108        Constraints,
109    ) -> MeasureResult
110    + 'static,
111) -> NodeId {
112    cranpose_core::debug_label_current_scope("SubcomposeLayout");
113    let policy_cell =
114        cranpose_core::remember(|| Rc::new(RefCell::new(None::<Rc<SubcomposeMeasurePolicy>>)))
115            .with(|cell| cell.clone());
116    let current_policy: Rc<SubcomposeMeasurePolicy> = Rc::new(measure_policy);
117    let policy_captures_changed = {
118        let mut policy_cell_ref = policy_cell.borrow_mut();
119        let changed = policy_cell_ref
120            .as_ref()
121            .is_none_or(|previous| !Rc::ptr_eq(previous, &current_policy));
122        *policy_cell_ref = Some(current_policy);
123        changed
124    };
125    let policy: Rc<SubcomposeMeasurePolicy> = cranpose_core::remember(move || {
126        let policy_cell = policy_cell.clone();
127        let policy: Rc<SubcomposeMeasurePolicy> =
128            Rc::new(
129                move |scope, constraints| match policy_cell.borrow().as_ref().cloned() {
130                    Some(current) => current(scope, constraints),
131                    None => empty_subcompose_measure_result(constraints),
132                },
133            );
134        policy
135    })
136    .with(|policy| policy.clone());
137    let id = cranpose_core::with_current_composer(|composer| {
138        composer.emit_node(|| SubcomposeLayoutNode::new(modifier.clone(), Rc::clone(&policy)))
139    });
140    let captured_context =
141        cranpose_core::with_current_composer(|composer| composer.capture_composition_context());
142    let composed_density = crate::density::density();
143    let direction = crate::layout_direction();
144    if let Err(err) = cranpose_core::with_node_mut(id, |node: &mut SubcomposeLayoutNode| {
145        node.set_modifier(modifier);
146        node.set_measure_policy(policy);
147        node.set_captured_context(captured_context);
148        node.set_density(composed_density);
149        node.set_layout_direction(direction);
150        if policy_captures_changed {
151            node.invalidate_subcomposition();
152        }
153    }) {
154        debug_assert!(false, "failed to update SubcomposeLayout node: {err}");
155    }
156    id
157}
158
159fn empty_subcompose_measure_result(constraints: Constraints) -> MeasureResult {
160    let (width, height) = constraints.constrain(0.0, 0.0);
161    MeasureResult::new(Size { width, height }, Vec::new())
162}
163
164#[composable(no_skip)]
165pub fn BoxWithConstraints<F>(modifier: Modifier, content: F) -> NodeId
166where
167    F: FnMut(BoxWithConstraintsScopeImpl) + 'static,
168{
169    let content_ref: Rc<RefCell<F>> = Rc::new(RefCell::new(content));
170    SubcomposeLayout(modifier, move |scope, constraints| {
171        let scope_impl = BoxWithConstraintsScopeImpl::new(constraints);
172        let scope_for_content = scope_impl;
173        let measurables = {
174            let content_ref = Rc::clone(&content_ref);
175            scope.subcompose(SlotId::new(0), constraints, move || {
176                cranpose_core::debug_label_current_scope("BoxWithConstraints.slot(0)");
177                let mut content = content_ref.borrow_mut();
178                content(scope_for_content);
179            })
180        };
181        let child_constraints = Constraints {
182            min_width: 0.0,
183            max_width: constraints.max_width,
184            min_height: 0.0,
185            max_height: constraints.max_height,
186        };
187
188        let mut width = 0.0_f32;
189        let mut height = 0.0_f32;
190        let mut placements = Vec::with_capacity(measurables.len());
191
192        for measurable in measurables {
193            let placeable = scope.measure(measurable, child_constraints);
194            width = width.max(placeable.width());
195            height = height.max(placeable.height());
196            placeable.place(0.0, 0.0);
197            placements.push(Placement::new(placeable.node_id(), 0.0, 0.0, 0));
198        }
199
200        width = width.clamp(constraints.min_width, constraints.max_width);
201        height = height.clamp(constraints.min_height, constraints.max_height);
202        scope.layout(width, height, placements)
203    })
204}
205
206#[cfg(test)]
207#[path = "tests/layout_tests.rs"]
208mod tests;