Skip to main content

cranpose_ui/modifier_nodes/
size.rs

1// The size modifier: the element that bounds its content's size. It is a
2// plain element: a chain keeps its bounds as words.
3
4use cranpose_foundation::{
5    Constraints, InvalidationKind, Measurable, ModifierNodeContext, NodeCapabilities, PlainElement,
6    PlainIntrinsic, PlainLayout, PlainLayoutFns, PrepareAt, Size,
7};
8
9// Which of a size element's bounds a slot of its values holds, and the bit
10// of its flags that says the slot holds a bound.
11const MIN_WIDTH: usize = 0;
12const MAX_WIDTH: usize = 1;
13const MIN_HEIGHT: usize = 2;
14const MAX_HEIGHT: usize = 3;
15// The incoming constraints take precedence over the bounds.
16const ENFORCE_INCOMING: u32 = 1 << 4;
17// The values are the constraints the bounds ask for at a coordinator's
18// density, each on a whole device pixel; the two bits after tell whether
19// the bounds fixed the width and the height.
20const PREPARED: u32 = 1 << 5;
21const FIXED_WIDTH: u32 = 1 << 6;
22const FIXED_HEIGHT: u32 = 1 << 7;
23
24/// Element that bounds the size of its content: a plain element, which a
25/// chain keeps as words.
26///
27/// Matches Kotlin: `SizeElement` in foundation-layout/src/commonMain/kotlin/androidx/compose/foundation/layout/Size.kt
28#[derive(Debug, Clone, PartialEq)]
29pub struct SizeElement {
30    // The bounds in logical pixels, 0 for one left open.
31    values: [f32; 4],
32    flags: u32,
33}
34
35impl SizeElement {
36    /// Creates an element that fixes the width and height, in logical pixels. A `None` length is
37    /// left free. The incoming constraints take precedence.
38    pub fn new(width: Option<f32>, height: Option<f32>) -> Self {
39        Self::with_constraints(width, width, height, height, true)
40    }
41
42    /// Creates an element with the given widths and heights, in logical pixels. A `None` bound is
43    /// left open. When `enforce_incoming` is true, the incoming constraints take precedence over
44    /// these bounds.
45    pub fn with_constraints(
46        min_width: Option<f32>,
47        max_width: Option<f32>,
48        min_height: Option<f32>,
49        max_height: Option<f32>,
50        enforce_incoming: bool,
51    ) -> Self {
52        let mut values = [0.0; 4];
53        let mut flags = if enforce_incoming {
54            ENFORCE_INCOMING
55        } else {
56            0
57        };
58        let bounds = [min_width, max_width, min_height, max_height];
59        for (slot, bound) in bounds.into_iter().enumerate() {
60            if let Some(value) = bound {
61                values[slot] = value;
62                flags |= 1 << slot;
63            }
64        }
65        Self { values, flags }
66    }
67
68    fn bound(&self, slot: usize) -> Option<f32> {
69        (self.flags & (1 << slot) != 0).then_some(self.values[slot])
70    }
71
72    /// Returns the smallest width in logical pixels, or `None` for no minimum.
73    pub fn min_width(&self) -> Option<f32> {
74        self.bound(MIN_WIDTH)
75    }
76
77    /// Returns the largest width in logical pixels, or `None` for no maximum.
78    pub fn max_width(&self) -> Option<f32> {
79        self.bound(MAX_WIDTH)
80    }
81
82    /// Returns the smallest height in logical pixels, or `None` for no minimum.
83    pub fn min_height(&self) -> Option<f32> {
84        self.bound(MIN_HEIGHT)
85    }
86
87    /// Returns the largest height in logical pixels, or `None` for no maximum.
88    pub fn max_height(&self) -> Option<f32> {
89        self.bound(MAX_HEIGHT)
90    }
91
92    /// Returns whether the incoming constraints take precedence over these bounds.
93    pub fn enforce_incoming(&self) -> bool {
94        self.flags & ENFORCE_INCOMING != 0
95    }
96
97    // Whether the bounds of the axis whose slots are `min` and `max` fix
98    // its size: both set, and equal.
99    fn fixes(&self, min: usize, max: usize, fixed: u32) -> bool {
100        if self.flags & PREPARED != 0 {
101            return self.flags & fixed != 0;
102        }
103        self.bound(min).is_some() && self.bound(min) == self.bound(max)
104    }
105
106    fn fixes_width(&self) -> bool {
107        self.fixes(MIN_WIDTH, MAX_WIDTH, FIXED_WIDTH)
108    }
109
110    fn fixes_height(&self) -> bool {
111        self.fixes(MIN_HEIGHT, MAX_HEIGHT, FIXED_HEIGHT)
112    }
113
114    // Whether no bound of the axis whose slots are `min` and `max` is set.
115    fn frees(&self, min: usize, max: usize) -> bool {
116        self.flags & ((1 << min) | (1 << max)) == 0
117    }
118
119    // The constraints the sizes ask for, each on a whole device pixel of
120    // `density` as Compose's `SizeNode` rounds them: those a coordinator
121    // prepared, or worked out here.
122    fn target_constraints(&self, density: f32) -> Constraints {
123        if self.flags & PREPARED != 0 {
124            let [min_width, max_width, min_height, max_height] = self.values;
125            return Constraints {
126                min_width,
127                max_width,
128                min_height,
129                max_height,
130            };
131        }
132        self.round_targets(density)
133    }
134
135    fn round_targets(&self, density: f32) -> Constraints {
136        use cranpose_ui_layout::round_to_px;
137
138        let max_width = self
139            .max_width()
140            .map_or(f32::INFINITY, |v| round_to_px(v, density).max(0.0));
141        let max_height = self
142            .max_height()
143            .map_or(f32::INFINITY, |v| round_to_px(v, density).max(0.0));
144
145        let min_width = self.min_width().map_or(0.0, |v| {
146            let clamped = round_to_px(v, density).clamp(0.0, max_width);
147            if clamped == f32::INFINITY {
148                0.0
149            } else {
150                clamped
151            }
152        });
153
154        let min_height = self.min_height().map_or(0.0, |v| {
155            let clamped = round_to_px(v, density).clamp(0.0, max_height);
156            if clamped == f32::INFINITY {
157                0.0
158            } else {
159                clamped
160            }
161        });
162
163        Constraints {
164            min_width,
165            max_width,
166            min_height,
167            max_height,
168        }
169    }
170    #[inline]
171    pub(crate) fn inner_constraints_prepared(&self, constraints: Constraints) -> Constraints {
172        let [min_width, max_width, min_height, max_height] = self.values;
173        self.inner_constraints_with_target(
174            constraints,
175            Constraints {
176                min_width,
177                max_width,
178                min_height,
179                max_height,
180            },
181        )
182    }
183
184    #[inline]
185    fn inner_constraints(&self, constraints: Constraints, density: f32) -> Constraints {
186        self.inner_constraints_with_target(constraints, self.target_constraints(density))
187    }
188
189    #[inline]
190    fn inner_constraints_with_target(
191        &self,
192        constraints: Constraints,
193        target: Constraints,
194    ) -> Constraints {
195        if self.enforce_incoming() {
196            Constraints {
197                min_width: target
198                    .min_width
199                    .max(constraints.min_width)
200                    .min(constraints.max_width),
201                max_width: target
202                    .max_width
203                    .min(constraints.max_width)
204                    .max(constraints.min_width),
205                min_height: target
206                    .min_height
207                    .max(constraints.min_height)
208                    .min(constraints.max_height),
209                max_height: target
210                    .max_height
211                    .min(constraints.max_height)
212                    .max(constraints.min_height),
213            }
214        } else {
215            let resolved_min_width = if self.min_width().is_some() {
216                target.min_width
217            } else {
218                constraints.min_width.min(target.max_width)
219            };
220            let resolved_max_width = if self.max_width().is_some() {
221                target.max_width
222            } else {
223                constraints.max_width.max(target.min_width)
224            };
225            let resolved_min_height = if self.min_height().is_some() {
226                target.min_height
227            } else {
228                constraints.min_height.min(target.max_height)
229            };
230            let resolved_max_height = if self.max_height().is_some() {
231                target.max_height
232            } else {
233                constraints.max_height.max(target.min_height)
234            };
235            Constraints {
236                min_width: resolved_min_width,
237                max_width: resolved_max_width,
238                min_height: resolved_min_height,
239                max_height: resolved_max_height,
240            }
241        }
242    }
243
244    #[inline]
245    pub(crate) fn place_size_prepared(
246        &self,
247        wrapped_constraints: Constraints,
248        child: Size,
249    ) -> Size {
250        let [min_width, _, min_height, _] = self.values;
251        let width = if self.flags & FIXED_WIDTH != 0
252            && min_width >= wrapped_constraints.min_width
253            && min_width <= wrapped_constraints.max_width
254        {
255            min_width
256        } else {
257            child.width
258        };
259        let height = if self.flags & FIXED_HEIGHT != 0
260            && min_height >= wrapped_constraints.min_height
261            && min_height <= wrapped_constraints.max_height
262        {
263            min_height
264        } else {
265            child.height
266        };
267        Size { width, height }
268    }
269
270    #[inline]
271    fn place_size(&self, wrapped_constraints: Constraints, child: Size, density: f32) -> Size {
272        let target = self.target_constraints(density);
273        let width = if self.fixes_width()
274            && target.min_width >= wrapped_constraints.min_width
275            && target.min_width <= wrapped_constraints.max_width
276        {
277            target.min_width
278        } else {
279            child.width
280        };
281        let height = if self.fixes_height()
282            && target.min_height >= wrapped_constraints.min_height
283            && target.min_height <= wrapped_constraints.max_height
284        {
285            target.min_height
286        } else {
287            child.height
288        };
289        Size { width, height }
290    }
291}
292
293impl PlainElement for SizeElement {
294    const WORDS: usize = 5;
295    const CAPABILITIES: NodeCapabilities = NodeCapabilities::LAYOUT;
296    const UPDATE_INVALIDATION: Option<InvalidationKind> = Some(InvalidationKind::Layout);
297    const LAYOUT: Option<&'static PlainLayoutFns> = Some(&PlainLayoutFns::of::<Self>());
298
299    #[inline]
300    fn to_words(&self, words: &mut [u32]) {
301        let [a, b, c, d] = self.values.map(f32::to_bits);
302        words.copy_from_slice(&[a, b, c, d, self.flags]);
303    }
304
305    // One length check for the five words, where an index each would
306    // check five times. A coordinator hands more words than the element's.
307    #[inline]
308    fn from_words(words: &[u32]) -> Self {
309        let (values, flags) = match *words {
310            [a, b, c, d, flags, ..] => ([a, b, c, d], flags),
311            _ => ([0; 4], 0),
312        };
313        Self {
314            values: values.map(f32::from_bits),
315            flags,
316        }
317    }
318}
319
320impl PlainLayout for SizeElement {
321    const PREPARES: bool = true;
322
323    fn prepared(self, at: PrepareAt) -> Self {
324        let target = self.round_targets(at.density);
325        let mut flags = self.flags | PREPARED;
326        if self.fixes_width() {
327            flags |= FIXED_WIDTH;
328        }
329        if self.fixes_height() {
330            flags |= FIXED_HEIGHT;
331        }
332        Self {
333            values: [
334                target.min_width,
335                target.max_width,
336                target.min_height,
337                target.max_height,
338            ],
339            flags,
340        }
341    }
342
343    fn measure_hold(
344        &self,
345        density: f32,
346        _constraints: Constraints,
347        size: Size,
348        wrapped: cranpose_ui_layout::WrappedHold,
349    ) -> Option<cranpose_ui_layout::ConstraintsHold> {
350        if !self.enforce_incoming() {
351            return None;
352        }
353        let target = self.target_constraints(density);
354        Some(cranpose_ui_layout::ConstraintsHold {
355            width: size_axis_hold(
356                (self.fixes_width(), self.frees(MIN_WIDTH, MAX_WIDTH)),
357                target.min_width,
358                size.width,
359                wrapped.hold.map(|hold| hold.width),
360            )?,
361            height: size_axis_hold(
362                (self.fixes_height(), self.frees(MIN_HEIGHT, MAX_HEIGHT)),
363                target.min_height,
364                size.height,
365                wrapped.hold.map(|hold| hold.height),
366            )?,
367        })
368    }
369
370    fn measure(
371        &self,
372        context: &mut dyn ModifierNodeContext,
373        measurable: &dyn Measurable,
374        constraints: Constraints,
375    ) -> cranpose_ui_layout::LayoutModifierMeasureResult {
376        let density = context.density();
377        let wrapped_constraints = self.inner_constraints(constraints, density);
378        let placeable = measurable.measure(wrapped_constraints);
379        let size = self.place_size(
380            wrapped_constraints,
381            Size {
382                width: placeable.width(),
383                height: placeable.height(),
384            },
385            density,
386        );
387        cranpose_ui_layout::LayoutModifierMeasureResult::with_size(size)
388    }
389
390    fn intrinsic(&self, measurable: &dyn Measurable, kind: PlainIntrinsic, density: f32) -> f32 {
391        let axis = if kind.is_width() {
392            SizeAxis::Width
393        } else {
394            SizeAxis::Height
395        };
396        size_intrinsic(
397            self.target_constraints(density),
398            axis,
399            self.enforce_incoming(),
400            kind.cross(),
401            |cross| kind.at(cross).of(measurable),
402        )
403    }
404}
405
406// One axis of what a size modifier that enforces incoming constraints
407// holds for: a fixed size that fit holds while the bounds allow it, and an
408// axis it leaves unsized, as `free` tells, passes the bounds to its content
409// and holds what the content holds.
410fn size_axis_hold(
411    (fixed, free): (bool, bool),
412    target: f32,
413    size: f32,
414    wrapped: Option<cranpose_ui_layout::AxisHold>,
415) -> Option<cranpose_ui_layout::AxisHold> {
416    if fixed && size == target {
417        Some(cranpose_ui_layout::AxisHold::sized(target))
418    } else if free {
419        wrapped
420    } else {
421        None
422    }
423}
424
425#[derive(Clone, Copy)]
426enum SizeAxis {
427    Width,
428    Height,
429}
430
431fn size_intrinsic(
432    target: Constraints,
433    axis: SizeAxis,
434    enforce_incoming: bool,
435    cross: f32,
436    intrinsic: impl FnOnce(f32) -> f32,
437) -> f32 {
438    let (target_min, target_max, cross_min, cross_max) = match axis {
439        SizeAxis::Width => (
440            target.min_width,
441            target.max_width,
442            target.min_height,
443            target.max_height,
444        ),
445        SizeAxis::Height => (
446            target.min_height,
447            target.max_height,
448            target.min_width,
449            target.max_width,
450        ),
451    };
452    if target_min == target_max && target_max != f32::INFINITY {
453        target_max
454    } else {
455        let child_cross = if enforce_incoming {
456            cross
457        } else {
458            cross.clamp(cross_min, cross_max)
459        };
460        intrinsic(child_cross).clamp(target_min, target_max)
461    }
462}