cranpose_ui_layout/core.rs
1//! Core layout traits and types shared by Compose UI widgets.
2
3use std::{any::Any, fmt, rc::Rc};
4
5use cranpose_core::NodeId;
6use cranpose_ui_graphics::Size;
7
8use crate::{
9 Alignment, HorizontalAlignment, Measurables, VerticalAlignment, constraints::Constraints,
10};
11
12/// Parent data for flex layouts (Row/Column weights and alignment).
13#[derive(Clone, Copy, Debug, Default)]
14pub struct FlexParentData {
15 /// Weight for distributing remaining space in the main axis.
16 /// If > 0.0, this child participates in weighted distribution.
17 pub weight: f32,
18
19 /// Whether to fill the allocated space when using weight.
20 /// If true, child gets tight constraints; if false, child gets loose constraints.
21 pub fill: bool,
22}
23
24impl FlexParentData {
25 /// A child's share of the room left over, and whether it fills it.
26 pub fn new(weight: f32, fill: bool) -> Self {
27 Self { weight, fill }
28 }
29
30 /// Whether the child takes a share of the room left over.
31 pub fn has_weight(&self) -> bool {
32 self.weight > 0.0
33 }
34}
35
36/// Data a child's modifier gives one kind of parent layout, which that
37/// layout's measure policy reads by its type: a grid cell, or the data of
38/// an app's own layout. Compose's `ParentDataModifierNode` data. Every
39/// `'static` type with `Debug` and `PartialEq` is layout data.
40pub trait LayoutData: Any + fmt::Debug {
41 /// Whether `other` holds the same data, so a parent can keep its last
42 /// measure.
43 fn same_as(&self, other: &dyn LayoutData) -> bool;
44
45 /// The data as `Any`, to read it by its type.
46 fn as_any(&self) -> &dyn Any;
47}
48
49impl<T: Any + fmt::Debug + PartialEq> LayoutData for T {
50 fn same_as(&self, other: &dyn LayoutData) -> bool {
51 other
52 .as_any()
53 .downcast_ref::<T>()
54 .is_some_and(|other| other == self)
55 }
56
57 fn as_any(&self) -> &dyn Any {
58 self
59 }
60}
61
62/// Layout metadata supplied by a child for its direct parent.
63///
64/// Weight/fill apply to Row and Column. Alignment values override the
65/// corresponding parent layout's default alignment for this child only.
66#[derive(Clone, Debug, Default)]
67pub struct ParentData {
68 /// The child's share of a Row's or Column's room left over; 0 for none.
69 pub weight: f32,
70 /// Whether a weighted child fills its share or may be smaller.
71 pub fill: bool,
72 /// Where the child sits in a Box, over the Box's own alignment.
73 pub box_alignment: Option<Alignment>,
74 /// Where the child sits across a Row, over the Row's own alignment.
75 pub row_alignment: Option<VerticalAlignment>,
76 /// Aligns this child's first baseline with other baseline-aligned Row children.
77 pub row_baseline: bool,
78 /// Where the child sits across a Column, over the Column's own alignment.
79 pub column_alignment: Option<HorizontalAlignment>,
80 /// The fraction of the parent's width the child's outermost horizontal
81 /// fill modifier asks for; 0 without one. A FlexBox reads it as the
82 /// child's default grow. Compose's `FillModifierParentData`.
83 pub fill_width_fraction: f32,
84 /// The same for height.
85 pub fill_height_fraction: f32,
86 /// The data of the child's outermost [`LayoutData`] modifier, for a
87 /// parent that reads it by its type.
88 pub layout_data: Option<Rc<dyn LayoutData>>,
89}
90
91impl PartialEq for ParentData {
92 fn eq(&self, other: &Self) -> bool {
93 self.weight == other.weight
94 && self.fill == other.fill
95 && self.box_alignment == other.box_alignment
96 && self.row_alignment == other.row_alignment
97 && self.row_baseline == other.row_baseline
98 && self.column_alignment == other.column_alignment
99 && self.fill_width_fraction == other.fill_width_fraction
100 && self.fill_height_fraction == other.fill_height_fraction
101 && match (&self.layout_data, &other.layout_data) {
102 (None, None) => true,
103 (Some(data), Some(other)) => Rc::ptr_eq(data, other) || data.same_as(&**other),
104 _ => false,
105 }
106 }
107}
108
109impl From<FlexParentData> for ParentData {
110 fn from(value: FlexParentData) -> Self {
111 Self {
112 weight: value.weight,
113 fill: value.fill,
114 ..Self::default()
115 }
116 }
117}
118
119impl ParentData {
120 /// Whether the child takes a share of the room left over.
121 pub fn has_weight(&self) -> bool {
122 self.weight > 0.0
123 }
124
125 /// The child's [`LayoutData`] when it is a `T`.
126 pub fn layout_data<T: Any>(&self) -> Option<&T> {
127 self.layout_data.as_deref()?.as_any().downcast_ref()
128 }
129}
130
131/// Object capable of measuring a layout child and exposing intrinsic sizes.
132pub trait Measurable {
133 /// Measures the child with the provided constraints, returning a [`Placeable`].
134 fn measure(&self, constraints: Constraints) -> Placeable;
135
136 /// The size the last measure gave its parent and the incoming
137 /// constraints that measurement holds for: see
138 /// [`crate::ConstraintsHold`]. `None`, the default, when it cannot tell.
139 fn measured_hold(&self) -> Option<(Size, crate::ConstraintsHold)> {
140 None
141 }
142
143 /// Returns the minimum width achievable for the given height.
144 fn min_intrinsic_width(&self, height: f32) -> f32;
145
146 /// Returns the maximum width achievable for the given height.
147 fn max_intrinsic_width(&self, height: f32) -> f32;
148
149 /// Returns the minimum height achievable for the given width.
150 fn min_intrinsic_height(&self, width: f32) -> f32;
151
152 /// Returns the maximum height achievable for the given width.
153 fn max_intrinsic_height(&self, width: f32) -> f32;
154
155 /// Returns flex parent data if this measurable has weight/fill properties.
156 /// Default implementation returns None (no weight).
157 fn flex_parent_data(&self) -> Option<FlexParentData> {
158 None
159 }
160
161 /// Returns all metadata consumed by the direct parent layout.
162 ///
163 /// The default preserves the older `flex_parent_data` customization
164 /// point so existing custom measurables continue to provide weights.
165 fn parent_data(&self) -> ParentData {
166 self.flex_parent_data().map_or_default(Into::into)
167 }
168}
169
170// A reference measures as what it refers to, so a list of
171// `&dyn Measurable` holds children of several types.
172impl<M: Measurable + ?Sized> Measurable for &M {
173 fn measure(&self, constraints: Constraints) -> Placeable {
174 (**self).measure(constraints)
175 }
176
177 fn measured_hold(&self) -> Option<(Size, crate::ConstraintsHold)> {
178 (**self).measured_hold()
179 }
180
181 fn min_intrinsic_width(&self, height: f32) -> f32 {
182 (**self).min_intrinsic_width(height)
183 }
184
185 fn max_intrinsic_width(&self, height: f32) -> f32 {
186 (**self).max_intrinsic_width(height)
187 }
188
189 fn min_intrinsic_height(&self, width: f32) -> f32 {
190 (**self).min_intrinsic_height(width)
191 }
192
193 fn max_intrinsic_height(&self, width: f32) -> f32 {
194 (**self).max_intrinsic_height(width)
195 }
196
197 fn flex_parent_data(&self) -> Option<FlexParentData> {
198 (**self).flex_parent_data()
199 }
200
201 fn parent_data(&self) -> ParentData {
202 (**self).parent_data()
203 }
204}
205
206/// Result of running a measurement pass for a single child: its size, node
207/// and alignment lines. A policy places the child with a [`Placement`] of
208/// that node in its [`MeasureResult`], where Compose calls
209/// `Placeable.place` in its `layout` block.
210pub struct Placeable {
211 width: f32,
212 height: f32,
213 node_id: NodeId,
214 content_offset_x: f32,
215 content_offset_y: f32,
216 alignment_lines: crate::AlignmentLines,
217}
218
219impl Placeable {
220 /// A placeable of `width` by `height` for the node `node_id`.
221 pub fn value(width: f32, height: f32, node_id: NodeId) -> Self {
222 Self {
223 width,
224 height,
225 node_id,
226 content_offset_x: 0.0,
227 content_offset_y: 0.0,
228 alignment_lines: crate::AlignmentLines::default(),
229 }
230 }
231
232 /// Creates a pure-value placeable with a content offset.
233 pub fn value_with_offset(
234 width: f32,
235 height: f32,
236 node_id: NodeId,
237 content_offset: (f32, f32),
238 ) -> Self {
239 Self {
240 width,
241 height,
242 node_id,
243 content_offset_x: content_offset.0,
244 content_offset_y: content_offset.1,
245 alignment_lines: crate::AlignmentLines::default(),
246 }
247 }
248
249 /// Returns the measured width of the child.
250 pub fn width(&self) -> f32 {
251 self.width
252 }
253
254 /// Returns the measured height of the child.
255 pub fn height(&self) -> f32 {
256 self.height
257 }
258
259 /// Returns the identifier for the underlying layout node.
260 pub fn node_id(&self) -> NodeId {
261 self.node_id
262 }
263
264 /// Returns the accumulated content offset from the coordinator chain.
265 pub fn content_offset(&self) -> (f32, f32) {
266 (self.content_offset_x, self.content_offset_y)
267 }
268
269 /// Supplies alignment lines relative to this placeable's top edge.
270 pub fn with_alignment_lines(mut self, alignment_lines: crate::AlignmentLines) -> Self {
271 self.alignment_lines = alignment_lines;
272 self
273 }
274
275 /// Returns the text baselines relative to this placeable's top edge.
276 pub fn alignment_lines(&self) -> crate::AlignmentLines {
277 self.alignment_lines
278 }
279}
280
281/// Scope for measurement operations.
282///
283/// This is Compose's `MeasureScope` -- the receiver `MeasurePolicy.measure` runs
284/// on, which is what lets a measure pass see the density of the subtree it is
285/// measuring rather than some process-wide default. There is no sensible
286/// fallback value for either method: a policy that reads density must be given
287/// the real grid, so both are required rather than defaulted.
288pub trait MeasureScope {
289 /// Returns the current density for converting Dp to pixels.
290 fn density(&self) -> f32;
291
292 /// Returns the current font scale for converting Sp to pixels.
293 fn font_scale(&self) -> f32;
294}
295
296/// Policy responsible for measuring and placing children. A layout compares
297/// the policy it is given with the one its node holds, through [`Any`].
298pub trait MeasurePolicy: Any {
299 /// Runs the measurement pass with the provided children and constraints.
300 fn measure(
301 &self,
302 scope: &dyn MeasureScope,
303 measurables: Measurables<'_>,
304 constraints: Constraints,
305 ) -> MeasureResult;
306
307 /// Runs measurement into caller-owned placement storage.
308 ///
309 /// The default preserves the public [`MeasurePolicy::measure`] contract for custom
310 /// policies. Built-in policies override this to avoid allocating a fresh placement
311 /// vector on every measure pass.
312 fn measure_into(
313 &self,
314 scope: &dyn MeasureScope,
315 measurables: Measurables<'_>,
316 constraints: Constraints,
317 placements: &mut Vec<Placement>,
318 ) -> Measurement {
319 let result = self.measure(scope, measurables, constraints);
320 placements.clear();
321 placements.extend(result.placements);
322 Measurement {
323 size: result.size,
324 alignment_lines: result.alignment_lines,
325 }
326 }
327
328 /// The incoming constraints the measure that sized the layout `size`
329 /// under `constraints` holds for, when the policy can tell: see
330 /// [`crate::ConstraintsHold`]. `None`, the default, holds for
331 /// `constraints` alone.
332 fn measure_hold(
333 &self,
334 _measurables: Measurables<'_>,
335 _constraints: Constraints,
336 _size: Size,
337 ) -> Option<crate::ConstraintsHold> {
338 None
339 }
340
341 /// Whether this policy may lay its children out otherwise when a child's
342 /// parent data goes from `before` to `after`. The default reads all of
343 /// it; a policy that reads part of it answers for that part, so a change
344 /// elsewhere keeps its measurement.
345 fn reads_parent_data_change(&self, before: &ParentData, after: &ParentData) -> bool {
346 before != after
347 }
348
349 /// Whether the measure under `constraints` gave a size and child
350 /// positions that no child's size enters: a child that measures to
351 /// another size then leaves this layout as it is, and the layout keeps
352 /// its measurement. `false`, the default, measures the layout again.
353 fn ignores_child_sizes(
354 &self,
355 _measurables: Measurables<'_>,
356 _constraints: Constraints,
357 ) -> bool {
358 false
359 }
360
361 /// Computes the minimum intrinsic width of this policy.
362 fn min_intrinsic_width(&self, measurables: Measurables<'_>, height: f32) -> f32;
363
364 /// Computes the maximum intrinsic width of this policy.
365 fn max_intrinsic_width(&self, measurables: Measurables<'_>, height: f32) -> f32;
366
367 /// Computes the minimum intrinsic height of this policy.
368 fn min_intrinsic_height(&self, measurables: Measurables<'_>, width: f32) -> f32;
369
370 /// Computes the maximum intrinsic height of this policy.
371 fn max_intrinsic_height(&self, measurables: Measurables<'_>, width: f32) -> f32;
372}
373
374/// The size and explicit alignment lines produced by a measure policy.
375#[derive(Clone, Copy, Debug, Default, PartialEq)]
376pub struct Measurement {
377 /// The size occupied by the measured layout.
378 pub size: Size,
379 /// Explicit baselines in this layout's coordinates; unspecified lines are inherited.
380 pub alignment_lines: crate::AlignmentLines,
381}
382
383impl From<Size> for Measurement {
384 fn from(size: Size) -> Self {
385 Self {
386 size,
387 alignment_lines: crate::AlignmentLines::default(),
388 }
389 }
390}
391
392/// Result of a measurement operation.
393#[derive(Clone, Debug)]
394pub struct MeasureResult {
395 /// The size the layout takes.
396 pub size: Size,
397 /// Explicit baselines in this layout's coordinates; unspecified lines are inherited.
398 pub alignment_lines: crate::AlignmentLines,
399 /// Where the children go.
400 pub placements: Vec<Placement>,
401}
402
403impl MeasureResult {
404 /// Creates a result from a size or a measurement that already has alignment lines.
405 pub fn new(measurement: impl Into<Measurement>, placements: Vec<Placement>) -> Self {
406 let measurement = measurement.into();
407 Self {
408 size: measurement.size,
409 alignment_lines: measurement.alignment_lines,
410 placements,
411 }
412 }
413
414 /// Reports explicit lines relative to this layout's top edge.
415 pub fn with_alignment_lines(mut self, alignment_lines: crate::AlignmentLines) -> Self {
416 self.alignment_lines = alignment_lines;
417 self
418 }
419}
420
421/// Placement information for a measured child.
422#[derive(Clone, Copy, Debug)]
423pub struct Placement {
424 /// The child placed.
425 pub node_id: NodeId,
426 /// Its left edge in the parent, in logical pixels.
427 pub x: f32,
428 /// Its top edge in the parent, in logical pixels.
429 pub y: f32,
430 /// Its draw order among its siblings: higher draws on top and takes a
431 /// tap first. It adds to the child's `Modifier::z_index`, as the
432 /// `zIndex` of Compose's `Placeable.place` does.
433 pub z_index: f32,
434}
435
436impl Placement {
437 /// `node_id` at `(x, y)` in the parent, drawn in `z_index` order.
438 pub fn new(node_id: NodeId, x: f32, y: f32, z_index: f32) -> Self {
439 Self {
440 node_id,
441 x,
442 y,
443 z_index,
444 }
445 }
446}
447
448/// Result of a layout modifier measurement operation.
449///
450/// Unlike `MeasureResult` which is for `MeasurePolicy` (multiple children),
451/// this type is specifically for layout modifiers which wrap a single piece
452/// of content and need to specify where that wrapped content should be placed.
453#[derive(Clone, Copy, Debug)]
454pub struct LayoutModifierMeasureResult {
455 /// The size this modifier will occupy.
456 pub size: Size,
457 /// The offset at which to place the wrapped content relative to
458 /// the top-left corner of this modifier's bounds.
459 /// For example, PaddingNode returns (padding.left, padding.top) here
460 /// to offset the child by the padding amount.
461 pub placement_offset_x: f32,
462 /// The vertical offset of the wrapped content, as `placement_offset_x`.
463 pub placement_offset_y: f32,
464 /// Explicit alignment lines. Unspecified lines are inherited from wrapped content.
465 pub alignment_lines: crate::AlignmentLines,
466}
467
468impl LayoutModifierMeasureResult {
469 /// A modifier of `size` that places its content at the offset.
470 pub fn new(size: Size, placement_offset_x: f32, placement_offset_y: f32) -> Self {
471 Self {
472 size,
473 placement_offset_x,
474 placement_offset_y,
475 alignment_lines: crate::AlignmentLines::default(),
476 }
477 }
478
479 /// Creates a result with zero placement offset (wrapped content placed at 0,0).
480 pub fn with_size(size: Size) -> Self {
481 Self {
482 size,
483 placement_offset_x: 0.0,
484 placement_offset_y: 0.0,
485 alignment_lines: crate::AlignmentLines::default(),
486 }
487 }
488
489 /// Overrides the wrapped content's alignment lines in this modifier's coordinates.
490 pub fn with_alignment_lines(mut self, alignment_lines: crate::AlignmentLines) -> Self {
491 self.alignment_lines = alignment_lines;
492 self
493 }
494}