1use std::cell::RefCell;
2
3use cranpose_ui_graphics::whole;
4use cranpose_ui_layout::{
5 Axis, Constraints, MeasurePolicy, MeasureResult, MeasureScope, ParentData, Placement,
6 bias_offset, round_to_px,
7};
8
9use super::empty_measure_policy::empty_layout_hold;
10use crate::{
11 layout::core::{
12 Arrangement, HorizontalAlignment, LinearArrangement, Measurable, Measurables,
13 VerticalAlignment,
14 },
15 thread_state,
16};
17
18#[derive(Clone, Debug, PartialEq)]
56pub struct FlexMeasurePolicy {
57 pub axis: Axis,
59 pub main_axis_arrangement: LinearArrangement,
61 pub cross_axis_alignment: CrossAxisAlignment,
63 pub density: f32,
66 pub layout_direction: crate::LayoutDirection,
68}
69
70pub(crate) struct WeightShares {
74 density: f32,
75 unit_px: f32,
76 remainder_px: f32,
77}
78
79impl WeightShares {
80 pub(crate) fn new(
81 remaining: f32,
82 weights: impl Iterator<Item = f32> + Clone,
83 density: f32,
84 ) -> Self {
85 let density = if density > 0.0 && density.is_finite() {
86 density
87 } else {
88 1.0
89 };
90 let total_weight: f32 = weights.clone().sum();
91 let remaining_px = whole::round(remaining * density);
92 let unit_px = if total_weight > 0.0 {
93 remaining_px / total_weight
94 } else {
95 0.0
96 };
97 let rounded_px: f32 = weights
98 .map(|weight| whole::floor(unit_px * weight + 0.5))
99 .sum();
100 Self {
101 density,
102 unit_px,
103 remainder_px: remaining_px - rounded_px,
104 }
105 }
106
107 pub(crate) fn next_share(&mut self, weight: f32) -> f32 {
109 let step = if self.remainder_px > 0.0 {
110 1.0
111 } else if self.remainder_px < 0.0 {
112 -1.0
113 } else {
114 0.0
115 };
116 self.remainder_px -= step;
117 (whole::floor(self.unit_px * weight + 0.5) + step).max(0.0) / self.density
118 }
119}
120
121#[derive(Clone, Copy, Debug, PartialEq)]
124pub enum CrossAxisAlignment {
125 Start,
127 Center,
129 End,
131}
132
133impl CrossAxisAlignment {
134 fn align(&self, available: f32, child: f32, density: f32) -> f32 {
136 let bias = match self {
137 Self::Start => -1.0,
138 Self::Center => 0.0,
139 Self::End => 1.0,
140 };
141 bias_offset(bias, available, child, density)
142 }
143}
144
145impl From<HorizontalAlignment> for CrossAxisAlignment {
146 fn from(alignment: HorizontalAlignment) -> Self {
147 match alignment {
148 HorizontalAlignment::Start => Self::Start,
149 HorizontalAlignment::CenterHorizontally => Self::Center,
150 HorizontalAlignment::End => Self::End,
151 }
152 }
153}
154
155impl From<VerticalAlignment> for CrossAxisAlignment {
156 fn from(alignment: VerticalAlignment) -> Self {
157 match alignment {
158 VerticalAlignment::Top => Self::Start,
159 VerticalAlignment::CenterVertically => Self::Center,
160 VerticalAlignment::Bottom => Self::End,
161 }
162 }
163}
164
165impl FlexMeasurePolicy {
166 pub fn new(
168 axis: Axis,
169 main_axis_arrangement: LinearArrangement,
170 cross_axis_alignment: CrossAxisAlignment,
171 density: f32,
172 ) -> Self {
173 Self {
174 axis,
175 main_axis_arrangement,
176 cross_axis_alignment,
177 density,
178 layout_direction: crate::LayoutDirection::Ltr,
179 }
180 }
181
182 pub fn row(
184 horizontal_arrangement: LinearArrangement,
185 vertical_alignment: VerticalAlignment,
186 density: f32,
187 ) -> Self {
188 Self::new(
189 Axis::Horizontal,
190 horizontal_arrangement,
191 vertical_alignment.into(),
192 density,
193 )
194 }
195
196 pub fn column(
198 vertical_arrangement: LinearArrangement,
199 horizontal_alignment: HorizontalAlignment,
200 density: f32,
201 ) -> Self {
202 Self::new(
203 Axis::Vertical,
204 vertical_arrangement,
205 horizontal_alignment.into(),
206 density,
207 )
208 }
209
210 fn get_axis_constraints(&self, constraints: Constraints) -> (f32, f32, f32, f32) {
211 match self.axis {
212 Axis::Horizontal => (
213 constraints.min_width,
214 constraints.max_width,
215 constraints.min_height,
216 constraints.max_height,
217 ),
218 Axis::Vertical => (
219 constraints.min_height,
220 constraints.max_height,
221 constraints.min_width,
222 constraints.max_width,
223 ),
224 }
225 }
226
227 fn make_constraints(
228 &self,
229 min_main: f32,
230 max_main: f32,
231 min_cross: f32,
232 max_cross: f32,
233 ) -> Constraints {
234 match self.axis {
235 Axis::Horizontal => Constraints {
236 min_width: min_main,
237 max_width: max_main,
238 min_height: min_cross,
239 max_height: max_cross,
240 },
241 Axis::Vertical => Constraints {
242 min_width: min_cross,
243 max_width: max_cross,
244 min_height: min_main,
245 max_height: max_main,
246 },
247 }
248 }
249
250 fn get_main_axis_size(&self, width: f32, height: f32) -> f32 {
251 match self.axis {
252 Axis::Horizontal => width,
253 Axis::Vertical => height,
254 }
255 }
256
257 fn get_cross_axis_size(&self, width: f32, height: f32) -> f32 {
258 match self.axis {
259 Axis::Horizontal => height,
260 Axis::Vertical => width,
261 }
262 }
263
264 fn measure_fixed_children(
270 &self,
271 measurables: Measurables<'_>,
272 children: &mut [FlexChild],
273 (max_main, max_cross): (f32, f32),
274 spacing: f32,
275 ) -> (f32, f32) {
276 let main_axis_bounded = max_main.is_finite();
277 let mut fixed_space = 0.0_f32;
278 let mut max_cross_size = 0.0_f32;
279 for (child, measurable) in children.iter_mut().zip(measurables) {
280 if child.data.has_weight() {
281 continue;
282 }
283 let available_main = if main_axis_bounded {
284 (max_main - fixed_space).max(0.0)
285 } else {
286 max_main
287 };
288 let placeable =
289 measurable.measure(self.make_constraints(0.0, available_main, 0.0, max_cross));
290 let main_size = self.get_main_axis_size(placeable.width(), placeable.height());
291 let spacing_after = if main_axis_bounded {
292 spacing.min(available_main - main_size).max(0.0)
293 } else {
294 spacing
295 };
296 fixed_space += main_size + spacing_after;
297 max_cross_size =
298 max_cross_size.max(self.get_cross_axis_size(placeable.width(), placeable.height()));
299 child.placeable = Some(placeable);
300 }
301 (fixed_space, max_cross_size)
302 }
303
304 fn intrinsic_main_size(
308 &self,
309 measurables: Measurables<'_>,
310 main_size: impl Fn(&dyn Measurable) -> f32,
311 ) -> f32 {
312 if measurables.is_empty() {
313 return 0.0;
314 }
315 let mut fixed_space = 0.0_f32;
316 let mut weight_unit = 0.0_f32;
317 let mut total_weight = 0.0_f32;
318 for measurable in measurables {
319 let size = main_size(measurable);
320 match child_weight(measurable) {
321 Some(weight) => {
322 total_weight += weight;
323 weight_unit = weight_unit.max(round_to_px(size / weight, self.density));
324 }
325 None => fixed_space += size,
326 }
327 }
328 round_to_px(weight_unit * total_weight, self.density)
329 + fixed_space
330 + self.get_spacing() * (measurables.len() - 1) as f32
331 }
332
333 fn intrinsic_cross_size(
339 &self,
340 measurables: Measurables<'_>,
341 main_available: f32,
342 main_size: impl Fn(&dyn Measurable, f32) -> f32,
343 cross_size: impl Fn(&dyn Measurable, f32) -> f32,
344 ) -> f32 {
345 if measurables.is_empty() {
346 return 0.0;
347 }
348 let mut fixed_space =
349 (self.get_spacing() * (measurables.len() - 1) as f32).min(main_available);
350 let mut cross = 0.0_f32;
351 let mut total_weight = 0.0_f32;
352 for measurable in measurables {
353 if let Some(weight) = child_weight(measurable) {
354 total_weight += weight;
355 continue;
356 }
357 let space =
358 main_size(measurable, f32::INFINITY).min((main_available - fixed_space).max(0.0));
359 fixed_space += space;
360 cross = cross.max(cross_size(measurable, space));
361 }
362 if total_weight == 0.0 {
363 return cross;
364 }
365 let weight_unit = if main_available.is_finite() {
366 round_to_px(
367 (main_available - fixed_space).max(0.0) / total_weight,
368 self.density,
369 )
370 } else {
371 f32::INFINITY
372 };
373 for measurable in measurables {
374 if let Some(weight) = child_weight(measurable) {
375 cross = cross.max(cross_size(
376 measurable,
377 round_to_px(weight_unit * weight, self.density),
378 ));
379 }
380 }
381 cross
382 }
383
384 fn get_spacing(&self) -> f32 {
385 self.main_axis_arrangement.spacing(self.density)
386 }
387
388 fn measure_weighted_children(
389 &self,
390 measurables: Measurables<'_>,
391 children: &mut [FlexChild],
392 (max_main, max_cross): (f32, f32),
393 (fixed_space, spacing): (f32, f32),
394 ) -> f32 {
395 let weights = children
396 .iter()
397 .filter(|child| child.data.has_weight())
398 .map(|child| child.data.weight);
399 let weighted = weights.clone().count();
400 if weighted == 0 {
401 return 0.0;
402 }
403 let remaining_main = (max_main - fixed_space - spacing * (weighted - 1) as f32).max(0.0);
404 let mut shares = WeightShares::new(remaining_main, weights, self.density);
405 let mut max_cross_size = 0.0_f32;
406 for (child, measurable) in children.iter_mut().zip(measurables) {
407 let data = &child.data;
408 if !data.has_weight() {
409 continue;
410 }
411 let constraints = if max_main.is_finite() {
412 let allocated = shares.next_share(data.weight);
413 let minimum = if data.fill { allocated } else { 0.0 };
414 self.make_constraints(minimum, allocated, 0.0, max_cross)
415 } else {
416 self.make_constraints(0.0, max_main, 0.0, max_cross)
417 };
418 let placeable = measurable.measure(constraints);
419 max_cross_size =
420 max_cross_size.max(self.get_cross_axis_size(placeable.width(), placeable.height()));
421 child.placeable = Some(placeable);
422 }
423 max_cross_size
424 }
425
426 fn measured_extents(&self, children: &[FlexChild]) -> (f32, f32, f32) {
427 let mut main = 0.0;
428 let mut before = 0.0_f32;
429 let mut after = 0.0_f32;
430 for (placeable, data) in measured(children) {
431 main += self.get_main_axis_size(placeable.width(), placeable.height());
432 if self.axis == Axis::Horizontal
433 && data.row_baseline
434 && let Some(baseline) = placeable.alignment_lines().first_baseline()
435 {
436 before = before.max(baseline);
437 after = after.max(placeable.height() - baseline);
438 }
439 }
440 (main, before, after)
441 }
442
443 fn cross_axis_position(
444 &self,
445 placeable: &cranpose_ui_layout::Placeable,
446 parent_data: &ParentData,
447 container_cross: f32,
448 before_baseline: f32,
449 ) -> f32 {
450 if self.axis == Axis::Horizontal && parent_data.row_baseline {
451 return placeable
452 .alignment_lines()
453 .first_baseline()
454 .map_or(0.0, |baseline| before_baseline - baseline);
455 }
456 let alignment = match self.axis {
457 Axis::Horizontal => parent_data
458 .row_alignment
459 .map_or(self.cross_axis_alignment, Into::into),
460 Axis::Vertical => parent_data
461 .column_alignment
462 .map_or(self.cross_axis_alignment, Into::into),
463 };
464 let child_cross = self.get_cross_axis_size(placeable.width(), placeable.height());
465 alignment.align(container_cross, child_cross, self.density)
466 }
467}
468
469fn child_main_range(
473 child_max: cranpose_ui_layout::BoundRange,
474 max_main: f32,
475 fixed_space: f32,
476 child_main: f32,
477 spacing: f32,
478) -> Option<cranpose_ui_layout::BoundRange> {
479 use cranpose_ui_layout::BoundRange;
480 if !max_main.is_finite() {
481 return child_max
482 .contains(f32::INFINITY)
483 .then_some(BoundRange::exactly(f32::INFINITY));
484 }
485 if (max_main - fixed_space).max(0.0) - child_main < spacing {
486 return None;
487 }
488 child_max
489 .outset(fixed_space)
490 .intersect(BoundRange::from(fixed_space + child_main + spacing))
491}
492
493fn child_weight(measurable: &dyn Measurable) -> Option<f32> {
495 measurable
496 .flex_parent_data()
497 .map(|data| data.weight)
498 .filter(|weight| *weight > 0.0)
499}
500
501struct FlexChild {
504 data: ParentData,
505 placeable: Option<cranpose_ui_layout::Placeable>,
506}
507
508#[derive(Default)]
511struct FlexLists {
512 children: Vec<FlexChild>,
513 main_sizes: Vec<f32>,
514 main_positions: Vec<f32>,
515}
516
517impl FlexLists {
518 fn bytes(&self) -> usize {
520 self.children.capacity() * size_of::<FlexChild>()
521 + (self.main_sizes.capacity() + self.main_positions.capacity()) * size_of::<f32>()
522 }
523}
524
525pub(crate) struct SpareFlexLists(RefCell<Spares>);
531
532struct Spares {
533 sets: Vec<FlexLists>,
535 bytes: usize,
537}
538
539impl Spares {
540 const SETS: usize = 128;
543 const IDLE_BYTES: usize = 64 * 1024;
545
546 fn keep(&mut self, lists: FlexLists) {
550 let top = lists.bytes();
551 self.bytes += top;
552 self.sets.push(lists);
553 while self.sets.len() > Self::SETS || self.bytes - top > Self::IDLE_BYTES {
554 let idle = &self.sets[..self.sets.len() - 1];
555 let Some(largest) = (0..idle.len()).max_by_key(|&at| idle[at].bytes()) else {
556 break;
557 };
558 self.bytes -= self.sets.remove(largest).bytes();
559 }
560 }
561
562 fn take(&mut self) -> Option<FlexLists> {
563 let lists = self.sets.pop()?;
564 self.bytes -= lists.bytes();
565 Some(lists)
566 }
567}
568
569impl SpareFlexLists {
570 pub(crate) const fn new() -> Self {
571 Self(RefCell::new(Spares {
572 sets: Vec::new(),
573 bytes: 0,
574 }))
575 }
576
577 fn take() -> FlexLists {
578 thread_state::with(|state| state.spare_flex_lists.0.borrow_mut().take()).unwrap_or_default()
579 }
580
581 fn give(mut lists: FlexLists) {
582 lists.children.clear();
583 lists.main_sizes.clear();
584 lists.main_positions.clear();
585 thread_state::with(|state| state.spare_flex_lists.0.borrow_mut().keep(lists));
586 }
587}
588
589fn measured(
592 children: &[FlexChild],
593) -> impl Iterator<Item = (&cranpose_ui_layout::Placeable, &ParentData)> {
594 children
595 .iter()
596 .filter_map(|child| Some((child.placeable.as_ref()?, &child.data)))
597}
598
599impl MeasurePolicy for FlexMeasurePolicy {
600 fn measure(
601 &self,
602 scope: &dyn MeasureScope,
603 measurables: Measurables<'_>,
604 constraints: Constraints,
605 ) -> MeasureResult {
606 let mut placements = Vec::new();
607 let measurement = self.measure_into(scope, measurables, constraints, &mut placements);
608 MeasureResult::new(measurement, placements)
609 }
610
611 fn measure_hold(
615 &self,
616 measurables: Measurables<'_>,
617 constraints: Constraints,
618 size: crate::modifier::Size,
619 ) -> Option<cranpose_ui_layout::ConstraintsHold> {
620 use cranpose_ui_layout::{AxisHold, BoundRange, ConstraintsHold};
621 if measurables.is_empty() {
622 return empty_layout_hold(constraints, size);
623 }
624 if measurables
625 .iter()
626 .any(|measurable| measurable.parent_data().has_weight())
627 {
628 return None;
629 }
630 let (_, max_main, _, _) = self.get_axis_constraints(constraints);
631 let spacing = self.get_spacing();
632 let mut main = BoundRange::ANY;
633 let mut cross = BoundRange::ANY;
634 let mut fixed_space = 0.0_f32;
635 let mut total_main = 0.0_f32;
636 let mut cross_size = 0.0_f32;
637 for measurable in measurables {
638 let (child, hold) = measurable.measured_hold()?;
639 let (main_hold, cross_hold) = match self.axis {
640 Axis::Horizontal => (hold.width, hold.height),
641 Axis::Vertical => (hold.height, hold.width),
642 };
643 let child_main = self.get_main_axis_size(child.width, child.height);
644 main = main.intersect(child_main_range(
645 main_hold.max,
646 max_main,
647 fixed_space,
648 child_main,
649 spacing,
650 )?)?;
651 cross = cross.intersect(cross_hold.max)?;
652 fixed_space += child_main + spacing;
653 total_main += child_main;
654 cross_size = cross_size.max(self.get_cross_axis_size(child.width, child.height));
655 }
656 total_main += spacing * (measurables.len() - 1) as f32;
657 let size_main = self.get_main_axis_size(size.width, size.height);
658 let size_cross = self.get_cross_axis_size(size.width, size.height);
659 if size_main != total_main || size_cross != cross_size {
661 return None;
662 }
663 let main = AxisHold {
664 min: BoundRange::up_to(size_main),
665 max: main.intersect(BoundRange::from(size_main))?,
666 };
667 let cross = AxisHold {
668 min: BoundRange::up_to(size_cross),
669 max: cross.intersect(BoundRange::from(size_cross))?,
670 };
671 Some(match self.axis {
672 Axis::Horizontal => ConstraintsHold {
673 width: main,
674 height: cross,
675 },
676 Axis::Vertical => ConstraintsHold {
677 width: cross,
678 height: main,
679 },
680 })
681 }
682
683 fn measure_into(
684 &self,
685 _scope: &dyn MeasureScope,
686 measurables: Measurables<'_>,
687 constraints: Constraints,
688 placements: &mut Vec<Placement>,
689 ) -> cranpose_ui_layout::Measurement {
690 placements.clear();
691 if measurables.is_empty() {
692 let (width, height) = constraints.constrain(0.0, 0.0);
693 return crate::modifier::Size { width, height }.into();
694 }
695
696 let (min_main, max_main, min_cross, max_cross) = self.get_axis_constraints(constraints);
697 let spacing = self.get_spacing();
698
699 let mut lists = SpareFlexLists::take();
700 let FlexLists {
701 children,
702 main_sizes,
703 main_positions,
704 } = &mut lists;
705 children.extend(measurables.iter().map(|child| FlexChild {
706 data: child.parent_data(),
707 placeable: None,
708 }));
709 let (fixed_space, mut max_cross_size) =
710 self.measure_fixed_children(measurables, children, (max_main, max_cross), spacing);
711
712 let num_children = measurables.len();
713 let total_spacing = if num_children > 1 {
714 spacing * (num_children - 1) as f32
715 } else {
716 0.0
717 };
718
719 max_cross_size = max_cross_size.max(self.measure_weighted_children(
720 measurables,
721 children,
722 (max_main, max_cross),
723 (fixed_space, spacing),
724 ));
725
726 let (total_main, before_baseline, after_baseline) = self.measured_extents(children);
727 let total_main = total_main + total_spacing;
728 max_cross_size = max_cross_size.max(before_baseline + after_baseline);
729
730 let container_main = total_main.clamp(min_main, max_main);
731 let container_cross = max_cross_size.clamp(min_cross, max_cross);
732
733 main_sizes.extend(
734 measured(children).map(|(p, _)| self.get_main_axis_size(p.width(), p.height())),
735 );
736 main_positions.resize(main_sizes.len(), 0.0);
737
738 let arrangement = if total_main > container_main && !self.main_axis_arrangement.is_spaced()
739 {
740 LinearArrangement::Start
741 } else {
742 self.main_axis_arrangement
743 };
744 arrangement.arrange(self.density, container_main, main_sizes, main_positions);
745
746 placements.reserve(children.len());
747 for ((placeable, data), &main_pos) in measured(children).zip(main_positions.iter()) {
748 let cross_pos =
749 self.cross_axis_position(placeable, data, container_cross, before_baseline);
750
751 let (x, y) = match self.axis {
752 Axis::Horizontal => (main_pos, cross_pos),
753 Axis::Vertical => (cross_pos, main_pos),
754 };
755 let width = match self.axis {
756 Axis::Horizontal => container_main,
757 Axis::Vertical => container_cross,
758 };
759 let x = self.layout_direction.place_x(x, width, placeable.width());
760
761 placements.push(Placement::new(placeable.node_id(), x, y, 0.0));
762 }
763 SpareFlexLists::give(lists);
764
765 let (width, height) = match self.axis {
766 Axis::Horizontal => (container_main, container_cross),
767 Axis::Vertical => (container_cross, container_main),
768 };
769
770 crate::modifier::Size { width, height }.into()
771 }
772
773 fn min_intrinsic_width(&self, measurables: Measurables<'_>, height: f32) -> f32 {
774 match self.axis {
775 Axis::Horizontal => {
776 self.intrinsic_main_size(measurables, |m| m.min_intrinsic_width(height))
777 }
778 Axis::Vertical => self.intrinsic_cross_size(
779 measurables,
780 height,
781 |m, width| m.max_intrinsic_height(width),
782 |m, main| m.min_intrinsic_width(main),
783 ),
784 }
785 }
786
787 fn max_intrinsic_width(&self, measurables: Measurables<'_>, height: f32) -> f32 {
788 match self.axis {
789 Axis::Horizontal => {
790 self.intrinsic_main_size(measurables, |m| m.max_intrinsic_width(height))
791 }
792 Axis::Vertical => self.intrinsic_cross_size(
793 measurables,
794 height,
795 |m, width| m.max_intrinsic_height(width),
796 |m, main| m.max_intrinsic_width(main),
797 ),
798 }
799 }
800
801 fn min_intrinsic_height(&self, measurables: Measurables<'_>, width: f32) -> f32 {
802 match self.axis {
803 Axis::Horizontal => self.intrinsic_cross_size(
804 measurables,
805 width,
806 |m, height| m.max_intrinsic_width(height),
807 |m, main| m.min_intrinsic_height(main),
808 ),
809 Axis::Vertical => {
810 self.intrinsic_main_size(measurables, |m| m.min_intrinsic_height(width))
811 }
812 }
813 }
814
815 fn max_intrinsic_height(&self, measurables: Measurables<'_>, width: f32) -> f32 {
816 match self.axis {
817 Axis::Horizontal => self.intrinsic_cross_size(
818 measurables,
819 width,
820 |m, height| m.max_intrinsic_width(height),
821 |m, main| m.max_intrinsic_height(main),
822 ),
823 Axis::Vertical => {
824 self.intrinsic_main_size(measurables, |m| m.max_intrinsic_height(width))
825 }
826 }
827 }
828}