Skip to main content

sui_layout/
lib.rs

1#![forbid(unsafe_code)]
2
3use std::sync::Arc;
4
5use sui_core::{DpiInfo, ImageHandle, Point, Rect, Size};
6use sui_scene::ImageRegistry;
7use sui_text::{
8    FontRegistry, PersistentTextLayout, TextDocument, TextLayout, TextLayoutHandle,
9    TextLayoutRequest, TextMeasurement, TextStyle, TextSystem,
10};
11
12const FLEX_EPSILON: f32 = 0.001;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Axis {
16    Horizontal,
17    Vertical,
18}
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum Alignment {
22    Start,
23    Center,
24    End,
25    Stretch,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum FlexWrap {
30    NoWrap,
31    Wrap,
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum FlexJustify {
36    Start,
37    Center,
38    End,
39    SpaceBetween,
40    SpaceAround,
41    SpaceEvenly,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum FlexAlignContent {
46    Start,
47    Center,
48    End,
49    Stretch,
50    SpaceBetween,
51    SpaceAround,
52    SpaceEvenly,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq)]
56pub enum FlexBasis {
57    Auto,
58    Points(f32),
59    Fraction(f32),
60    GapAwareFraction(f32),
61}
62
63#[derive(Debug, Clone, Copy, PartialEq)]
64pub struct FlexStyle {
65    pub axis: Axis,
66    pub wrap: FlexWrap,
67    pub main_gap: f32,
68    pub cross_gap: f32,
69    pub justify: FlexJustify,
70    pub align_items: Alignment,
71    pub align_content: FlexAlignContent,
72}
73
74impl FlexStyle {
75    pub const fn new(axis: Axis) -> Self {
76        Self {
77            axis,
78            wrap: FlexWrap::NoWrap,
79            main_gap: 0.0,
80            cross_gap: 0.0,
81            justify: FlexJustify::Start,
82            align_items: Alignment::Start,
83            align_content: FlexAlignContent::Start,
84        }
85    }
86
87    pub const fn horizontal() -> Self {
88        Self::new(Axis::Horizontal)
89    }
90
91    pub const fn vertical() -> Self {
92        Self::new(Axis::Vertical)
93    }
94
95    pub fn wrap(mut self, wrap: FlexWrap) -> Self {
96        self.wrap = wrap;
97        self
98    }
99
100    pub fn gap(mut self, gap: f32) -> Self {
101        let gap = finite_non_negative(gap);
102        self.main_gap = gap;
103        self.cross_gap = gap;
104        self
105    }
106
107    pub fn main_gap(mut self, gap: f32) -> Self {
108        self.main_gap = finite_non_negative(gap);
109        self
110    }
111
112    pub fn cross_gap(mut self, gap: f32) -> Self {
113        self.cross_gap = finite_non_negative(gap);
114        self
115    }
116
117    pub fn justify(mut self, justify: FlexJustify) -> Self {
118        self.justify = justify;
119        self
120    }
121
122    pub fn align_items(mut self, alignment: Alignment) -> Self {
123        self.align_items = alignment;
124        self
125    }
126
127    pub fn align_content(mut self, alignment: FlexAlignContent) -> Self {
128        self.align_content = alignment;
129        self
130    }
131}
132
133impl Default for FlexStyle {
134    fn default() -> Self {
135        Self::horizontal()
136    }
137}
138
139#[derive(Debug, Clone, Copy, PartialEq)]
140pub struct FlexItem {
141    pub grow: f32,
142    pub shrink: f32,
143    pub basis: FlexBasis,
144    pub min_size: Size,
145    pub max_size: Size,
146    pub align_self: Option<Alignment>,
147}
148
149impl FlexItem {
150    pub const fn new() -> Self {
151        Self {
152            grow: 0.0,
153            shrink: 1.0,
154            basis: FlexBasis::Auto,
155            min_size: Size::ZERO,
156            max_size: Size::new(f32::INFINITY, f32::INFINITY),
157            align_self: None,
158        }
159    }
160
161    pub const fn fill() -> Self {
162        Self {
163            grow: 1.0,
164            shrink: 1.0,
165            basis: FlexBasis::Points(0.0),
166            min_size: Size::ZERO,
167            max_size: Size::new(f32::INFINITY, f32::INFINITY),
168            align_self: None,
169        }
170    }
171
172    pub fn flex(grow: f32) -> Self {
173        Self::fill().grow(grow)
174    }
175
176    pub fn fixed(basis: f32) -> Self {
177        Self::new().basis(basis).no_shrink()
178    }
179
180    pub fn grow(mut self, grow: f32) -> Self {
181        self.grow = finite_non_negative(grow);
182        self
183    }
184
185    pub fn shrink(mut self, shrink: f32) -> Self {
186        self.shrink = finite_non_negative(shrink);
187        self
188    }
189
190    pub fn no_shrink(mut self) -> Self {
191        self.shrink = 0.0;
192        self
193    }
194
195    pub fn basis(mut self, basis: f32) -> Self {
196        self.basis = FlexBasis::Points(finite_non_negative(basis));
197        self
198    }
199
200    pub fn basis_fraction(mut self, fraction: f32) -> Self {
201        self.basis = FlexBasis::Fraction(finite_non_negative(fraction));
202        self
203    }
204
205    pub fn basis_gap_aware_fraction(mut self, fraction: f32) -> Self {
206        self.basis = FlexBasis::GapAwareFraction(finite_non_negative(fraction));
207        self
208    }
209
210    pub fn auto_basis(mut self) -> Self {
211        self.basis = FlexBasis::Auto;
212        self
213    }
214
215    pub fn min_size(mut self, min_size: Size) -> Self {
216        self.min_size = Size::new(
217            finite_non_negative(min_size.width),
218            finite_non_negative(min_size.height),
219        );
220        self
221    }
222
223    pub fn min_width(mut self, min_width: f32) -> Self {
224        self.min_size.width = finite_non_negative(min_width);
225        self
226    }
227
228    pub fn min_height(mut self, min_height: f32) -> Self {
229        self.min_size.height = finite_non_negative(min_height);
230        self
231    }
232
233    pub fn max_size(mut self, max_size: Size) -> Self {
234        self.max_size = Size::new(
235            non_negative_or_infinity(max_size.width),
236            non_negative_or_infinity(max_size.height),
237        );
238        self
239    }
240
241    pub fn max_width(mut self, max_width: f32) -> Self {
242        self.max_size.width = non_negative_or_infinity(max_width);
243        self
244    }
245
246    pub fn max_height(mut self, max_height: f32) -> Self {
247        self.max_size.height = non_negative_or_infinity(max_height);
248        self
249    }
250
251    pub fn align_self(mut self, alignment: Alignment) -> Self {
252        self.align_self = Some(alignment);
253        self
254    }
255
256    pub fn inherit_alignment(mut self) -> Self {
257        self.align_self = None;
258        self
259    }
260}
261
262impl Default for FlexItem {
263    fn default() -> Self {
264        Self::new()
265    }
266}
267
268#[derive(Debug, Clone, PartialEq)]
269pub struct FlexLayout {
270    pub size: Size,
271    pub items: Vec<FlexItemLayout>,
272    pub lines: Vec<FlexLineLayout>,
273}
274
275impl FlexLayout {
276    pub fn empty(size: Size) -> Self {
277        Self {
278            size,
279            items: Vec::new(),
280            lines: Vec::new(),
281        }
282    }
283}
284
285#[derive(Debug, Clone, Copy, PartialEq)]
286pub struct FlexItemLayout {
287    pub rect: Rect,
288    pub measured_size: Size,
289    pub line: usize,
290}
291
292#[derive(Debug, Clone, Copy, PartialEq)]
293pub struct FlexLineLayout {
294    pub item_start: usize,
295    pub item_end: usize,
296    pub rect: Rect,
297}
298
299pub fn flex_layout<F>(
300    style: FlexStyle,
301    items: &[FlexItem],
302    constraints: Constraints,
303    mut measure_child: F,
304) -> FlexLayout
305where
306    F: FnMut(usize, Constraints) -> Size,
307{
308    let initial_measurements = items
309        .iter()
310        .enumerate()
311        .map(|(index, item)| {
312            let child_constraints = flex_child_constraints(style, *item, constraints);
313            let measured_size = clamp_item_size(*item, measure_child(index, child_constraints));
314            (child_constraints, measured_size)
315        })
316        .collect::<Vec<_>>();
317    let measured_sizes = initial_measurements
318        .iter()
319        .map(|(_, measured_size)| *measured_size)
320        .collect::<Vec<_>>();
321    let initial_layout = flex_layout_from_measured(style, items, constraints, &measured_sizes);
322
323    // Flex basis and grow/shrink resolution can assign a child a very different
324    // main-axis extent from the one used for its intrinsic measurement. Text is
325    // the important example: `FlexItem::flex(1.0)` has a zero-point basis, so an
326    // initial width of zero produces a one-glyph-per-line layout even though the
327    // item is then grown across the row. Measure again at the resolved allocation
328    // so width-dependent children can rebuild wrapping and report the resulting
329    // cross-axis size before the final line layout is computed.
330    let resolved_sizes = items
331        .iter()
332        .enumerate()
333        .map(|(index, item)| {
334            let resolved_main = initial_layout
335                .items
336                .get(index)
337                .map(|layout| axis_main(style.axis, layout.rect.size))
338                .unwrap_or(0.0);
339            let child_constraints =
340                resolved_flex_child_constraints(style, *item, constraints, resolved_main);
341            let (initial_constraints, initial_size) = initial_measurements[index];
342            if child_constraints == initial_constraints {
343                initial_size
344            } else {
345                clamp_item_size(*item, measure_child(index, child_constraints))
346            }
347        })
348        .collect::<Vec<_>>();
349
350    flex_layout_from_measured(style, items, constraints, &resolved_sizes)
351}
352
353pub fn arrange_flex(
354    style: FlexStyle,
355    items: &[FlexItem],
356    container_size: Size,
357    measured_sizes: &[Size],
358) -> FlexLayout {
359    flex_layout_from_measured(
360        style,
361        items,
362        Constraints::tight(Size::new(
363            finite_non_negative(container_size.width),
364            finite_non_negative(container_size.height),
365        )),
366        measured_sizes,
367    )
368}
369
370#[derive(Debug, Clone, Copy, PartialEq, Default)]
371pub struct Padding {
372    pub left: f32,
373    pub top: f32,
374    pub right: f32,
375    pub bottom: f32,
376}
377
378impl Padding {
379    pub const ZERO: Self = Self::all(0.0);
380
381    pub const fn all(value: f32) -> Self {
382        Self {
383            left: value,
384            top: value,
385            right: value,
386            bottom: value,
387        }
388    }
389
390    pub fn inset(self, size: Size) -> Size {
391        Size::new(
392            (size.width - (self.left + self.right)).max(0.0),
393            (size.height - (self.top + self.bottom)).max(0.0),
394        )
395    }
396
397    pub const fn offset(self) -> Point {
398        Point::new(self.left, self.top)
399    }
400}
401
402#[derive(Debug, Clone, Copy, PartialEq)]
403pub struct Constraints {
404    pub min: Size,
405    pub max: Size,
406}
407
408impl Constraints {
409    pub const UNBOUNDED: Self = Self {
410        min: Size::ZERO,
411        max: Size::new(f32::INFINITY, f32::INFINITY),
412    };
413
414    pub const fn new(min: Size, max: Size) -> Self {
415        Self { min, max }
416    }
417
418    pub const fn tight(size: Size) -> Self {
419        Self {
420            min: size,
421            max: size,
422        }
423    }
424
425    pub fn loosen(self) -> Self {
426        Self {
427            min: Size::ZERO,
428            max: self.max,
429        }
430    }
431
432    pub fn clamp(self, size: Size) -> Size {
433        Size::new(
434            size.width.clamp(self.min.width, self.max.width),
435            size.height.clamp(self.min.height, self.max.height),
436        )
437    }
438}
439
440#[derive(Debug, Clone)]
441pub struct LayoutContext {
442    dpi_info: DpiInfo,
443    text_system: Arc<TextSystem>,
444    font_registry: Arc<FontRegistry>,
445    image_registry: Arc<ImageRegistry>,
446}
447
448impl LayoutContext {
449    pub fn new(
450        dpi_info: DpiInfo,
451        text_system: Arc<TextSystem>,
452        font_registry: Arc<FontRegistry>,
453        image_registry: Arc<ImageRegistry>,
454    ) -> Self {
455        Self {
456            dpi_info,
457            text_system,
458            font_registry,
459            image_registry,
460        }
461    }
462
463    pub const fn dpi(&self) -> DpiInfo {
464        self.dpi_info
465    }
466
467    pub fn measure_text(
468        &self,
469        text: impl Into<String>,
470        style: TextStyle,
471    ) -> sui_core::Result<TextMeasurement> {
472        self.text_system
473            .measure_text(text, style, self.font_registry.as_ref())
474    }
475
476    pub fn measure_document(&self, document: TextDocument) -> sui_core::Result<TextMeasurement> {
477        self.text_system
478            .measure_document(document, self.font_registry.as_ref())
479    }
480
481    pub fn shape_text(
482        &self,
483        text: impl Into<String>,
484        box_size: Size,
485        style: TextStyle,
486    ) -> sui_core::Result<TextLayout> {
487        self.text_system
488            .shape_text(text, box_size, style, self.font_registry.as_ref())
489    }
490
491    pub fn shape_text_persistent(
492        &self,
493        handle: Option<TextLayoutHandle>,
494        text: impl Into<String>,
495        box_size: Size,
496        style: TextStyle,
497    ) -> sui_core::Result<PersistentTextLayout> {
498        self.text_system.shape_text_persistent(
499            handle,
500            text,
501            box_size,
502            style,
503            self.font_registry.as_ref(),
504        )
505    }
506
507    pub fn layout_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
508        self.text_system
509            .layout_document(request, self.font_registry.as_ref())
510    }
511
512    pub fn layout_document_persistent(
513        &self,
514        handle: Option<TextLayoutHandle>,
515        request: TextLayoutRequest,
516    ) -> sui_core::Result<PersistentTextLayout> {
517        self.text_system
518            .layout_document_persistent(handle, request, self.font_registry.as_ref())
519    }
520
521    pub fn image_size(&self, image: ImageHandle) -> Option<Size> {
522        self.image_registry
523            .dimensions(image)
524            .map(|(width, height)| Size::new(width as f32, height as f32))
525    }
526}
527
528impl Default for Constraints {
529    fn default() -> Self {
530        Self::UNBOUNDED
531    }
532}
533
534#[derive(Debug, Clone, Copy)]
535struct ResolvedFlexItem {
536    measured_size: Size,
537    base_size: Size,
538}
539
540#[derive(Debug, Clone, Copy)]
541struct FlexLine {
542    start: usize,
543    end: usize,
544    main: f32,
545    cross: f32,
546}
547
548fn flex_layout_from_measured(
549    style: FlexStyle,
550    items: &[FlexItem],
551    constraints: Constraints,
552    measured_sizes: &[Size],
553) -> FlexLayout {
554    if items.is_empty() {
555        return FlexLayout::empty(constraints.clamp(Size::ZERO));
556    }
557
558    let (_, initial_lines) = resolve_flex_lines(style, items, constraints, measured_sizes);
559    let natural_size = natural_flex_size(style, &initial_lines);
560    let size = constraints.clamp(natural_size);
561    let arrange_constraints = Constraints::tight(size);
562    let (resolved, lines) = resolve_flex_lines(style, items, arrange_constraints, measured_sizes);
563
564    arrange_resolved_flex(style, items, size, &resolved, &lines)
565}
566
567fn resolve_flex_lines(
568    style: FlexStyle,
569    items: &[FlexItem],
570    constraints: Constraints,
571    measured_sizes: &[Size],
572) -> (Vec<ResolvedFlexItem>, Vec<FlexLine>) {
573    let main_gap = finite_non_negative(style.main_gap);
574    let available_main = axis_main(style.axis, constraints.max);
575    let wrap_limit = if style.wrap == FlexWrap::Wrap && available_main.is_finite() {
576        available_main.max(0.0)
577    } else {
578        f32::INFINITY
579    };
580
581    let resolved = items
582        .iter()
583        .enumerate()
584        .map(|(index, item)| {
585            let measured = measured_sizes.get(index).copied().unwrap_or(Size::ZERO);
586            resolve_flex_item(style.axis, style.main_gap, *item, constraints, measured)
587        })
588        .collect::<Vec<_>>();
589
590    let mut lines = Vec::new();
591    let mut start = 0usize;
592    let mut main = 0.0f32;
593    let mut cross = 0.0f32;
594
595    for (index, item) in resolved.iter().enumerate() {
596        let item_main = axis_main(style.axis, item.base_size);
597        let item_cross = axis_cross(style.axis, item.base_size);
598        let spacing_before = if index == start { 0.0 } else { main_gap };
599
600        if style.wrap == FlexWrap::Wrap
601            && index > start
602            && main + spacing_before + item_main > wrap_limit + FLEX_EPSILON
603        {
604            lines.push(FlexLine {
605                start,
606                end: index,
607                main,
608                cross,
609            });
610            start = index;
611            main = item_main;
612            cross = item_cross;
613        } else {
614            main += spacing_before + item_main;
615            cross = cross.max(item_cross);
616        }
617    }
618
619    lines.push(FlexLine {
620        start,
621        end: resolved.len(),
622        main,
623        cross,
624    });
625
626    (resolved, lines)
627}
628
629fn resolve_flex_item(
630    axis: Axis,
631    main_gap: f32,
632    item: FlexItem,
633    constraints: Constraints,
634    measured_size: Size,
635) -> ResolvedFlexItem {
636    let measured_size = clamp_item_size(item, measured_size);
637    let min_main = item_min_main(axis, item);
638    let max_main = item_max_main(axis, item);
639    let min_cross = item_min_cross(axis, item);
640    let max_cross = item_max_cross(axis, item);
641
642    let base_main = basis_main_size(axis, main_gap, item.basis, constraints, measured_size)
643        .clamp(min_main, max_main);
644    let base_cross = axis_cross(axis, measured_size).clamp(min_cross, max_cross);
645
646    ResolvedFlexItem {
647        measured_size,
648        base_size: axis_size(axis, base_main, base_cross),
649    }
650}
651
652fn natural_flex_size(style: FlexStyle, lines: &[FlexLine]) -> Size {
653    let main = lines.iter().map(|line| line.main).fold(0.0f32, f32::max);
654    let cross_gap = finite_non_negative(style.cross_gap);
655    let cross = lines
656        .iter()
657        .enumerate()
658        .map(|(index, line)| line.cross + if index == 0 { 0.0 } else { cross_gap })
659        .sum();
660
661    axis_size(style.axis, main, cross)
662}
663
664fn arrange_resolved_flex(
665    style: FlexStyle,
666    items: &[FlexItem],
667    size: Size,
668    resolved: &[ResolvedFlexItem],
669    lines: &[FlexLine],
670) -> FlexLayout {
671    if lines.is_empty() {
672        return FlexLayout::empty(size);
673    }
674
675    let main_gap = finite_non_negative(style.main_gap);
676    let cross_gap = finite_non_negative(style.cross_gap);
677    let container_main = axis_main(style.axis, size);
678    let container_cross = axis_cross(style.axis, size);
679    let natural_cross = lines
680        .iter()
681        .enumerate()
682        .map(|(index, line)| line.cross + if index == 0 { 0.0 } else { cross_gap })
683        .sum::<f32>();
684    let extra_cross = (container_cross - natural_cross).max(0.0);
685    let line_count = lines.len();
686    let (cross_start, arranged_cross_gap, stretch_cross) =
687        cross_distribution(style.align_content, line_count, cross_gap, extra_cross);
688
689    let mut item_layouts = Vec::with_capacity(resolved.len());
690    let mut line_layouts = Vec::with_capacity(lines.len());
691    let mut cross_cursor = cross_start;
692
693    for (line_index, line) in lines.iter().enumerate() {
694        let count = line.end - line.start;
695        let line_cross = line.cross + stretch_cross;
696        let line_items = &resolved[line.start..line.end];
697        let target_mains = flex_line_main_sizes(
698            style.axis,
699            &items[line.start..line.end],
700            line_items,
701            container_main,
702            main_gap,
703        );
704        let used_main = target_mains.iter().sum::<f32>();
705        let gap_total = main_gap * count.saturating_sub(1) as f32;
706        let leftover_main = (container_main - used_main - gap_total).max(0.0);
707        let (main_start, arranged_main_gap) =
708            main_distribution(style.justify, count, main_gap, leftover_main);
709        let mut main_cursor = main_start;
710
711        for (offset, target_main) in target_mains.into_iter().enumerate() {
712            let index = line.start + offset;
713            let item = items[index];
714            let resolved_item = resolved[index];
715            let alignment = item.align_self.unwrap_or(style.align_items);
716            let item_cross = arranged_cross_size(
717                style.axis,
718                item,
719                alignment,
720                resolved_item.base_size,
721                line_cross,
722            );
723            let cross_offset = aligned_offset(alignment, line_cross - item_cross);
724            let rect = axis_rect(
725                style.axis,
726                main_cursor,
727                cross_cursor + cross_offset,
728                target_main,
729                item_cross,
730            );
731
732            item_layouts.push(FlexItemLayout {
733                rect,
734                measured_size: resolved_item.measured_size,
735                line: line_index,
736            });
737            main_cursor += target_main + arranged_main_gap;
738        }
739
740        line_layouts.push(FlexLineLayout {
741            item_start: line.start,
742            item_end: line.end,
743            rect: axis_rect(style.axis, 0.0, cross_cursor, container_main, line_cross),
744        });
745        cross_cursor += line_cross + arranged_cross_gap;
746    }
747
748    FlexLayout {
749        size,
750        items: item_layouts,
751        lines: line_layouts,
752    }
753}
754
755fn flex_line_main_sizes(
756    axis: Axis,
757    items: &[FlexItem],
758    line_items: &[ResolvedFlexItem],
759    container_main: f32,
760    main_gap: f32,
761) -> Vec<f32> {
762    let count = line_items.len();
763    let gap_total = finite_non_negative(main_gap) * count.saturating_sub(1) as f32;
764    let available_for_items = if container_main.is_finite() {
765        (container_main - gap_total).max(0.0)
766    } else {
767        line_items
768            .iter()
769            .map(|item| axis_main(axis, item.base_size))
770            .sum()
771    };
772    let base_sum = line_items
773        .iter()
774        .map(|item| axis_main(axis, item.base_size))
775        .sum::<f32>();
776    let free = available_for_items - base_sum;
777
778    if free > 0.0 {
779        if items
780            .iter()
781            .any(|item| finite_non_negative(item.grow) > 0.0)
782        {
783            return distribute_grow_space(axis, items, line_items, available_for_items);
784        }
785    } else if free < 0.0 {
786        let deficit = -free;
787        let total_shrink = items
788            .iter()
789            .zip(line_items.iter())
790            .map(|(item, resolved)| {
791                finite_non_negative(item.shrink) * axis_main(axis, resolved.base_size)
792            })
793            .sum::<f32>();
794        if total_shrink > 0.0 {
795            return items
796                .iter()
797                .zip(line_items.iter())
798                .map(|(item, resolved)| {
799                    let base = axis_main(axis, resolved.base_size);
800                    let weight = finite_non_negative(item.shrink) * base;
801                    let min = item_min_main(axis, *item);
802                    (base - (deficit * weight / total_shrink)).max(min)
803                })
804                .collect();
805        }
806    }
807
808    line_items
809        .iter()
810        .map(|item| axis_main(axis, item.base_size))
811        .collect()
812}
813
814fn distribute_grow_space(
815    axis: Axis,
816    items: &[FlexItem],
817    line_items: &[ResolvedFlexItem],
818    available_for_items: f32,
819) -> Vec<f32> {
820    let mut sizes = line_items
821        .iter()
822        .map(|item| axis_main(axis, item.base_size))
823        .collect::<Vec<_>>();
824    let mut frozen = vec![false; sizes.len()];
825
826    loop {
827        let remaining = available_for_items - sizes.iter().sum::<f32>();
828        if remaining <= FLEX_EPSILON {
829            break;
830        }
831
832        let total_grow = items
833            .iter()
834            .zip(frozen.iter())
835            .filter(|(_, frozen)| !**frozen)
836            .map(|(item, _)| finite_non_negative(item.grow))
837            .sum::<f32>();
838        if total_grow <= FLEX_EPSILON {
839            break;
840        }
841
842        let mut clamped = false;
843        for index in 0..sizes.len() {
844            if frozen[index] {
845                continue;
846            }
847
848            let grow = finite_non_negative(items[index].grow);
849            if grow <= 0.0 {
850                frozen[index] = true;
851                continue;
852            }
853
854            let proposed = sizes[index] + (remaining * grow / total_grow);
855            let max = item_max_main(axis, items[index]);
856            if proposed >= max - FLEX_EPSILON {
857                sizes[index] = max;
858                frozen[index] = true;
859                clamped = true;
860            } else {
861                sizes[index] = proposed;
862            }
863        }
864
865        if !clamped {
866            break;
867        }
868    }
869
870    sizes
871}
872
873fn flex_child_constraints(
874    style: FlexStyle,
875    item: FlexItem,
876    constraints: Constraints,
877) -> Constraints {
878    let min_main = item_min_main(style.axis, item);
879    let max_main = match item.basis {
880        FlexBasis::Auto => axis_main(style.axis, constraints.max),
881        FlexBasis::Points(points) => finite_non_negative(points),
882        FlexBasis::Fraction(fraction) => flex_fraction_constraint_main_size(
883            style.axis,
884            constraints,
885            finite_non_negative(fraction),
886        ),
887        FlexBasis::GapAwareFraction(fraction) => flex_gap_aware_fraction_constraint_main_size(
888            style.axis,
889            constraints,
890            style.main_gap,
891            finite_non_negative(fraction),
892        ),
893    }
894    .min(item_max_main(style.axis, item))
895    .max(min_main);
896    let max_cross = axis_cross(style.axis, constraints.max)
897        .min(item_max_cross(style.axis, item))
898        .max(0.0);
899    let alignment = item.align_self.unwrap_or(style.align_items);
900    let min_cross = if alignment == Alignment::Stretch && max_cross.is_finite() {
901        max_cross
902    } else {
903        item_min_cross(style.axis, item).min(max_cross)
904    };
905
906    axis_constraints(style.axis, min_main, max_main, min_cross, max_cross)
907}
908
909fn resolved_flex_child_constraints(
910    style: FlexStyle,
911    item: FlexItem,
912    constraints: Constraints,
913    resolved_main: f32,
914) -> Constraints {
915    let intrinsic = flex_child_constraints(style, item, constraints);
916    let min_cross = axis_cross(style.axis, intrinsic.min);
917    let max_cross = axis_cross(style.axis, intrinsic.max);
918    let resolved_main = finite_non_negative(resolved_main).clamp(
919        item_min_main(style.axis, item),
920        item_max_main(style.axis, item),
921    );
922
923    axis_constraints(
924        style.axis,
925        resolved_main,
926        resolved_main,
927        min_cross,
928        max_cross,
929    )
930}
931
932fn arranged_cross_size(
933    axis: Axis,
934    item: FlexItem,
935    alignment: Alignment,
936    base_size: Size,
937    line_cross: f32,
938) -> f32 {
939    let min = item_min_cross(axis, item);
940    let max = item_max_cross(axis, item);
941    if alignment == Alignment::Stretch {
942        line_cross.clamp(min, max)
943    } else {
944        axis_cross(axis, base_size).min(line_cross).clamp(min, max)
945    }
946}
947
948fn basis_main_size(
949    axis: Axis,
950    main_gap: f32,
951    basis: FlexBasis,
952    constraints: Constraints,
953    measured_size: Size,
954) -> f32 {
955    match basis {
956        FlexBasis::Auto => axis_main(axis, measured_size),
957        FlexBasis::Points(points) => finite_non_negative(points),
958        FlexBasis::Fraction(fraction) => {
959            let available = axis_main(axis, constraints.max);
960            if available.is_finite() {
961                available.max(0.0) * finite_non_negative(fraction)
962            } else {
963                axis_main(axis, measured_size)
964            }
965        }
966        FlexBasis::GapAwareFraction(fraction) => {
967            let available = axis_main(axis, constraints.max);
968            if available.is_finite() {
969                gap_aware_fraction_basis(
970                    available.max(0.0),
971                    main_gap,
972                    finite_non_negative(fraction),
973                )
974            } else {
975                axis_main(axis, measured_size)
976            }
977        }
978    }
979}
980
981fn flex_fraction_constraint_main_size(axis: Axis, constraints: Constraints, fraction: f32) -> f32 {
982    let available = axis_main(axis, constraints.max);
983    if available.is_finite() {
984        available.max(0.0) * fraction
985    } else {
986        available
987    }
988}
989
990fn flex_gap_aware_fraction_constraint_main_size(
991    axis: Axis,
992    constraints: Constraints,
993    main_gap: f32,
994    fraction: f32,
995) -> f32 {
996    let available = axis_main(axis, constraints.max);
997    if available.is_finite() {
998        gap_aware_fraction_basis(available.max(0.0), main_gap, fraction)
999    } else {
1000        available
1001    }
1002}
1003
1004fn gap_aware_fraction_basis(available: f32, gap: f32, fraction: f32) -> f32 {
1005    let gap_share = (1.0 - fraction).max(0.0);
1006    (available * fraction - finite_non_negative(gap) * gap_share).max(0.0)
1007}
1008
1009fn cross_distribution(
1010    alignment: FlexAlignContent,
1011    count: usize,
1012    gap: f32,
1013    extra: f32,
1014) -> (f32, f32, f32) {
1015    if count == 0 || extra <= 0.0 {
1016        return (0.0, gap, 0.0);
1017    }
1018
1019    match alignment {
1020        FlexAlignContent::Start => (0.0, gap, 0.0),
1021        FlexAlignContent::Center => (extra * 0.5, gap, 0.0),
1022        FlexAlignContent::End => (extra, gap, 0.0),
1023        FlexAlignContent::Stretch => (0.0, gap, extra / count as f32),
1024        FlexAlignContent::SpaceBetween if count > 1 => {
1025            (0.0, gap + (extra / (count - 1) as f32), 0.0)
1026        }
1027        FlexAlignContent::SpaceAround => {
1028            let distributed = extra / count as f32;
1029            (distributed * 0.5, gap + distributed, 0.0)
1030        }
1031        FlexAlignContent::SpaceEvenly => {
1032            let distributed = extra / (count + 1) as f32;
1033            (distributed, gap + distributed, 0.0)
1034        }
1035        FlexAlignContent::SpaceBetween => (0.0, gap, 0.0),
1036    }
1037}
1038
1039fn main_distribution(justify: FlexJustify, count: usize, gap: f32, leftover: f32) -> (f32, f32) {
1040    if count == 0 || leftover <= 0.0 {
1041        return (0.0, gap);
1042    }
1043
1044    match justify {
1045        FlexJustify::Start => (0.0, gap),
1046        FlexJustify::Center => (leftover * 0.5, gap),
1047        FlexJustify::End => (leftover, gap),
1048        FlexJustify::SpaceBetween if count > 1 => (0.0, gap + (leftover / (count - 1) as f32)),
1049        FlexJustify::SpaceAround => {
1050            let distributed = leftover / count as f32;
1051            (distributed * 0.5, gap + distributed)
1052        }
1053        FlexJustify::SpaceEvenly => {
1054            let distributed = leftover / (count + 1) as f32;
1055            (distributed, gap + distributed)
1056        }
1057        FlexJustify::SpaceBetween => (0.0, gap),
1058    }
1059}
1060
1061fn clamp_item_size(item: FlexItem, size: Size) -> Size {
1062    Size::new(
1063        size.width.clamp(
1064            finite_non_negative(item.min_size.width),
1065            item_max_width(item),
1066        ),
1067        size.height.clamp(
1068            finite_non_negative(item.min_size.height),
1069            item_max_height(item),
1070        ),
1071    )
1072}
1073
1074fn axis_constraints(
1075    axis: Axis,
1076    min_main: f32,
1077    max_main: f32,
1078    min_cross: f32,
1079    max_cross: f32,
1080) -> Constraints {
1081    match axis {
1082        Axis::Horizontal => Constraints::new(
1083            Size::new(min_main, min_cross),
1084            Size::new(max_main, max_cross),
1085        ),
1086        Axis::Vertical => Constraints::new(
1087            Size::new(min_cross, min_main),
1088            Size::new(max_cross, max_main),
1089        ),
1090    }
1091}
1092
1093fn axis_main(axis: Axis, size: Size) -> f32 {
1094    match axis {
1095        Axis::Horizontal => size.width,
1096        Axis::Vertical => size.height,
1097    }
1098}
1099
1100fn axis_cross(axis: Axis, size: Size) -> f32 {
1101    match axis {
1102        Axis::Horizontal => size.height,
1103        Axis::Vertical => size.width,
1104    }
1105}
1106
1107fn axis_size(axis: Axis, main: f32, cross: f32) -> Size {
1108    match axis {
1109        Axis::Horizontal => Size::new(main, cross),
1110        Axis::Vertical => Size::new(cross, main),
1111    }
1112}
1113
1114fn axis_rect(axis: Axis, main: f32, cross: f32, main_size: f32, cross_size: f32) -> Rect {
1115    match axis {
1116        Axis::Horizontal => Rect::new(main, cross, main_size, cross_size),
1117        Axis::Vertical => Rect::new(cross, main, cross_size, main_size),
1118    }
1119}
1120
1121fn aligned_offset(alignment: Alignment, remaining: f32) -> f32 {
1122    let remaining = remaining.max(0.0);
1123    match alignment {
1124        Alignment::Start | Alignment::Stretch => 0.0,
1125        Alignment::Center => remaining * 0.5,
1126        Alignment::End => remaining,
1127    }
1128}
1129
1130fn item_min_main(axis: Axis, item: FlexItem) -> f32 {
1131    axis_main(axis, item.min_size).max(0.0)
1132}
1133
1134fn item_max_main(axis: Axis, item: FlexItem) -> f32 {
1135    axis_main(axis, Size::new(item_max_width(item), item_max_height(item)))
1136        .max(item_min_main(axis, item))
1137}
1138
1139fn item_min_cross(axis: Axis, item: FlexItem) -> f32 {
1140    axis_cross(axis, item.min_size).max(0.0)
1141}
1142
1143fn item_max_cross(axis: Axis, item: FlexItem) -> f32 {
1144    axis_cross(axis, Size::new(item_max_width(item), item_max_height(item)))
1145        .max(item_min_cross(axis, item))
1146}
1147
1148fn item_max_width(item: FlexItem) -> f32 {
1149    non_negative_or_infinity(item.max_size.width).max(finite_non_negative(item.min_size.width))
1150}
1151
1152fn item_max_height(item: FlexItem) -> f32 {
1153    non_negative_or_infinity(item.max_size.height).max(finite_non_negative(item.min_size.height))
1154}
1155
1156fn finite_non_negative(value: f32) -> f32 {
1157    if value.is_finite() {
1158        value.max(0.0)
1159    } else {
1160        0.0
1161    }
1162}
1163
1164fn non_negative_or_infinity(value: f32) -> f32 {
1165    if value.is_nan() || value < 0.0 {
1166        0.0
1167    } else {
1168        value
1169    }
1170}
1171
1172#[cfg(test)]
1173mod tests {
1174    use std::sync::Arc;
1175
1176    use super::{
1177        Alignment, Constraints, FlexAlignContent, FlexItem, FlexJustify, FlexStyle, FlexWrap,
1178        LayoutContext, arrange_flex, flex_layout,
1179    };
1180    use sui_core::{Color, DpiInfo, ImageHandle, Rect, Size};
1181    use sui_scene::{ImageRegistry, RegisteredImage};
1182    use sui_text::{FontRegistry, TextStyle, TextSystem};
1183
1184    fn assert_rect_approx_eq(actual: Rect, expected: Rect) {
1185        assert!((actual.x() - expected.x()).abs() < 0.001);
1186        assert!((actual.y() - expected.y()).abs() < 0.001);
1187        assert!((actual.width() - expected.width()).abs() < 0.001);
1188        assert!((actual.height() - expected.height()).abs() < 0.001);
1189    }
1190
1191    #[test]
1192    fn layout_context_measures_text_and_images_without_runtime_widget_state() {
1193        let mut images = ImageRegistry::new();
1194        images.insert(
1195            ImageHandle::new(7),
1196            RegisteredImage::from_rgba8(4, 2, vec![255; 4 * 2 * 4]).unwrap(),
1197        );
1198
1199        let layout = LayoutContext::new(
1200            DpiInfo::new(
1201                2.0,
1202                Some(192.0),
1203                Size::new(320.0, 180.0),
1204                Size::new(640.0, 360.0),
1205            ),
1206            Arc::new(TextSystem::new()),
1207            Arc::new(FontRegistry::new()),
1208            Arc::new(images),
1209        );
1210
1211        let measurement = layout
1212            .measure_text("hello", TextStyle::new(Color::WHITE))
1213            .unwrap();
1214
1215        assert!(measurement.width > 0.0);
1216        assert_eq!(layout.dpi().effective_dpi(), 192.0);
1217        assert_eq!(
1218            layout.image_size(ImageHandle::new(7)),
1219            Some(Size::new(4.0, 2.0))
1220        );
1221    }
1222
1223    #[test]
1224    fn flex_layout_distributes_grow_space() {
1225        let items = [
1226            FlexItem::new(),
1227            FlexItem::new().grow(1.0),
1228            FlexItem::new().grow(2.0),
1229        ];
1230        let measured = [
1231            Size::new(20.0, 10.0),
1232            Size::new(10.0, 10.0),
1233            Size::new(10.0, 10.0),
1234        ];
1235        let layout = flex_layout(
1236            FlexStyle::horizontal(),
1237            &items,
1238            Constraints::tight(Size::new(100.0, 20.0)),
1239            |index, _| measured[index],
1240        );
1241
1242        assert_eq!(layout.size, Size::new(100.0, 20.0));
1243        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 20.0, 10.0));
1244        assert_rect_approx_eq(layout.items[1].rect, Rect::new(20.0, 0.0, 30.0, 10.0));
1245        assert_rect_approx_eq(layout.items[2].rect, Rect::new(50.0, 0.0, 50.0, 10.0));
1246    }
1247
1248    #[test]
1249    fn flex_item_fill_creates_equal_columns() {
1250        let items = [FlexItem::fill(), FlexItem::fill()];
1251        let layout = flex_layout(
1252            FlexStyle::horizontal(),
1253            &items,
1254            Constraints::tight(Size::new(100.0, 12.0)),
1255            |_, _| Size::new(20.0, 10.0),
1256        );
1257
1258        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 50.0, 10.0));
1259        assert_rect_approx_eq(layout.items[1].rect, Rect::new(50.0, 0.0, 50.0, 10.0));
1260    }
1261
1262    #[test]
1263    fn flex_layout_remeasures_grown_children_at_their_resolved_main_size() {
1264        let items = [FlexItem::flex(1.0)];
1265        let mut seen = Vec::new();
1266        let layout = flex_layout(
1267            FlexStyle::horizontal(),
1268            &items,
1269            Constraints::new(Size::new(240.0, 0.0), Size::new(240.0, 200.0)),
1270            |_, constraints| {
1271                seen.push(constraints);
1272                if constraints.max.width <= 1.0 {
1273                    Size::new(constraints.max.width, 160.0)
1274                } else {
1275                    Size::new(constraints.max.width, 20.0)
1276                }
1277            },
1278        );
1279
1280        assert_eq!(seen.len(), 2);
1281        assert_eq!(seen[0].max.width, 0.0);
1282        assert_eq!(seen[1].min.width, 240.0);
1283        assert_eq!(seen[1].max.width, 240.0);
1284        assert_eq!(layout.size, Size::new(240.0, 20.0));
1285        assert_eq!(layout.items[0].measured_size, Size::new(240.0, 20.0));
1286        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 240.0, 20.0));
1287    }
1288
1289    #[test]
1290    fn flex_layout_supports_fraction_basis() {
1291        let items = [
1292            FlexItem::new().basis_fraction(0.25),
1293            FlexItem::new().basis_fraction(0.75),
1294        ];
1295        let layout = flex_layout(
1296            FlexStyle::horizontal(),
1297            &items,
1298            Constraints::tight(Size::new(200.0, 12.0)),
1299            |_, _| Size::new(10.0, 10.0),
1300        );
1301
1302        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 50.0, 10.0));
1303        assert_rect_approx_eq(layout.items[1].rect, Rect::new(50.0, 0.0, 150.0, 10.0));
1304    }
1305
1306    #[test]
1307    fn flex_layout_supports_gap_aware_fraction_basis() {
1308        let items = [
1309            FlexItem::new().basis_gap_aware_fraction(1.0 / 3.0),
1310            FlexItem::new().basis_gap_aware_fraction(1.0 / 3.0),
1311            FlexItem::new().basis_gap_aware_fraction(1.0 / 3.0),
1312        ];
1313        let layout = flex_layout(
1314            FlexStyle::horizontal().gap(10.0),
1315            &items,
1316            Constraints::tight(Size::new(320.0, 12.0)),
1317            |_, _| Size::new(10.0, 10.0),
1318        );
1319
1320        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 100.0, 10.0));
1321        assert_rect_approx_eq(layout.items[1].rect, Rect::new(110.0, 0.0, 100.0, 10.0));
1322        assert_rect_approx_eq(layout.items[2].rect, Rect::new(220.0, 0.0, 100.0, 10.0));
1323    }
1324
1325    #[test]
1326    fn flex_layout_wraps_gap_aware_fraction_lines_after_full_rows() {
1327        let items = [
1328            FlexItem::new().basis_gap_aware_fraction(1.0 / 3.0),
1329            FlexItem::new().basis_gap_aware_fraction(1.0 / 3.0),
1330            FlexItem::new().basis_gap_aware_fraction(1.0 / 3.0),
1331            FlexItem::new().basis_gap_aware_fraction(0.5),
1332            FlexItem::new().basis_gap_aware_fraction(0.5),
1333        ];
1334        let layout = flex_layout(
1335            FlexStyle::horizontal().wrap(FlexWrap::Wrap).gap(10.0),
1336            &items,
1337            Constraints::tight(Size::new(320.0, 100.0)),
1338            |_, _| Size::new(10.0, 10.0),
1339        );
1340
1341        assert_eq!(layout.lines.len(), 2);
1342        assert_eq!(layout.items[0].line, 0);
1343        assert_eq!(layout.items[2].line, 0);
1344        assert_eq!(layout.items[3].line, 1);
1345        assert_eq!(layout.items[4].line, 1);
1346        assert_rect_approx_eq(layout.items[3].rect, Rect::new(0.0, 20.0, 155.0, 10.0));
1347        assert_rect_approx_eq(layout.items[4].rect, Rect::new(165.0, 20.0, 155.0, 10.0));
1348    }
1349
1350    #[test]
1351    fn flex_layout_redistributes_grow_space_after_max_clamp() {
1352        let items = [FlexItem::fill().max_width(20.0), FlexItem::fill()];
1353        let layout = flex_layout(
1354            FlexStyle::horizontal(),
1355            &items,
1356            Constraints::tight(Size::new(100.0, 12.0)),
1357            |_, _| Size::new(0.0, 10.0),
1358        );
1359
1360        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 20.0, 10.0));
1361        assert_rect_approx_eq(layout.items[1].rect, Rect::new(20.0, 0.0, 80.0, 10.0));
1362    }
1363
1364    #[test]
1365    fn flex_layout_shrinks_items_when_space_is_tight() {
1366        let items = [
1367            FlexItem::new().min_width(20.0),
1368            FlexItem::new().min_width(20.0),
1369        ];
1370        let layout = flex_layout(
1371            FlexStyle::horizontal(),
1372            &items,
1373            Constraints::tight(Size::new(100.0, 12.0)),
1374            |index, _| {
1375                if index == 0 {
1376                    Size::new(80.0, 10.0)
1377                } else {
1378                    Size::new(40.0, 10.0)
1379                }
1380            },
1381        );
1382
1383        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 66.666664, 10.0));
1384        assert_rect_approx_eq(
1385            layout.items[1].rect,
1386            Rect::new(66.666664, 0.0, 33.333332, 10.0),
1387        );
1388    }
1389
1390    #[test]
1391    fn flex_layout_wraps_lines_with_cross_gap() {
1392        let items = [FlexItem::new(), FlexItem::new(), FlexItem::new()];
1393        let measured = [
1394            Size::new(30.0, 10.0),
1395            Size::new(30.0, 10.0),
1396            Size::new(30.0, 10.0),
1397        ];
1398        let layout = flex_layout(
1399            FlexStyle::horizontal().wrap(FlexWrap::Wrap).gap(5.0),
1400            &items,
1401            Constraints::tight(Size::new(50.0, 40.0)),
1402            |index, _| measured[index],
1403        );
1404
1405        assert_eq!(layout.lines.len(), 3);
1406        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 30.0, 10.0));
1407        assert_rect_approx_eq(layout.items[1].rect, Rect::new(0.0, 15.0, 30.0, 10.0));
1408        assert_rect_approx_eq(layout.items[2].rect, Rect::new(0.0, 30.0, 30.0, 10.0));
1409    }
1410
1411    #[test]
1412    fn flex_layout_justifies_remaining_space_between_items() {
1413        let items = [FlexItem::new(), FlexItem::new(), FlexItem::new()];
1414        let layout = flex_layout(
1415            FlexStyle::horizontal().justify(FlexJustify::SpaceBetween),
1416            &items,
1417            Constraints::tight(Size::new(100.0, 10.0)),
1418            |_, _| Size::new(10.0, 10.0),
1419        );
1420
1421        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 10.0, 10.0));
1422        assert_rect_approx_eq(layout.items[1].rect, Rect::new(45.0, 0.0, 10.0, 10.0));
1423        assert_rect_approx_eq(layout.items[2].rect, Rect::new(90.0, 0.0, 10.0, 10.0));
1424    }
1425
1426    #[test]
1427    fn flex_layout_stretches_items_and_lines_on_cross_axis() {
1428        let items = [FlexItem::new(), FlexItem::new()];
1429        let layout = flex_layout(
1430            FlexStyle::horizontal()
1431                .align_items(Alignment::Stretch)
1432                .align_content(FlexAlignContent::Stretch),
1433            &items,
1434            Constraints::tight(Size::new(60.0, 20.0)),
1435            |_, _| Size::new(20.0, 8.0),
1436        );
1437
1438        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 20.0, 20.0));
1439        assert_rect_approx_eq(layout.items[1].rect, Rect::new(20.0, 0.0, 20.0, 20.0));
1440    }
1441
1442    #[test]
1443    fn arrange_flex_uses_existing_measured_sizes() {
1444        let items = [FlexItem::new(), FlexItem::new().grow(1.0)];
1445        let layout = arrange_flex(
1446            FlexStyle::horizontal(),
1447            &items,
1448            Size::new(80.0, 12.0),
1449            &[Size::new(20.0, 8.0), Size::new(10.0, 8.0)],
1450        );
1451
1452        assert_rect_approx_eq(layout.items[0].rect, Rect::new(0.0, 0.0, 20.0, 8.0));
1453        assert_rect_approx_eq(layout.items[1].rect, Rect::new(20.0, 0.0, 60.0, 8.0));
1454    }
1455}