Skip to main content

cranpose_ui/widgets/
layout.rs

1//! Generic Layout widget and SubcomposeLayout
2
3use std::{
4    cell::{Cell, RefCell},
5    rc::Rc,
6};
7
8use cranpose_core::{NodeId, SlotId};
9use cranpose_foundation::NodeCapabilities;
10use cranpose_ui_graphics::Size;
11use cranpose_ui_layout::{MeasurePolicy, Placement};
12
13use super::{held_policy::held_policy, nodes::LayoutNode, scopes::BoxWithConstraintsScopeImpl};
14use crate::{
15    composable,
16    modifier::Modifier,
17    subcompose_layout::{
18        Constraints, MeasurePolicy as SubcomposeMeasurePolicy, MeasureResult, SubcomposeLayoutNode,
19        SubcomposeLayoutScope, SubcomposeMeasureScope, SubcomposeMeasureScopeImpl,
20    },
21};
22
23pub(crate) fn caller_modifier_changed(modifier: &Modifier) -> bool {
24    cranpose_core::remember(|| RefCell::new(modifier.clone())).with(|last| {
25        let changed = *last.borrow() != *modifier;
26        if changed {
27            *last.borrow_mut() = modifier.clone();
28        }
29        changed
30    })
31}
32
33/// The density and layout direction a layout node composes under. A widget
34/// reads them once, for its measure policy and its node: each read looks a
35/// composition local up.
36#[derive(Clone, Copy, Default)]
37pub(crate) struct LayoutEnvironment {
38    pub(crate) density: crate::density::Density,
39    pub(crate) direction: crate::layout_direction::LayoutDirection,
40}
41
42impl LayoutEnvironment {
43    /// The density and layout direction in force here.
44    pub(crate) fn current() -> Self {
45        Self {
46            density: crate::density::density(),
47            direction: crate::layout_direction(),
48        }
49    }
50}
51
52/// Emits a layout node whose children `measure_policy` measures and places. `content` composes the
53/// children. Compose's `Layout`.
54/// Like Compose's, it is inline: a state its content reads recomposes the
55/// composable that called it.
56#[composable(no_skip)]
57pub fn Layout<F, P>(modifier: Modifier, measure_policy: P, content: F) -> NodeId
58where
59    F: FnMut() + 'static,
60    P: MeasurePolicy + Clone + PartialEq + 'static,
61{
62    compose_layout(
63        modifier,
64        &measure_policy,
65        LayoutEnvironment::current(),
66        content,
67    )
68}
69
70/// Emits a layout node in the calling composable's group, so a widget that
71/// is one layout composes in one group rather than its own and `Layout`'s.
72pub(crate) fn compose_layout<F, P>(
73    modifier: Modifier,
74    measure_policy: &P,
75    environment: LayoutEnvironment,
76    mut content: F,
77) -> NodeId
78where
79    F: FnMut() + 'static,
80    P: MeasurePolicy + Clone + PartialEq,
81{
82    compose_layout_node(modifier, measure_policy, environment, &mut content)
83}
84
85// The layout node of `compose_layout` and its children's bracket, compiled
86// once: inlined, it puts the modifier's drop and the bracket into the body of
87// every widget call, about 200 bytes of wasm a call.
88#[inline(never)]
89fn compose_layout_node(
90    mut modifier: Modifier,
91    policy: &dyn PolicyUpdate,
92    environment: LayoutEnvironment,
93    content: &mut dyn FnMut(),
94) -> NodeId {
95    // One composer lookup for the node and its children's bracket: each
96    // lookup reads a thread-local.
97    cranpose_core::with_current_composer(|composer| {
98        let (id, provided, _) = emit_layout_node(composer, &mut modifier, policy, environment);
99        composer.push_parent(id);
100        compose_under_locals(provided, content);
101        composer.pop_parent();
102        id
103    })
104}
105
106// A layout node with no children, compiled once for each kind of modifier.
107#[inline(never)]
108pub(crate) fn compose_empty_layout(
109    mut modifier: impl NodeModifier,
110    environment: LayoutEnvironment,
111) -> NodeId {
112    cranpose_core::with_current_composer(|composer| {
113        let (id, provided, held) = emit_layout_node(
114            composer,
115            &mut modifier,
116            &crate::layout::policies::EmptyMeasurePolicy,
117            environment,
118        );
119        if provided.is_empty() {
120            // A made node has no children to sync. Inside a subcomposition
121            // its empty sync would settle its layout dirt, which its parent's
122            // sync of its new child carries up already.
123            if held != HeldChildren::Made {
124                composer.compose_no_children(id, held == HeldChildren::Some);
125            }
126        } else {
127            composer.push_parent(id);
128            compose_under_locals(provided, &mut || {});
129            composer.pop_parent();
130        }
131        id
132    })
133}
134
135// The steps of emitting a layout node that know its policy's type;
136// `emit_layout_node` takes the rest, compiled once for every policy type.
137trait PolicyUpdate {
138    // The policy as a node holds it.
139    fn held(&self) -> Rc<dyn MeasurePolicy>;
140    // Gives `node` the policy, unless the one it holds equals it.
141    fn update(&self, node: &mut LayoutNode);
142}
143
144impl<P: MeasurePolicy + Clone + PartialEq> PolicyUpdate for P {
145    fn held(&self) -> Rc<dyn MeasurePolicy> {
146        held_policy(self)
147    }
148
149    fn update(&self, node: &mut LayoutNode) {
150        let held = {
151            let runtime_state = node.layout_runtime_state().borrow();
152            let current: &dyn std::any::Any = runtime_state.measure_policy();
153            current.downcast_ref::<P>() == Some(self)
154        };
155        if !held {
156            node.set_measure_policy(held_policy(self));
157        }
158    }
159}
160
161// What a layout node's modifier is set from: a modifier, or what makes one
162// only when the node does not hold it already.
163pub(crate) trait NodeModifier {
164    // The composition locals the modifier provides.
165    fn provided_locals(&self) -> Vec<cranpose_core::ProvidedValue>;
166    // The modifier, for a node made new.
167    fn to_modifier(&self) -> Modifier;
168    // Sets the modifier on `node`; a modifier may give its value to the node
169    // and stay empty.
170    fn set_on(&mut self, node: &mut LayoutNode);
171}
172
173impl NodeModifier for Modifier {
174    fn provided_locals(&self) -> Vec<cranpose_core::ProvidedValue> {
175        self.provided_composition_locals()
176    }
177
178    fn to_modifier(&self) -> Modifier {
179        self.clone()
180    }
181
182    fn set_on(&mut self, node: &mut LayoutNode) {
183        node.set_modifier(std::mem::take(self));
184    }
185}
186
187// What an emit did with its layout node.
188#[derive(Clone, Copy, PartialEq, Eq)]
189enum Emitted {
190    // The node was there: it takes the modifier, the policy and the
191    // environment, unless it holds them already.
192    Kept,
193    // The emit made the node, which holds them already and no children.
194    Made,
195    // A node made as `Made` is, whose chain reads modifier locals: it takes
196    // its modifier again, from the parent it names now.
197    MadeReadingLocals,
198}
199
200// Emits and updates a layout node; returns it, the composition locals its
201// modifier provides and whether it holds children. The node keeps the policy
202// it holds while `policy` equals it. One body for every policy and modifier,
203// inlined into its two callers, which are out of line themselves.
204#[inline]
205fn emit_layout_node(
206    composer: &cranpose_core::Composer,
207    modifier: &mut dyn NodeModifier,
208    policy: &dyn PolicyUpdate,
209    environment: LayoutEnvironment,
210) -> (NodeId, Vec<cranpose_core::ProvidedValue>, HeldChildren) {
211    let provided = modifier.provided_locals();
212    let emitted = Cell::new(Emitted::Kept);
213    let fill = |node: &mut LayoutNode, shell| {
214        node.fill(&modifier.to_modifier(), policy.held(), environment, shell);
215        let reads_locals = node
216            .modifier_capabilities()
217            .contains(NodeCapabilities::MODIFIER_LOCALS);
218        emitted.set(if reads_locals {
219            Emitted::MadeReadingLocals
220        } else {
221            Emitted::Made
222        });
223    };
224    let id = composer.emit_recyclable_node(LayoutNode::bare_shell, fill);
225    if emitted.get() == Emitted::Made {
226        return (id, provided, HeldChildren::Made);
227    }
228    let holds_children = composer
229        .with_node_mut(id, |node: &mut LayoutNode| {
230            modifier.set_on(node);
231            policy.update(node);
232            node.set_density(environment.density);
233            node.set_layout_direction(environment.direction);
234            !node.children.is_empty()
235        })
236        .unwrap_or_else(|err| {
237            debug_assert!(false, "failed to update Layout node: {err}");
238            true
239        });
240    let held = match (emitted.get(), holds_children) {
241        (Emitted::MadeReadingLocals, _) => HeldChildren::Made,
242        (Emitted::Kept | Emitted::Made, true) => HeldChildren::Some,
243        (Emitted::Kept | Emitted::Made, false) => HeldChildren::None,
244    };
245    (id, provided, held)
246}
247
248// The children a node holds when its emit returns.
249#[derive(Clone, Copy, PartialEq, Eq)]
250enum HeldChildren {
251    // Children of its last composition.
252    Some,
253    // None.
254    None,
255    // None, and none ever: the emit made the node, so its composition
256    // closes no list of children it held.
257    Made,
258}
259
260fn compose_under_locals(provided: Vec<cranpose_core::ProvidedValue>, content: &mut dyn FnMut()) {
261    if provided.is_empty() {
262        content();
263        return;
264    }
265    cranpose_core::CompositionLocalProvider(provided, content);
266}
267
268/// Emits a layout node whose `measure_policy` composes its children during measurement, so the
269/// children can depend on the incoming constraints. Compose's `SubcomposeLayout`.
270#[composable]
271pub fn SubcomposeLayout(
272    modifier: Modifier,
273    measure_policy: impl for<'scope> Fn(
274        &mut SubcomposeMeasureScopeImpl<'scope>,
275        Constraints,
276    ) -> MeasureResult
277    + 'static,
278) -> NodeId {
279    cranpose_core::debug_label_current_scope("SubcomposeLayout");
280    let policy_cell =
281        cranpose_core::remember(|| Rc::new(RefCell::new(None::<Rc<SubcomposeMeasurePolicy>>)))
282            .with(|cell| Rc::clone(cell));
283    let current_policy: Rc<SubcomposeMeasurePolicy> = Rc::new(measure_policy);
284    let policy_captures_changed = {
285        let mut policy_cell_ref = policy_cell.borrow_mut();
286        let changed = policy_cell_ref
287            .as_ref()
288            .is_none_or(|previous| !Rc::ptr_eq(previous, &current_policy));
289        *policy_cell_ref = Some(current_policy);
290        changed
291    };
292    let policy: Rc<SubcomposeMeasurePolicy> = cranpose_core::remember(move || {
293        let policy_cell = Rc::clone(&policy_cell);
294        let policy: Rc<SubcomposeMeasurePolicy> =
295            Rc::new(
296                move |scope, constraints| match policy_cell.borrow().as_ref().cloned() {
297                    Some(current) => current(scope, constraints),
298                    None => empty_subcompose_measure_result(constraints),
299                },
300            );
301        policy
302    })
303    .with(|policy| Rc::clone(policy));
304    let id = cranpose_core::with_current_composer(|composer| {
305        composer.emit_node(|| SubcomposeLayoutNode::new(modifier.clone(), Rc::clone(&policy)))
306    });
307    let captured_context =
308        cranpose_core::with_current_composer(|composer| composer.capture_composition_context());
309    let composed_density = crate::density::density();
310    let direction = crate::layout_direction();
311    if let Err(err) = cranpose_core::with_node_mut(id, |node: &mut SubcomposeLayoutNode| {
312        node.set_modifier(modifier);
313        node.set_measure_policy(policy);
314        node.set_captured_context(captured_context);
315        node.set_density(composed_density);
316        node.set_layout_direction(direction);
317        if policy_captures_changed {
318            node.invalidate_subcomposition();
319        }
320    }) {
321        debug_assert!(false, "failed to update SubcomposeLayout node: {err}");
322    }
323    id
324}
325
326fn empty_subcompose_measure_result(constraints: Constraints) -> MeasureResult {
327    let (width, height) = constraints.constrain(0.0, 0.0);
328    MeasureResult::new(Size { width, height }, Vec::new())
329}
330
331/// Composes `content` with a scope that exposes the incoming constraints. All children are placed
332/// at the top start corner. Compose's `BoxWithConstraints`.
333#[composable(no_skip)]
334pub fn BoxWithConstraints<F>(modifier: Modifier, content: F) -> NodeId
335where
336    F: FnMut(BoxWithConstraintsScopeImpl) + 'static,
337{
338    let content_ref: Rc<RefCell<F>> = Rc::new(RefCell::new(content));
339    SubcomposeLayout(modifier, move |scope, constraints| {
340        let scope_impl = BoxWithConstraintsScopeImpl::new(constraints);
341        let scope_for_content = scope_impl;
342        let measurables = {
343            let content_ref = Rc::clone(&content_ref);
344            scope.subcompose(SlotId::new(0), constraints, move || {
345                cranpose_core::debug_label_current_scope("BoxWithConstraints.slot(0)");
346                let mut content = content_ref.borrow_mut();
347                content(scope_for_content);
348            })
349        };
350        let child_constraints = Constraints {
351            min_width: 0.0,
352            max_width: constraints.max_width,
353            min_height: 0.0,
354            max_height: constraints.max_height,
355        };
356
357        let mut width = 0.0_f32;
358        let mut height = 0.0_f32;
359        let mut placements = Vec::with_capacity(measurables.len());
360
361        for measurable in measurables {
362            let placeable = scope.measure(measurable, child_constraints);
363            width = width.max(placeable.width());
364            height = height.max(placeable.height());
365            placements.push(Placement::new(placeable.node_id(), 0.0, 0.0, 0.0));
366        }
367
368        width = width.clamp(constraints.min_width, constraints.max_width);
369        height = height.clamp(constraints.min_height, constraints.max_height);
370        scope.layout(width, height, placements)
371    })
372}
373
374#[cfg(test)]
375#[path = "tests/layout_tests.rs"]
376mod tests;