1use super::*;
2
3impl LayoutEngine {
5 pub fn compute(&mut self, tree: &mut SceneTree, viewport: Size) -> LayoutStats {
17 let Self {
18 track_damage,
19 damage_fallback,
20 layout_snapshots,
21 ..
22 } = self;
23 *track_damage = false;
24 *damage_fallback = LAYOUT_FALLBACK_NONE;
25 layout_snapshots.clear();
26 self.compute_inner(tree, viewport)
27 }
28
29 pub(crate) fn compute_with_damage(
42 &mut self,
43 tree: &mut SceneTree,
44 viewport: Size,
45 scale: f32,
46 ) -> (LayoutStats, LayoutDamageReport) {
47 {
48 let Self {
49 track_damage,
50 damage_fallback,
51 layout_snapshots,
52 ..
53 } = self;
54 *track_damage = true;
55 *damage_fallback = LAYOUT_FALLBACK_NONE;
56 layout_snapshots.clear();
57 }
58 let stats: LayoutStats = self.compute_inner(tree, viewport);
59 let fallback_after: u8 = {
60 let Self {
61 track_damage,
62 damage_fallback,
63 ..
64 } = self;
65 *track_damage = false;
66 *damage_fallback
67 };
68 if fallback_after != LAYOUT_FALLBACK_NONE {
69 let Self {
70 layout_snapshots, ..
71 } = self;
72 layout_snapshots.clear();
73 return (
74 stats,
75 LayoutDamageReport {
76 damage: DamageRegion::full(),
77 fallback_kind: fallback_after,
78 },
79 );
80 }
81 let mut damage: DamageRegion = DamageRegion::default();
82 let mut final_fallback: u8 = LAYOUT_FALLBACK_NONE;
83 let Self {
84 layout_snapshots, ..
85 } = self;
86 for snap in layout_snapshots.iter().copied() {
87 let Some(node) = tree.get_node(snap.id) else {
88 continue;
89 };
90 let lbox: LayoutBox = node.get_layout_box();
91 let new_bounds: Rect = lbox.get_bounds();
92 let new_content_bounds: Rect = lbox.get_content_bounds();
93 let new_content_size: Size = lbox.get_content_size();
94 let bounds_changed: bool = !Self::rect_approx_eq(snap.old_bounds, new_bounds);
95 let content_changed: bool =
96 !Self::rect_approx_eq(snap.old_content_bounds, new_content_bounds);
97 let is_scroll_box: bool =
98 node.style_ref().layout_ref().get_overflow() == Overflow::Scroll;
99 let scroll_content_changed: bool =
100 is_scroll_box && !Self::size_approx_eq(snap.old_content_size, new_content_size);
101 let geom_changed: bool = bounds_changed || content_changed;
102 if !geom_changed && !scroll_content_changed {
103 continue;
104 }
105 let is_portal_or_fixed: bool = matches!(node.get_kind(), NodeKind::Portal)
106 || node.style_ref().layout_ref().get_position() == Position::Fixed;
107 if is_portal_or_fixed {
108 final_fallback = LAYOUT_FALLBACK_PORTAL;
109 break;
110 }
111 if snap.has_old_screen {
112 damage.add_rect(SceneTree::scale_logical_to_phys_rect(
113 snap.old_screen,
114 scale,
115 ));
116 }
117 if new_bounds.get_width() > 0.0 && new_bounds.get_height() > 0.0 {
118 match tree.node_conservative_logical_rect(snap.id) {
119 Some(new_screen) => {
120 damage.add_rect(SceneTree::scale_logical_to_phys_rect(new_screen, scale));
121 }
122 None => {
123 final_fallback = LAYOUT_FALLBACK_UNSAFE;
124 break;
125 }
126 }
127 }
128 }
129 layout_snapshots.clear();
130 if final_fallback != LAYOUT_FALLBACK_NONE {
131 return (
132 stats,
133 LayoutDamageReport {
134 damage: DamageRegion::full(),
135 fallback_kind: final_fallback,
136 },
137 );
138 }
139 (
140 stats,
141 LayoutDamageReport {
142 damage,
143 fallback_kind: LAYOUT_FALLBACK_NONE,
144 },
145 )
146 }
147
148 fn compute_inner(&mut self, tree: &mut SceneTree, viewport: Size) -> LayoutStats {
160 let root_id: NodeId = tree.get_root();
161 let space: AvailableSpace = AvailableSpace::root(viewport);
162 let mut stats: LayoutStats = LayoutStats::default();
163 self.get_mut_children_scratch().clear();
164 self.get_mut_flow_scratch().clear();
165 self.get_mut_abs_scratch().clear();
166 self.get_mut_flex_items_scratch().clear();
167 self.get_mut_flex_lines_scratch().clear();
168 self.get_mut_translate_scratch().clear();
169 self.layout_node(tree, root_id, space, &mut stats);
170 debug_assert!(self.get_children_scratch().is_empty());
171 debug_assert!(self.get_flow_scratch().is_empty());
172 debug_assert!(self.get_abs_scratch().is_empty());
173 debug_assert!(self.get_flex_items_scratch().is_empty());
174 debug_assert!(self.get_flex_lines_scratch().is_empty());
175 debug_assert!(self.get_mut_translate_scratch().is_empty());
176 self.set_last_stats(stats);
177 stats
178 }
179
180 #[inline]
188 fn record_layout_snapshot(&mut self, tree: &SceneTree, node_id: NodeId) {
189 let Self {
190 track_damage,
191 damage_fallback,
192 layout_snapshots,
193 ..
194 } = self;
195 if !*track_damage || *damage_fallback != LAYOUT_FALLBACK_NONE {
196 return;
197 }
198 if layout_snapshots
199 .iter()
200 .any(|snap: &LayoutNodeSnapshot| snap.id == node_id)
201 {
202 return;
203 }
204 if layout_snapshots.len() >= DIRTY_PAINT_FULL_THRESHOLD {
205 *damage_fallback = LAYOUT_FALLBACK_OVERFLOW;
206 return;
207 }
208 let Some(node) = tree.get_node(node_id) else {
209 return;
210 };
211 let lbox: LayoutBox = node.get_layout_box();
212 let old_bounds: Rect = lbox.get_bounds();
213 let old_content_bounds: Rect = lbox.get_content_bounds();
214 let old_content_size: Size = lbox.get_content_size();
215 let (has_old_screen, old_screen): (bool, Rect) =
216 if old_bounds.get_width() > 0.0 && old_bounds.get_height() > 0.0 {
217 match tree.node_conservative_logical_rect(node_id) {
218 Some(rect) => (true, rect),
219 None => {
220 *damage_fallback = LAYOUT_FALLBACK_UNSAFE;
221 return;
222 }
223 }
224 } else {
225 (false, Rect::default())
226 };
227 layout_snapshots.push(LayoutNodeSnapshot {
228 id: node_id,
229 old_bounds,
230 old_content_bounds,
231 old_content_size,
232 has_old_screen,
233 old_screen,
234 });
235 }
236
237 #[inline]
248 fn rect_approx_eq(a: Rect, b: Rect) -> bool {
249 (a.get_x() - b.get_x()).abs() <= 0.001
250 && (a.get_y() - b.get_y()).abs() <= 0.001
251 && (a.get_width() - b.get_width()).abs() <= 0.001
252 && (a.get_height() - b.get_height()).abs() <= 0.001
253 }
254
255 #[inline]
266 fn size_approx_eq(a: Size, b: Size) -> bool {
267 (a.get_width() - b.get_width()).abs() <= 0.001
268 && (a.get_height() - b.get_height()).abs() <= 0.001
269 }
270
271 fn measure_text_cached(
284 &mut self,
285 text: &str,
286 style: TextStyle,
287 max_width: Option<f32>,
288 ) -> Size {
289 let measurer: DeterministicTextMeasurer = self.get_measurer();
290 self.get_mut_text_size_cache().get_or_measure(
291 text,
292 style,
293 max_width,
294 |raw: &str, text_style: TextStyle, limit: Option<f32>| {
295 measurer.measure_size(raw, text_style, limit)
296 },
297 )
298 }
299
300 fn layout_node(
314 &mut self,
315 tree: &mut SceneTree,
316 node_id: NodeId,
317 space: AvailableSpace,
318 stats: &mut LayoutStats,
319 ) -> Size {
320 let Some(node) = tree.get_node(node_id) else {
321 return Size::default();
322 };
323 if !node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
324 && let Some(prev_space) = node.cached_constraint()
325 && prev_space.can_reuse(space)
326 {
327 let prev_bounds: Rect = node.get_layout_box().get_bounds();
328 let cached_size: Size = Size::new(prev_bounds.get_width(), prev_bounds.get_height());
329 if !prev_space.same_origin(space) {
330 let dx: f32 = space.get_origin_x() - prev_space.get_origin_x();
331 let dy: f32 = space.get_origin_y() - prev_space.get_origin_y();
332 self.translate_subtree(tree, node_id, dx, dy);
333 }
334 stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
335 return cached_size;
336 }
337 stats.set_nodes_computed(stats.get_nodes_computed() + 1);
338 let style_ref: &Style = node.style_ref();
339 let Style {
340 layout: layout_ref,
341 paint: paint_ref,
342 text: text_ref,
343 } = style_ref;
344 if layout_ref.get_display() == Display::None {
345 let stack_base: usize = self.get_children_scratch().len();
346 self.get_mut_children_scratch().push(node_id);
347 while self.get_children_scratch().len() > stack_base {
348 if let Some(hid) = self.get_mut_children_scratch().pop() {
349 self.record_layout_snapshot(tree, hid);
350 if let Some(hidden_node) = tree.get_node_mut(hid) {
351 hidden_node.get_mut_layout_box().set_bounds(Rect::default());
352 hidden_node
353 .get_mut_layout_box()
354 .set_content_bounds(Rect::default());
355 if hid == node_id {
356 hidden_node.set_last_constraint(Some(space));
357 } else {
358 hidden_node.set_last_constraint(None);
359 }
360 hidden_node.get_mut_dirty().remove(DIRTY_LAYOUT_PASS_MASK);
361 self.get_mut_children_scratch()
362 .extend_from_slice(hidden_node.get_children().as_slice());
363 }
364 }
365 }
366 return Size::default();
367 }
368 let padding: Edges = layout_ref.get_padding();
369 let border_w: f32 = paint_ref.get_border().get_width();
370 let chrome_h: f32 = padding.horizontal() + border_w * 2.0;
371 let chrome_v: f32 = padding.vertical() + border_w * 2.0;
372 let explicit_w: Option<f32> = layout_ref
373 .get_width()
374 .resolve(space.get_width(), space.get_viewport());
375 let explicit_h: Option<f32> = layout_ref
376 .get_height()
377 .resolve(space.get_height(), space.get_viewport());
378 let mut resolved_w: Option<f32> = explicit_w;
379 let mut resolved_h: Option<f32> = explicit_h;
380 let stretched_w: bool = resolved_w.is_none() && space.get_stretch_width();
381 let stretched_h: bool = resolved_h.is_none() && space.get_stretch_height();
382 if stretched_w {
383 resolved_w = Some(space.get_width());
384 }
385 if stretched_h {
386 resolved_h = Some(space.get_height());
387 }
388 let min_w: f32 = layout_ref
389 .get_min_width()
390 .resolve(space.get_width(), space.get_viewport())
391 .unwrap_or(0.0);
392 let min_h: f32 = layout_ref
393 .get_min_height()
394 .resolve(space.get_height(), space.get_viewport())
395 .unwrap_or(0.0);
396 let max_w: f32 = layout_ref
397 .get_max_width()
398 .resolve(space.get_width(), space.get_viewport())
399 .unwrap_or(f32::INFINITY)
400 .max(min_w);
401 let max_h: f32 = layout_ref
402 .get_max_height()
403 .resolve(space.get_height(), space.get_viewport())
404 .unwrap_or(f32::INFINITY)
405 .max(min_h);
406 let aspect_ratio: Option<f32> = layout_ref.aspect_ratio_value();
407 if let Some(ratio) = aspect_ratio
408 && ratio > 0.0
409 {
410 if let Some(w) = resolved_w
411 && resolved_h.is_none()
412 {
413 resolved_h = Some(w.clamp(min_w, max_w) / ratio);
414 } else if let Some(h) = resolved_h
415 && resolved_w.is_none()
416 {
417 resolved_w = Some(h.clamp(min_h, max_h) * ratio);
418 }
419 }
420 let avail_w_outer: f32 = resolved_w
421 .unwrap_or(space.get_width())
422 .max(min_w)
423 .min(max_w);
424 let avail_h_outer: f32 = resolved_h
425 .unwrap_or(space.get_height())
426 .max(min_h)
427 .min(max_h);
428 let inner_avail_w: f32 = (avail_w_outer - chrome_h).max(0.0);
429 let inner_avail_h: f32 = (avail_h_outer - chrome_v).max(0.0);
430 let origin_x: f32 = space.get_origin_x();
431 let origin_y: f32 = space.get_origin_y();
432 let content_origin_x: f32 = origin_x + padding.get_left() + border_w;
433 let content_origin_y: f32 = origin_y + padding.get_top() + border_w;
434 let mut child_range: Option<(usize, usize)> = None;
435 let leaf_content_size: Option<Size> = match node.get_kind() {
436 NodeKind::Text(text) => Some(self.measure_text_cached(
437 text.as_str(),
438 *text_ref,
439 Some(inner_avail_w.max(1.0)),
440 )),
441 NodeKind::Image(img) => {
442 Some(Size::new(img.get_width() as f32, img.get_height() as f32))
443 }
444 NodeKind::Input(input_state) => {
445 let sample: &str = if input_state.get_value().is_empty() {
446 input_state.get_placeholder().as_str()
447 } else {
448 input_state.get_value().as_str()
449 };
450 let measured_size: Size =
451 self.measure_text_cached(sample, *text_ref, Some(inner_avail_w.max(1.0)));
452 Some(Size::new(
453 measured_size.get_width().max(120.0),
454 measured_size.get_height().max(20.0),
455 ))
456 }
457 NodeKind::View
458 | NodeKind::ScrollView
459 | NodeKind::Portal
460 | NodeKind::Fragment
461 | NodeKind::Canvas => {
462 let node_children: &[NodeId] = node.get_children().as_slice();
463 if node_children.is_empty() {
464 Some(Size::default())
465 } else {
466 let start: usize = self.get_children_scratch().len();
467 self.get_mut_children_scratch()
468 .extend_from_slice(node_children);
469 let end: usize = self.get_children_scratch().len();
470 child_range = Some((start, end));
471 None
472 }
473 }
474 };
475 let node_overflow: Overflow = layout_ref.get_overflow();
476 let node_flex_grow: f32 = layout_ref.get_flex_grow();
477 let content_size: Size = if let Some(size) = leaf_content_size {
478 size
479 } else if let Some((child_start, child_end)) = child_range {
480 let frame: ContainerFrame = ContainerFrame::new(
481 *layout_ref,
482 Size::new(inner_avail_w, inner_avail_h),
483 space.get_viewport(),
484 Point::new(content_origin_x, content_origin_y),
485 resolved_w.is_some(),
486 resolved_h.is_some(),
487 );
488 let size: Size = self.layout_children(tree, child_start, child_end, frame, stats);
489 self.get_mut_children_scratch().truncate(child_start);
490 size
491 } else {
492 Size::default()
493 };
494 let content_outer_w: f32 = content_size.get_width() + chrome_h;
495 let content_outer_h: f32 = content_size.get_height() + chrome_v;
496 let mut final_w: f32 = match (explicit_w, stretched_w) {
497 (Some(w), _) => w,
498 (None, true) => {
499 let base_w: f32 = resolved_w.unwrap_or(content_outer_w);
500 if node_overflow == Overflow::Visible
501 && node_flex_grow <= 0.0
502 && content_outer_w > base_w + 0.5
503 {
504 content_outer_w
505 } else {
506 base_w
507 }
508 }
509 (None, false) => content_outer_w,
510 };
511 let mut final_h: f32 = resolved_h.unwrap_or(content_outer_h);
512 if let Some(ratio) = aspect_ratio
513 && ratio > 0.0
514 {
515 if resolved_w.is_some() && resolved_h.is_none() {
516 final_h = final_w / ratio;
517 } else if resolved_h.is_some() && resolved_w.is_none() {
518 final_w = final_h * ratio;
519 }
520 }
521 final_w = final_w.clamp(min_w, max_w).max(0.0);
522 final_h = final_h.clamp(min_h, max_h).max(0.0);
523 let bounds: Rect = Rect::new(origin_x, origin_y, final_w, final_h);
524 let content_bounds: Rect = Rect::new(
525 content_origin_x,
526 content_origin_y,
527 (final_w - chrome_h).max(0.0),
528 (final_h - chrome_v).max(0.0),
529 );
530 self.record_layout_snapshot(tree, node_id);
531 if let Some(node) = tree.get_node_mut(node_id) {
532 node.get_mut_layout_box().set_bounds(bounds);
533 node.get_mut_layout_box().set_content_bounds(content_bounds);
534 node.get_mut_layout_box().set_content_size(content_size);
535 node.set_last_constraint(Some(space));
536 node.get_mut_dirty().remove(DIRTY_LAYOUT_PASS_MASK);
537 }
538 Size::new(final_w, final_h)
539 }
540
541 fn layout_children(
556 &mut self,
557 tree: &mut SceneTree,
558 child_start: usize,
559 child_end: usize,
560 frame: ContainerFrame,
561 stats: &mut LayoutStats,
562 ) -> Size {
563 let child_count: usize = child_end.saturating_sub(child_start);
564 if child_count == 0 {
565 return Size::default();
566 }
567 let parent_layout: LayoutStyle = frame.get_parent_layout();
568 let inner_avail: Size = frame.get_inner_avail();
569 let viewport: Size = frame.get_viewport();
570 let content_origin: Point = frame.get_content_origin();
571 let flex_dir_opt: Option<FlexDirection> = match parent_layout.get_display() {
572 Display::Grid => None,
573 Display::Block => Some(FlexDirection::Column),
574 Display::Flex | Display::None => Some(parent_layout.get_flex_direction()),
575 };
576 let is_row_dir: bool = matches!(
577 flex_dir_opt,
578 Some(FlexDirection::Row | FlexDirection::RowReverse)
579 );
580 let is_reverse_dir: bool = matches!(
581 flex_dir_opt,
582 Some(FlexDirection::RowReverse | FlexDirection::ColumnReverse)
583 );
584 let parent_align: AlignItems = parent_layout.get_align_items();
585 let parent_height_auto: bool = parent_layout.get_height() == Length::Auto;
586 let mut single_pass_ok: bool = flex_dir_opt.is_some()
587 && parent_layout.get_flex_wrap() != FlexWrap::Wrap
588 && !is_reverse_dir
589 && parent_layout.get_justify_content() == JustifyContent::Start;
590 let flow_start: usize = self.get_flow_scratch().len();
591 let abs_start: usize = self.get_abs_scratch().len();
592 for idx in child_start..child_end {
593 let child_id: NodeId = self.get_children_scratch()[idx];
594 if let Some(child_node) = tree.get_node(child_id) {
595 let Style {
596 layout: child_layout,
597 ..
598 } = child_node.style_ref();
599 if child_layout.get_display() == Display::None {
600 let _: Size = self.layout_node(
601 tree,
602 child_id,
603 AvailableSpace::new(0.0, 0.0, viewport, 0.0, 0.0),
604 stats,
605 );
606 continue;
607 }
608 match child_layout.get_position() {
609 Position::Relative => {
610 if single_pass_ok {
611 if child_layout.get_flex_grow() > 0.0 {
612 single_pass_ok = false;
613 } else {
614 let align: AlignItems = match child_layout.get_align_self() {
615 AlignSelf::Auto => parent_align,
616 AlignSelf::Stretch => AlignItems::Stretch,
617 AlignSelf::Start => AlignItems::Start,
618 AlignSelf::Center => AlignItems::Center,
619 AlignSelf::End => AlignItems::End,
620 };
621 let non_start_align: bool =
622 matches!(align, AlignItems::Center | AlignItems::End);
623 let auto_row_stretch: bool = align == AlignItems::Stretch
624 && is_row_dir
625 && child_layout.get_height() == Length::Auto
626 && parent_height_auto;
627 if non_start_align || auto_row_stretch {
628 single_pass_ok = false;
629 }
630 }
631 }
632 self.get_mut_flow_scratch().push(child_id);
633 }
634 Position::Absolute | Position::Fixed => {
635 self.get_mut_abs_scratch().push(child_id)
636 }
637 }
638 }
639 }
640 let flow_end: usize = self.get_flow_scratch().len();
641 let abs_end: usize = self.get_abs_scratch().len();
642 let flow_size: Size = if let Some(flex_dir) = flex_dir_opt {
643 self.layout_flex(
644 tree,
645 (flow_start, flow_end),
646 frame,
647 flex_dir,
648 single_pass_ok,
649 stats,
650 )
651 } else {
652 self.layout_grid(tree, flow_start, flow_end, frame, stats)
653 };
654 self.get_mut_flow_scratch().truncate(flow_start);
655 for abs_idx in abs_start..abs_end {
656 let abs_id: NodeId = self.get_abs_scratch()[abs_idx];
657 let child_layout_opt: Option<LayoutStyle> = tree
658 .get_node(abs_id)
659 .map(|node: &SceneNode| node.style_ref().get_layout());
660 let Some(child_layout) = child_layout_opt else {
661 continue;
662 };
663 let is_fixed: bool = child_layout.get_position() == Position::Fixed;
664 let ref_origin: Point = if is_fixed {
665 Point::new(0.0, 0.0)
666 } else {
667 content_origin
668 };
669 let ref_size: Size = if is_fixed { viewport } else { inner_avail };
670 let resolved_w: Option<f32> = child_layout
671 .get_width()
672 .resolve(ref_size.get_width(), viewport);
673 let resolved_h: Option<f32> = child_layout
674 .get_height()
675 .resolve(ref_size.get_height(), viewport);
676 let needs_intrinsic: bool = (resolved_w.is_none()
677 && child_layout.left_offset().is_none()
678 && child_layout.right_offset().is_some())
679 || (resolved_h.is_none()
680 && child_layout.top_offset().is_none()
681 && child_layout.bottom_offset().is_some());
682 let probed: Size = if needs_intrinsic {
683 let probe_space: AvailableSpace = AvailableSpace::new(
684 ref_size.get_width(),
685 ref_size.get_height(),
686 viewport,
687 ref_origin.get_x(),
688 ref_origin.get_y(),
689 );
690 self.layout_node(tree, abs_id, probe_space, stats)
691 } else {
692 Size::new(ref_size.get_width(), ref_size.get_height())
693 };
694 let child_w: f32 = resolved_w.unwrap_or(probed.get_width());
695 let child_h: f32 = resolved_h.unwrap_or(probed.get_height());
696 let x: f32 = if let Some(left) = child_layout.left_offset() {
697 ref_origin.get_x() + left
698 } else if let Some(right) = child_layout.right_offset() {
699 ref_origin.get_x() + (ref_size.get_width() - child_w - right)
700 } else {
701 ref_origin.get_x()
702 };
703 let y: f32 = if let Some(top) = child_layout.top_offset() {
704 ref_origin.get_y() + top
705 } else if let Some(bottom) = child_layout.bottom_offset() {
706 ref_origin.get_y() + (ref_size.get_height() - child_h - bottom)
707 } else {
708 ref_origin.get_y()
709 };
710 let abs_space: AvailableSpace =
711 AvailableSpace::new(ref_size.get_width(), ref_size.get_height(), viewport, x, y);
712 let _: Size = self.layout_node(tree, abs_id, abs_space, stats);
713 }
714 self.get_mut_abs_scratch().truncate(abs_start);
715 flow_size
716 }
717
718 fn layout_flex(
734 &mut self,
735 tree: &mut SceneTree,
736 flow_range: (usize, usize),
737 frame: ContainerFrame,
738 direction: FlexDirection,
739 single_pass_ok: bool,
740 stats: &mut LayoutStats,
741 ) -> Size {
742 let (flow_start, flow_end): (usize, usize) = flow_range;
743 let count_all: usize = flow_end.saturating_sub(flow_start);
744 if count_all == 0 {
745 return Size::default();
746 }
747 let parent_layout: LayoutStyle = frame.get_parent_layout();
748 let inner_avail: Size = frame.get_inner_avail();
749 let viewport: Size = frame.get_viewport();
750 let content_origin: Point = frame.get_content_origin();
751 let is_row: bool = matches!(direction, FlexDirection::Row | FlexDirection::RowReverse);
752 let is_reverse: bool = matches!(
753 direction,
754 FlexDirection::RowReverse | FlexDirection::ColumnReverse
755 );
756 let main_gap: f32 = if is_row {
757 parent_layout.get_column_gap()
758 } else {
759 parent_layout.get_row_gap()
760 };
761 let cross_gap: f32 = if is_row {
762 parent_layout.get_row_gap()
763 } else {
764 parent_layout.get_column_gap()
765 };
766 let main_avail: f32 = if is_row {
767 inner_avail.get_width()
768 } else {
769 inner_avail.get_height()
770 };
771 let cross_avail: f32 = if is_row {
772 inner_avail.get_height()
773 } else {
774 inner_avail.get_width()
775 };
776 if is_reverse {
777 self.get_mut_flow_scratch()[flow_start..flow_end].reverse();
778 }
779 let wrap_enabled: bool = parent_layout.get_flex_wrap() == FlexWrap::Wrap;
780 if single_pass_ok {
781 let parent_align: AlignItems = parent_layout.get_align_items();
782 let mut main_cursor: f32 = 0.0;
783 let mut max_cross: f32 = 0.0;
784 let records_start: usize = self.get_flex_items_scratch().len();
785 for offset in 0..count_all {
786 let child_id: NodeId = self.get_flow_scratch()[flow_start + offset];
787 let (margin, align, width_auto, height_auto, clean_cache): (
788 Edges,
789 AlignItems,
790 bool,
791 bool,
792 Option<(AvailableSpace, Size)>,
793 ) = if let Some(node) = tree.get_node(child_id) {
794 let Style {
795 layout: child_layout,
796 ..
797 } = node.style_ref();
798 let a: AlignItems = match child_layout.get_align_self() {
799 AlignSelf::Auto => parent_align,
800 AlignSelf::Stretch => AlignItems::Stretch,
801 AlignSelf::Start => AlignItems::Start,
802 AlignSelf::Center => AlignItems::Center,
803 AlignSelf::End => AlignItems::End,
804 };
805 let cached: Option<(AvailableSpace, Size)> =
806 if !node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
807 && let Some(prev_space) = node.cached_constraint()
808 {
809 let prev_bounds: Rect = node.get_layout_box().get_bounds();
810 Some((
811 prev_space,
812 Size::new(prev_bounds.get_width(), prev_bounds.get_height()),
813 ))
814 } else {
815 None
816 };
817 (
818 child_layout.get_margin(),
819 a,
820 child_layout.get_width() == Length::Auto,
821 child_layout.get_height() == Length::Auto,
822 cached,
823 )
824 } else {
825 (Edges::default(), parent_align, true, true, None)
826 };
827 let (x, y): (f32, f32) = if is_row {
828 (
829 content_origin.get_x() + main_cursor + margin.get_left(),
830 content_origin.get_y() + margin.get_top(),
831 )
832 } else {
833 (
834 content_origin.get_x() + margin.get_left(),
835 content_origin.get_y() + main_cursor + margin.get_top(),
836 )
837 };
838 let stretch_w: bool = !is_row && align == AlignItems::Stretch && width_auto;
839 let stretch_h: bool = is_row && align == AlignItems::Stretch && height_auto;
840 let space_w: f32 = if stretch_w {
841 (inner_avail.get_width() - margin.horizontal()).max(0.0)
842 } else {
843 inner_avail.get_width()
844 };
845 let space_h: f32 = if stretch_h {
846 (inner_avail.get_height() - margin.vertical()).max(0.0)
847 } else {
848 inner_avail.get_height()
849 };
850 let final_space: AvailableSpace =
851 AvailableSpace::new(space_w, space_h, viewport, x, y)
852 .with_stretch(stretch_w, stretch_h);
853 let placed: Size = if let Some((prev_space, prev_size)) = clean_cache
854 && prev_space.can_reuse(final_space)
855 {
856 if !prev_space.same_origin(final_space) {
857 let dx: f32 = x - prev_space.get_origin_x();
858 let dy: f32 = y - prev_space.get_origin_y();
859 self.translate_subtree(tree, child_id, dx, dy);
860 }
861 stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
862 prev_size
863 } else {
864 self.layout_node(tree, child_id, final_space, stats)
865 };
866 let target_w: f32 = if stretch_w {
867 space_w.max(placed.get_width())
868 } else {
869 placed.get_width()
870 };
871 let target_h: f32 = if stretch_h {
872 space_h.max(placed.get_height())
873 } else {
874 placed.get_height()
875 };
876 if (stretch_w && target_w > placed.get_width() + 0.01)
877 || (stretch_h && target_h > placed.get_height() + 0.01)
878 {
879 self.record_layout_snapshot(tree, child_id);
880 if let Some(node) = tree.get_node_mut(child_id) {
881 let mut b: Rect = node.get_layout_box().get_bounds();
882 b.set_width(target_w);
883 b.set_height(target_h);
884 node.get_mut_layout_box().set_bounds(b);
885 }
886 }
887 if stretch_w {
888 self.get_mut_flex_items_scratch().push(FlexItemRecord {
889 node_id: child_id,
890 size: Size::new(target_w, target_h),
891 probed_size: Size::default(),
892 probed_origin: Point::default(),
893 margin,
894 flex_grow: 0.0,
895 align_self: AlignSelf::Stretch,
896 overflow: Overflow::Visible,
897 flags: 0,
898 });
899 }
900 if is_row {
901 main_cursor += target_w + margin.horizontal();
902 max_cross = max_cross.max(target_h + margin.vertical());
903 } else {
904 main_cursor += target_h + margin.vertical();
905 max_cross = max_cross.max(target_w + margin.horizontal());
906 }
907 if offset + 1 < count_all {
908 main_cursor += main_gap;
909 }
910 }
911 let records_end: usize = self.get_flex_items_scratch().len();
912 if records_end > records_start && max_cross > cross_avail + 0.5 {
913 for rec_idx in records_start..records_end {
914 let rec: FlexItemRecord = self.get_flex_items_scratch()[rec_idx];
915 let widened: f32 =
916 (max_cross - rec.margin.horizontal()).max(rec.size.get_width());
917 self.record_layout_snapshot(tree, rec.node_id);
918 if let Some(node) = tree.get_node_mut(rec.node_id) {
919 let mut b: Rect = node.get_layout_box().get_bounds();
920 b.set_width(widened);
921 node.get_mut_layout_box().set_bounds(b);
922 }
923 }
924 }
925 self.get_mut_flex_items_scratch().truncate(records_start);
926 return if is_row {
927 Size::new(main_cursor, max_cross)
928 } else {
929 Size::new(max_cross, main_cursor)
930 };
931 }
932 let items_start: usize = self.get_flex_items_scratch().len();
933 let probe_template: AvailableSpace = AvailableSpace::new(
934 inner_avail.get_width(),
935 inner_avail.get_height(),
936 viewport,
937 content_origin.get_x(),
938 content_origin.get_y(),
939 );
940 let mut total_grow: f32 = 0.0;
941 let mut single_line_main: f32 = 0.0;
942 let mut single_line_cross: f32 = 0.0;
943 for flow_idx in flow_start..flow_end {
944 let child_id: NodeId = self.get_flow_scratch()[flow_idx];
945 let mut rec: FlexItemRecord = FlexItemRecord {
946 node_id: child_id,
947 size: Size::default(),
948 probed_size: Size::default(),
949 probed_origin: Point::default(),
950 margin: Edges::default(),
951 flex_grow: 0.0,
952 align_self: AlignSelf::Auto,
953 overflow: Overflow::Visible,
954 flags: FLEX_ITEM_DEFAULT_LEAF_FLAGS,
955 };
956 let mut zero_basis_size: Option<Size> = None;
957 let mut clean_probe: Option<(Size, Point)> = None;
958 if let Some(node) = tree.get_node(child_id) {
959 let style_ref: &Style = node.style_ref();
960 let Style {
961 layout: child_layout,
962 paint: child_paint,
963 ..
964 } = style_ref;
965 let width_len: Length = child_layout.get_width();
966 let height_len: Length = child_layout.get_height();
967 let grow: f32 = child_layout.get_flex_grow();
968 let width_auto: bool = width_len == Length::Auto;
969 let height_auto: bool = height_len == Length::Auto;
970 let is_leaf: bool = matches!(
971 node.get_kind(),
972 NodeKind::Text(_) | NodeKind::Image(_) | NodeKind::Input(_)
973 ) || node.get_children().is_empty();
974 let mut f: u16 = 0;
975 if width_auto {
976 f |= FLEX_ITEM_WIDTH_AUTO;
977 }
978 if height_auto {
979 f |= FLEX_ITEM_HEIGHT_AUTO;
980 }
981 if matches!(width_len, Length::Percent(_)) {
982 f |= FLEX_ITEM_WIDTH_PERCENT;
983 }
984 if matches!(height_len, Length::Percent(_)) {
985 f |= FLEX_ITEM_HEIGHT_PERCENT;
986 }
987 if matches!(child_layout.get_min_width(), Length::Percent(_))
988 || matches!(child_layout.get_max_width(), Length::Percent(_))
989 {
990 f |= FLEX_ITEM_MINMAX_W_PERCENT;
991 }
992 if matches!(child_layout.get_min_height(), Length::Percent(_))
993 || matches!(child_layout.get_max_height(), Length::Percent(_))
994 {
995 f |= FLEX_ITEM_MINMAX_H_PERCENT;
996 }
997 if child_layout.aspect_ratio_value().is_some() {
998 f |= FLEX_ITEM_HAS_ASPECT_RATIO;
999 }
1000 if child_layout.get_min_height() != Length::Auto
1001 || child_layout.get_max_height() != Length::Auto
1002 {
1003 f |= FLEX_ITEM_MINMAX_H_SET;
1004 }
1005 if is_leaf {
1006 f |= FLEX_ITEM_IS_LEAF;
1007 }
1008 let zero_basis: bool =
1009 !wrap_enabled && grow > 0.0 && if is_row { width_auto } else { height_auto };
1010 if zero_basis {
1011 zero_basis_size = if is_row {
1012 let h: f32 = height_len.resolve(cross_avail, viewport).unwrap_or(0.0);
1013 Some(Size::new(0.0, h))
1014 } else {
1015 let w: f32 = width_len.resolve(cross_avail, viewport).unwrap_or(0.0);
1016 Some(Size::new(w, 0.0))
1017 };
1018 } else if !node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
1019 && let Some(prev) = node.cached_constraint()
1020 && prev.can_reuse(probe_template)
1021 {
1022 let b: Rect = node.get_layout_box().get_bounds();
1023 let probed_h: f32 = if is_leaf
1024 && height_auto
1025 && (f & (FLEX_ITEM_MINMAX_H_SET | FLEX_ITEM_HAS_ASPECT_RATIO)) == 0
1026 {
1027 let pad: Edges = child_layout.get_padding();
1028 let bw: f32 = child_paint.get_border().get_width();
1029 let chrome_v: f32 = pad.vertical() + bw * 2.0;
1030 (node.get_layout_box().get_content_size().get_height() + chrome_v).max(0.0)
1031 } else {
1032 b.get_height()
1033 };
1034 clean_probe = Some((
1035 Size::new(b.get_width(), probed_h),
1036 Point::new(prev.get_origin_x(), prev.get_origin_y()),
1037 ));
1038 }
1039 rec.margin = child_layout.get_margin();
1040 rec.flex_grow = grow;
1041 rec.align_self = child_layout.get_align_self();
1042 rec.overflow = child_layout.get_overflow();
1043 rec.flags = f;
1044 }
1045 total_grow += rec.flex_grow;
1046 let (child_size, probed_origin): (Size, Point) = if let Some(zb) = zero_basis_size {
1047 (zb, content_origin)
1048 } else if let Some((cached_size, cached_origin)) = clean_probe {
1049 rec.flags |= FLEX_ITEM_PROBED;
1050 stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
1051 (cached_size, cached_origin)
1052 } else {
1053 let measured: Size = self.layout_node(tree, child_id, probe_template, stats);
1054 rec.flags |= FLEX_ITEM_PROBED;
1055 (measured, content_origin)
1056 };
1057 if !wrap_enabled {
1058 if is_row {
1059 single_line_main += child_size.get_width() + rec.margin.horizontal();
1060 single_line_cross =
1061 single_line_cross.max(child_size.get_height() + rec.margin.vertical());
1062 } else {
1063 single_line_main += child_size.get_height() + rec.margin.vertical();
1064 single_line_cross =
1065 single_line_cross.max(child_size.get_width() + rec.margin.horizontal());
1066 }
1067 }
1068 rec.size = child_size;
1069 rec.probed_size = child_size;
1070 rec.probed_origin = probed_origin;
1071 self.get_mut_flex_items_scratch().push(rec);
1072 }
1073 let items_end: usize = self.get_flex_items_scratch().len();
1074 if !wrap_enabled {
1075 let line_ctx: FlexLineContext = FlexLineContext {
1076 frame,
1077 is_row,
1078 wrap_enabled: false,
1079 main_gap,
1080 main_avail,
1081 cross_avail,
1082 total_grow,
1083 line_count: 1,
1084 };
1085 let line_size: Size = self.layout_flex_line(
1086 tree,
1087 (items_start, items_end),
1088 0.0,
1089 Some((single_line_main, single_line_cross)),
1090 line_ctx,
1091 stats,
1092 );
1093 self.get_mut_flex_items_scratch().truncate(items_start);
1094 return line_size;
1095 }
1096 let lines_start: usize = self.get_flex_lines_scratch().len();
1097 let mut cur_line_start: usize = items_start;
1098 let mut line_main: f32 = 0.0;
1099 for item_idx in items_start..items_end {
1100 let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1101 let item_main: f32 = if is_row {
1102 item.size.get_width() + item.margin.horizontal()
1103 } else {
1104 item.size.get_height() + item.margin.vertical()
1105 };
1106 let line_empty: bool = item_idx == cur_line_start;
1107 let needed: f32 = if line_empty {
1108 item_main
1109 } else {
1110 line_main + main_gap + item_main
1111 };
1112 if !line_empty && needed > main_avail && main_avail > 0.0 {
1113 self.get_mut_flex_lines_scratch()
1114 .push((cur_line_start, item_idx));
1115 cur_line_start = item_idx;
1116 line_main = item_main;
1117 } else {
1118 line_main = needed;
1119 }
1120 }
1121 if cur_line_start < items_end {
1122 self.get_mut_flex_lines_scratch()
1123 .push((cur_line_start, items_end));
1124 }
1125 let lines_end: usize = self.get_flex_lines_scratch().len();
1126 let mut cross_cursor: f32 = 0.0;
1127 let mut max_main_extent: f32 = 0.0;
1128 let line_count: usize = lines_end.saturating_sub(lines_start);
1129 let line_ctx: FlexLineContext = FlexLineContext {
1130 frame,
1131 is_row,
1132 wrap_enabled: true,
1133 main_gap,
1134 main_avail,
1135 cross_avail,
1136 total_grow,
1137 line_count,
1138 };
1139 for line_offset in 0..line_count {
1140 let line_range: (usize, usize) =
1141 self.get_flex_lines_scratch()[lines_start + line_offset];
1142 let line_size: Size =
1143 self.layout_flex_line(tree, line_range, cross_cursor, None, line_ctx, stats);
1144 if is_row {
1145 max_main_extent = max_main_extent.max(line_size.get_width());
1146 cross_cursor += line_size.get_height();
1147 } else {
1148 max_main_extent = max_main_extent.max(line_size.get_height());
1149 cross_cursor += line_size.get_width();
1150 }
1151 if line_offset + 1 < line_count {
1152 cross_cursor += cross_gap;
1153 }
1154 }
1155 self.get_mut_flex_lines_scratch().truncate(lines_start);
1156 self.get_mut_flex_items_scratch().truncate(items_start);
1157 if is_row {
1158 Size::new(max_main_extent, cross_cursor)
1159 } else {
1160 Size::new(cross_cursor, max_main_extent)
1161 }
1162 }
1163
1164 #[inline(always)]
1180 fn layout_flex_line(
1181 &mut self,
1182 tree: &mut SceneTree,
1183 line_range: (usize, usize),
1184 cross_cursor: f32,
1185 precomputed: Option<(f32, f32)>,
1186 ctx: FlexLineContext,
1187 stats: &mut LayoutStats,
1188 ) -> Size {
1189 let (line_start, line_end): (usize, usize) = line_range;
1190 let frame: ContainerFrame = ctx.frame;
1191 let is_row: bool = ctx.is_row;
1192 let wrap_enabled: bool = ctx.wrap_enabled;
1193 let main_gap: f32 = ctx.main_gap;
1194 let main_avail: f32 = ctx.main_avail;
1195 let cross_avail: f32 = ctx.cross_avail;
1196 let total_grow: f32 = ctx.total_grow;
1197 let line_count: usize = ctx.line_count;
1198 let parent_layout: LayoutStyle = frame.get_parent_layout();
1199 let inner_avail: Size = frame.get_inner_avail();
1200 let viewport: Size = frame.get_viewport();
1201 let content_origin: Point = frame.get_content_origin();
1202 let count: usize = line_end.saturating_sub(line_start);
1203 let gaps_total: f32 = if count > 1 {
1204 main_gap * ((count - 1) as f32)
1205 } else {
1206 0.0
1207 };
1208 let has_definite_or_grow: bool = frame.get_definite_width() || total_grow > 0.0;
1209 let effective_main_avail: f32 = if is_row {
1210 if has_definite_or_grow || wrap_enabled {
1211 main_avail
1212 } else {
1213 parent_layout
1214 .get_min_width()
1215 .resolve(viewport.get_width(), viewport)
1216 .map(|mw: f32| (mw - parent_layout.get_padding().horizontal()).max(0.0))
1217 .unwrap_or(0.0)
1218 }
1219 } else if frame.get_definite_height() {
1220 main_avail
1221 } else {
1222 parent_layout
1223 .get_min_height()
1224 .resolve(viewport.get_height(), viewport)
1225 .map(|mh: f32| (mh - parent_layout.get_padding().vertical()).max(0.0))
1226 .unwrap_or(0.0)
1227 };
1228 let (final_used_main, line_cross): (f32, f32) = if let Some((items_main, pre_cross)) =
1229 precomputed
1230 && total_grow == 0.0
1231 {
1232 (items_main + gaps_total, pre_cross)
1233 } else {
1234 let used_main: f32 = if let Some((items_main, _)) = precomputed {
1235 items_main + gaps_total
1236 } else {
1237 let mut acc: f32 = gaps_total;
1238 for item_idx in line_start..line_end {
1239 let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1240 let sz: f32 = if is_row {
1241 item.size.get_width() + item.margin.horizontal()
1242 } else {
1243 item.size.get_height() + item.margin.vertical()
1244 };
1245 acc += sz;
1246 }
1247 acc
1248 };
1249 let free_main: f32 = (effective_main_avail - used_main).max(0.0);
1250 if total_grow > 0.0 && free_main > 0.0 && !wrap_enabled {
1251 for item_idx in line_start..line_end {
1252 let item: &mut FlexItemRecord =
1253 &mut self.get_mut_flex_items_scratch()[item_idx];
1254 let grow: f32 = item.flex_grow;
1255 if grow > 0.0 {
1256 let extra: f32 = free_main * (grow / total_grow);
1257 if is_row {
1258 item.size.set_width(item.size.get_width() + extra);
1259 } else {
1260 item.size.set_height(item.size.get_height() + extra);
1261 }
1262 }
1263 }
1264 }
1265 if !wrap_enabled && total_grow > 0.0 {
1266 for item_idx in line_start..line_end {
1267 let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1268 let auto_cross: bool = item.flex_grow > 0.0
1269 && if is_row {
1270 (item.flags & FLEX_ITEM_HEIGHT_AUTO) != 0
1271 } else {
1272 (item.flags & FLEX_ITEM_WIDTH_AUTO) != 0
1273 };
1274 if auto_cross {
1275 let probe_w: f32 = if is_row {
1276 item.size.get_width()
1277 } else {
1278 cross_avail
1279 };
1280 let probe_h: f32 = if is_row {
1281 cross_avail
1282 } else {
1283 item.size.get_height()
1284 };
1285 let probe_sp: AvailableSpace = AvailableSpace::new(
1286 probe_w,
1287 probe_h,
1288 viewport,
1289 content_origin.get_x(),
1290 content_origin.get_y(),
1291 );
1292 let measured: Size = self.layout_node(tree, item.node_id, probe_sp, stats);
1293 let slot: &mut FlexItemRecord =
1294 &mut self.get_mut_flex_items_scratch()[item_idx];
1295 if is_row {
1296 slot.size.set_height(measured.get_height());
1297 } else {
1298 slot.size.set_width(measured.get_width());
1299 }
1300 slot.flags &= !FLEX_ITEM_PROBED;
1301 }
1302 }
1303 }
1304 let mut sum_main: f32 = gaps_total;
1305 let mut max_cross: f32 = 0.0;
1306 for item_idx in line_start..line_end {
1307 let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1308 if is_row {
1309 sum_main += item.size.get_width() + item.margin.horizontal();
1310 max_cross = max_cross.max(item.size.get_height() + item.margin.vertical());
1311 } else {
1312 sum_main += item.size.get_height() + item.margin.vertical();
1313 max_cross = max_cross.max(item.size.get_width() + item.margin.horizontal());
1314 }
1315 }
1316 (sum_main, max_cross)
1317 };
1318 let rem: f32 = (effective_main_avail - final_used_main).max(0.0);
1319 let (mut main_cursor, extra_step): (f32, f32) = match parent_layout.get_justify_content() {
1320 JustifyContent::Start => (0.0, 0.0),
1321 JustifyContent::Center => (rem * 0.5, 0.0),
1322 JustifyContent::End => (rem, 0.0),
1323 JustifyContent::SpaceBetween => {
1324 if count > 1 {
1325 (0.0, rem / ((count - 1) as f32))
1326 } else {
1327 (0.0, 0.0)
1328 }
1329 }
1330 JustifyContent::SpaceAround => {
1331 let slot: f32 = rem / (count.max(1) as f32);
1332 (slot * 0.5, slot)
1333 }
1334 JustifyContent::SpaceEvenly => {
1335 let slot: f32 = rem / ((count + 1) as f32);
1336 (slot, slot)
1337 }
1338 };
1339 let definite_cross: bool = !is_row || frame.get_definite_height();
1340 let effective_line_cross: f32 = if line_count == 1 && !wrap_enabled && definite_cross {
1341 line_cross.max(cross_avail)
1342 } else {
1343 line_cross
1344 };
1345 let mut actual_line_cross: f32 = line_cross;
1346 let parent_align: AlignItems = parent_layout.get_align_items();
1347 for idx in 0..count {
1348 let rec: FlexItemRecord = self.get_flex_items_scratch()[line_start + idx];
1349 let child_id: NodeId = rec.node_id;
1350 let child_size: Size = rec.size;
1351 let margin: Edges = rec.margin;
1352 let width_auto: bool = (rec.flags & FLEX_ITEM_WIDTH_AUTO) != 0;
1353 let height_auto: bool = (rec.flags & FLEX_ITEM_HEIGHT_AUTO) != 0;
1354 let is_leaf: bool = (rec.flags & FLEX_ITEM_IS_LEAF) != 0;
1355 let item_cross: f32 = if is_row {
1356 child_size.get_height()
1357 } else {
1358 child_size.get_width()
1359 };
1360 let align: AlignItems = match rec.align_self {
1361 AlignSelf::Auto => parent_align,
1362 AlignSelf::Stretch => AlignItems::Stretch,
1363 AlignSelf::Start => AlignItems::Start,
1364 AlignSelf::Center => AlignItems::Center,
1365 AlignSelf::End => AlignItems::End,
1366 };
1367 let avail_item_cross: f32 = (effective_line_cross
1368 - if is_row {
1369 margin.vertical()
1370 } else {
1371 margin.horizontal()
1372 })
1373 .max(0.0);
1374 let cross_offset: f32 = match align {
1375 AlignItems::Start | AlignItems::Stretch => 0.0,
1376 AlignItems::Center => ((avail_item_cross - item_cross) * 0.5).max(0.0),
1377 AlignItems::End => (avail_item_cross - item_cross).max(0.0),
1378 };
1379 let auto_cross_grow: bool = !wrap_enabled
1380 && rec.flex_grow > 0.0
1381 && if is_row { height_auto } else { width_auto };
1382 let target_w: f32 = if !is_row && align == AlignItems::Stretch && width_auto {
1383 avail_item_cross.max(child_size.get_width())
1384 } else {
1385 child_size.get_width()
1386 };
1387 let target_h: f32 = if is_row && align == AlignItems::Stretch && height_auto {
1388 avail_item_cross.max(child_size.get_height())
1389 } else {
1390 child_size.get_height()
1391 };
1392 let (x, y): (f32, f32) = if is_row {
1393 (
1394 content_origin.get_x() + main_cursor + margin.get_left(),
1395 content_origin.get_y() + cross_cursor + cross_offset + margin.get_top(),
1396 )
1397 } else {
1398 (
1399 content_origin.get_x() + cross_cursor + cross_offset + margin.get_left(),
1400 content_origin.get_y() + main_cursor + margin.get_top(),
1401 )
1402 };
1403 let space_w: f32 = if (rec.flags & FLEX_ITEM_WIDTH_PERCENT) != 0 {
1404 inner_avail.get_width()
1405 } else if auto_cross_grow && !is_row {
1406 cross_avail
1407 } else {
1408 target_w
1409 };
1410 let space_h: f32 = if (rec.flags & FLEX_ITEM_HEIGHT_PERCENT) != 0 {
1411 inner_avail.get_height()
1412 } else if auto_cross_grow && is_row {
1413 cross_avail
1414 } else {
1415 target_h
1416 };
1417 let stretch_child_w: bool = !(auto_cross_grow && !is_row)
1418 && ((!is_row && align == AlignItems::Stretch && width_auto)
1419 || (is_row && rec.flex_grow > 0.0 && width_auto));
1420 let stretch_child_h: bool = !(auto_cross_grow && is_row)
1421 && ((is_row && align == AlignItems::Stretch && height_auto)
1422 || (!is_row && rec.flex_grow > 0.0 && height_auto));
1423 let same_w: bool = (target_w - rec.probed_size.get_width()).abs() <= 0.001;
1424 let same_h: bool = (target_h - rec.probed_size.get_height()).abs() <= 0.001;
1425 let width_fixed_or_leaf: bool = is_leaf || !width_auto;
1426 let width_no_pct_bounds: bool = (rec.flags & FLEX_ITEM_MINMAX_W_PERCENT) == 0;
1427 let width_invariant: bool = (space_w - inner_avail.get_width()).abs() <= 0.01
1428 || (width_fixed_or_leaf && width_no_pct_bounds);
1429 let height_fixed_or_leaf: bool = is_leaf || !height_auto;
1430 let height_no_pct_bounds: bool = (rec.flags & FLEX_ITEM_MINMAX_H_PERCENT) == 0;
1431 let height_invariant: bool = (space_h - inner_avail.get_height()).abs() <= 0.01
1432 || (height_fixed_or_leaf && height_no_pct_bounds);
1433 let probed_ok: bool = (rec.flags & FLEX_ITEM_PROBED) != 0
1434 && !auto_cross_grow
1435 && (rec.flags & FLEX_ITEM_HAS_ASPECT_RATIO) == 0
1436 && width_invariant
1437 && height_invariant;
1438 let can_translate_exact: bool = probed_ok
1439 && same_w
1440 && same_h
1441 && (is_leaf || (!stretch_child_w && !stretch_child_h));
1442 let can_stretch_leaf_h: bool = probed_ok
1443 && is_leaf
1444 && is_row
1445 && same_w
1446 && !stretch_child_w
1447 && stretch_child_h
1448 && height_auto
1449 && (rec.flags & FLEX_ITEM_MINMAX_H_SET) == 0;
1450 if can_translate_exact {
1451 let dx: f32 = x - rec.probed_origin.get_x();
1452 let dy: f32 = y - rec.probed_origin.get_y();
1453 if dx.abs() > 0.001 || dy.abs() > 0.001 {
1454 self.translate_subtree(tree, child_id, dx, dy);
1455 }
1456 } else if can_stretch_leaf_h {
1457 self.record_layout_snapshot(tree, child_id);
1458 if let Some(node) = tree.get_node_mut(child_id) {
1459 let cur_bounds: Rect = node.get_layout_box().get_bounds();
1460 let same_box: bool = (cur_bounds.get_x() - x).abs() <= 0.001
1461 && (cur_bounds.get_y() - y).abs() <= 0.001
1462 && (cur_bounds.get_width() - target_w).abs() <= 0.001
1463 && (cur_bounds.get_height() - target_h).abs() <= 0.001;
1464 if !same_box {
1465 let Style {
1466 layout: child_layout,
1467 paint: child_paint,
1468 ..
1469 } = node.style_ref();
1470 let pad: Edges = child_layout.get_padding();
1471 let bw: f32 = child_paint.get_border().get_width();
1472 let chrome_h: f32 = pad.horizontal() + bw * 2.0;
1473 let chrome_v: f32 = pad.vertical() + bw * 2.0;
1474 let new_bounds: Rect = Rect::new(x, y, target_w, target_h);
1475 let new_content: Rect = Rect::new(
1476 x + pad.get_left() + bw,
1477 y + pad.get_top() + bw,
1478 (target_w - chrome_h).max(0.0),
1479 (target_h - chrome_v).max(0.0),
1480 );
1481 node.get_mut_layout_box().set_bounds(new_bounds);
1482 node.get_mut_layout_box().set_content_bounds(new_content);
1483 if let Some(mut c) = node.cached_constraint() {
1484 c.set_origin_x(x);
1485 c.set_origin_y(y);
1486 node.set_last_constraint(Some(c));
1487 }
1488 }
1489 }
1490 } else {
1491 let final_space: AvailableSpace =
1492 AvailableSpace::new(space_w, space_h, viewport, x, y)
1493 .with_stretch(stretch_child_w, stretch_child_h);
1494 let placed: Size = self.layout_node(tree, child_id, final_space, stats);
1495 self.record_layout_snapshot(tree, child_id);
1496 if let Some(node) = tree.get_node_mut(child_id) {
1497 let mut b: Rect = node.get_layout_box().get_bounds();
1498 let is_clipped: bool =
1499 matches!(rec.overflow, Overflow::Hidden | Overflow::Scroll);
1500 if auto_cross_grow {
1501 if is_row {
1502 b.set_width(target_w);
1503 b.set_height(placed.get_height());
1504 actual_line_cross =
1505 actual_line_cross.max(placed.get_height() + margin.vertical());
1506 } else {
1507 b.set_width(placed.get_width());
1508 b.set_height(target_h);
1509 actual_line_cross =
1510 actual_line_cross.max(placed.get_width() + margin.horizontal());
1511 }
1512 } else if is_clipped || rec.flex_grow > 0.0 {
1513 b.set_width(target_w);
1514 b.set_height(target_h);
1515 } else {
1516 b.set_width(target_w.max(placed.get_width()));
1517 b.set_height(target_h.max(placed.get_height()));
1518 }
1519 node.get_mut_layout_box().set_bounds(b);
1520 }
1521 }
1522 let advance: f32 = if is_row {
1523 target_w + margin.horizontal()
1524 } else {
1525 target_h + margin.vertical()
1526 };
1527 main_cursor += advance;
1528 if idx + 1 < count {
1529 main_cursor += main_gap + extra_step;
1530 }
1531 }
1532 if is_row {
1533 Size::new(final_used_main, actual_line_cross)
1534 } else {
1535 Size::new(actual_line_cross, final_used_main)
1536 }
1537 }
1538
1539 fn layout_grid(
1554 &mut self,
1555 tree: &mut SceneTree,
1556 flow_start: usize,
1557 flow_end: usize,
1558 frame: ContainerFrame,
1559 stats: &mut LayoutStats,
1560 ) -> Size {
1561 if flow_start >= flow_end {
1562 return Size::default();
1563 }
1564 let parent_layout: LayoutStyle = frame.get_parent_layout();
1565 let inner_avail: Size = frame.get_inner_avail();
1566 let viewport: Size = frame.get_viewport();
1567 let content_origin: Point = frame.get_content_origin();
1568 let cols: usize = (parent_layout.get_grid_columns() as usize).max(1);
1569 let col_gap: f32 = parent_layout.get_column_gap();
1570 let row_gap: f32 = parent_layout.get_row_gap();
1571 let total_col_gaps: f32 = col_gap * ((cols.saturating_sub(1)) as f32);
1572 let col_w: f32 = ((inner_avail.get_width() - total_col_gaps) / (cols as f32)).max(0.0);
1573 let col_step: f32 = col_w + col_gap;
1574 let origin_x: f32 = content_origin.get_x();
1575 let origin_y: f32 = content_origin.get_y();
1576 let inner_h: f32 = inner_avail.get_height();
1577 let mut y_cursor: f32 = 0.0;
1578 let mut idx: usize = flow_start;
1579 while idx < flow_end {
1580 let row_end: usize = (idx + cols).min(flow_end);
1581 let mut row_h: f32 = 0.0;
1582 let mut min_row_h: f32 = f32::INFINITY;
1583 let y: f32 = origin_y + y_cursor;
1584 let mut x: f32 = origin_x;
1585 for pos in idx..row_end {
1586 let child_id: NodeId = self.get_flow_scratch()[pos];
1587 let (auto_w, clean_cache): (bool, Option<(AvailableSpace, Size)>) =
1588 if let Some(n) = tree.get_node(child_id) {
1589 let Style { layout, .. } = n.style_ref();
1590 let is_auto_w: bool = layout.get_width() == Length::Auto;
1591 let cached: Option<(AvailableSpace, Size)> =
1592 if !n.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
1593 && let Some(prev_space) = n.cached_constraint()
1594 {
1595 let prev_bounds: Rect = n.get_layout_box().get_bounds();
1596 Some((
1597 prev_space,
1598 Size::new(prev_bounds.get_width(), prev_bounds.get_height()),
1599 ))
1600 } else {
1601 None
1602 };
1603 (is_auto_w, cached)
1604 } else {
1605 (false, None)
1606 };
1607 let cell_space: AvailableSpace =
1608 AvailableSpace::new(col_w, inner_h, viewport, x, y).with_stretch(auto_w, false);
1609 let child_size: Size = if let Some((prev_space, prev_size)) = clean_cache
1610 && prev_space.can_reuse(cell_space)
1611 {
1612 if !prev_space.same_origin(cell_space) {
1613 let dx: f32 = x - prev_space.get_origin_x();
1614 let dy: f32 = y - prev_space.get_origin_y();
1615 self.translate_subtree(tree, child_id, dx, dy);
1616 }
1617 stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
1618 prev_size
1619 } else {
1620 self.layout_node(tree, child_id, cell_space, stats)
1621 };
1622 if (child_size.get_width() - col_w).abs() > 0.001 {
1623 self.record_layout_snapshot(tree, child_id);
1624 if let Some(node) = tree.get_node_mut(child_id) {
1625 let mut b: Rect = node.get_layout_box().get_bounds();
1626 b.set_width(col_w);
1627 node.get_mut_layout_box().set_bounds(b);
1628 }
1629 }
1630 let ch: f32 = child_size.get_height();
1631 row_h = row_h.max(ch);
1632 min_row_h = min_row_h.min(ch);
1633 x += col_step;
1634 }
1635 if row_end - idx > 1 && min_row_h < row_h {
1636 for pos in idx..row_end {
1637 let child_id: NodeId = self.get_flow_scratch()[pos];
1638 let needs_stretch: bool =
1639 tree.get_node(child_id).is_some_and(|n: &SceneNode| {
1640 n.get_layout_box().get_bounds().get_height() < row_h
1641 });
1642 if needs_stretch {
1643 self.record_layout_snapshot(tree, child_id);
1644 if let Some(node) = tree.get_node_mut(child_id) {
1645 let mut b: Rect = node.get_layout_box().get_bounds();
1646 b.set_height(row_h);
1647 node.get_mut_layout_box().set_bounds(b);
1648 }
1649 }
1650 }
1651 }
1652 y_cursor += row_h;
1653 if row_end < flow_end {
1654 y_cursor += row_gap;
1655 }
1656 idx = row_end;
1657 }
1658 Size::new(inner_avail.get_width(), y_cursor)
1659 }
1660
1661 fn translate_subtree(&mut self, tree: &mut SceneTree, root_id: NodeId, dx: f32, dy: f32) {
1671 if dx == 0.0 && dy == 0.0 {
1672 return;
1673 }
1674 self.record_layout_snapshot(tree, root_id);
1675 let Some(root_node) = tree.get_node_mut(root_id) else {
1676 return;
1677 };
1678 let Style { layout, .. } = root_node.style_ref();
1679 let root_none_disp: bool = layout.get_display() == Display::None;
1680 if let Some(mut c) = root_node.cached_constraint() {
1681 c.set_origin_x(c.get_origin_x() + dx);
1682 c.set_origin_y(c.get_origin_y() + dy);
1683 root_node.set_last_constraint(Some(c));
1684 }
1685 if root_none_disp {
1686 return;
1687 }
1688 let mut root_bounds: Rect = root_node.get_layout_box().get_bounds();
1689 root_bounds.set_x(root_bounds.get_x() + dx);
1690 root_bounds.set_y(root_bounds.get_y() + dy);
1691 root_node.get_mut_layout_box().set_bounds(root_bounds);
1692 let mut root_content: Rect = root_node.get_layout_box().get_content_bounds();
1693 root_content.set_x(root_content.get_x() + dx);
1694 root_content.set_y(root_content.get_y() + dy);
1695 root_node
1696 .get_mut_layout_box()
1697 .set_content_bounds(root_content);
1698 let root_children: &[NodeId] = root_node.get_children().as_slice();
1699 if root_children.is_empty() {
1700 return;
1701 }
1702 self.get_mut_translate_scratch().clear();
1703 self.get_mut_translate_scratch()
1704 .extend_from_slice(root_children);
1705 while let Some(nid) = self.get_mut_translate_scratch().pop() {
1706 let (is_fixed_pos, is_none_disp): (bool, bool) = match tree.get_node(nid) {
1707 Some(node) => {
1708 let Style { layout, .. } = node.style_ref();
1709 (
1710 layout.get_position() == Position::Fixed,
1711 layout.get_display() == Display::None,
1712 )
1713 }
1714 None => continue,
1715 };
1716 if is_fixed_pos {
1717 continue;
1718 }
1719 if !is_none_disp {
1720 self.record_layout_snapshot(tree, nid);
1721 }
1722 let Some(node) = tree.get_node_mut(nid) else {
1723 continue;
1724 };
1725 if let Some(mut c) = node.cached_constraint() {
1726 c.set_origin_x(c.get_origin_x() + dx);
1727 c.set_origin_y(c.get_origin_y() + dy);
1728 node.set_last_constraint(Some(c));
1729 }
1730 if is_none_disp {
1731 continue;
1732 }
1733 let mut bounds: Rect = node.get_layout_box().get_bounds();
1734 bounds.set_x(bounds.get_x() + dx);
1735 bounds.set_y(bounds.get_y() + dy);
1736 node.get_mut_layout_box().set_bounds(bounds);
1737 let mut content: Rect = node.get_layout_box().get_content_bounds();
1738 content.set_x(content.get_x() + dx);
1739 content.set_y(content.get_y() + dy);
1740 node.get_mut_layout_box().set_content_bounds(content);
1741 let children_slice: &[NodeId] = node.get_children().as_slice();
1742 if !children_slice.is_empty() {
1743 self.get_mut_translate_scratch()
1744 .extend_from_slice(children_slice);
1745 }
1746 }
1747 }
1748}