Skip to main content

euv_core/layout/engine/
impl.rs

1use super::*;
2
3/// Core layout solver and hit-testing operations for `LayoutEngine`.
4impl LayoutEngine {
5    /// Computes layout for the entire `tree` within `viewport`, skipping clean cached subtrees.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Mutable layout engine.
10    /// - `&mut SceneTree` - Retained scene tree to lay out.
11    /// - `Size` - Logical viewport dimensions.
12    ///
13    /// # Returns
14    ///
15    /// - `LayoutStats` - Computed vs cached subtree counts.
16    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    /// Computes layout for `tree` while recording pre/post-layout conservative bounds diffs into a tight `LayoutDamageReport`.
30    ///
31    /// # Arguments
32    ///
33    /// - `&Self` - Mutable layout engine.
34    /// - `&mut SceneTree` - Retained scene tree to lay out.
35    /// - `Size` - Logical viewport dimensions.
36    /// - `f32` - Active display scale factor for outward-rounded physical damage rects.
37    ///
38    /// # Returns
39    ///
40    /// - `(LayoutStats, LayoutDamageReport)` - Layout pass stats and surgical physical damage or fallback cause.
41    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    /// Executes the core layout traversal over `tree` using the current `track_damage` mode.
149    ///
150    /// # Arguments
151    ///
152    /// - `&Self` - Mutable layout engine.
153    /// - `&mut SceneTree` - Retained scene tree to lay out.
154    /// - `Size` - Logical viewport dimensions.
155    ///
156    /// # Returns
157    ///
158    /// - `LayoutStats` - Computed vs cached subtree counts.
159    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    /// Records the first pre-layout geometry snapshot of `node_id` when surgical damage tracking is active.
181    ///
182    /// # Arguments
183    ///
184    /// - `&Self` - Mutable layout engine.
185    /// - `&SceneTree` - Retained scene tree prior to writing `node_id`'s updated layout box.
186    /// - `NodeId` - Target node handle about to be mutated.
187    #[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    /// Returns `true` when two layout rectangles are equal within subpixel tolerance.
238    ///
239    /// # Arguments
240    ///
241    /// - `Rect` - First rectangle.
242    /// - `Rect` - Second rectangle.
243    ///
244    /// # Returns
245    ///
246    /// - `bool` - Whether position and dimensions match within `0.001` logical pixels.
247    #[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    /// Returns `true` when two layout sizes are equal within subpixel tolerance.
256    ///
257    /// # Arguments
258    ///
259    /// - `Size` - First size.
260    /// - `Size` - Second size.
261    ///
262    /// # Returns
263    ///
264    /// - `bool` - Whether width and height match within `0.001` logical pixels.
265    #[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    /// Measures text bounding dimensions through the bounded `TextSizeCache`, delegating misses to `TextMeasurer::measure_size`.
272    ///
273    /// # Arguments
274    ///
275    /// - `&Self` - Mutable layout engine reference.
276    /// - `&str` - UTF-8 text content to measure.
277    /// - `TextStyle` - Active typography style.
278    /// - `Option<f32>` - Optional maximum wrap width in logical pixels.
279    ///
280    /// # Returns
281    ///
282    /// - `Size` - Exact measured bounding dimensions.
283    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    /// Performs recursive layout on `node_id` with O(1) clean-subtree caching.
301    ///
302    /// # Arguments
303    ///
304    /// - `&Self` - Mutable layout engine reference.
305    /// - `&mut SceneTree` - Mutable scene tree.
306    /// - `NodeId` - Node handle to compute.
307    /// - `AvailableSpace` - Parent space constraint and origin.
308    /// - `&mut LayoutStats` - Mutable telemetry counters.
309    ///
310    /// # Returns
311    ///
312    /// - `Size` - Computed border-box dimensions of `node_id`.
313    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 node_overflow: Overflow = layout_ref.get_overflow();
435        let node_flex_grow: f32 = layout_ref.get_flex_grow();
436        let width_independent: bool = explicit_w.is_some()
437            || (stretched_w
438                && resolved_w.is_some()
439                && (node_overflow != Overflow::Visible || node_flex_grow > 0.0));
440        let height_independent: bool =
441            resolved_h.is_some() && layout_ref.get_height() != Length::Auto;
442        let skip_leaf_measure: bool =
443            node_overflow != Overflow::Scroll && width_independent && height_independent;
444        let mut child_range: Option<(usize, usize)> = None;
445        let leaf_content_size: Option<Size> = match node.get_kind() {
446            NodeKind::Text(text) => {
447                if skip_leaf_measure {
448                    Some(Size::new(inner_avail_w, inner_avail_h))
449                } else {
450                    Some(self.measure_text_cached(
451                        text.as_str(),
452                        *text_ref,
453                        Some(inner_avail_w.max(1.0)),
454                    ))
455                }
456            }
457            NodeKind::Image(img) => {
458                Some(Size::new(img.get_width() as f32, img.get_height() as f32))
459            }
460            NodeKind::Input(input_state) => {
461                if skip_leaf_measure {
462                    Some(Size::new(inner_avail_w, inner_avail_h))
463                } else {
464                    let sample: &str = if input_state.get_value().is_empty() {
465                        input_state.get_placeholder().as_str()
466                    } else {
467                        input_state.get_value().as_str()
468                    };
469                    let measured_size: Size =
470                        self.measure_text_cached(sample, *text_ref, Some(inner_avail_w.max(1.0)));
471                    Some(Size::new(
472                        measured_size.get_width().max(120.0),
473                        measured_size.get_height().max(20.0),
474                    ))
475                }
476            }
477            NodeKind::View
478            | NodeKind::ScrollView
479            | NodeKind::Portal
480            | NodeKind::Fragment
481            | NodeKind::Canvas => {
482                let node_children: &[NodeId] = node.get_children().as_slice();
483                if node_children.is_empty() {
484                    Some(Size::default())
485                } else {
486                    let start: usize = self.get_children_scratch().len();
487                    self.get_mut_children_scratch()
488                        .extend_from_slice(node_children);
489                    let end: usize = self.get_children_scratch().len();
490                    child_range = Some((start, end));
491                    None
492                }
493            }
494        };
495        let content_size: Size = if let Some(size) = leaf_content_size {
496            size
497        } else if let Some((child_start, child_end)) = child_range {
498            let frame: ContainerFrame = ContainerFrame::new(
499                *layout_ref,
500                Size::new(inner_avail_w, inner_avail_h),
501                space.get_viewport(),
502                Point::new(content_origin_x, content_origin_y),
503                resolved_w.is_some(),
504                resolved_h.is_some(),
505            );
506            let size: Size = self.layout_children(tree, child_start, child_end, frame, stats);
507            self.get_mut_children_scratch().truncate(child_start);
508            size
509        } else {
510            Size::default()
511        };
512        let content_outer_w: f32 = content_size.get_width() + chrome_h;
513        let content_outer_h: f32 = content_size.get_height() + chrome_v;
514        let mut final_w: f32 = match (explicit_w, stretched_w) {
515            (Some(w), _) => w,
516            (None, true) => {
517                let base_w: f32 = resolved_w.unwrap_or(content_outer_w);
518                if node_overflow == Overflow::Visible
519                    && node_flex_grow <= 0.0
520                    && content_outer_w > base_w + 0.5
521                {
522                    content_outer_w
523                } else {
524                    base_w
525                }
526            }
527            (None, false) => content_outer_w,
528        };
529        let mut final_h: f32 = resolved_h.unwrap_or(content_outer_h);
530        if let Some(ratio) = aspect_ratio
531            && ratio > 0.0
532        {
533            if resolved_w.is_some() && resolved_h.is_none() {
534                final_h = final_w / ratio;
535            } else if resolved_h.is_some() && resolved_w.is_none() {
536                final_w = final_h * ratio;
537            }
538        }
539        final_w = final_w.clamp(min_w, max_w).max(0.0);
540        final_h = final_h.clamp(min_h, max_h).max(0.0);
541        let bounds: Rect = Rect::new(origin_x, origin_y, final_w, final_h);
542        let content_bounds: Rect = Rect::new(
543            content_origin_x,
544            content_origin_y,
545            (final_w - chrome_h).max(0.0),
546            (final_h - chrome_v).max(0.0),
547        );
548        self.record_layout_snapshot(tree, node_id);
549        if let Some(node) = tree.get_node_mut(node_id) {
550            node.get_mut_layout_box().set_bounds(bounds);
551            node.get_mut_layout_box().set_content_bounds(content_bounds);
552            node.get_mut_layout_box().set_content_size(content_size);
553            node.set_last_constraint(Some(space));
554            node.get_mut_dirty().remove(DIRTY_LAYOUT_PASS_MASK);
555        }
556        Size::new(final_w, final_h)
557    }
558
559    /// Lays out children according to Flex, Grid, or Block rules plus Absolute/Fixed overlays.
560    ///
561    /// # Arguments
562    ///
563    /// - `&Self` - Mutable layout engine reference.
564    /// - `&mut SceneTree` - Mutable scene tree.
565    /// - `usize` - Inclusive start index into `children_scratch`.
566    /// - `usize` - Exclusive end index into `children_scratch`.
567    /// - `ContainerFrame` - Parent layout constraints and origin.
568    /// - `&mut LayoutStats` - Mutable telemetry counters.
569    ///
570    /// # Returns
571    ///
572    /// - `Size` - Intrinsic aggregate content size occupied by flow children.
573    fn layout_children(
574        &mut self,
575        tree: &mut SceneTree,
576        child_start: usize,
577        child_end: usize,
578        frame: ContainerFrame,
579        stats: &mut LayoutStats,
580    ) -> Size {
581        let child_count: usize = child_end.saturating_sub(child_start);
582        if child_count == 0 {
583            return Size::default();
584        }
585        let parent_layout: LayoutStyle = frame.get_parent_layout();
586        let inner_avail: Size = frame.get_inner_avail();
587        let viewport: Size = frame.get_viewport();
588        let content_origin: Point = frame.get_content_origin();
589        let flex_dir_opt: Option<FlexDirection> = match parent_layout.get_display() {
590            Display::Grid => None,
591            Display::Block => Some(FlexDirection::Column),
592            Display::Flex | Display::None => Some(parent_layout.get_flex_direction()),
593        };
594        let is_row_dir: bool = matches!(
595            flex_dir_opt,
596            Some(FlexDirection::Row | FlexDirection::RowReverse)
597        );
598        let is_reverse_dir: bool = matches!(
599            flex_dir_opt,
600            Some(FlexDirection::RowReverse | FlexDirection::ColumnReverse)
601        );
602        let parent_align: AlignItems = parent_layout.get_align_items();
603        let parent_height_auto: bool = parent_layout.get_height() == Length::Auto;
604        let mut single_pass_ok: bool = flex_dir_opt.is_some()
605            && parent_layout.get_flex_wrap() != FlexWrap::Wrap
606            && !is_reverse_dir
607            && parent_layout.get_justify_content() == JustifyContent::Start;
608        let flow_start: usize = self.get_flow_scratch().len();
609        let abs_start: usize = self.get_abs_scratch().len();
610        for idx in child_start..child_end {
611            let child_id: NodeId = self.get_children_scratch()[idx];
612            if let Some(child_node) = tree.get_node(child_id) {
613                let Style {
614                    layout: child_layout,
615                    ..
616                } = child_node.style_ref();
617                if child_layout.get_display() == Display::None {
618                    let _: Size = self.layout_node(
619                        tree,
620                        child_id,
621                        AvailableSpace::new(0.0, 0.0, viewport, 0.0, 0.0),
622                        stats,
623                    );
624                    continue;
625                }
626                match child_layout.get_position() {
627                    Position::Relative => {
628                        if single_pass_ok {
629                            if child_layout.get_flex_grow() > 0.0 {
630                                single_pass_ok = false;
631                            } else {
632                                let align: AlignItems = match child_layout.get_align_self() {
633                                    AlignSelf::Auto => parent_align,
634                                    AlignSelf::Stretch => AlignItems::Stretch,
635                                    AlignSelf::Start => AlignItems::Start,
636                                    AlignSelf::Center => AlignItems::Center,
637                                    AlignSelf::End => AlignItems::End,
638                                };
639                                let non_start_align: bool =
640                                    matches!(align, AlignItems::Center | AlignItems::End);
641                                let auto_row_stretch: bool = align == AlignItems::Stretch
642                                    && is_row_dir
643                                    && child_layout.get_height() == Length::Auto
644                                    && parent_height_auto;
645                                if non_start_align || auto_row_stretch {
646                                    single_pass_ok = false;
647                                }
648                            }
649                        }
650                        self.get_mut_flow_scratch().push(child_id);
651                    }
652                    Position::Absolute | Position::Fixed => {
653                        self.get_mut_abs_scratch().push(child_id)
654                    }
655                }
656            }
657        }
658        let flow_end: usize = self.get_flow_scratch().len();
659        let abs_end: usize = self.get_abs_scratch().len();
660        let flow_size: Size = if let Some(flex_dir) = flex_dir_opt {
661            self.layout_flex(
662                tree,
663                (flow_start, flow_end),
664                frame,
665                flex_dir,
666                single_pass_ok,
667                stats,
668            )
669        } else {
670            self.layout_grid(tree, flow_start, flow_end, frame, stats)
671        };
672        self.get_mut_flow_scratch().truncate(flow_start);
673        for abs_idx in abs_start..abs_end {
674            let abs_id: NodeId = self.get_abs_scratch()[abs_idx];
675            let child_layout_opt: Option<LayoutStyle> = tree
676                .get_node(abs_id)
677                .map(|node: &SceneNode| node.style_ref().get_layout());
678            let Some(child_layout) = child_layout_opt else {
679                continue;
680            };
681            let is_fixed: bool = child_layout.get_position() == Position::Fixed;
682            let ref_origin: Point = if is_fixed {
683                Point::new(0.0, 0.0)
684            } else {
685                content_origin
686            };
687            let ref_size: Size = if is_fixed { viewport } else { inner_avail };
688            let resolved_w: Option<f32> = child_layout
689                .get_width()
690                .resolve(ref_size.get_width(), viewport);
691            let resolved_h: Option<f32> = child_layout
692                .get_height()
693                .resolve(ref_size.get_height(), viewport);
694            let needs_intrinsic: bool = (resolved_w.is_none()
695                && child_layout.left_offset().is_none()
696                && child_layout.right_offset().is_some())
697                || (resolved_h.is_none()
698                    && child_layout.top_offset().is_none()
699                    && child_layout.bottom_offset().is_some());
700            let probed: Size = if needs_intrinsic {
701                let probe_space: AvailableSpace = AvailableSpace::new(
702                    ref_size.get_width(),
703                    ref_size.get_height(),
704                    viewport,
705                    ref_origin.get_x(),
706                    ref_origin.get_y(),
707                );
708                self.layout_node(tree, abs_id, probe_space, stats)
709            } else {
710                Size::new(ref_size.get_width(), ref_size.get_height())
711            };
712            let child_w: f32 = resolved_w.unwrap_or(probed.get_width());
713            let child_h: f32 = resolved_h.unwrap_or(probed.get_height());
714            let x: f32 = if let Some(left) = child_layout.left_offset() {
715                ref_origin.get_x() + left
716            } else if let Some(right) = child_layout.right_offset() {
717                ref_origin.get_x() + (ref_size.get_width() - child_w - right)
718            } else {
719                ref_origin.get_x()
720            };
721            let y: f32 = if let Some(top) = child_layout.top_offset() {
722                ref_origin.get_y() + top
723            } else if let Some(bottom) = child_layout.bottom_offset() {
724                ref_origin.get_y() + (ref_size.get_height() - child_h - bottom)
725            } else {
726                ref_origin.get_y()
727            };
728            let abs_space: AvailableSpace =
729                AvailableSpace::new(ref_size.get_width(), ref_size.get_height(), viewport, x, y);
730            let _: Size = self.layout_node(tree, abs_id, abs_space, stats);
731        }
732        self.get_mut_abs_scratch().truncate(abs_start);
733        flow_size
734    }
735
736    /// Executes single-line or multi-line Flexbox layout with grow, gap, justification, and alignment.
737    ///
738    /// # Arguments
739    ///
740    /// - `&Self` - Mutable layout engine reference.
741    /// - `&mut SceneTree` - Mutable scene tree.
742    /// - `(usize, usize)` - Inclusive start and exclusive end indices into `flow_scratch`.
743    /// - `ContainerFrame` - Container constraints and origin.
744    /// - `FlexDirection` - Effective main-axis direction.
745    /// - `bool` - Whether single-pass flex fast-path eligibility was confirmed while collecting flow children.
746    /// - `&mut LayoutStats` - Mutable telemetry counters.
747    ///
748    /// # Returns
749    ///
750    /// - `Size` - Aggregate content size of all flex lines.
751    fn layout_flex(
752        &mut self,
753        tree: &mut SceneTree,
754        flow_range: (usize, usize),
755        frame: ContainerFrame,
756        direction: FlexDirection,
757        single_pass_ok: bool,
758        stats: &mut LayoutStats,
759    ) -> Size {
760        let (flow_start, flow_end): (usize, usize) = flow_range;
761        let count_all: usize = flow_end.saturating_sub(flow_start);
762        if count_all == 0 {
763            return Size::default();
764        }
765        let parent_layout: LayoutStyle = frame.get_parent_layout();
766        let inner_avail: Size = frame.get_inner_avail();
767        let viewport: Size = frame.get_viewport();
768        let content_origin: Point = frame.get_content_origin();
769        let is_row: bool = matches!(direction, FlexDirection::Row | FlexDirection::RowReverse);
770        let is_reverse: bool = matches!(
771            direction,
772            FlexDirection::RowReverse | FlexDirection::ColumnReverse
773        );
774        let main_gap: f32 = if is_row {
775            parent_layout.get_column_gap()
776        } else {
777            parent_layout.get_row_gap()
778        };
779        let cross_gap: f32 = if is_row {
780            parent_layout.get_row_gap()
781        } else {
782            parent_layout.get_column_gap()
783        };
784        let main_avail: f32 = if is_row {
785            inner_avail.get_width()
786        } else {
787            inner_avail.get_height()
788        };
789        let cross_avail: f32 = if is_row {
790            inner_avail.get_height()
791        } else {
792            inner_avail.get_width()
793        };
794        if is_reverse {
795            self.get_mut_flow_scratch()[flow_start..flow_end].reverse();
796        }
797        let wrap_enabled: bool = parent_layout.get_flex_wrap() == FlexWrap::Wrap;
798        if single_pass_ok {
799            let parent_align: AlignItems = parent_layout.get_align_items();
800            let mut main_cursor: f32 = 0.0;
801            let mut max_cross: f32 = 0.0;
802            let records_start: usize = self.get_flex_items_scratch().len();
803            for offset in 0..count_all {
804                let child_id: NodeId = self.get_flow_scratch()[flow_start + offset];
805                let (margin, align, width_auto, height_auto, clean_cache): (
806                    Edges,
807                    AlignItems,
808                    bool,
809                    bool,
810                    Option<(AvailableSpace, Size)>,
811                ) = if let Some(node) = tree.get_node(child_id) {
812                    let Style {
813                        layout: child_layout,
814                        ..
815                    } = node.style_ref();
816                    let a: AlignItems = match child_layout.get_align_self() {
817                        AlignSelf::Auto => parent_align,
818                        AlignSelf::Stretch => AlignItems::Stretch,
819                        AlignSelf::Start => AlignItems::Start,
820                        AlignSelf::Center => AlignItems::Center,
821                        AlignSelf::End => AlignItems::End,
822                    };
823                    let cached: Option<(AvailableSpace, Size)> =
824                        if !node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
825                            && let Some(prev_space) = node.cached_constraint()
826                        {
827                            let prev_bounds: Rect = node.get_layout_box().get_bounds();
828                            Some((
829                                prev_space,
830                                Size::new(prev_bounds.get_width(), prev_bounds.get_height()),
831                            ))
832                        } else {
833                            None
834                        };
835                    (
836                        child_layout.get_margin(),
837                        a,
838                        child_layout.get_width() == Length::Auto,
839                        child_layout.get_height() == Length::Auto,
840                        cached,
841                    )
842                } else {
843                    (Edges::default(), parent_align, true, true, None)
844                };
845                let (x, y): (f32, f32) = if is_row {
846                    (
847                        content_origin.get_x() + main_cursor + margin.get_left(),
848                        content_origin.get_y() + margin.get_top(),
849                    )
850                } else {
851                    (
852                        content_origin.get_x() + margin.get_left(),
853                        content_origin.get_y() + main_cursor + margin.get_top(),
854                    )
855                };
856                let stretch_w: bool = !is_row && align == AlignItems::Stretch && width_auto;
857                let stretch_h: bool = is_row && align == AlignItems::Stretch && height_auto;
858                let space_w: f32 = if stretch_w {
859                    (inner_avail.get_width() - margin.horizontal()).max(0.0)
860                } else {
861                    inner_avail.get_width()
862                };
863                let space_h: f32 = if stretch_h {
864                    (inner_avail.get_height() - margin.vertical()).max(0.0)
865                } else {
866                    inner_avail.get_height()
867                };
868                let final_space: AvailableSpace =
869                    AvailableSpace::new(space_w, space_h, viewport, x, y)
870                        .with_stretch(stretch_w, stretch_h);
871                let placed: Size = if let Some((prev_space, prev_size)) = clean_cache
872                    && prev_space.can_reuse(final_space)
873                {
874                    if !prev_space.same_origin(final_space) {
875                        let dx: f32 = x - prev_space.get_origin_x();
876                        let dy: f32 = y - prev_space.get_origin_y();
877                        self.translate_subtree(tree, child_id, dx, dy);
878                    }
879                    stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
880                    prev_size
881                } else {
882                    self.layout_node(tree, child_id, final_space, stats)
883                };
884                let target_w: f32 = if stretch_w {
885                    space_w.max(placed.get_width())
886                } else {
887                    placed.get_width()
888                };
889                let target_h: f32 = if stretch_h {
890                    space_h.max(placed.get_height())
891                } else {
892                    placed.get_height()
893                };
894                if (stretch_w && target_w > placed.get_width() + 0.01)
895                    || (stretch_h && target_h > placed.get_height() + 0.01)
896                {
897                    self.record_layout_snapshot(tree, child_id);
898                    if let Some(node) = tree.get_node_mut(child_id) {
899                        let mut b: Rect = node.get_layout_box().get_bounds();
900                        b.set_width(target_w);
901                        b.set_height(target_h);
902                        node.get_mut_layout_box().set_bounds(b);
903                    }
904                }
905                if stretch_w {
906                    self.get_mut_flex_items_scratch().push(FlexItemRecord {
907                        node_id: child_id,
908                        size: Size::new(target_w, target_h),
909                        probed_size: Size::default(),
910                        probed_origin: Point::default(),
911                        margin,
912                        flex_grow: 0.0,
913                        align_self: AlignSelf::Stretch,
914                        overflow: Overflow::Visible,
915                        flags: 0,
916                    });
917                }
918                if is_row {
919                    main_cursor += target_w + margin.horizontal();
920                    max_cross = max_cross.max(target_h + margin.vertical());
921                } else {
922                    main_cursor += target_h + margin.vertical();
923                    max_cross = max_cross.max(target_w + margin.horizontal());
924                }
925                if offset + 1 < count_all {
926                    main_cursor += main_gap;
927                }
928            }
929            let records_end: usize = self.get_flex_items_scratch().len();
930            if records_end > records_start && max_cross > cross_avail + 0.5 {
931                for rec_idx in records_start..records_end {
932                    let rec: FlexItemRecord = self.get_flex_items_scratch()[rec_idx];
933                    let widened: f32 =
934                        (max_cross - rec.margin.horizontal()).max(rec.size.get_width());
935                    self.record_layout_snapshot(tree, rec.node_id);
936                    if let Some(node) = tree.get_node_mut(rec.node_id) {
937                        let mut b: Rect = node.get_layout_box().get_bounds();
938                        b.set_width(widened);
939                        node.get_mut_layout_box().set_bounds(b);
940                    }
941                }
942            }
943            self.get_mut_flex_items_scratch().truncate(records_start);
944            return if is_row {
945                Size::new(main_cursor, max_cross)
946            } else {
947                Size::new(max_cross, main_cursor)
948            };
949        }
950        let items_start: usize = self.get_flex_items_scratch().len();
951        let probe_template: AvailableSpace = AvailableSpace::new(
952            inner_avail.get_width(),
953            inner_avail.get_height(),
954            viewport,
955            content_origin.get_x(),
956            content_origin.get_y(),
957        );
958        let mut total_grow: f32 = 0.0;
959        let mut single_line_main: f32 = 0.0;
960        let mut single_line_cross: f32 = 0.0;
961        for flow_idx in flow_start..flow_end {
962            let child_id: NodeId = self.get_flow_scratch()[flow_idx];
963            let mut rec: FlexItemRecord = FlexItemRecord {
964                node_id: child_id,
965                size: Size::default(),
966                probed_size: Size::default(),
967                probed_origin: Point::default(),
968                margin: Edges::default(),
969                flex_grow: 0.0,
970                align_self: AlignSelf::Auto,
971                overflow: Overflow::Visible,
972                flags: FLEX_ITEM_DEFAULT_LEAF_FLAGS,
973            };
974            let mut zero_basis_size: Option<Size> = None;
975            let mut clean_probe: Option<(Size, Point)> = None;
976            if let Some(node) = tree.get_node(child_id) {
977                let style_ref: &Style = node.style_ref();
978                let Style {
979                    layout: child_layout,
980                    paint: child_paint,
981                    ..
982                } = style_ref;
983                let width_len: Length = child_layout.get_width();
984                let height_len: Length = child_layout.get_height();
985                let grow: f32 = child_layout.get_flex_grow();
986                let width_auto: bool = width_len == Length::Auto;
987                let height_auto: bool = height_len == Length::Auto;
988                let is_leaf: bool = matches!(
989                    node.get_kind(),
990                    NodeKind::Text(_) | NodeKind::Image(_) | NodeKind::Input(_)
991                ) || node.get_children().is_empty();
992                let mut f: u16 = 0;
993                if width_auto {
994                    f |= FLEX_ITEM_WIDTH_AUTO;
995                }
996                if height_auto {
997                    f |= FLEX_ITEM_HEIGHT_AUTO;
998                }
999                if matches!(width_len, Length::Percent(_)) {
1000                    f |= FLEX_ITEM_WIDTH_PERCENT;
1001                }
1002                if matches!(height_len, Length::Percent(_)) {
1003                    f |= FLEX_ITEM_HEIGHT_PERCENT;
1004                }
1005                if matches!(child_layout.get_min_width(), Length::Percent(_))
1006                    || matches!(child_layout.get_max_width(), Length::Percent(_))
1007                {
1008                    f |= FLEX_ITEM_MINMAX_W_PERCENT;
1009                }
1010                if matches!(child_layout.get_min_height(), Length::Percent(_))
1011                    || matches!(child_layout.get_max_height(), Length::Percent(_))
1012                {
1013                    f |= FLEX_ITEM_MINMAX_H_PERCENT;
1014                }
1015                if child_layout.aspect_ratio_value().is_some() {
1016                    f |= FLEX_ITEM_HAS_ASPECT_RATIO;
1017                }
1018                if child_layout.get_min_height() != Length::Auto
1019                    || child_layout.get_max_height() != Length::Auto
1020                {
1021                    f |= FLEX_ITEM_MINMAX_H_SET;
1022                }
1023                if is_leaf {
1024                    f |= FLEX_ITEM_IS_LEAF;
1025                }
1026                let zero_basis: bool =
1027                    !wrap_enabled && grow > 0.0 && if is_row { width_auto } else { height_auto };
1028                if zero_basis {
1029                    zero_basis_size = if is_row {
1030                        let h: f32 = height_len.resolve(cross_avail, viewport).unwrap_or(0.0);
1031                        Some(Size::new(0.0, h))
1032                    } else {
1033                        let w: f32 = width_len.resolve(cross_avail, viewport).unwrap_or(0.0);
1034                        Some(Size::new(w, 0.0))
1035                    };
1036                } else if !node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
1037                    && let Some(prev) = node.cached_constraint()
1038                    && prev.can_reuse(probe_template)
1039                {
1040                    let b: Rect = node.get_layout_box().get_bounds();
1041                    let probed_h: f32 = if is_leaf
1042                        && height_auto
1043                        && (f & (FLEX_ITEM_MINMAX_H_SET | FLEX_ITEM_HAS_ASPECT_RATIO)) == 0
1044                    {
1045                        let pad: Edges = child_layout.get_padding();
1046                        let bw: f32 = child_paint.get_border().get_width();
1047                        let chrome_v: f32 = pad.vertical() + bw * 2.0;
1048                        (node.get_layout_box().get_content_size().get_height() + chrome_v).max(0.0)
1049                    } else {
1050                        b.get_height()
1051                    };
1052                    clean_probe = Some((
1053                        Size::new(b.get_width(), probed_h),
1054                        Point::new(prev.get_origin_x(), prev.get_origin_y()),
1055                    ));
1056                }
1057                rec.margin = child_layout.get_margin();
1058                rec.flex_grow = grow;
1059                rec.align_self = child_layout.get_align_self();
1060                rec.overflow = child_layout.get_overflow();
1061                rec.flags = f;
1062            }
1063            total_grow += rec.flex_grow;
1064            let (child_size, probed_origin): (Size, Point) = if let Some(zb) = zero_basis_size {
1065                (zb, content_origin)
1066            } else if let Some((cached_size, cached_origin)) = clean_probe {
1067                rec.flags |= FLEX_ITEM_PROBED;
1068                stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
1069                (cached_size, cached_origin)
1070            } else {
1071                let measured: Size = self.layout_node(tree, child_id, probe_template, stats);
1072                rec.flags |= FLEX_ITEM_PROBED;
1073                (measured, content_origin)
1074            };
1075            if !wrap_enabled {
1076                if is_row {
1077                    single_line_main += child_size.get_width() + rec.margin.horizontal();
1078                    single_line_cross =
1079                        single_line_cross.max(child_size.get_height() + rec.margin.vertical());
1080                } else {
1081                    single_line_main += child_size.get_height() + rec.margin.vertical();
1082                    single_line_cross =
1083                        single_line_cross.max(child_size.get_width() + rec.margin.horizontal());
1084                }
1085            }
1086            rec.size = child_size;
1087            rec.probed_size = child_size;
1088            rec.probed_origin = probed_origin;
1089            self.get_mut_flex_items_scratch().push(rec);
1090        }
1091        let items_end: usize = self.get_flex_items_scratch().len();
1092        if !wrap_enabled {
1093            let line_ctx: FlexLineContext = FlexLineContext {
1094                frame,
1095                is_row,
1096                wrap_enabled: false,
1097                main_gap,
1098                main_avail,
1099                cross_avail,
1100                total_grow,
1101                line_count: 1,
1102            };
1103            let line_size: Size = self.layout_flex_line(
1104                tree,
1105                (items_start, items_end),
1106                0.0,
1107                Some((single_line_main, single_line_cross)),
1108                line_ctx,
1109                stats,
1110            );
1111            self.get_mut_flex_items_scratch().truncate(items_start);
1112            return line_size;
1113        }
1114        let lines_start: usize = self.get_flex_lines_scratch().len();
1115        let mut cur_line_start: usize = items_start;
1116        let mut line_main: f32 = 0.0;
1117        for item_idx in items_start..items_end {
1118            let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1119            let item_main: f32 = if is_row {
1120                item.size.get_width() + item.margin.horizontal()
1121            } else {
1122                item.size.get_height() + item.margin.vertical()
1123            };
1124            let line_empty: bool = item_idx == cur_line_start;
1125            let needed: f32 = if line_empty {
1126                item_main
1127            } else {
1128                line_main + main_gap + item_main
1129            };
1130            if !line_empty && needed > main_avail && main_avail > 0.0 {
1131                self.get_mut_flex_lines_scratch()
1132                    .push((cur_line_start, item_idx));
1133                cur_line_start = item_idx;
1134                line_main = item_main;
1135            } else {
1136                line_main = needed;
1137            }
1138        }
1139        if cur_line_start < items_end {
1140            self.get_mut_flex_lines_scratch()
1141                .push((cur_line_start, items_end));
1142        }
1143        let lines_end: usize = self.get_flex_lines_scratch().len();
1144        let mut cross_cursor: f32 = 0.0;
1145        let mut max_main_extent: f32 = 0.0;
1146        let line_count: usize = lines_end.saturating_sub(lines_start);
1147        for line_offset in 0..line_count {
1148            let line_range: (usize, usize) =
1149                self.get_flex_lines_scratch()[lines_start + line_offset];
1150            let mut line_grow: f32 = 0.0;
1151            for item_idx in line_range.0..line_range.1 {
1152                line_grow += self.get_flex_items_scratch()[item_idx].flex_grow;
1153            }
1154            let line_ctx: FlexLineContext = FlexLineContext {
1155                frame,
1156                is_row,
1157                wrap_enabled: true,
1158                main_gap,
1159                main_avail,
1160                cross_avail,
1161                total_grow: line_grow,
1162                line_count,
1163            };
1164            let line_size: Size =
1165                self.layout_flex_line(tree, line_range, cross_cursor, None, line_ctx, stats);
1166            if is_row {
1167                max_main_extent = max_main_extent.max(line_size.get_width());
1168                cross_cursor += line_size.get_height();
1169            } else {
1170                max_main_extent = max_main_extent.max(line_size.get_height());
1171                cross_cursor += line_size.get_width();
1172            }
1173            if line_offset + 1 < line_count {
1174                cross_cursor += cross_gap;
1175            }
1176        }
1177        self.get_mut_flex_lines_scratch().truncate(lines_start);
1178        self.get_mut_flex_items_scratch().truncate(items_start);
1179        if is_row {
1180            Size::new(max_main_extent, cross_cursor)
1181        } else {
1182            Size::new(cross_cursor, max_main_extent)
1183        }
1184    }
1185
1186    /// Places a single contiguous flex line slice `[line_start..line_end)` and returns its occupied `(width, height)`.
1187    ///
1188    /// # Arguments
1189    ///
1190    /// - `&Self` - Mutable layout engine reference.
1191    /// - `&mut SceneTree` - Mutable scene tree.
1192    /// - `(usize, usize)` - Inclusive start and exclusive end indices into `flex_items_scratch`.
1193    /// - `f32` - Cross-axis cursor offset where this line begins.
1194    /// - `Option<(f32, f32)>` - Optional pre-accumulated `(items_main_sum, line_cross)` for unwrapped single-line passes.
1195    /// - `FlexLineContext` - Enclosing container axis and gap parameters.
1196    /// - `&mut LayoutStats` - Mutable telemetry counters.
1197    ///
1198    /// # Returns
1199    ///
1200    /// - `Size` - Occupied `(width, height)` extent of this flex line.
1201    #[inline(always)]
1202    fn layout_flex_line(
1203        &mut self,
1204        tree: &mut SceneTree,
1205        line_range: (usize, usize),
1206        cross_cursor: f32,
1207        precomputed: Option<(f32, f32)>,
1208        ctx: FlexLineContext,
1209        stats: &mut LayoutStats,
1210    ) -> Size {
1211        let (line_start, line_end): (usize, usize) = line_range;
1212        let frame: ContainerFrame = ctx.frame;
1213        let is_row: bool = ctx.is_row;
1214        let wrap_enabled: bool = ctx.wrap_enabled;
1215        let main_gap: f32 = ctx.main_gap;
1216        let main_avail: f32 = ctx.main_avail;
1217        let cross_avail: f32 = ctx.cross_avail;
1218        let total_grow: f32 = ctx.total_grow;
1219        let line_count: usize = ctx.line_count;
1220        let parent_layout: LayoutStyle = frame.get_parent_layout();
1221        let inner_avail: Size = frame.get_inner_avail();
1222        let viewport: Size = frame.get_viewport();
1223        let content_origin: Point = frame.get_content_origin();
1224        let count: usize = line_end.saturating_sub(line_start);
1225        let gaps_total: f32 = if count > 1 {
1226            main_gap * ((count - 1) as f32)
1227        } else {
1228            0.0
1229        };
1230        let has_definite_or_grow: bool = frame.get_definite_width() || total_grow > 0.0;
1231        let effective_main_avail: f32 = if is_row {
1232            if has_definite_or_grow || wrap_enabled {
1233                main_avail
1234            } else {
1235                parent_layout
1236                    .get_min_width()
1237                    .resolve(viewport.get_width(), viewport)
1238                    .map(|mw: f32| (mw - parent_layout.get_padding().horizontal()).max(0.0))
1239                    .unwrap_or(0.0)
1240            }
1241        } else if frame.get_definite_height() {
1242            main_avail
1243        } else {
1244            parent_layout
1245                .get_min_height()
1246                .resolve(viewport.get_height(), viewport)
1247                .map(|mh: f32| (mh - parent_layout.get_padding().vertical()).max(0.0))
1248                .unwrap_or(0.0)
1249        };
1250        let (final_used_main, line_cross): (f32, f32) = if let Some((items_main, pre_cross)) =
1251            precomputed
1252            && total_grow == 0.0
1253        {
1254            (items_main + gaps_total, pre_cross)
1255        } else {
1256            let used_main: f32 = if let Some((items_main, _)) = precomputed {
1257                items_main + gaps_total
1258            } else {
1259                let mut acc: f32 = gaps_total;
1260                for item_idx in line_start..line_end {
1261                    let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1262                    let sz: f32 = if is_row {
1263                        item.size.get_width() + item.margin.horizontal()
1264                    } else {
1265                        item.size.get_height() + item.margin.vertical()
1266                    };
1267                    acc += sz;
1268                }
1269                acc
1270            };
1271            let free_main: f32 = (effective_main_avail - used_main).max(0.0);
1272            if total_grow > 0.0 && free_main > 0.0 {
1273                for item_idx in line_start..line_end {
1274                    let item: &mut FlexItemRecord =
1275                        &mut self.get_mut_flex_items_scratch()[item_idx];
1276                    let grow: f32 = item.flex_grow;
1277                    if grow > 0.0 {
1278                        let extra: f32 = free_main * (grow / total_grow);
1279                        if is_row {
1280                            item.size.set_width(item.size.get_width() + extra);
1281                        } else {
1282                            item.size.set_height(item.size.get_height() + extra);
1283                        }
1284                    }
1285                }
1286            }
1287            if total_grow > 0.0 {
1288                for item_idx in line_start..line_end {
1289                    let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1290                    let auto_cross: bool = item.flex_grow > 0.0
1291                        && if is_row {
1292                            (item.flags & FLEX_ITEM_HEIGHT_AUTO) != 0
1293                        } else {
1294                            (item.flags & FLEX_ITEM_WIDTH_AUTO) != 0
1295                        };
1296                    if auto_cross {
1297                        let probe_w: f32 = if is_row {
1298                            item.size.get_width()
1299                        } else {
1300                            cross_avail
1301                        };
1302                        let probe_h: f32 = if is_row {
1303                            cross_avail
1304                        } else {
1305                            item.size.get_height()
1306                        };
1307                        let probe_sp: AvailableSpace = AvailableSpace::new(
1308                            probe_w,
1309                            probe_h,
1310                            viewport,
1311                            content_origin.get_x(),
1312                            content_origin.get_y(),
1313                        );
1314                        let measured: Size = self.layout_node(tree, item.node_id, probe_sp, stats);
1315                        let slot: &mut FlexItemRecord =
1316                            &mut self.get_mut_flex_items_scratch()[item_idx];
1317                        if is_row {
1318                            slot.size.set_height(measured.get_height());
1319                        } else {
1320                            slot.size.set_width(measured.get_width());
1321                        }
1322                        slot.flags &= !FLEX_ITEM_PROBED;
1323                    }
1324                }
1325            }
1326            let mut sum_main: f32 = gaps_total;
1327            let mut max_cross: f32 = 0.0;
1328            for item_idx in line_start..line_end {
1329                let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1330                if is_row {
1331                    sum_main += item.size.get_width() + item.margin.horizontal();
1332                    max_cross = max_cross.max(item.size.get_height() + item.margin.vertical());
1333                } else {
1334                    sum_main += item.size.get_height() + item.margin.vertical();
1335                    max_cross = max_cross.max(item.size.get_width() + item.margin.horizontal());
1336                }
1337            }
1338            (sum_main, max_cross)
1339        };
1340        let rem: f32 = (effective_main_avail - final_used_main).max(0.0);
1341        let (mut main_cursor, extra_step): (f32, f32) = match parent_layout.get_justify_content() {
1342            JustifyContent::Start => (0.0, 0.0),
1343            JustifyContent::Center => (rem * 0.5, 0.0),
1344            JustifyContent::End => (rem, 0.0),
1345            JustifyContent::SpaceBetween => {
1346                if count > 1 {
1347                    (0.0, rem / ((count - 1) as f32))
1348                } else {
1349                    (0.0, 0.0)
1350                }
1351            }
1352            JustifyContent::SpaceAround => {
1353                let slot: f32 = rem / (count.max(1) as f32);
1354                (slot * 0.5, slot)
1355            }
1356            JustifyContent::SpaceEvenly => {
1357                let slot: f32 = rem / ((count + 1) as f32);
1358                (slot, slot)
1359            }
1360        };
1361        let definite_cross: bool = !is_row || frame.get_definite_height();
1362        let effective_line_cross: f32 = if line_count == 1 && !wrap_enabled && definite_cross {
1363            line_cross.max(cross_avail)
1364        } else {
1365            line_cross
1366        };
1367        let mut actual_line_cross: f32 = line_cross;
1368        let parent_align: AlignItems = parent_layout.get_align_items();
1369        for idx in 0..count {
1370            let rec: FlexItemRecord = self.get_flex_items_scratch()[line_start + idx];
1371            let child_id: NodeId = rec.node_id;
1372            let child_size: Size = rec.size;
1373            let margin: Edges = rec.margin;
1374            let width_auto: bool = (rec.flags & FLEX_ITEM_WIDTH_AUTO) != 0;
1375            let height_auto: bool = (rec.flags & FLEX_ITEM_HEIGHT_AUTO) != 0;
1376            let is_leaf: bool = (rec.flags & FLEX_ITEM_IS_LEAF) != 0;
1377            let item_cross: f32 = if is_row {
1378                child_size.get_height()
1379            } else {
1380                child_size.get_width()
1381            };
1382            let align: AlignItems = match rec.align_self {
1383                AlignSelf::Auto => parent_align,
1384                AlignSelf::Stretch => AlignItems::Stretch,
1385                AlignSelf::Start => AlignItems::Start,
1386                AlignSelf::Center => AlignItems::Center,
1387                AlignSelf::End => AlignItems::End,
1388            };
1389            let avail_item_cross: f32 = (effective_line_cross
1390                - if is_row {
1391                    margin.vertical()
1392                } else {
1393                    margin.horizontal()
1394                })
1395            .max(0.0);
1396            let cross_offset: f32 = match align {
1397                AlignItems::Start | AlignItems::Stretch => 0.0,
1398                AlignItems::Center => ((avail_item_cross - item_cross) * 0.5).max(0.0),
1399                AlignItems::End => (avail_item_cross - item_cross).max(0.0),
1400            };
1401            let auto_cross_grow: bool =
1402                rec.flex_grow > 0.0 && if is_row { height_auto } else { width_auto };
1403            let target_w: f32 = if !is_row && align == AlignItems::Stretch && width_auto {
1404                avail_item_cross.max(child_size.get_width())
1405            } else {
1406                child_size.get_width()
1407            };
1408            let target_h: f32 = if is_row && align == AlignItems::Stretch && height_auto {
1409                avail_item_cross.max(child_size.get_height())
1410            } else {
1411                child_size.get_height()
1412            };
1413            let (x, y): (f32, f32) = if is_row {
1414                (
1415                    content_origin.get_x() + main_cursor + margin.get_left(),
1416                    content_origin.get_y() + cross_cursor + cross_offset + margin.get_top(),
1417                )
1418            } else {
1419                (
1420                    content_origin.get_x() + cross_cursor + cross_offset + margin.get_left(),
1421                    content_origin.get_y() + main_cursor + margin.get_top(),
1422                )
1423            };
1424            let space_w: f32 = if (rec.flags & FLEX_ITEM_WIDTH_PERCENT) != 0 {
1425                inner_avail.get_width()
1426            } else if auto_cross_grow && !is_row {
1427                cross_avail
1428            } else {
1429                target_w
1430            };
1431            let space_h: f32 = if (rec.flags & FLEX_ITEM_HEIGHT_PERCENT) != 0 {
1432                inner_avail.get_height()
1433            } else if auto_cross_grow && is_row {
1434                cross_avail
1435            } else {
1436                target_h
1437            };
1438            let stretch_child_w: bool = !(auto_cross_grow && !is_row)
1439                && ((!is_row && align == AlignItems::Stretch && width_auto)
1440                    || (is_row && rec.flex_grow > 0.0 && width_auto));
1441            let stretch_child_h: bool = !(auto_cross_grow && is_row)
1442                && ((is_row && align == AlignItems::Stretch && height_auto)
1443                    || (!is_row && rec.flex_grow > 0.0 && height_auto));
1444            let same_w: bool = (target_w - rec.probed_size.get_width()).abs() <= 0.001;
1445            let same_h: bool = (target_h - rec.probed_size.get_height()).abs() <= 0.001;
1446            let width_fixed_or_leaf: bool = is_leaf || !width_auto;
1447            let width_no_pct_bounds: bool = (rec.flags & FLEX_ITEM_MINMAX_W_PERCENT) == 0;
1448            let width_invariant: bool = (space_w - inner_avail.get_width()).abs() <= 0.01
1449                || (width_fixed_or_leaf && width_no_pct_bounds);
1450            let height_fixed_or_leaf: bool = is_leaf || !height_auto;
1451            let height_no_pct_bounds: bool = (rec.flags & FLEX_ITEM_MINMAX_H_PERCENT) == 0;
1452            let height_invariant: bool = (space_h - inner_avail.get_height()).abs() <= 0.01
1453                || (height_fixed_or_leaf && height_no_pct_bounds);
1454            let probed_ok: bool = (rec.flags & FLEX_ITEM_PROBED) != 0
1455                && !auto_cross_grow
1456                && (rec.flags & FLEX_ITEM_HAS_ASPECT_RATIO) == 0
1457                && width_invariant
1458                && height_invariant;
1459            let can_translate_exact: bool = probed_ok
1460                && same_w
1461                && same_h
1462                && (is_leaf || (!stretch_child_w && !stretch_child_h));
1463            let can_stretch_leaf_h: bool = probed_ok
1464                && is_leaf
1465                && is_row
1466                && same_w
1467                && !stretch_child_w
1468                && stretch_child_h
1469                && height_auto
1470                && (rec.flags & FLEX_ITEM_MINMAX_H_SET) == 0;
1471            if can_translate_exact {
1472                let dx: f32 = x - rec.probed_origin.get_x();
1473                let dy: f32 = y - rec.probed_origin.get_y();
1474                if dx.abs() > 0.001 || dy.abs() > 0.001 {
1475                    self.translate_subtree(tree, child_id, dx, dy);
1476                }
1477            } else if can_stretch_leaf_h {
1478                self.record_layout_snapshot(tree, child_id);
1479                if let Some(node) = tree.get_node_mut(child_id) {
1480                    let cur_bounds: Rect = node.get_layout_box().get_bounds();
1481                    let same_box: bool = (cur_bounds.get_x() - x).abs() <= 0.001
1482                        && (cur_bounds.get_y() - y).abs() <= 0.001
1483                        && (cur_bounds.get_width() - target_w).abs() <= 0.001
1484                        && (cur_bounds.get_height() - target_h).abs() <= 0.001;
1485                    if !same_box {
1486                        let Style {
1487                            layout: child_layout,
1488                            paint: child_paint,
1489                            ..
1490                        } = node.style_ref();
1491                        let pad: Edges = child_layout.get_padding();
1492                        let bw: f32 = child_paint.get_border().get_width();
1493                        let chrome_h: f32 = pad.horizontal() + bw * 2.0;
1494                        let chrome_v: f32 = pad.vertical() + bw * 2.0;
1495                        let new_bounds: Rect = Rect::new(x, y, target_w, target_h);
1496                        let new_content: Rect = Rect::new(
1497                            x + pad.get_left() + bw,
1498                            y + pad.get_top() + bw,
1499                            (target_w - chrome_h).max(0.0),
1500                            (target_h - chrome_v).max(0.0),
1501                        );
1502                        node.get_mut_layout_box().set_bounds(new_bounds);
1503                        node.get_mut_layout_box().set_content_bounds(new_content);
1504                        if let Some(mut c) = node.cached_constraint() {
1505                            c.set_origin_x(x);
1506                            c.set_origin_y(y);
1507                            node.set_last_constraint(Some(c));
1508                        }
1509                    }
1510                }
1511            } else {
1512                let final_space: AvailableSpace =
1513                    AvailableSpace::new(space_w, space_h, viewport, x, y)
1514                        .with_stretch(stretch_child_w, stretch_child_h);
1515                let placed: Size = self.layout_node(tree, child_id, final_space, stats);
1516                self.record_layout_snapshot(tree, child_id);
1517                if let Some(node) = tree.get_node_mut(child_id) {
1518                    let mut b: Rect = node.get_layout_box().get_bounds();
1519                    let is_clipped: bool =
1520                        matches!(rec.overflow, Overflow::Hidden | Overflow::Scroll);
1521                    if auto_cross_grow {
1522                        if is_row {
1523                            b.set_width(target_w);
1524                            b.set_height(placed.get_height());
1525                            actual_line_cross =
1526                                actual_line_cross.max(placed.get_height() + margin.vertical());
1527                        } else {
1528                            b.set_width(placed.get_width());
1529                            b.set_height(target_h);
1530                            actual_line_cross =
1531                                actual_line_cross.max(placed.get_width() + margin.horizontal());
1532                        }
1533                    } else if is_clipped || rec.flex_grow > 0.0 {
1534                        b.set_width(target_w);
1535                        b.set_height(target_h);
1536                    } else {
1537                        b.set_width(target_w.max(placed.get_width()));
1538                        b.set_height(target_h.max(placed.get_height()));
1539                    }
1540                    node.get_mut_layout_box().set_bounds(b);
1541                }
1542            }
1543            let advance: f32 = if is_row {
1544                target_w + margin.horizontal()
1545            } else {
1546                target_h + margin.vertical()
1547            };
1548            main_cursor += advance;
1549            if idx + 1 < count {
1550                main_cursor += main_gap + extra_step;
1551            }
1552        }
1553        if is_row {
1554            Size::new(final_used_main, actual_line_cross)
1555        } else {
1556            Size::new(actual_line_cross, final_used_main)
1557        }
1558    }
1559
1560    /// Executes uniform-column CSS Grid layout with row and column gaps.
1561    ///
1562    /// # Arguments
1563    ///
1564    /// - `&Self` - Mutable layout engine reference.
1565    /// - `&mut SceneTree` - Mutable scene tree.
1566    /// - `usize` - Inclusive start index into `flow_scratch`.
1567    /// - `usize` - Exclusive end index into `flow_scratch`.
1568    /// - `ContainerFrame` - Grid container constraints and origin.
1569    /// - `&mut LayoutStats` - Mutable telemetry counters.
1570    ///
1571    /// # Returns
1572    ///
1573    /// - `Size` - Aggregate grid content dimensions.
1574    fn layout_grid(
1575        &mut self,
1576        tree: &mut SceneTree,
1577        flow_start: usize,
1578        flow_end: usize,
1579        frame: ContainerFrame,
1580        stats: &mut LayoutStats,
1581    ) -> Size {
1582        if flow_start >= flow_end {
1583            return Size::default();
1584        }
1585        let parent_layout: LayoutStyle = frame.get_parent_layout();
1586        let inner_avail: Size = frame.get_inner_avail();
1587        let viewport: Size = frame.get_viewport();
1588        let content_origin: Point = frame.get_content_origin();
1589        let cols: usize = (parent_layout.get_grid_columns() as usize).max(1);
1590        let col_gap: f32 = parent_layout.get_column_gap();
1591        let row_gap: f32 = parent_layout.get_row_gap();
1592        let total_col_gaps: f32 = col_gap * ((cols.saturating_sub(1)) as f32);
1593        let col_w: f32 = ((inner_avail.get_width() - total_col_gaps) / (cols as f32)).max(0.0);
1594        let col_step: f32 = col_w + col_gap;
1595        let origin_x: f32 = content_origin.get_x();
1596        let origin_y: f32 = content_origin.get_y();
1597        let inner_h: f32 = inner_avail.get_height();
1598        let mut y_cursor: f32 = 0.0;
1599        let mut idx: usize = flow_start;
1600        while idx < flow_end {
1601            let row_end: usize = (idx + cols).min(flow_end);
1602            let mut row_h: f32 = 0.0;
1603            let mut min_row_h: f32 = f32::INFINITY;
1604            let y: f32 = origin_y + y_cursor;
1605            let mut x: f32 = origin_x;
1606            for pos in idx..row_end {
1607                let child_id: NodeId = self.get_flow_scratch()[pos];
1608                let (auto_w, clean_cache): (bool, Option<(AvailableSpace, Size)>) =
1609                    if let Some(n) = tree.get_node(child_id) {
1610                        let Style { layout, .. } = n.style_ref();
1611                        let is_auto_w: bool = layout.get_width() == Length::Auto;
1612                        let cached: Option<(AvailableSpace, Size)> =
1613                            if !n.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
1614                                && let Some(prev_space) = n.cached_constraint()
1615                            {
1616                                let prev_bounds: Rect = n.get_layout_box().get_bounds();
1617                                Some((
1618                                    prev_space,
1619                                    Size::new(prev_bounds.get_width(), prev_bounds.get_height()),
1620                                ))
1621                            } else {
1622                                None
1623                            };
1624                        (is_auto_w, cached)
1625                    } else {
1626                        (false, None)
1627                    };
1628                let cell_space: AvailableSpace =
1629                    AvailableSpace::new(col_w, inner_h, viewport, x, y).with_stretch(auto_w, false);
1630                let child_size: Size = if let Some((prev_space, prev_size)) = clean_cache
1631                    && prev_space.can_reuse(cell_space)
1632                {
1633                    if !prev_space.same_origin(cell_space) {
1634                        let dx: f32 = x - prev_space.get_origin_x();
1635                        let dy: f32 = y - prev_space.get_origin_y();
1636                        self.translate_subtree(tree, child_id, dx, dy);
1637                    }
1638                    stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
1639                    prev_size
1640                } else {
1641                    self.layout_node(tree, child_id, cell_space, stats)
1642                };
1643                if (child_size.get_width() - col_w).abs() > 0.001 {
1644                    self.record_layout_snapshot(tree, child_id);
1645                    if let Some(node) = tree.get_node_mut(child_id) {
1646                        let mut b: Rect = node.get_layout_box().get_bounds();
1647                        b.set_width(col_w);
1648                        node.get_mut_layout_box().set_bounds(b);
1649                    }
1650                }
1651                let ch: f32 = child_size.get_height();
1652                row_h = row_h.max(ch);
1653                min_row_h = min_row_h.min(ch);
1654                x += col_step;
1655            }
1656            if row_end - idx > 1 && min_row_h < row_h {
1657                for pos in idx..row_end {
1658                    let child_id: NodeId = self.get_flow_scratch()[pos];
1659                    let needs_stretch: bool =
1660                        tree.get_node(child_id).is_some_and(|n: &SceneNode| {
1661                            n.get_layout_box().get_bounds().get_height() < row_h
1662                        });
1663                    if needs_stretch {
1664                        self.record_layout_snapshot(tree, child_id);
1665                        if let Some(node) = tree.get_node_mut(child_id) {
1666                            let mut b: Rect = node.get_layout_box().get_bounds();
1667                            b.set_height(row_h);
1668                            node.get_mut_layout_box().set_bounds(b);
1669                        }
1670                    }
1671                }
1672            }
1673            y_cursor += row_h;
1674            if row_end < flow_end {
1675                y_cursor += row_gap;
1676            }
1677            idx = row_end;
1678        }
1679        Size::new(inner_avail.get_width(), y_cursor)
1680    }
1681
1682    /// Translates the cached layout geometry of `root_id` and all non-fixed descendants by `(dx, dy)` in O(subtree) without re-running layout or text measurement.
1683    ///
1684    /// # Arguments
1685    ///
1686    /// - `&Self` - Mutable layout engine reference.
1687    /// - `&mut SceneTree` - Mutable retained scene tree.
1688    /// - `NodeId` - Root node of the clean subtree being shifted.
1689    /// - `f32` - Horizontal translation delta in logical pixels.
1690    /// - `f32` - Vertical translation delta in logical pixels.
1691    fn translate_subtree(&mut self, tree: &mut SceneTree, root_id: NodeId, dx: f32, dy: f32) {
1692        if dx == 0.0 && dy == 0.0 {
1693            return;
1694        }
1695        self.record_layout_snapshot(tree, root_id);
1696        let Some(root_node) = tree.get_node_mut(root_id) else {
1697            return;
1698        };
1699        let Style { layout, .. } = root_node.style_ref();
1700        let root_none_disp: bool = layout.get_display() == Display::None;
1701        if let Some(mut c) = root_node.cached_constraint() {
1702            c.set_origin_x(c.get_origin_x() + dx);
1703            c.set_origin_y(c.get_origin_y() + dy);
1704            root_node.set_last_constraint(Some(c));
1705        }
1706        if root_none_disp {
1707            return;
1708        }
1709        let mut root_bounds: Rect = root_node.get_layout_box().get_bounds();
1710        root_bounds.set_x(root_bounds.get_x() + dx);
1711        root_bounds.set_y(root_bounds.get_y() + dy);
1712        root_node.get_mut_layout_box().set_bounds(root_bounds);
1713        let mut root_content: Rect = root_node.get_layout_box().get_content_bounds();
1714        root_content.set_x(root_content.get_x() + dx);
1715        root_content.set_y(root_content.get_y() + dy);
1716        root_node
1717            .get_mut_layout_box()
1718            .set_content_bounds(root_content);
1719        let root_children: &[NodeId] = root_node.get_children().as_slice();
1720        if root_children.is_empty() {
1721            return;
1722        }
1723        self.get_mut_translate_scratch().clear();
1724        self.get_mut_translate_scratch()
1725            .extend_from_slice(root_children);
1726        while let Some(nid) = self.get_mut_translate_scratch().pop() {
1727            let (is_fixed_pos, is_none_disp): (bool, bool) = match tree.get_node(nid) {
1728                Some(node) => {
1729                    let Style { layout, .. } = node.style_ref();
1730                    (
1731                        layout.get_position() == Position::Fixed,
1732                        layout.get_display() == Display::None,
1733                    )
1734                }
1735                None => continue,
1736            };
1737            if is_fixed_pos {
1738                continue;
1739            }
1740            if !is_none_disp {
1741                self.record_layout_snapshot(tree, nid);
1742            }
1743            let Some(node) = tree.get_node_mut(nid) else {
1744                continue;
1745            };
1746            if let Some(mut c) = node.cached_constraint() {
1747                c.set_origin_x(c.get_origin_x() + dx);
1748                c.set_origin_y(c.get_origin_y() + dy);
1749                node.set_last_constraint(Some(c));
1750            }
1751            if is_none_disp {
1752                continue;
1753            }
1754            let mut bounds: Rect = node.get_layout_box().get_bounds();
1755            bounds.set_x(bounds.get_x() + dx);
1756            bounds.set_y(bounds.get_y() + dy);
1757            node.get_mut_layout_box().set_bounds(bounds);
1758            let mut content: Rect = node.get_layout_box().get_content_bounds();
1759            content.set_x(content.get_x() + dx);
1760            content.set_y(content.get_y() + dy);
1761            node.get_mut_layout_box().set_content_bounds(content);
1762            let children_slice: &[NodeId] = node.get_children().as_slice();
1763            if !children_slice.is_empty() {
1764                self.get_mut_translate_scratch()
1765                    .extend_from_slice(children_slice);
1766            }
1767        }
1768    }
1769}