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
29/// The density and layout direction a layout node composes under. A widget
30/// reads them once, for its measure policy and its node: each read looks a
31/// composition local up.
32#[derive(Clone, Copy)]
33pub(crate) struct LayoutEnvironment {
34    pub(crate) density: crate::density::Density,
35    pub(crate) direction: crate::layout_direction::LayoutDirection,
36}
37
38impl LayoutEnvironment {
39    /// The density and layout direction in force here.
40    pub(crate) fn current() -> Self {
41        Self {
42            density: crate::density::density(),
43            direction: crate::layout_direction(),
44        }
45    }
46}
47
48/// Emits a layout node whose children `measure_policy` measures and places. `content` composes the
49/// children. Compose's `Layout`.
50/// Like Compose's, it is inline: a state its content reads recomposes the
51/// composable that called it.
52#[composable(no_skip)]
53pub fn Layout<F, P>(modifier: Modifier, measure_policy: P, content: F) -> NodeId
54where
55    F: FnMut() + 'static,
56    P: MeasurePolicy + Clone + PartialEq + 'static,
57{
58    compose_layout(
59        modifier,
60        measure_policy,
61        LayoutEnvironment::current(),
62        content,
63    )
64}
65
66/// Emits a layout node in the calling composable's group, so a widget that
67/// is one layout composes in one group rather than its own and `Layout`'s.
68pub(crate) fn compose_layout<F, P>(
69    modifier: Modifier,
70    measure_policy: P,
71    environment: LayoutEnvironment,
72    mut content: F,
73) -> NodeId
74where
75    F: FnMut() + 'static,
76    P: MeasurePolicy + Clone + PartialEq,
77{
78    // One composer lookup for the node and its children's bracket: each
79    // lookup reads a thread-local.
80    cranpose_core::with_current_composer(|composer| {
81        let (id, provided, _) = emit_layout_node(composer, modifier, measure_policy, environment);
82        composer.push_parent(id);
83        compose_under_locals(provided, &mut content);
84        composer.pop_parent();
85        id
86    })
87}
88
89pub(crate) fn compose_empty_layout(modifier: Modifier, environment: LayoutEnvironment) -> NodeId {
90    cranpose_core::with_current_composer(|composer| {
91        let (id, provided, holds_children) = emit_layout_node(
92            composer,
93            modifier,
94            crate::layout::policies::EmptyMeasurePolicy,
95            environment,
96        );
97        if provided.is_empty() {
98            composer.compose_no_children(id, holds_children);
99        } else {
100            composer.push_parent(id);
101            compose_under_locals(provided, &mut || {});
102            composer.pop_parent();
103        }
104        id
105    })
106}
107
108/// Emits and updates a layout node; returns it, the composition locals its
109/// modifier provides and whether it holds children. The node keeps the policy
110/// it holds while `policy` equals it.
111fn emit_layout_node<P: MeasurePolicy + Clone + PartialEq>(
112    composer: &cranpose_core::Composer,
113    modifier: Modifier,
114    policy: P,
115    environment: LayoutEnvironment,
116) -> (NodeId, Vec<cranpose_core::ProvidedValue>, bool) {
117    let provided = modifier.provided_composition_locals();
118    let id = composer.emit_recyclable_node(
119        || LayoutNode::new(modifier.clone(), Rc::new(policy.clone())),
120        |node| *node = LayoutNode::new(modifier.clone(), Rc::new(policy.clone())),
121    );
122    let holds_children = composer
123        .with_node_mut(id, |node: &mut LayoutNode| {
124            node.set_modifier(modifier);
125            node.update_measure_policy(policy);
126            node.set_density(environment.density);
127            node.set_layout_direction(environment.direction);
128            !node.children.is_empty()
129        })
130        .unwrap_or_else(|err| {
131            debug_assert!(false, "failed to update Layout node: {err}");
132            true
133        });
134    (id, provided, holds_children)
135}
136
137fn compose_under_locals(provided: Vec<cranpose_core::ProvidedValue>, content: &mut dyn FnMut()) {
138    if provided.is_empty() {
139        content();
140        return;
141    }
142    cranpose_core::CompositionLocalProvider(provided, content);
143}
144
145/// Emits a layout node whose `measure_policy` composes its children during measurement, so the
146/// children can depend on the incoming constraints. Compose's `SubcomposeLayout`.
147#[composable]
148pub fn SubcomposeLayout(
149    modifier: Modifier,
150    measure_policy: impl for<'scope> Fn(
151        &mut SubcomposeMeasureScopeImpl<'scope>,
152        Constraints,
153    ) -> MeasureResult
154    + 'static,
155) -> NodeId {
156    cranpose_core::debug_label_current_scope("SubcomposeLayout");
157    let policy_cell =
158        cranpose_core::remember(|| Rc::new(RefCell::new(None::<Rc<SubcomposeMeasurePolicy>>)))
159            .with(|cell| cell.clone());
160    let current_policy: Rc<SubcomposeMeasurePolicy> = Rc::new(measure_policy);
161    let policy_captures_changed = {
162        let mut policy_cell_ref = policy_cell.borrow_mut();
163        let changed = policy_cell_ref
164            .as_ref()
165            .is_none_or(|previous| !Rc::ptr_eq(previous, &current_policy));
166        *policy_cell_ref = Some(current_policy);
167        changed
168    };
169    let policy: Rc<SubcomposeMeasurePolicy> = cranpose_core::remember(move || {
170        let policy_cell = policy_cell.clone();
171        let policy: Rc<SubcomposeMeasurePolicy> =
172            Rc::new(
173                move |scope, constraints| match policy_cell.borrow().as_ref().cloned() {
174                    Some(current) => current(scope, constraints),
175                    None => empty_subcompose_measure_result(constraints),
176                },
177            );
178        policy
179    })
180    .with(|policy| policy.clone());
181    let id = cranpose_core::with_current_composer(|composer| {
182        composer.emit_node(|| SubcomposeLayoutNode::new(modifier.clone(), Rc::clone(&policy)))
183    });
184    let captured_context =
185        cranpose_core::with_current_composer(|composer| composer.capture_composition_context());
186    let composed_density = crate::density::density();
187    let direction = crate::layout_direction();
188    if let Err(err) = cranpose_core::with_node_mut(id, |node: &mut SubcomposeLayoutNode| {
189        node.set_modifier(modifier);
190        node.set_measure_policy(policy);
191        node.set_captured_context(captured_context);
192        node.set_density(composed_density);
193        node.set_layout_direction(direction);
194        if policy_captures_changed {
195            node.invalidate_subcomposition();
196        }
197    }) {
198        debug_assert!(false, "failed to update SubcomposeLayout node: {err}");
199    }
200    id
201}
202
203fn empty_subcompose_measure_result(constraints: Constraints) -> MeasureResult {
204    let (width, height) = constraints.constrain(0.0, 0.0);
205    MeasureResult::new(Size { width, height }, Vec::new())
206}
207
208/// Composes `content` with a scope that exposes the incoming constraints. All children are placed
209/// at the top start corner. Compose's `BoxWithConstraints`.
210#[composable(no_skip)]
211pub fn BoxWithConstraints<F>(modifier: Modifier, content: F) -> NodeId
212where
213    F: FnMut(BoxWithConstraintsScopeImpl) + 'static,
214{
215    let content_ref: Rc<RefCell<F>> = Rc::new(RefCell::new(content));
216    SubcomposeLayout(modifier, move |scope, constraints| {
217        let scope_impl = BoxWithConstraintsScopeImpl::new(constraints);
218        let scope_for_content = scope_impl;
219        let measurables = {
220            let content_ref = Rc::clone(&content_ref);
221            scope.subcompose(SlotId::new(0), constraints, move || {
222                cranpose_core::debug_label_current_scope("BoxWithConstraints.slot(0)");
223                let mut content = content_ref.borrow_mut();
224                content(scope_for_content);
225            })
226        };
227        let child_constraints = Constraints {
228            min_width: 0.0,
229            max_width: constraints.max_width,
230            min_height: 0.0,
231            max_height: constraints.max_height,
232        };
233
234        let mut width = 0.0_f32;
235        let mut height = 0.0_f32;
236        let mut placements = Vec::with_capacity(measurables.len());
237
238        for measurable in measurables {
239            let placeable = scope.measure(measurable, child_constraints);
240            width = width.max(placeable.width());
241            height = height.max(placeable.height());
242            placeable.place(0.0, 0.0);
243            placements.push(Placement::new(placeable.node_id(), 0.0, 0.0, 0));
244        }
245
246        width = width.clamp(constraints.min_width, constraints.max_width);
247        height = height.clamp(constraints.min_height, constraints.max_height);
248        scope.layout(width, height, placements)
249    })
250}
251
252#[cfg(test)]
253#[path = "tests/layout_tests.rs"]
254mod tests;