Skip to main content

euv_core/layout/engine/
impl.rs

1use super::*;
2
3/// Core layout solver, split cache management, and spatial 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        if layout_snapshots.capacity() < DIRTY_PAINT_FULL_THRESHOLD {
27            layout_snapshots.reserve(DIRTY_PAINT_FULL_THRESHOLD);
28        }
29        self.compute_inner(tree, viewport)
30    }
31
32    /// Computes layout for `tree` while recording pre/post-layout conservative bounds diffs into a tight `LayoutDamageReport`.
33    ///
34    /// # Arguments
35    ///
36    /// - `&Self` - Mutable layout engine.
37    /// - `&mut SceneTree` - Retained scene tree to lay out.
38    /// - `Size` - Logical viewport dimensions.
39    /// - `f32` - Active display scale factor for outward-rounded physical damage rects.
40    ///
41    /// # Returns
42    ///
43    /// - `(LayoutStats, LayoutDamageReport)` - Layout pass stats and surgical physical damage or fallback cause.
44    pub(crate) fn compute_with_damage(
45        &mut self,
46        tree: &mut SceneTree,
47        viewport: Size,
48        scale: f32,
49    ) -> (LayoutStats, LayoutDamageReport) {
50        {
51            let Self {
52                track_damage,
53                damage_fallback,
54                layout_snapshots,
55                split_cache,
56                ..
57            } = self;
58            *track_damage = true;
59            *damage_fallback = LAYOUT_FALLBACK_NONE;
60            layout_snapshots.clear();
61            split_cache.begin_snapshot_pass();
62        }
63        let stats: LayoutStats = self.compute_inner(tree, viewport);
64        let fallback_after: u8 = {
65            let Self {
66                track_damage,
67                damage_fallback,
68                ..
69            } = self;
70            *track_damage = false;
71            *damage_fallback
72        };
73        if fallback_after != LAYOUT_FALLBACK_NONE {
74            let Self {
75                layout_snapshots, ..
76            } = self;
77            layout_snapshots.clear();
78            return (
79                stats,
80                LayoutDamageReport {
81                    damage: DamageRegion::full(),
82                    fallback_kind: fallback_after,
83                },
84            );
85        }
86        let mut damage: DamageRegion = DamageRegion::default();
87        let mut final_fallback: u8 = LAYOUT_FALLBACK_NONE;
88        let Self {
89            layout_snapshots, ..
90        } = self;
91        for snap in layout_snapshots.iter().copied() {
92            let Some(node) = tree.get_node(snap.id) else {
93                continue;
94            };
95            let lbox: LayoutBox = node.get_layout_box();
96            let new_bounds: Rect = lbox.get_bounds();
97            let new_content_bounds: Rect = lbox.get_content_bounds();
98            let new_content_size: Size = lbox.get_content_size();
99            let bounds_changed: bool = !Self::rect_approx_eq(snap.old_bounds, new_bounds);
100            let content_changed: bool =
101                !Self::rect_approx_eq(snap.old_content_bounds, new_content_bounds);
102            let is_scroll_box: bool =
103                node.style_ref().layout_ref().get_overflow() == Overflow::Scroll;
104            let scroll_content_changed: bool =
105                is_scroll_box && !Self::size_approx_eq(snap.old_content_size, new_content_size);
106            let geom_changed: bool = bounds_changed || content_changed;
107            if !geom_changed && !scroll_content_changed {
108                continue;
109            }
110            let is_portal_or_fixed: bool = matches!(node.get_kind(), NodeKind::Portal)
111                || node.style_ref().layout_ref().get_position() == Position::Fixed;
112            if is_portal_or_fixed {
113                final_fallback = LAYOUT_FALLBACK_PORTAL;
114                break;
115            }
116            if snap.has_old_screen {
117                damage.add_rect(SceneTree::scale_logical_to_phys_rect(
118                    snap.old_screen,
119                    scale,
120                ));
121            }
122            if new_bounds.get_width() > 0.0 && new_bounds.get_height() > 0.0 {
123                match tree.node_conservative_logical_rect(snap.id) {
124                    Some(new_screen) => {
125                        damage.add_rect(SceneTree::scale_logical_to_phys_rect(new_screen, scale));
126                    }
127                    None => {
128                        final_fallback = LAYOUT_FALLBACK_UNSAFE;
129                        break;
130                    }
131                }
132            }
133        }
134        layout_snapshots.clear();
135        if final_fallback != LAYOUT_FALLBACK_NONE {
136            return (
137                stats,
138                LayoutDamageReport {
139                    damage: DamageRegion::full(),
140                    fallback_kind: final_fallback,
141                },
142            );
143        }
144        (
145            stats,
146            LayoutDamageReport {
147                damage,
148                fallback_kind: LAYOUT_FALLBACK_NONE,
149            },
150        )
151    }
152
153    /// Executes the core layout traversal over `tree` using the current `track_damage` mode.
154    ///
155    /// # Arguments
156    ///
157    /// - `&Self` - Mutable layout engine.
158    /// - `&mut SceneTree` - Retained scene tree to lay out.
159    /// - `Size` - Logical viewport dimensions.
160    ///
161    /// # Returns
162    ///
163    /// - `LayoutStats` - Computed vs cached subtree counts.
164    fn compute_inner(&mut self, tree: &mut SceneTree, viewport: Size) -> LayoutStats {
165        let root_id: NodeId = tree.get_root();
166        let space: AvailableSpace = AvailableSpace::root(viewport);
167        let mut stats: LayoutStats = LayoutStats::default();
168        {
169            let Self {
170                split_cache,
171                last_split_stats,
172                ..
173            } = self;
174            split_cache.begin_pass();
175            *last_split_stats = SplitCacheStats::default();
176        }
177        self.get_mut_children_scratch().clear();
178        self.get_mut_flow_scratch().clear();
179        self.get_mut_abs_scratch().clear();
180        self.get_mut_flex_items_scratch().clear();
181        self.get_mut_flex_lines_scratch().clear();
182        self.get_mut_translate_scratch().clear();
183        let _: (Size, u8, f32) = self.layout_node_mode(
184            tree,
185            root_id,
186            space,
187            LayoutRunMode::PerformLayout,
188            &mut stats,
189        );
190        debug_assert!(self.get_children_scratch().is_empty());
191        debug_assert!(self.get_flow_scratch().is_empty());
192        debug_assert!(self.get_abs_scratch().is_empty());
193        debug_assert!(self.get_flex_items_scratch().is_empty());
194        debug_assert!(self.get_flex_lines_scratch().is_empty());
195        debug_assert!(self.get_mut_translate_scratch().is_empty());
196        {
197            let Self { split_cache, .. } = self;
198            split_cache.mark_synced(root_id, tree.get_revision());
199        }
200        self.set_last_stats(stats);
201        let invalidations: u64 = tree.get_layout_invalidations();
202        let changed_now: u64 = stats.get_nodes_changed() as u64;
203        let telemetry: &mut LayoutTelemetry = self.get_mut_telemetry();
204        telemetry.set_invalidations(invalidations);
205        telemetry.set_passes(telemetry.get_passes().saturating_add(1));
206        if changed_now > 0 {
207            telemetry.set_changed_passes(telemetry.get_changed_passes().saturating_add(1));
208            telemetry.set_changed_nodes_total(
209                telemetry
210                    .get_changed_nodes_total()
211                    .saturating_add(changed_now),
212            );
213        }
214        stats
215    }
216
217    /// Returns cumulative `LayoutTelemetry` counters (`invalidations`, `passes`, `changed_passes`, `changed_nodes_total`).
218    ///
219    /// # Arguments
220    ///
221    /// - `&Self` - Layout engine reference.
222    ///
223    /// # Returns
224    ///
225    /// - `LayoutTelemetry` - Cumulative layout telemetry snapshot.
226    #[must_use]
227    pub fn layout_telemetry(&self) -> LayoutTelemetry {
228        self.get_telemetry()
229    }
230
231    /// Resets cumulative `LayoutTelemetry` counters to zero.
232    ///
233    /// # Arguments
234    ///
235    /// - `&Self` - Mutable layout engine.
236    pub fn reset_telemetry(&mut self) {
237        self.set_telemetry(LayoutTelemetry::default());
238    }
239
240    /// Returns per-pass split measure/final layout cache and interval text cache diagnostics.
241    ///
242    /// # Arguments
243    ///
244    /// - `&Self` - Layout engine reference.
245    ///
246    /// # Returns
247    ///
248    /// - `SplitCacheStats` - Split cache hit/miss diagnostics from the most recent layout pass.
249    #[must_use]
250    pub fn split_cache_stats(&self) -> SplitCacheStats {
251        let Self {
252            last_split_stats, ..
253        } = self;
254        *last_split_stats
255    }
256
257    /// Returns the cached spatial `subtree_bounds` computed for `node_id`, if valid.
258    ///
259    /// # Arguments
260    ///
261    /// - `&Self` - Layout engine reference.
262    /// - `NodeId` - Target scene node handle.
263    ///
264    /// # Returns
265    ///
266    /// - `Option<Rect>` - Cached subtree visual/interactive bounding box in root logical coordinates.
267    #[must_use]
268    pub fn subtree_bounds(&self, node_id: NodeId) -> Option<Rect> {
269        let Self { split_cache, .. } = self;
270        split_cache.subtree_bounds_for(node_id)
271    }
272
273    /// Performs zero-allocation spatial hit-testing accelerated by cached `subtree_bounds` and `has_nonzero_z_child`.
274    ///
275    /// # Arguments
276    ///
277    /// - `&Self` - Layout engine reference owning the spatial cache.
278    /// - `&SceneTree` - Retained scene tree after layout.
279    /// - `Point` - Logical pointer coordinates in root space.
280    ///
281    /// # Returns
282    ///
283    /// - `Option<NodeId>` - Topmost matching node handle, if any.
284    #[must_use]
285    pub fn hit_test(&self, tree: &SceneTree, point: Point) -> Option<NodeId> {
286        let mut visited: usize = 0;
287        let Self { split_cache, .. } = self;
288        hit_test_with_cache(tree, point, Some(split_cache), &mut visited)
289    }
290
291    /// Performs zero-allocation spatial hit-testing and also returns the number of inspected scene nodes.
292    ///
293    /// # Arguments
294    ///
295    /// - `&Self` - Layout engine reference owning the spatial cache.
296    /// - `&SceneTree` - Retained scene tree after layout.
297    /// - `Point` - Logical pointer coordinates in root space.
298    ///
299    /// # Returns
300    ///
301    /// - `(Option<NodeId>, usize)` - Pair of `(topmost_hit, nodes_visited)`.
302    #[must_use]
303    pub fn hit_test_with_visited(&self, tree: &SceneTree, point: Point) -> (Option<NodeId>, usize) {
304        let mut visited: usize = 0;
305        let Self { split_cache, .. } = self;
306        let hit: Option<NodeId> = hit_test_with_cache(tree, point, Some(split_cache), &mut visited);
307        (hit, visited)
308    }
309
310    /// Records the first pre-layout geometry snapshot of `node_id` in O(1) using generation-stamped deduplication.
311    ///
312    /// # Arguments
313    ///
314    /// - `&Self` - Mutable layout engine.
315    /// - `&SceneTree` - Retained scene tree prior to writing `node_id`'s updated layout box.
316    /// - `NodeId` - Target node handle about to be mutated.
317    #[inline]
318    fn record_layout_snapshot(&mut self, tree: &SceneTree, node_id: NodeId) {
319        let Self {
320            track_damage,
321            damage_fallback,
322            layout_snapshots,
323            split_cache,
324            ..
325        } = self;
326        if !*track_damage || *damage_fallback != LAYOUT_FALLBACK_NONE {
327            return;
328        }
329        if split_cache.is_snapshot_seen(node_id) {
330            return;
331        }
332        if layout_snapshots.len() >= DIRTY_PAINT_FULL_THRESHOLD {
333            *damage_fallback = LAYOUT_FALLBACK_OVERFLOW;
334            return;
335        }
336        let Some(node) = tree.get_node(node_id) else {
337            return;
338        };
339        let lbox: LayoutBox = node.get_layout_box();
340        let old_bounds: Rect = lbox.get_bounds();
341        let old_content_bounds: Rect = lbox.get_content_bounds();
342        let old_content_size: Size = lbox.get_content_size();
343        let (has_old_screen, old_screen): (bool, Rect) =
344            if old_bounds.get_width() > 0.0 && old_bounds.get_height() > 0.0 {
345                match tree.node_conservative_logical_rect(node_id) {
346                    Some(rect) => (true, rect),
347                    None => {
348                        *damage_fallback = LAYOUT_FALLBACK_UNSAFE;
349                        return;
350                    }
351                }
352            } else {
353                (false, Rect::default())
354            };
355        split_cache.mark_snapshot_seen(node_id);
356        layout_snapshots.push(LayoutNodeSnapshot {
357            id: node_id,
358            old_bounds,
359            old_content_bounds,
360            old_content_size,
361            has_old_screen,
362            old_screen,
363        });
364    }
365
366    /// Returns `true` when two layout rectangles are equal within subpixel tolerance.
367    ///
368    /// # Arguments
369    ///
370    /// - `Rect` - First rectangle.
371    /// - `Rect` - Second rectangle.
372    ///
373    /// # Returns
374    ///
375    /// - `bool` - Whether position and dimensions match within `0.001` logical pixels.
376    #[inline]
377    fn rect_approx_eq(a: Rect, b: Rect) -> bool {
378        (a.get_x() - b.get_x()).abs() <= 0.001
379            && (a.get_y() - b.get_y()).abs() <= 0.001
380            && (a.get_width() - b.get_width()).abs() <= 0.001
381            && (a.get_height() - b.get_height()).abs() <= 0.001
382    }
383
384    /// Returns `true` when `length` depends on the root viewport dimensions (`vw` or `vh`).
385    ///
386    /// # Arguments
387    ///
388    /// - `Length` - Length value to classify.
389    ///
390    /// # Returns
391    ///
392    /// - `bool` - `true` when `length` is `Length::ViewportWidth` or `Length::ViewportHeight`.
393    #[inline(always)]
394    fn is_viewport_length(length: Length) -> bool {
395        matches!(length, Length::ViewportWidth(_)) || matches!(length, Length::ViewportHeight(_))
396    }
397
398    /// Returns `true` when two layout sizes are equal within subpixel tolerance.
399    ///
400    /// # Arguments
401    ///
402    /// - `Size` - First size.
403    /// - `Size` - Second size.
404    ///
405    /// # Returns
406    ///
407    /// - `bool` - Whether width and height match within `0.001` logical pixels.
408    #[inline]
409    fn size_approx_eq(a: Size, b: Size) -> bool {
410        (a.get_width() - b.get_width()).abs() <= 0.001
411            && (a.get_height() - b.get_height()).abs() <= 0.001
412    }
413
414    /// Measures text bounding dimensions via per-node cached 128-bit hashes and the interval-aware `TextSizeCache`.
415    ///
416    /// # Arguments
417    ///
418    /// - `&Self` - Mutable layout engine reference.
419    /// - `NodeId` - Target text or input node handle.
420    /// - `&str` - UTF-8 text content to measure.
421    /// - `TextStyle` - Active typography style.
422    /// - `Option<f32>` - Optional maximum wrap width in logical pixels.
423    /// - `bool` - Whether `DIRTY_TEXT` is set on the node.
424    ///
425    /// # Returns
426    ///
427    /// - `TextSizeMeasurement` - Exact measured bounding dimensions and wrap-interval metadata.
428    fn measure_node_text_cached(
429        &mut self,
430        node_id: NodeId,
431        text: &str,
432        style: TextStyle,
433        max_width: Option<f32>,
434        dirty_text: bool,
435    ) -> TextSizeMeasurement {
436        let measurer: DeterministicTextMeasurer = self.get_measurer();
437        let Self {
438            text_size_cache,
439            split_cache,
440            last_split_stats,
441            ..
442        } = self;
443        let Some((hash_a, hash_b, text_len, reused_hash)) =
444            split_cache.text_hash_for_node(node_id, text, dirty_text)
445        else {
446            let measured: Size = measurer.measure_size(text, style, max_width);
447            return TextSizeMeasurement {
448                size: measured,
449                unwrapped: false,
450                max_content_w: f32::INFINITY,
451                cache_hit: false,
452            };
453        };
454        if reused_hash {
455            last_split_stats.text_hash_reuses = last_split_stats.text_hash_reuses.saturating_add(1);
456        }
457        let result: TextSizeMeasurement = text_size_cache.get_or_measure_hashed(
458            text,
459            (hash_a, hash_b, text_len),
460            style,
461            max_width,
462            |raw: &str, text_style: TextStyle, limit: Option<f32>| {
463                measurer.measure_size(raw, text_style, limit)
464            },
465        );
466        if result.cache_hit {
467            last_split_stats.text_interval_hits =
468                last_split_stats.text_interval_hits.saturating_add(1);
469        }
470        result
471    }
472
473    /// Computes or retrieves cached layout for `node_id` in either `ComputeSize` (measure) or `PerformLayout` (final) mode.
474    ///
475    /// # Arguments
476    ///
477    /// - `&Self` - Mutable layout engine reference.
478    /// - `&mut SceneTree` - Mutable scene tree.
479    /// - `NodeId` - Node handle to measure or lay out.
480    /// - `AvailableSpace` - Parent space constraint and origin.
481    /// - `LayoutRunMode` - `ComputeSize` probe vs `PerformLayout` placement mode.
482    /// - `&mut LayoutStats` - Mutable telemetry counters.
483    ///
484    /// # Returns
485    ///
486    /// - `(Size, u8, f32)` - Computed border-box size, dependency mask (`LAYOUT_DEP_*`), and invariant `min_avail_w`.
487    fn layout_node_mode(
488        &mut self,
489        tree: &mut SceneTree,
490        node_id: NodeId,
491        space: AvailableSpace,
492        mode: LayoutRunMode,
493        stats: &mut LayoutStats,
494    ) -> (Size, u8, f32) {
495        let is_dirty: bool = match tree.get_node(node_id) {
496            Some(node) => node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK),
497            None => return (Size::default(), LAYOUT_DEP_NONE, 0.0),
498        };
499        let (slot_idx, content_gen): (usize, u32) = {
500            let Self { split_cache, .. } = self;
501            split_cache.prepare_node(node_id, is_dirty)
502        };
503        if mode == LayoutRunMode::ComputeSize {
504            let measure_hit: Option<(Size, u8, f32)> = {
505                let Self { split_cache, .. } = self;
506                split_cache.lookup_measure(slot_idx, space, content_gen)
507            };
508            if let Some(hit) = measure_hit {
509                let Self {
510                    last_split_stats, ..
511                } = self;
512                last_split_stats.measure_hits = last_split_stats.measure_hits.saturating_add(1);
513                stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
514                return hit;
515            }
516            if !is_dirty {
517                let final_hit: Option<FinalLayoutSlot> = {
518                    let Self { split_cache, .. } = self;
519                    split_cache.lookup_final(slot_idx, content_gen)
520                };
521                if let Some(fslot) = final_hit
522                    && !fslot.hidden
523                    && fslot.space.can_reuse(space)
524                {
525                    let Self {
526                        last_split_stats, ..
527                    } = self;
528                    last_split_stats.measure_hits = last_split_stats.measure_hits.saturating_add(1);
529                    stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
530                    return (fslot.size, fslot.dep_flags, fslot.min_avail_w);
531                }
532            }
533            {
534                let Self {
535                    last_split_stats, ..
536                } = self;
537                last_split_stats.measure_misses = last_split_stats.measure_misses.saturating_add(1);
538            }
539            stats.set_nodes_computed(stats.get_nodes_computed() + 1);
540        } else {
541            if !is_dirty {
542                let final_hit: Option<FinalLayoutSlot> = {
543                    let Self { split_cache, .. } = self;
544                    split_cache.lookup_final(slot_idx, content_gen)
545                };
546                if let Some(fslot) = final_hit
547                    && fslot.space.can_reuse(space)
548                {
549                    if fslot.hidden {
550                        let Self {
551                            last_split_stats, ..
552                        } = self;
553                        last_split_stats.final_hits = last_split_stats.final_hits.saturating_add(1);
554                        stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
555                        return (Size::default(), LAYOUT_DEP_NONE, 0.0);
556                    }
557                    if !fslot.space.same_origin(space) {
558                        let dx: f32 = space.get_origin_x() - fslot.space.get_origin_x();
559                        let dy: f32 = space.get_origin_y() - fslot.space.get_origin_y();
560                        self.translate_subtree(tree, node_id, dx, dy);
561                        if dx.abs() > 0.001 || dy.abs() > 0.001 {
562                            stats.set_nodes_changed(stats.get_nodes_changed().saturating_add(1));
563                        }
564                    }
565                    if fslot.post_stretched {
566                        let restored_opt: Option<(Rect, Rect, Size)> = {
567                            let Self { split_cache, .. } = self;
568                            split_cache.lookup_final(slot_idx, content_gen).map(
569                                |s: FinalLayoutSlot| (s.bounds, s.content_bounds, s.content_size),
570                            )
571                        };
572                        if let Some((r_bounds, r_content, r_csize)) = restored_opt {
573                            self.record_layout_snapshot(tree, node_id);
574                            if let Some(node) = tree.get_node_mut(node_id) {
575                                node.get_mut_layout_box().set_bounds(r_bounds);
576                                node.get_mut_layout_box().set_content_bounds(r_content);
577                                node.get_mut_layout_box().set_content_size(r_csize);
578                            }
579                            let Self { split_cache, .. } = self;
580                            if let Some(slot_mut) = split_cache.final_slots[slot_idx].as_mut() {
581                                slot_mut.post_stretched = false;
582                            }
583                        }
584                    }
585                    let Self {
586                        last_split_stats, ..
587                    } = self;
588                    last_split_stats.final_hits = last_split_stats.final_hits.saturating_add(1);
589                    stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
590                    return (fslot.size, fslot.dep_flags, fslot.min_avail_w);
591                }
592            }
593            {
594                let Self {
595                    last_split_stats, ..
596                } = self;
597                last_split_stats.final_misses = last_split_stats.final_misses.saturating_add(1);
598            }
599            stats.set_nodes_computed(stats.get_nodes_computed() + 1);
600        }
601        let Some(node) = tree.get_node(node_id) else {
602            return (Size::default(), LAYOUT_DEP_NONE, 0.0);
603        };
604        let style_ref: &Style = node.style_ref();
605        let Style {
606            layout: layout_ref,
607            paint: paint_ref,
608            text: text_ref,
609        } = style_ref;
610        if layout_ref.get_display() == Display::None {
611            {
612                let Self {
613                    last_split_stats, ..
614                } = self;
615                last_split_stats.display_none_skips =
616                    last_split_stats.display_none_skips.saturating_add(1);
617            }
618            if mode == LayoutRunMode::ComputeSize {
619                let Self { split_cache, .. } = self;
620                split_cache.store_measure(
621                    slot_idx,
622                    space,
623                    LayoutRunMode::ComputeSize,
624                    content_gen,
625                    (Size::default(), LAYOUT_DEP_NONE, 0.0),
626                );
627                return (Size::default(), LAYOUT_DEP_NONE, 0.0);
628            }
629            self.record_layout_snapshot(tree, node_id);
630            let (prev_content_size, had_subtree_dirty): (Size, bool) =
631                if let Some(hidden_node) = tree.get_node_mut(node_id) {
632                    let old_b: Rect = hidden_node.get_layout_box().get_bounds();
633                    let csize: Size = hidden_node.get_layout_box().get_content_size();
634                    let sub_dirty: bool = hidden_node.get_dirty().intersects(DIRTY_SUBTREE_LAYOUT);
635                    if !Self::rect_approx_eq(old_b, Rect::default()) {
636                        stats.set_nodes_changed(stats.get_nodes_changed().saturating_add(1));
637                    }
638                    hidden_node.get_mut_layout_box().set_bounds(Rect::default());
639                    hidden_node
640                        .get_mut_layout_box()
641                        .set_content_bounds(Rect::default());
642                    hidden_node.set_last_constraint(Some(space));
643                    hidden_node.get_mut_dirty().remove(DIRTY_LAYOUT_PASS_MASK);
644                    (csize, sub_dirty)
645                } else {
646                    (Size::default(), false)
647                };
648            if let Some(meta) = tree.get_mut_meta().get_mut(node_id.as_usize()) {
649                let next_dirty: u16 = meta.get_dirty() & !DIRTY_LAYOUT_PASS_MASK;
650                let _: &mut NodeMeta = meta.set_dirty(next_dirty);
651            }
652            if had_subtree_dirty {
653                tree.set_has_stale_hidden_dirty(true);
654            }
655            let Self { split_cache, .. } = self;
656            split_cache.store_final(
657                slot_idx,
658                FinalLayoutSlot {
659                    space,
660                    subtree_gen: content_gen,
661                    size: Size::default(),
662                    bounds: Rect::default(),
663                    content_bounds: Rect::default(),
664                    content_size: prev_content_size,
665                    dep_flags: LAYOUT_DEP_NONE,
666                    min_avail_w: 0.0,
667                    post_stretched: false,
668                    hidden: true,
669                },
670            );
671            split_cache.store_subtree_meta(slot_idx, Rect::default(), false);
672            return (Size::default(), LAYOUT_DEP_NONE, 0.0);
673        }
674        let w_len: Length = layout_ref.get_width();
675        let h_len: Length = layout_ref.get_height();
676        let min_w_len: Length = layout_ref.get_min_width();
677        let max_w_len: Length = layout_ref.get_max_width();
678        let min_h_len: Length = layout_ref.get_min_height();
679        let max_h_len: Length = layout_ref.get_max_height();
680        let mut own_deps: u8 = LAYOUT_DEP_NONE;
681        if matches!(w_len, Length::Percent(_))
682            || matches!(min_w_len, Length::Percent(_))
683            || matches!(max_w_len, Length::Percent(_))
684        {
685            own_deps |= LAYOUT_DEP_AVAIL_W;
686        }
687        if matches!(h_len, Length::Percent(_))
688            || matches!(min_h_len, Length::Percent(_))
689            || matches!(max_h_len, Length::Percent(_))
690        {
691            own_deps |= LAYOUT_DEP_AVAIL_H;
692        }
693        if Self::is_viewport_length(w_len)
694            || Self::is_viewport_length(h_len)
695            || Self::is_viewport_length(min_w_len)
696            || Self::is_viewport_length(max_w_len)
697            || Self::is_viewport_length(min_h_len)
698            || Self::is_viewport_length(max_h_len)
699        {
700            own_deps |= LAYOUT_DEP_VIEWPORT;
701        }
702        let padding: Edges = layout_ref.get_padding();
703        let border_w: f32 = paint_ref.get_border().get_width();
704        let node_transform: Transform2D = paint_ref.get_transform();
705        let node_scroll: Point = node.get_layout_box().get_scroll_offset();
706        let self_is_portal: bool = matches!(node.get_kind(), NodeKind::Portal)
707            || layout_ref.get_position() == Position::Fixed;
708        let chrome_h: f32 = padding.horizontal() + border_w * 2.0;
709        let chrome_v: f32 = padding.vertical() + border_w * 2.0;
710        let explicit_w: Option<f32> = w_len.resolve(space.get_width(), space.get_viewport());
711        let explicit_h: Option<f32> = h_len.resolve(space.get_height(), space.get_viewport());
712        let mut resolved_w: Option<f32> = explicit_w;
713        let mut resolved_h: Option<f32> = explicit_h;
714        let stretched_w: bool = resolved_w.is_none() && space.get_stretch_width();
715        let stretched_h: bool = resolved_h.is_none() && space.get_stretch_height();
716        if stretched_w {
717            resolved_w = Some(space.get_width());
718            own_deps |= LAYOUT_DEP_AVAIL_W;
719        }
720        if stretched_h {
721            resolved_h = Some(space.get_height());
722            own_deps |= LAYOUT_DEP_AVAIL_H;
723        }
724        let min_w: f32 = min_w_len
725            .resolve(space.get_width(), space.get_viewport())
726            .unwrap_or(0.0);
727        let min_h: f32 = min_h_len
728            .resolve(space.get_height(), space.get_viewport())
729            .unwrap_or(0.0);
730        let max_w: f32 = max_w_len
731            .resolve(space.get_width(), space.get_viewport())
732            .unwrap_or(f32::INFINITY)
733            .max(min_w);
734        let max_h: f32 = max_h_len
735            .resolve(space.get_height(), space.get_viewport())
736            .unwrap_or(f32::INFINITY)
737            .max(min_h);
738        let aspect_ratio: Option<f32> = layout_ref.aspect_ratio_value();
739        if let Some(ratio) = aspect_ratio
740            && ratio > 0.0
741        {
742            if let Some(w) = resolved_w
743                && resolved_h.is_none()
744            {
745                resolved_h = Some(w.clamp(min_w, max_w) / ratio);
746            } else if let Some(h) = resolved_h
747                && resolved_w.is_none()
748            {
749                resolved_w = Some(h.clamp(min_h, max_h) * ratio);
750            }
751        }
752        let node_overflow: Overflow = layout_ref.get_overflow();
753        let node_flex_grow: f32 = layout_ref.get_flex_grow();
754        let width_independent: bool = explicit_w.is_some()
755            || (stretched_w
756                && resolved_w.is_some()
757                && (node_overflow != Overflow::Visible || node_flex_grow > 0.0));
758        let height_independent: bool = resolved_h.is_some() && h_len != Length::Auto;
759        if mode == LayoutRunMode::ComputeSize && width_independent && resolved_h.is_some() {
760            let final_w: f32 = resolved_w.unwrap_or(0.0).clamp(min_w, max_w).max(0.0);
761            let final_h: f32 = resolved_h.unwrap_or(0.0).clamp(min_h, max_h).max(0.0);
762            let final_size: Size = Size::new(final_w, final_h);
763            let Self { split_cache, .. } = self;
764            split_cache.store_measure(
765                slot_idx,
766                space,
767                LayoutRunMode::ComputeSize,
768                content_gen,
769                (final_size, own_deps, 0.0),
770            );
771            return (final_size, own_deps, 0.0);
772        }
773        let avail_w_outer: f32 = resolved_w
774            .unwrap_or(space.get_width())
775            .max(min_w)
776            .min(max_w);
777        let avail_h_outer: f32 = resolved_h
778            .unwrap_or(space.get_height())
779            .max(min_h)
780            .min(max_h);
781        let inner_avail_w: f32 = (avail_w_outer - chrome_h).max(0.0);
782        let inner_avail_h: f32 = (avail_h_outer - chrome_v).max(0.0);
783        let origin_x: f32 = space.get_origin_x();
784        let origin_y: f32 = space.get_origin_y();
785        let content_origin_x: f32 = origin_x + padding.get_left() + border_w;
786        let content_origin_y: f32 = origin_y + padding.get_top() + border_w;
787        let shields_avail_w: bool = resolved_w.is_some() && (own_deps & LAYOUT_DEP_AVAIL_W) == 0;
788        let shields_avail_h: bool = resolved_h.is_some() && (own_deps & LAYOUT_DEP_AVAIL_H) == 0;
789        let skip_leaf_measure: bool =
790            node_overflow != Overflow::Scroll && width_independent && height_independent;
791        let dirty_text: bool = node.get_dirty().intersects(DIRTY_TEXT);
792        let mut child_range: Option<(usize, usize)> = None;
793        let mut child_deps: u8 = LAYOUT_DEP_NONE;
794        let mut child_min_aw: f32 = 0.0;
795        let leaf_content_size: Option<Size> = match node.get_kind() {
796            NodeKind::Text(text) => {
797                if skip_leaf_measure {
798                    Some(Size::new(inner_avail_w, inner_avail_h))
799                } else {
800                    let measured: TextSizeMeasurement = self.measure_node_text_cached(
801                        node_id,
802                        text.as_str(),
803                        *text_ref,
804                        Some(inner_avail_w.max(1.0)),
805                        dirty_text,
806                    );
807                    if text_ref.get_overflow() != TextOverflow::Clip {
808                        if measured.unwrapped && measured.max_content_w.is_finite() {
809                            child_min_aw = measured.max_content_w + 0.5;
810                        } else {
811                            child_deps |= LAYOUT_DEP_AVAIL_W;
812                        }
813                    }
814                    Some(measured.size)
815                }
816            }
817            NodeKind::Image(img) => {
818                Some(Size::new(img.get_width() as f32, img.get_height() as f32))
819            }
820            NodeKind::Input(input_state) => {
821                if skip_leaf_measure {
822                    Some(Size::new(inner_avail_w, inner_avail_h))
823                } else {
824                    let sample: &str = if input_state.get_value().is_empty() {
825                        input_state.get_placeholder().as_str()
826                    } else {
827                        input_state.get_value().as_str()
828                    };
829                    let measured: TextSizeMeasurement = self.measure_node_text_cached(
830                        node_id,
831                        sample,
832                        *text_ref,
833                        Some(inner_avail_w.max(1.0)),
834                        dirty_text,
835                    );
836                    if text_ref.get_overflow() != TextOverflow::Clip {
837                        if measured.unwrapped && measured.max_content_w.is_finite() {
838                            child_min_aw = measured.max_content_w + 0.5;
839                        } else {
840                            child_deps |= LAYOUT_DEP_AVAIL_W;
841                        }
842                    }
843                    Some(Size::new(
844                        measured.size.get_width().max(120.0),
845                        measured.size.get_height().max(20.0),
846                    ))
847                }
848            }
849            NodeKind::View
850            | NodeKind::ScrollView
851            | NodeKind::Portal
852            | NodeKind::Fragment
853            | NodeKind::Canvas(_) => {
854                if !tree.has_children(node_id) {
855                    Some(Size::default())
856                } else {
857                    let start: usize = self.get_children_scratch().len();
858                    self.get_mut_children_scratch()
859                        .extend(tree.children_iter(node_id));
860                    let end: usize = self.get_children_scratch().len();
861                    child_range = Some((start, end));
862                    None
863                }
864            }
865        };
866        let parent_layout_copy: LayoutStyle = *layout_ref;
867        let content_size: Size = if let Some(size) = leaf_content_size {
868            size
869        } else if let Some((child_start, child_end)) = child_range {
870            let min_inner_size: Size =
871                Size::new((min_w - chrome_h).max(0.0), (min_h - chrome_v).max(0.0));
872            let frame: ContainerFrame = ContainerFrame::new(
873                parent_layout_copy,
874                Size::new(inner_avail_w, inner_avail_h),
875                space.get_viewport(),
876                Point::new(content_origin_x, content_origin_y),
877                resolved_w.is_some(),
878                resolved_h.is_some(),
879                min_inner_size,
880            );
881            let (size, c_deps, c_min_aw): (Size, u8, f32) =
882                self.layout_children(tree, (child_start, child_end), frame, mode, stats);
883            child_deps = c_deps;
884            child_min_aw = c_min_aw;
885            if mode == LayoutRunMode::ComputeSize {
886                self.get_mut_children_scratch().truncate(child_start);
887            }
888            size
889        } else {
890            Size::default()
891        };
892        let content_outer_w: f32 = content_size.get_width() + chrome_h;
893        let content_outer_h: f32 = content_size.get_height() + chrome_v;
894        let mut final_w: f32 = match (explicit_w, stretched_w) {
895            (Some(w), _) => w,
896            (None, true) => {
897                let base_w: f32 = resolved_w.unwrap_or(content_outer_w);
898                if node_overflow == Overflow::Visible
899                    && node_flex_grow <= 0.0
900                    && content_outer_w > base_w + 0.5
901                {
902                    content_outer_w
903                } else {
904                    base_w
905                }
906            }
907            (None, false) => content_outer_w,
908        };
909        let mut final_h: f32 = resolved_h.unwrap_or(content_outer_h);
910        if let Some(ratio) = aspect_ratio
911            && ratio > 0.0
912        {
913            if resolved_w.is_some() && resolved_h.is_none() {
914                final_h = final_w / ratio;
915            } else if resolved_h.is_some() && resolved_w.is_none() {
916                final_w = final_h * ratio;
917            }
918        }
919        final_w = final_w.clamp(min_w, max_w).max(0.0);
920        final_h = final_h.clamp(min_h, max_h).max(0.0);
921        let final_size: Size = Size::new(final_w, final_h);
922        let mut final_deps: u8 = own_deps | (child_deps & LAYOUT_DEP_VIEWPORT);
923        let mut final_min_aw: f32 = 0.0;
924        if !shields_avail_w {
925            if (child_deps & LAYOUT_DEP_AVAIL_W) != 0 {
926                final_deps |= LAYOUT_DEP_AVAIL_W;
927            } else if child_min_aw > 0.0 {
928                final_min_aw = child_min_aw + chrome_h;
929            }
930        }
931        if !shields_avail_h {
932            final_deps |= child_deps & LAYOUT_DEP_AVAIL_H;
933        }
934        if mode == LayoutRunMode::ComputeSize {
935            let Self { split_cache, .. } = self;
936            split_cache.store_measure(
937                slot_idx,
938                space,
939                LayoutRunMode::ComputeSize,
940                content_gen,
941                (final_size, final_deps, final_min_aw),
942            );
943            return (final_size, final_deps, final_min_aw);
944        }
945        let bounds: Rect = Rect::new(origin_x, origin_y, final_w, final_h);
946        let content_bounds: Rect = Rect::new(
947            content_origin_x,
948            content_origin_y,
949            (final_w - chrome_h).max(0.0),
950            (final_h - chrome_v).max(0.0),
951        );
952        self.record_layout_snapshot(tree, node_id);
953        if let Some(node) = tree.get_node_mut(node_id) {
954            let prev_box: LayoutBox = node.get_layout_box();
955            let changed: bool = !Self::rect_approx_eq(prev_box.get_bounds(), bounds)
956                || !Self::rect_approx_eq(prev_box.get_content_bounds(), content_bounds)
957                || !Self::size_approx_eq(prev_box.get_content_size(), content_size);
958            if changed {
959                stats.set_nodes_changed(stats.get_nodes_changed().saturating_add(1));
960            }
961            node.get_mut_layout_box().set_bounds(bounds);
962            node.get_mut_layout_box().set_content_bounds(content_bounds);
963            node.get_mut_layout_box().set_content_size(content_size);
964            node.set_last_constraint(Some(space));
965            node.get_mut_dirty().remove(DIRTY_LAYOUT_PASS_MASK);
966        }
967        if let Some(meta) = tree.get_mut_meta().get_mut(node_id.as_usize()) {
968            let next_dirty: u16 = meta.get_dirty() & !DIRTY_LAYOUT_PASS_MASK;
969            let _: &mut NodeMeta = meta.set_dirty(next_dirty);
970        }
971        let own_vis: Rect = shifted_node_bounds(bounds, Point::default(), node_transform);
972        let is_clipped: bool = matches!(node_overflow, Overflow::Hidden | Overflow::Scroll);
973        let mut sub_bounds: Rect = own_vis;
974        let mut has_nonzero_z: bool = false;
975        if let Some((c_start, c_end)) = child_range {
976            let tx: f32 = node_transform.get_translate_x() - node_scroll.get_x();
977            let ty: f32 = node_transform.get_translate_y() - node_scroll.get_y();
978            for idx in c_start..c_end {
979                let cid: NodeId = self.get_children_scratch()[idx];
980                if let Some(cnode) = tree.get_node(cid) {
981                    let clayout: &LayoutStyle = cnode.style_ref().layout_ref();
982                    if clayout.get_z_index() != 0 {
983                        has_nonzero_z = true;
984                    }
985                    let c_is_portal: bool = matches!(cnode.get_kind(), NodeKind::Portal)
986                        || clayout.get_position() == Position::Fixed;
987                    if !is_clipped
988                        && clayout.get_display() != Display::None
989                        && (self_is_portal || !c_is_portal)
990                    {
991                        let child_sb: Rect = {
992                            let Self { split_cache, .. } = self;
993                            split_cache.subtree_bounds_for(cid)
994                        }
995                        .unwrap_or_else(|| {
996                            shifted_node_bounds(
997                                cnode.get_layout_box().get_bounds(),
998                                Point::default(),
999                                cnode.style_ref().paint_ref().get_transform(),
1000                            )
1001                        });
1002                        if child_sb.get_width() > 0.0 && child_sb.get_height() > 0.0 {
1003                            let shifted_child: Rect = Rect::new(
1004                                child_sb.get_x() + tx,
1005                                child_sb.get_y() + ty,
1006                                child_sb.get_width(),
1007                                child_sb.get_height(),
1008                            );
1009                            sub_bounds = sub_bounds.union(shifted_child);
1010                        }
1011                    }
1012                }
1013            }
1014            self.get_mut_children_scratch().truncate(c_start);
1015        }
1016        let Self { split_cache, .. } = self;
1017        split_cache.store_final(
1018            slot_idx,
1019            FinalLayoutSlot {
1020                space,
1021                subtree_gen: content_gen,
1022                size: final_size,
1023                bounds,
1024                content_bounds,
1025                content_size,
1026                dep_flags: final_deps,
1027                min_avail_w: final_min_aw,
1028                post_stretched: false,
1029                hidden: false,
1030            },
1031        );
1032        if split_cache
1033            .lookup_measure(slot_idx, space, content_gen)
1034            .is_none()
1035        {
1036            split_cache.store_measure(
1037                slot_idx,
1038                space,
1039                LayoutRunMode::PerformLayout,
1040                content_gen,
1041                (final_size, final_deps, final_min_aw),
1042            );
1043        }
1044        split_cache.store_subtree_meta(slot_idx, sub_bounds, has_nonzero_z);
1045        (final_size, final_deps, final_min_aw)
1046    }
1047
1048    /// Lays out children according to Flex, Grid, or Block rules plus Absolute/Fixed overlays in `PerformLayout`.
1049    ///
1050    /// # Arguments
1051    ///
1052    /// - `&Self` - Mutable layout engine reference.
1053    /// - `&mut SceneTree` - Mutable scene tree.
1054    /// - `(usize, usize)` - Inclusive start and exclusive end indices into `children_scratch`.
1055    /// - `ContainerFrame` - Parent layout constraints and origin.
1056    /// - `LayoutRunMode` - `ComputeSize` probe vs `PerformLayout` placement mode.
1057    /// - `&mut LayoutStats` - Mutable telemetry counters.
1058    ///
1059    /// # Returns
1060    ///
1061    /// - `(Size, u8, f32)` - Aggregate flow content size, dependency mask, and invariant `min_avail_w`.
1062    fn layout_children(
1063        &mut self,
1064        tree: &mut SceneTree,
1065        child_range: (usize, usize),
1066        frame: ContainerFrame,
1067        mode: LayoutRunMode,
1068        stats: &mut LayoutStats,
1069    ) -> (Size, u8, f32) {
1070        let (child_start, child_end): (usize, usize) = child_range;
1071        let child_count: usize = child_end.saturating_sub(child_start);
1072        if child_count == 0 {
1073            return (Size::default(), LAYOUT_DEP_NONE, 0.0);
1074        }
1075        let parent_layout: LayoutStyle = frame.get_parent_layout();
1076        let inner_avail: Size = frame.get_inner_avail();
1077        let viewport: Size = frame.get_viewport();
1078        let content_origin: Point = frame.get_content_origin();
1079        let flex_dir_opt: Option<FlexDirection> = match parent_layout.get_display() {
1080            Display::Grid => None,
1081            Display::Block => Some(FlexDirection::Column),
1082            Display::Flex | Display::None => Some(parent_layout.get_flex_direction()),
1083        };
1084        let is_row_dir: bool = matches!(
1085            flex_dir_opt,
1086            Some(FlexDirection::Row | FlexDirection::RowReverse)
1087        );
1088        let is_reverse_dir: bool = matches!(
1089            flex_dir_opt,
1090            Some(FlexDirection::RowReverse | FlexDirection::ColumnReverse)
1091        );
1092        let parent_align: AlignItems = parent_layout.get_align_items();
1093        let parent_height_auto: bool = parent_layout.get_height() == Length::Auto;
1094        let parent_bounded_main: bool = if is_row_dir {
1095            frame.get_definite_width() || parent_layout.get_max_width() != Length::Auto
1096        } else {
1097            frame.get_definite_height() || parent_layout.get_max_height() != Length::Auto
1098        };
1099        let mut single_pass_ok: bool = flex_dir_opt.is_some()
1100            && parent_layout.get_flex_wrap() != FlexWrap::Wrap
1101            && !is_reverse_dir
1102            && parent_layout.get_justify_content() == JustifyContent::Start;
1103        let mut shrinkable_flow_children: usize = 0;
1104        let flow_start: usize = self.get_flow_scratch().len();
1105        let abs_start: usize = self.get_abs_scratch().len();
1106        for idx in child_start..child_end {
1107            let child_id: NodeId = self.get_children_scratch()[idx];
1108            if let Some(child_node) = tree.get_node(child_id) {
1109                let Style {
1110                    layout: child_layout,
1111                    ..
1112                } = child_node.style_ref();
1113                if child_layout.get_display() == Display::None {
1114                    if mode == LayoutRunMode::PerformLayout {
1115                        let _: (Size, u8, f32) = self.layout_node_mode(
1116                            tree,
1117                            child_id,
1118                            AvailableSpace::new(0.0, 0.0, viewport, 0.0, 0.0),
1119                            LayoutRunMode::PerformLayout,
1120                            stats,
1121                        );
1122                    }
1123                    continue;
1124                }
1125                match child_layout.get_position() {
1126                    Position::Relative => {
1127                        if single_pass_ok {
1128                            if parent_bounded_main && child_layout.get_flex_shrink() > 0.0 {
1129                                let can_shrink_child: bool = if is_row_dir {
1130                                    child_layout.get_min_width() != Length::Auto
1131                                        || child_layout.get_overflow() != Overflow::Visible
1132                                        || !matches!(child_node.get_kind(), NodeKind::Text(_))
1133                                        || child_node.style_ref().text_ref().get_overflow()
1134                                            != TextOverflow::Clip
1135                                } else {
1136                                    child_layout.get_min_height() != Length::Auto
1137                                        || child_layout.get_overflow() != Overflow::Visible
1138                                };
1139                                if can_shrink_child {
1140                                    shrinkable_flow_children += 1;
1141                                }
1142                            }
1143                            if child_layout.get_flex_grow() > 0.0 {
1144                                single_pass_ok = false;
1145                            } else {
1146                                let align: AlignItems = match child_layout.get_align_self() {
1147                                    AlignSelf::Auto => parent_align,
1148                                    AlignSelf::Stretch => AlignItems::Stretch,
1149                                    AlignSelf::Start => AlignItems::Start,
1150                                    AlignSelf::Center => AlignItems::Center,
1151                                    AlignSelf::End => AlignItems::End,
1152                                };
1153                                let non_start_align: bool =
1154                                    matches!(align, AlignItems::Center | AlignItems::End);
1155                                let auto_row_stretch: bool = align == AlignItems::Stretch
1156                                    && is_row_dir
1157                                    && child_layout.get_height() == Length::Auto
1158                                    && (parent_height_auto
1159                                        || frame.get_min_inner_size().get_height() > 0.0);
1160                                if non_start_align || auto_row_stretch {
1161                                    single_pass_ok = false;
1162                                }
1163                            }
1164                        }
1165                        self.get_mut_flow_scratch().push(child_id);
1166                    }
1167                    Position::Absolute | Position::Fixed => {
1168                        if mode == LayoutRunMode::PerformLayout {
1169                            self.get_mut_abs_scratch().push(child_id);
1170                        }
1171                    }
1172                }
1173            }
1174        }
1175        let flow_end: usize = self.get_flow_scratch().len();
1176        let flow_count: usize = flow_end.saturating_sub(flow_start);
1177        if single_pass_ok && shrinkable_flow_children > 0 && (!is_row_dir || flow_count >= 2) {
1178            single_pass_ok = false;
1179        }
1180        let abs_end: usize = self.get_abs_scratch().len();
1181        let flow_result: (Size, u8, f32) = if let Some(flex_dir) = flex_dir_opt {
1182            self.layout_flex(
1183                tree,
1184                (flow_start, flow_end),
1185                frame,
1186                flex_dir,
1187                (single_pass_ok, mode),
1188                stats,
1189            )
1190        } else {
1191            self.layout_grid(tree, (flow_start, flow_end), frame, mode, stats)
1192        };
1193        self.get_mut_flow_scratch().truncate(flow_start);
1194        if mode == LayoutRunMode::PerformLayout {
1195            for abs_idx in abs_start..abs_end {
1196                let abs_id: NodeId = self.get_abs_scratch()[abs_idx];
1197                let child_layout_opt: Option<LayoutStyle> = tree
1198                    .get_node(abs_id)
1199                    .map(|node: &SceneNode| node.style_ref().get_layout());
1200                let Some(child_layout) = child_layout_opt else {
1201                    continue;
1202                };
1203                let is_fixed: bool = child_layout.get_position() == Position::Fixed;
1204                let ref_origin: Point = if is_fixed {
1205                    Point::new(0.0, 0.0)
1206                } else {
1207                    content_origin
1208                };
1209                let ref_size: Size = if is_fixed { viewport } else { inner_avail };
1210                let resolved_w: Option<f32> = child_layout
1211                    .get_width()
1212                    .resolve(ref_size.get_width(), viewport);
1213                let resolved_h: Option<f32> = child_layout
1214                    .get_height()
1215                    .resolve(ref_size.get_height(), viewport);
1216                let needs_intrinsic: bool = (resolved_w.is_none()
1217                    && child_layout.left_offset().is_none()
1218                    && child_layout.right_offset().is_some())
1219                    || (resolved_h.is_none()
1220                        && child_layout.top_offset().is_none()
1221                        && child_layout.bottom_offset().is_some());
1222                let probed: Size = if needs_intrinsic {
1223                    let probe_space: AvailableSpace = AvailableSpace::new(
1224                        ref_size.get_width(),
1225                        ref_size.get_height(),
1226                        viewport,
1227                        ref_origin.get_x(),
1228                        ref_origin.get_y(),
1229                    );
1230                    self.layout_node_mode(
1231                        tree,
1232                        abs_id,
1233                        probe_space,
1234                        LayoutRunMode::ComputeSize,
1235                        stats,
1236                    )
1237                    .0
1238                } else {
1239                    Size::new(ref_size.get_width(), ref_size.get_height())
1240                };
1241                let child_w: f32 = resolved_w.unwrap_or(probed.get_width());
1242                let child_h: f32 = resolved_h.unwrap_or(probed.get_height());
1243                let x: f32 = if let Some(left) = child_layout.left_offset() {
1244                    ref_origin.get_x() + left
1245                } else if let Some(right) = child_layout.right_offset() {
1246                    ref_origin.get_x() + (ref_size.get_width() - child_w - right)
1247                } else {
1248                    ref_origin.get_x()
1249                };
1250                let y: f32 = if let Some(top) = child_layout.top_offset() {
1251                    ref_origin.get_y() + top
1252                } else if let Some(bottom) = child_layout.bottom_offset() {
1253                    ref_origin.get_y() + (ref_size.get_height() - child_h - bottom)
1254                } else {
1255                    ref_origin.get_y()
1256                };
1257                let abs_space: AvailableSpace = AvailableSpace::new(
1258                    ref_size.get_width(),
1259                    ref_size.get_height(),
1260                    viewport,
1261                    x,
1262                    y,
1263                );
1264                let _: (Size, u8, f32) = self.layout_node_mode(
1265                    tree,
1266                    abs_id,
1267                    abs_space,
1268                    LayoutRunMode::PerformLayout,
1269                    stats,
1270                );
1271            }
1272            self.get_mut_abs_scratch().truncate(abs_start);
1273        }
1274        flow_result
1275    }
1276
1277    /// Executes single-line or multi-line Flexbox layout with split `ComputeSize` probing and `PerformLayout` placement.
1278    ///
1279    /// # Arguments
1280    ///
1281    /// - `&Self` - Mutable layout engine reference.
1282    /// - `&mut SceneTree` - Mutable scene tree.
1283    /// - `(usize, usize)` - Inclusive start and exclusive end indices into `flow_scratch`.
1284    /// - `ContainerFrame` - Container constraints and origin.
1285    /// - `FlexDirection` - Effective main-axis direction.
1286    /// - `(bool, LayoutRunMode)` - Pair of `(single_pass_ok, run_mode)`.
1287    /// - `&mut LayoutStats` - Mutable telemetry counters.
1288    ///
1289    /// # Returns
1290    ///
1291    /// - `(Size, u8, f32)` - Aggregate content size, dependency mask, and invariant `min_avail_w`.
1292    fn layout_flex(
1293        &mut self,
1294        tree: &mut SceneTree,
1295        flow_range: (usize, usize),
1296        frame: ContainerFrame,
1297        direction: FlexDirection,
1298        mode_flags: (bool, LayoutRunMode),
1299        stats: &mut LayoutStats,
1300    ) -> (Size, u8, f32) {
1301        let (flow_start, flow_end): (usize, usize) = flow_range;
1302        let (single_pass_ok, mode): (bool, LayoutRunMode) = mode_flags;
1303        let count_all: usize = flow_end.saturating_sub(flow_start);
1304        if count_all == 0 {
1305            return (Size::default(), LAYOUT_DEP_NONE, 0.0);
1306        }
1307        let parent_layout: LayoutStyle = frame.get_parent_layout();
1308        let inner_avail: Size = frame.get_inner_avail();
1309        let viewport: Size = frame.get_viewport();
1310        let content_origin: Point = frame.get_content_origin();
1311        let is_row: bool = matches!(direction, FlexDirection::Row | FlexDirection::RowReverse);
1312        let is_reverse: bool = matches!(
1313            direction,
1314            FlexDirection::RowReverse | FlexDirection::ColumnReverse
1315        );
1316        let main_gap: f32 = if is_row {
1317            parent_layout.get_column_gap()
1318        } else {
1319            parent_layout.get_row_gap()
1320        };
1321        let cross_gap: f32 = if is_row {
1322            parent_layout.get_row_gap()
1323        } else {
1324            parent_layout.get_column_gap()
1325        };
1326        let main_avail: f32 = if is_row {
1327            inner_avail.get_width()
1328        } else {
1329            inner_avail.get_height()
1330        };
1331        let cross_avail: f32 = if is_row {
1332            inner_avail.get_height()
1333        } else {
1334            inner_avail.get_width()
1335        };
1336        if is_reverse {
1337            self.get_mut_flow_scratch()[flow_start..flow_end].reverse();
1338        }
1339        let wrap_enabled: bool = parent_layout.get_flex_wrap() == FlexWrap::Wrap;
1340        if single_pass_ok {
1341            let parent_align: AlignItems = parent_layout.get_align_items();
1342            let mut main_cursor: f32 = 0.0;
1343            let mut max_cross: f32 = 0.0;
1344            let mut agg_deps: u8 = LAYOUT_DEP_NONE;
1345            let mut agg_min_aw: f32 = 0.0;
1346            let records_start: usize = self.get_flex_items_scratch().len();
1347            for offset in 0..count_all {
1348                let child_id: NodeId = self.get_flow_scratch()[flow_start + offset];
1349                let (margin, align, width_auto, height_auto, c_overflow, c_transform): (
1350                    Edges,
1351                    AlignItems,
1352                    bool,
1353                    bool,
1354                    Overflow,
1355                    Transform2D,
1356                ) = if let Some(node) = tree.get_node(child_id) {
1357                    let Style {
1358                        layout: child_layout,
1359                        paint: child_paint,
1360                        ..
1361                    } = node.style_ref();
1362                    let a: AlignItems = match child_layout.get_align_self() {
1363                        AlignSelf::Auto => parent_align,
1364                        AlignSelf::Stretch => AlignItems::Stretch,
1365                        AlignSelf::Start => AlignItems::Start,
1366                        AlignSelf::Center => AlignItems::Center,
1367                        AlignSelf::End => AlignItems::End,
1368                    };
1369                    (
1370                        child_layout.get_margin(),
1371                        a,
1372                        child_layout.get_width() == Length::Auto,
1373                        child_layout.get_height() == Length::Auto,
1374                        child_layout.get_overflow(),
1375                        child_paint.get_transform(),
1376                    )
1377                } else {
1378                    (
1379                        Edges::default(),
1380                        parent_align,
1381                        true,
1382                        true,
1383                        Overflow::Visible,
1384                        Transform2D::default(),
1385                    )
1386                };
1387                let (x, y): (f32, f32) = if is_row {
1388                    (
1389                        content_origin.get_x() + main_cursor + margin.get_left(),
1390                        content_origin.get_y() + margin.get_top(),
1391                    )
1392                } else {
1393                    (
1394                        content_origin.get_x() + margin.get_left(),
1395                        content_origin.get_y() + main_cursor + margin.get_top(),
1396                    )
1397                };
1398                let stretch_w: bool = !is_row && align == AlignItems::Stretch && width_auto;
1399                let stretch_h: bool = is_row && align == AlignItems::Stretch && height_auto;
1400                if stretch_w {
1401                    agg_deps |= LAYOUT_DEP_AVAIL_W;
1402                }
1403                if stretch_h {
1404                    agg_deps |= LAYOUT_DEP_AVAIL_H;
1405                }
1406                let space_w: f32 = if stretch_w {
1407                    (inner_avail.get_width() - margin.horizontal()).max(0.0)
1408                } else {
1409                    inner_avail.get_width()
1410                };
1411                let space_h: f32 = if stretch_h {
1412                    (inner_avail.get_height() - margin.vertical()).max(0.0)
1413                } else {
1414                    inner_avail.get_height()
1415                };
1416                let final_space: AvailableSpace =
1417                    AvailableSpace::new(space_w, space_h, viewport, x, y)
1418                        .with_stretch(stretch_w, stretch_h);
1419                let (placed, c_deps, c_min_aw): (Size, u8, f32) =
1420                    self.layout_node_mode(tree, child_id, final_space, mode, stats);
1421                agg_deps |= c_deps;
1422                if c_min_aw > 0.0 {
1423                    agg_min_aw = agg_min_aw.max(c_min_aw + margin.horizontal());
1424                }
1425                let target_w: f32 = if stretch_w {
1426                    space_w.max(placed.get_width())
1427                } else {
1428                    placed.get_width()
1429                };
1430                let target_h: f32 = if stretch_h {
1431                    space_h.max(placed.get_height())
1432                } else {
1433                    placed.get_height()
1434                };
1435                if mode == LayoutRunMode::PerformLayout {
1436                    if (stretch_w && target_w > placed.get_width() + 0.01)
1437                        || (stretch_h && target_h > placed.get_height() + 0.01)
1438                    {
1439                        self.record_layout_snapshot(tree, child_id);
1440                        let updated_b: Option<Rect> =
1441                            if let Some(node) = tree.get_node_mut(child_id) {
1442                                let mut b: Rect = node.get_layout_box().get_bounds();
1443                                b.set_width(target_w);
1444                                b.set_height(target_h);
1445                                node.get_mut_layout_box().set_bounds(b);
1446                                Some(b)
1447                            } else {
1448                                None
1449                            };
1450                        if let Some(b) = updated_b {
1451                            let is_clipped: bool =
1452                                matches!(c_overflow, Overflow::Hidden | Overflow::Scroll);
1453                            let Self { split_cache, .. } = self;
1454                            split_cache.mark_post_stretched(child_id, b, c_transform, is_clipped);
1455                        }
1456                    }
1457                    if stretch_w {
1458                        self.get_mut_flex_items_scratch().push(FlexItemRecord::new(
1459                            child_id,
1460                            Size::new(target_w, target_h),
1461                            margin,
1462                            AlignSelf::Stretch,
1463                            c_overflow,
1464                            0,
1465                        ));
1466                    }
1467                }
1468                if is_row {
1469                    main_cursor += target_w + margin.horizontal();
1470                    max_cross = max_cross.max(target_h + margin.vertical());
1471                } else {
1472                    main_cursor += target_h + margin.vertical();
1473                    max_cross = max_cross.max(target_w + margin.horizontal());
1474                }
1475                if offset + 1 < count_all {
1476                    main_cursor += main_gap;
1477                }
1478            }
1479            let records_end: usize = self.get_flex_items_scratch().len();
1480            if mode == LayoutRunMode::PerformLayout
1481                && records_end > records_start
1482                && max_cross > cross_avail + 0.5
1483            {
1484                for rec_idx in records_start..records_end {
1485                    let rec: FlexItemRecord = self.get_flex_items_scratch()[rec_idx];
1486                    let widened: f32 =
1487                        (max_cross - rec.get_margin().horizontal()).max(rec.get_size().get_width());
1488                    self.record_layout_snapshot(tree, rec.get_node_id());
1489                    let updated_opt: Option<(Rect, Transform2D)> =
1490                        if let Some(node) = tree.get_node_mut(rec.get_node_id()) {
1491                            let tr: Transform2D = node.style_ref().paint_ref().get_transform();
1492                            let mut b: Rect = node.get_layout_box().get_bounds();
1493                            b.set_width(widened);
1494                            node.get_mut_layout_box().set_bounds(b);
1495                            Some((b, tr))
1496                        } else {
1497                            None
1498                        };
1499                    if let Some((b, tr)) = updated_opt {
1500                        let is_clipped: bool =
1501                            matches!(rec.get_overflow(), Overflow::Hidden | Overflow::Scroll);
1502                        let Self { split_cache, .. } = self;
1503                        split_cache.mark_post_stretched(rec.get_node_id(), b, tr, is_clipped);
1504                    }
1505                }
1506            }
1507            self.get_mut_flex_items_scratch().truncate(records_start);
1508            let out_size: Size = if is_row {
1509                Size::new(main_cursor, max_cross)
1510            } else {
1511                Size::new(max_cross, main_cursor)
1512            };
1513            return (out_size, agg_deps, agg_min_aw);
1514        }
1515        let items_start: usize = self.get_flex_items_scratch().len();
1516        let probe_template: AvailableSpace = AvailableSpace::new(
1517            inner_avail.get_width(),
1518            inner_avail.get_height(),
1519            viewport,
1520            content_origin.get_x(),
1521            content_origin.get_y(),
1522        );
1523        let mut total_grow: f32 = 0.0;
1524        let mut single_line_main: f32 = 0.0;
1525        let mut single_line_cross: f32 = 0.0;
1526        let mut pass1_deps: u8 = LAYOUT_DEP_NONE;
1527        let mut pass1_min_aw: f32 = 0.0;
1528        for flow_idx in flow_start..flow_end {
1529            let child_id: NodeId = self.get_flow_scratch()[flow_idx];
1530            let mut rec: FlexItemRecord = FlexItemRecord::new(
1531                child_id,
1532                Size::default(),
1533                Edges::default(),
1534                AlignSelf::Auto,
1535                Overflow::Visible,
1536                FLEX_ITEM_DEFAULT_FLAGS,
1537            );
1538            let _: &mut FlexItemRecord = rec.set_flex_shrink(1.0);
1539            let mut zero_basis_size: Option<Size> = None;
1540            let mut explicit_min_main: Option<f32> = None;
1541            let mut is_unwrapped_clip_text: bool = false;
1542            let mut has_px_main: bool = false;
1543            if let Some(node) = tree.get_node(child_id) {
1544                let child_style: &Style = node.style_ref();
1545                let child_layout: &LayoutStyle = child_style.layout_ref();
1546                let child_text: &TextStyle = child_style.text_ref();
1547                let width_len: Length = child_layout.get_width();
1548                let height_len: Length = child_layout.get_height();
1549                has_px_main = matches!(if is_row { width_len } else { height_len }, Length::Px(_));
1550                let min_main_len: Length = if is_row {
1551                    child_layout.get_min_width()
1552                } else {
1553                    child_layout.get_min_height()
1554                };
1555                if matches!(min_main_len, Length::Percent(_)) {
1556                    pass1_deps |= if is_row {
1557                        LAYOUT_DEP_AVAIL_W
1558                    } else {
1559                        LAYOUT_DEP_AVAIL_H
1560                    };
1561                }
1562                if Self::is_viewport_length(min_main_len) {
1563                    pass1_deps |= LAYOUT_DEP_VIEWPORT;
1564                }
1565                explicit_min_main = min_main_len.resolve(main_avail, viewport);
1566                is_unwrapped_clip_text = matches!(node.get_kind(), NodeKind::Text(_))
1567                    && child_text.get_overflow() == TextOverflow::Clip;
1568                let grow: f32 = child_layout.get_flex_grow();
1569                let shrink: f32 = child_layout.get_flex_shrink().max(0.0);
1570                let width_auto: bool = width_len == Length::Auto;
1571                let height_auto: bool = height_len == Length::Auto;
1572                let mut f: u16 = 0;
1573                if width_auto {
1574                    f |= FLEX_ITEM_WIDTH_AUTO;
1575                }
1576                if height_auto {
1577                    f |= FLEX_ITEM_HEIGHT_AUTO;
1578                }
1579                if matches!(width_len, Length::Percent(_)) {
1580                    f |= FLEX_ITEM_WIDTH_PERCENT;
1581                }
1582                if matches!(height_len, Length::Percent(_)) {
1583                    f |= FLEX_ITEM_HEIGHT_PERCENT;
1584                }
1585                let zero_basis: bool =
1586                    !wrap_enabled && grow > 0.0 && if is_row { width_auto } else { height_auto };
1587                if zero_basis {
1588                    if is_row {
1589                        if matches!(height_len, Length::Percent(_)) {
1590                            pass1_deps |= LAYOUT_DEP_AVAIL_H;
1591                        }
1592                        if Self::is_viewport_length(height_len) {
1593                            pass1_deps |= LAYOUT_DEP_VIEWPORT;
1594                        }
1595                        let h: f32 = height_len.resolve(cross_avail, viewport).unwrap_or(0.0);
1596                        zero_basis_size = Some(Size::new(0.0, h));
1597                    } else {
1598                        if matches!(width_len, Length::Percent(_)) {
1599                            pass1_deps |= LAYOUT_DEP_AVAIL_W;
1600                        }
1601                        if Self::is_viewport_length(width_len) {
1602                            pass1_deps |= LAYOUT_DEP_VIEWPORT;
1603                        }
1604                        let w: f32 = width_len.resolve(cross_avail, viewport).unwrap_or(0.0);
1605                        zero_basis_size = Some(Size::new(w, 0.0));
1606                    }
1607                }
1608                let _: &mut FlexItemRecord = rec.set_margin(child_layout.get_margin());
1609                let _: &mut FlexItemRecord = rec.set_flex_grow(grow);
1610                let _: &mut FlexItemRecord = rec.set_flex_shrink(shrink);
1611                let _: &mut FlexItemRecord = rec.set_align_self(child_layout.get_align_self());
1612                let _: &mut FlexItemRecord = rec.set_overflow(child_layout.get_overflow());
1613                let _: &mut FlexItemRecord = rec.set_flags(f);
1614            }
1615            total_grow += rec.get_flex_grow();
1616            let child_size: Size = if let Some(zb) = zero_basis_size {
1617                zb
1618            } else {
1619                let (measured, c_deps, c_min_aw): (Size, u8, f32) = self.layout_node_mode(
1620                    tree,
1621                    child_id,
1622                    probe_template,
1623                    LayoutRunMode::ComputeSize,
1624                    stats,
1625                );
1626                pass1_deps |= c_deps;
1627                if c_min_aw > 0.0 {
1628                    pass1_min_aw = pass1_min_aw.max(c_min_aw + rec.get_margin().horizontal());
1629                }
1630                measured
1631            };
1632            let resolved_min_main: f32 = if let Some(explicit_min) = explicit_min_main {
1633                explicit_min.max(0.0)
1634            } else if rec.get_overflow() == Overflow::Scroll
1635                || (rec.get_overflow() == Overflow::Hidden && !has_px_main)
1636            {
1637                0.0
1638            } else if is_row {
1639                if is_unwrapped_clip_text {
1640                    child_size.get_width()
1641                } else {
1642                    0.0
1643                }
1644            } else {
1645                child_size.get_height()
1646            };
1647            let _: &mut FlexItemRecord = rec.set_min_main(resolved_min_main);
1648            if !wrap_enabled {
1649                if is_row {
1650                    single_line_main += child_size.get_width() + rec.get_margin().horizontal();
1651                    single_line_cross = single_line_cross
1652                        .max(child_size.get_height() + rec.get_margin().vertical());
1653                } else {
1654                    single_line_main += child_size.get_height() + rec.get_margin().vertical();
1655                    single_line_cross = single_line_cross
1656                        .max(child_size.get_width() + rec.get_margin().horizontal());
1657                }
1658            }
1659            let _: &mut FlexItemRecord = rec.set_size(child_size);
1660            self.get_mut_flex_items_scratch().push(rec);
1661        }
1662        let items_end: usize = self.get_flex_items_scratch().len();
1663        if !wrap_enabled {
1664            let mut line_ctx: FlexLineContext = FlexLineContext::new(
1665                frame,
1666                is_row,
1667                main_gap,
1668                main_avail,
1669                cross_avail,
1670                total_grow,
1671                mode,
1672            );
1673            let _: &mut FlexLineContext = line_ctx.set_line_count(1);
1674            let (line_size, line_deps, line_min_aw): (Size, u8, f32) = self.layout_flex_line(
1675                tree,
1676                (items_start, items_end),
1677                0.0,
1678                Some((single_line_main, single_line_cross)),
1679                line_ctx,
1680                stats,
1681            );
1682            self.get_mut_flex_items_scratch().truncate(items_start);
1683            return (
1684                line_size,
1685                pass1_deps | line_deps,
1686                pass1_min_aw.max(line_min_aw),
1687            );
1688        }
1689        let lines_start: usize = self.get_flex_lines_scratch().len();
1690        let mut cur_line_start: usize = items_start;
1691        let mut line_main: f32 = 0.0;
1692        for item_idx in items_start..items_end {
1693            let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1694            let item_main: f32 = if is_row {
1695                item.get_size().get_width() + item.get_margin().horizontal()
1696            } else {
1697                item.get_size().get_height() + item.get_margin().vertical()
1698            };
1699            let line_empty: bool = item_idx == cur_line_start;
1700            let needed: f32 = if line_empty {
1701                item_main
1702            } else {
1703                line_main + main_gap + item_main
1704            };
1705            if !line_empty && needed > main_avail && main_avail > 0.0 {
1706                self.get_mut_flex_lines_scratch()
1707                    .push((cur_line_start, item_idx));
1708                cur_line_start = item_idx;
1709                line_main = item_main;
1710            } else {
1711                line_main = needed;
1712            }
1713        }
1714        if cur_line_start < items_end {
1715            self.get_mut_flex_lines_scratch()
1716                .push((cur_line_start, items_end));
1717        }
1718        let lines_end: usize = self.get_flex_lines_scratch().len();
1719        let mut cross_cursor: f32 = 0.0;
1720        let mut max_main_extent: f32 = 0.0;
1721        let line_count: usize = lines_end.saturating_sub(lines_start);
1722        let mut wrap_deps: u8 = pass1_deps;
1723        let mut wrap_min_aw: f32 = pass1_min_aw;
1724        if is_row {
1725            if line_count > 1 {
1726                wrap_deps |= LAYOUT_DEP_AVAIL_W;
1727            } else {
1728                wrap_min_aw = wrap_min_aw.max(line_main + 0.5);
1729            }
1730        } else {
1731            wrap_deps |= LAYOUT_DEP_AVAIL_H;
1732        }
1733        for line_offset in 0..line_count {
1734            let line_range: (usize, usize) =
1735                self.get_flex_lines_scratch()[lines_start + line_offset];
1736            let mut line_grow: f32 = 0.0;
1737            for item_idx in line_range.0..line_range.1 {
1738                line_grow += self.get_flex_items_scratch()[item_idx].get_flex_grow();
1739            }
1740            let mut line_ctx: FlexLineContext = FlexLineContext::new(
1741                frame,
1742                is_row,
1743                main_gap,
1744                main_avail,
1745                cross_avail,
1746                line_grow,
1747                mode,
1748            );
1749            let _: &mut FlexLineContext = line_ctx.set_wrap_enabled(true);
1750            let _: &mut FlexLineContext = line_ctx.set_line_count(line_count);
1751            let (line_size, l_deps, l_min_aw): (Size, u8, f32) =
1752                self.layout_flex_line(tree, line_range, cross_cursor, None, line_ctx, stats);
1753            wrap_deps |= l_deps;
1754            wrap_min_aw = wrap_min_aw.max(l_min_aw);
1755            if is_row {
1756                max_main_extent = max_main_extent.max(line_size.get_width());
1757                cross_cursor += line_size.get_height();
1758            } else {
1759                max_main_extent = max_main_extent.max(line_size.get_height());
1760                cross_cursor += line_size.get_width();
1761            }
1762            if line_offset + 1 < line_count {
1763                cross_cursor += cross_gap;
1764            }
1765        }
1766        self.get_mut_flex_lines_scratch().truncate(lines_start);
1767        self.get_mut_flex_items_scratch().truncate(items_start);
1768        let out_size: Size = if is_row {
1769            Size::new(max_main_extent, cross_cursor)
1770        } else {
1771            Size::new(cross_cursor, max_main_extent)
1772        };
1773        (out_size, wrap_deps, wrap_min_aw)
1774    }
1775
1776    /// Resolves flex-grow and places a single flex line slice `[line_start..line_end)`, skipping Pass 3 in `ComputeSize` mode.
1777    ///
1778    /// # Arguments
1779    ///
1780    /// - `&Self` - Mutable layout engine reference.
1781    /// - `&mut SceneTree` - Mutable scene tree.
1782    /// - `(usize, usize)` - Inclusive start and exclusive end indices into `flex_items_scratch`.
1783    /// - `f32` - Cross-axis cursor offset where this line begins.
1784    /// - `Option<(f32, f32)>` - Optional pre-accumulated `(items_main_sum, line_cross)` for unwrapped single-line passes.
1785    /// - `FlexLineContext` - Enclosing container axis, gap, and execution mode parameters.
1786    /// - `&mut LayoutStats` - Mutable telemetry counters.
1787    ///
1788    /// # Returns
1789    ///
1790    /// - `(Size, u8, f32)` - Occupied `(width, height)` extent, dependency mask, and invariant `min_avail_w`.
1791    #[inline(always)]
1792    fn layout_flex_line(
1793        &mut self,
1794        tree: &mut SceneTree,
1795        line_range: (usize, usize),
1796        cross_cursor: f32,
1797        precomputed: Option<(f32, f32)>,
1798        ctx: FlexLineContext,
1799        stats: &mut LayoutStats,
1800    ) -> (Size, u8, f32) {
1801        let (line_start, line_end): (usize, usize) = line_range;
1802        let frame: ContainerFrame = ctx.get_frame();
1803        let is_row: bool = ctx.get_is_row();
1804        let wrap_enabled: bool = ctx.get_wrap_enabled();
1805        let main_gap: f32 = ctx.get_main_gap();
1806        let main_avail: f32 = ctx.get_main_avail();
1807        let cross_avail: f32 = ctx.get_cross_avail();
1808        let total_grow: f32 = ctx.get_total_grow();
1809        let line_count: usize = ctx.get_line_count();
1810        let mode: LayoutRunMode = ctx.get_mode();
1811        let parent_layout: LayoutStyle = frame.get_parent_layout();
1812        let inner_avail: Size = frame.get_inner_avail();
1813        let viewport: Size = frame.get_viewport();
1814        let content_origin: Point = frame.get_content_origin();
1815        let count: usize = line_end.saturating_sub(line_start);
1816        let gaps_total: f32 = if count > 1 {
1817            main_gap * ((count - 1) as f32)
1818        } else {
1819            0.0
1820        };
1821        let mut line_deps: u8 = LAYOUT_DEP_NONE;
1822        let mut line_min_aw: f32 = 0.0;
1823        let has_definite_or_grow: bool = frame.get_definite_width() || total_grow > 0.0;
1824        let effective_main_avail: f32 = if is_row {
1825            if has_definite_or_grow || wrap_enabled {
1826                if total_grow > 0.0 {
1827                    line_deps |= LAYOUT_DEP_AVAIL_W;
1828                }
1829                main_avail
1830            } else {
1831                let min_w_len: Length = parent_layout.get_min_width();
1832                if matches!(min_w_len, Length::Percent(_)) || Self::is_viewport_length(min_w_len) {
1833                    line_deps |= LAYOUT_DEP_VIEWPORT;
1834                }
1835                frame.get_min_inner_size().get_width()
1836            }
1837        } else if frame.get_definite_height() {
1838            if total_grow > 0.0 {
1839                line_deps |= LAYOUT_DEP_AVAIL_H;
1840            }
1841            main_avail
1842        } else {
1843            let min_h_len: Length = parent_layout.get_min_height();
1844            if matches!(min_h_len, Length::Percent(_)) || Self::is_viewport_length(min_h_len) {
1845                line_deps |= LAYOUT_DEP_VIEWPORT;
1846            }
1847            frame.get_min_inner_size().get_height()
1848        };
1849        let has_main_cap: bool = parent_layout.get_overflow() != Overflow::Scroll
1850            && if is_row {
1851                frame.get_definite_width() || parent_layout.get_max_width() != Length::Auto
1852            } else {
1853                frame.get_definite_height() || parent_layout.get_max_height() != Length::Auto
1854            };
1855        let pre_overflows: bool = !wrap_enabled
1856            && has_main_cap
1857            && precomputed
1858                .map(|(items_main, _): (f32, f32)| items_main + gaps_total > main_avail + 0.5)
1859                .unwrap_or(false);
1860        let mut line_shrunk: bool = false;
1861        let (final_used_main, line_cross): (f32, f32) = if let Some((items_main, pre_cross)) =
1862            precomputed
1863            && total_grow == 0.0
1864            && !pre_overflows
1865        {
1866            (items_main + gaps_total, pre_cross)
1867        } else {
1868            let used_main: f32 = if let Some((items_main, _)) = precomputed {
1869                items_main + gaps_total
1870            } else {
1871                let mut acc: f32 = gaps_total;
1872                for item_idx in line_start..line_end {
1873                    let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1874                    let sz: f32 = if is_row {
1875                        item.get_size().get_width() + item.get_margin().horizontal()
1876                    } else {
1877                        item.get_size().get_height() + item.get_margin().vertical()
1878                    };
1879                    acc += sz;
1880                }
1881                acc
1882            };
1883            let free_main: f32 = (effective_main_avail - used_main).max(0.0);
1884            let mut any_main_resized: bool = false;
1885            if total_grow > 0.0 && free_main > 0.0 {
1886                for item_idx in line_start..line_end {
1887                    let item: &mut FlexItemRecord =
1888                        &mut self.get_mut_flex_items_scratch()[item_idx];
1889                    let grow: f32 = item.get_flex_grow();
1890                    if grow > 0.0 {
1891                        let extra: f32 = free_main * (grow / total_grow);
1892                        if is_row {
1893                            let next_w: f32 = item.get_size().get_width() + extra;
1894                            item.get_mut_size().set_width(next_w);
1895                        } else {
1896                            let next_h: f32 = item.get_size().get_height() + extra;
1897                            item.get_mut_size().set_height(next_h);
1898                        }
1899                        any_main_resized = true;
1900                    }
1901                }
1902            } else if !wrap_enabled && has_main_cap && used_main > main_avail + 0.5 {
1903                line_deps |= if is_row {
1904                    LAYOUT_DEP_AVAIL_W
1905                } else {
1906                    LAYOUT_DEP_AVAIL_H
1907                };
1908                let mut rem_overflow: f32 = used_main - main_avail;
1909                for _ in 0..4usize {
1910                    if rem_overflow <= 0.05 {
1911                        break;
1912                    }
1913                    let mut weighted_sum: f32 = 0.0;
1914                    for item_idx in line_start..line_end {
1915                        let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1916                        let cur_main: f32 = if is_row {
1917                            item.get_size().get_width()
1918                        } else {
1919                            item.get_size().get_height()
1920                        };
1921                        if item.get_flex_shrink() > 0.0 && cur_main > item.get_min_main() + 0.05 {
1922                            weighted_sum += item.get_flex_shrink() * cur_main.max(1.0);
1923                        }
1924                    }
1925                    if weighted_sum <= 0.0 {
1926                        break;
1927                    }
1928                    let pass_overflow: f32 = rem_overflow;
1929                    let mut absorbed: f32 = 0.0;
1930                    for item_idx in line_start..line_end {
1931                        let item: &mut FlexItemRecord =
1932                            &mut self.get_mut_flex_items_scratch()[item_idx];
1933                        let cur_main: f32 = if is_row {
1934                            item.get_size().get_width()
1935                        } else {
1936                            item.get_size().get_height()
1937                        };
1938                        let min_m: f32 = item.get_min_main();
1939                        let shrink_f: f32 = item.get_flex_shrink();
1940                        if shrink_f > 0.0 && cur_main > min_m + 0.05 {
1941                            let w: f32 = shrink_f * cur_main.max(1.0);
1942                            let raw_cut: f32 = pass_overflow * (w / weighted_sum);
1943                            let next_main: f32 = (cur_main - raw_cut).max(min_m);
1944                            let cut: f32 = cur_main - next_main;
1945                            if cut > 0.01 {
1946                                if is_row {
1947                                    item.get_mut_size().set_width(next_main);
1948                                } else {
1949                                    item.get_mut_size().set_height(next_main);
1950                                }
1951                                absorbed += cut;
1952                                any_main_resized = true;
1953                                line_shrunk = true;
1954                            }
1955                        }
1956                    }
1957                    if absorbed <= 0.01 {
1958                        break;
1959                    }
1960                    rem_overflow = (rem_overflow - absorbed).max(0.0);
1961                }
1962            }
1963            if total_grow > 0.0 || any_main_resized {
1964                for item_idx in line_start..line_end {
1965                    let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1966                    let resized_item: bool = item.get_flex_grow() > 0.0 || any_main_resized;
1967                    let auto_cross: bool = resized_item
1968                        && if is_row {
1969                            (item.get_flags() & FLEX_ITEM_HEIGHT_AUTO) != 0
1970                        } else {
1971                            (item.get_flags() & FLEX_ITEM_WIDTH_AUTO) != 0
1972                        };
1973                    if auto_cross {
1974                        let probe_w: f32 = if is_row {
1975                            item.get_size().get_width()
1976                        } else {
1977                            cross_avail
1978                        };
1979                        let probe_h: f32 = if is_row {
1980                            cross_avail
1981                        } else {
1982                            item.get_size().get_height()
1983                        };
1984                        let stretch_pw: bool =
1985                            is_row && (item.get_flags() & FLEX_ITEM_WIDTH_AUTO) != 0;
1986                        let stretch_ph: bool =
1987                            !is_row && (item.get_flags() & FLEX_ITEM_HEIGHT_AUTO) != 0;
1988                        let probe_sp: AvailableSpace = AvailableSpace::new(
1989                            probe_w,
1990                            probe_h,
1991                            viewport,
1992                            content_origin.get_x(),
1993                            content_origin.get_y(),
1994                        )
1995                        .with_stretch(stretch_pw, stretch_ph);
1996                        let (measured, c_deps, c_min_aw): (Size, u8, f32) = self.layout_node_mode(
1997                            tree,
1998                            item.get_node_id(),
1999                            probe_sp,
2000                            LayoutRunMode::ComputeSize,
2001                            stats,
2002                        );
2003                        line_deps |= c_deps;
2004                        if c_min_aw > 0.0 {
2005                            line_min_aw =
2006                                line_min_aw.max(c_min_aw + item.get_margin().horizontal());
2007                        }
2008                        let slot: &mut FlexItemRecord =
2009                            &mut self.get_mut_flex_items_scratch()[item_idx];
2010                        if is_row {
2011                            slot.get_mut_size().set_height(measured.get_height());
2012                        } else {
2013                            slot.get_mut_size().set_width(measured.get_width());
2014                        }
2015                    }
2016                }
2017            }
2018            let mut sum_main: f32 = gaps_total;
2019            let mut max_cross: f32 = 0.0;
2020            for item_idx in line_start..line_end {
2021                let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
2022                if is_row {
2023                    sum_main += item.get_size().get_width() + item.get_margin().horizontal();
2024                    max_cross =
2025                        max_cross.max(item.get_size().get_height() + item.get_margin().vertical());
2026                } else {
2027                    sum_main += item.get_size().get_height() + item.get_margin().vertical();
2028                    max_cross =
2029                        max_cross.max(item.get_size().get_width() + item.get_margin().horizontal());
2030                }
2031            }
2032            (sum_main, max_cross)
2033        };
2034        if mode == LayoutRunMode::ComputeSize {
2035            let sz: Size = if is_row {
2036                Size::new(final_used_main, line_cross)
2037            } else {
2038                Size::new(line_cross, final_used_main)
2039            };
2040            return (sz, line_deps, line_min_aw);
2041        }
2042        let rem: f32 = (effective_main_avail - final_used_main).max(0.0);
2043        let (mut main_cursor, extra_step): (f32, f32) = match parent_layout.get_justify_content() {
2044            JustifyContent::Start => (0.0, 0.0),
2045            JustifyContent::Center => (rem * 0.5, 0.0),
2046            JustifyContent::End => (rem, 0.0),
2047            JustifyContent::SpaceBetween => {
2048                if count > 1 {
2049                    (0.0, rem / ((count - 1) as f32))
2050                } else {
2051                    (0.0, 0.0)
2052                }
2053            }
2054            JustifyContent::SpaceAround => {
2055                let slot: f32 = rem / (count.max(1) as f32);
2056                (slot * 0.5, slot)
2057            }
2058            JustifyContent::SpaceEvenly => {
2059                let slot: f32 = rem / ((count + 1) as f32);
2060                (slot, slot)
2061            }
2062        };
2063        let min_cross: f32 = if is_row {
2064            frame.get_min_inner_size().get_height()
2065        } else {
2066            frame.get_min_inner_size().get_width()
2067        };
2068        let definite_cross: bool = !is_row || frame.get_definite_height();
2069        let effective_line_cross: f32 = if line_count == 1 {
2070            let floor_cross: f32 = if definite_cross && (!wrap_enabled || is_row) {
2071                cross_avail.max(min_cross)
2072            } else {
2073                min_cross
2074            };
2075            line_cross.max(floor_cross)
2076        } else {
2077            line_cross
2078        };
2079        let mut actual_line_cross: f32 = line_cross;
2080        let parent_align: AlignItems = parent_layout.get_align_items();
2081        for idx in 0..count {
2082            let rec: FlexItemRecord = self.get_flex_items_scratch()[line_start + idx];
2083            let child_id: NodeId = rec.get_node_id();
2084            let child_size: Size = rec.get_size();
2085            let margin: Edges = rec.get_margin();
2086            let width_auto: bool = (rec.get_flags() & FLEX_ITEM_WIDTH_AUTO) != 0;
2087            let height_auto: bool = (rec.get_flags() & FLEX_ITEM_HEIGHT_AUTO) != 0;
2088            let item_cross: f32 = if is_row {
2089                child_size.get_height()
2090            } else {
2091                child_size.get_width()
2092            };
2093            let align: AlignItems = match rec.get_align_self() {
2094                AlignSelf::Auto => parent_align,
2095                AlignSelf::Stretch => AlignItems::Stretch,
2096                AlignSelf::Start => AlignItems::Start,
2097                AlignSelf::Center => AlignItems::Center,
2098                AlignSelf::End => AlignItems::End,
2099            };
2100            let avail_item_cross: f32 = (effective_line_cross
2101                - if is_row {
2102                    margin.vertical()
2103                } else {
2104                    margin.horizontal()
2105                })
2106            .max(0.0);
2107            let cross_offset: f32 = match align {
2108                AlignItems::Start | AlignItems::Stretch => 0.0,
2109                AlignItems::Center => ((avail_item_cross - item_cross) * 0.5).max(0.0),
2110                AlignItems::End => (avail_item_cross - item_cross).max(0.0),
2111            };
2112            let main_resized_item: bool = rec.get_flex_grow() > 0.0 || line_shrunk;
2113            let auto_cross_grow: bool =
2114                main_resized_item && if is_row { height_auto } else { width_auto };
2115            let target_w: f32 = if !is_row && align == AlignItems::Stretch && width_auto {
2116                avail_item_cross.max(child_size.get_width())
2117            } else {
2118                child_size.get_width()
2119            };
2120            let target_h: f32 = if is_row && align == AlignItems::Stretch && height_auto {
2121                avail_item_cross.max(child_size.get_height())
2122            } else {
2123                child_size.get_height()
2124            };
2125            let (x, y): (f32, f32) = if is_row {
2126                (
2127                    content_origin.get_x() + main_cursor + margin.get_left(),
2128                    content_origin.get_y() + cross_cursor + cross_offset + margin.get_top(),
2129                )
2130            } else {
2131                (
2132                    content_origin.get_x() + cross_cursor + cross_offset + margin.get_left(),
2133                    content_origin.get_y() + main_cursor + margin.get_top(),
2134                )
2135            };
2136            let space_w: f32 = if (rec.get_flags() & FLEX_ITEM_WIDTH_PERCENT) != 0 {
2137                inner_avail.get_width()
2138            } else if auto_cross_grow && !is_row {
2139                cross_avail
2140            } else {
2141                target_w
2142            };
2143            let space_h: f32 = if (rec.get_flags() & FLEX_ITEM_HEIGHT_PERCENT) != 0 {
2144                inner_avail.get_height()
2145            } else if auto_cross_grow && is_row {
2146                cross_avail
2147            } else {
2148                target_h
2149            };
2150            let stretch_child_w: bool = !(auto_cross_grow && !is_row)
2151                && ((!is_row && align == AlignItems::Stretch && width_auto)
2152                    || (is_row && main_resized_item && width_auto));
2153            let stretch_child_h: bool = !(auto_cross_grow && is_row)
2154                && ((is_row && align == AlignItems::Stretch && height_auto)
2155                    || (!is_row && main_resized_item && height_auto));
2156            let final_space: AvailableSpace = AvailableSpace::new(space_w, space_h, viewport, x, y)
2157                .with_stretch(stretch_child_w, stretch_child_h);
2158            let (placed, _, _): (Size, u8, f32) = self.layout_node_mode(
2159                tree,
2160                child_id,
2161                final_space,
2162                LayoutRunMode::PerformLayout,
2163                stats,
2164            );
2165            let is_clipped: bool =
2166                matches!(rec.get_overflow(), Overflow::Hidden | Overflow::Scroll);
2167            let mut placed_final: Size = placed;
2168            if auto_cross_grow && matches!(align, AlignItems::Center | AlignItems::End) {
2169                let actual_item_cross: f32 = if is_row {
2170                    placed_final.get_height()
2171                } else {
2172                    placed_final.get_width()
2173                };
2174                let refined_offset: f32 = match align {
2175                    AlignItems::Center => ((avail_item_cross - actual_item_cross) * 0.5).max(0.0),
2176                    AlignItems::End => (avail_item_cross - actual_item_cross).max(0.0),
2177                    AlignItems::Start | AlignItems::Stretch => cross_offset,
2178                };
2179                let delta_cross: f32 = refined_offset - cross_offset;
2180                if delta_cross.abs() > 0.001 {
2181                    let (next_x, next_y): (f32, f32) = if is_row {
2182                        (x, y + delta_cross)
2183                    } else {
2184                        (x + delta_cross, y)
2185                    };
2186                    let shifted_space: AvailableSpace =
2187                        AvailableSpace::new(space_w, space_h, viewport, next_x, next_y)
2188                            .with_stretch(stretch_child_w, stretch_child_h);
2189                    let (re_placed, _, _): (Size, u8, f32) = self.layout_node_mode(
2190                        tree,
2191                        child_id,
2192                        shifted_space,
2193                        LayoutRunMode::PerformLayout,
2194                        stats,
2195                    );
2196                    placed_final = re_placed;
2197                }
2198            }
2199            let (desired_w, desired_h): (f32, f32) = if auto_cross_grow {
2200                if is_row {
2201                    actual_line_cross =
2202                        actual_line_cross.max(placed_final.get_height() + margin.vertical());
2203                    (target_w, placed_final.get_height())
2204                } else {
2205                    actual_line_cross =
2206                        actual_line_cross.max(placed_final.get_width() + margin.horizontal());
2207                    (placed_final.get_width(), target_h)
2208                }
2209            } else if is_clipped || main_resized_item {
2210                (target_w, target_h)
2211            } else {
2212                (
2213                    target_w.max(placed_final.get_width()),
2214                    target_h.max(placed_final.get_height()),
2215                )
2216            };
2217            let needs_box_adjust: bool = tree.get_node(child_id).is_some_and(|n: &SceneNode| {
2218                let b: Rect = n.get_layout_box().get_bounds();
2219                (b.get_width() - desired_w).abs() > 0.001
2220                    || (b.get_height() - desired_h).abs() > 0.001
2221            });
2222            if needs_box_adjust {
2223                self.record_layout_snapshot(tree, child_id);
2224                let adjusted_opt: Option<(Rect, Transform2D)> =
2225                    if let Some(node) = tree.get_node_mut(child_id) {
2226                        let pad: Edges = node.style_ref().layout_ref().get_padding();
2227                        let bw: f32 = node.style_ref().paint_ref().get_border().get_width();
2228                        let tr: Transform2D = node.style_ref().paint_ref().get_transform();
2229                        let mut b: Rect = node.get_layout_box().get_bounds();
2230                        b.set_width(desired_w);
2231                        b.set_height(desired_h);
2232                        let mut cb: Rect = node.get_layout_box().get_content_bounds();
2233                        cb.set_width((desired_w - pad.horizontal() - bw * 2.0).max(0.0));
2234                        cb.set_height((desired_h - pad.vertical() - bw * 2.0).max(0.0));
2235                        node.get_mut_layout_box().set_bounds(b);
2236                        node.get_mut_layout_box().set_content_bounds(cb);
2237                        Some((b, tr))
2238                    } else {
2239                        None
2240                    };
2241                if let Some((b, tr)) = adjusted_opt {
2242                    let Self { split_cache, .. } = self;
2243                    split_cache.mark_post_stretched(child_id, b, tr, is_clipped);
2244                }
2245            }
2246            let advance: f32 = if is_row {
2247                target_w + margin.horizontal()
2248            } else {
2249                target_h + margin.vertical()
2250            };
2251            main_cursor += advance;
2252            if idx + 1 < count {
2253                main_cursor += main_gap + extra_step;
2254            }
2255        }
2256        let sz: Size = if is_row {
2257            Size::new(final_used_main, actual_line_cross)
2258        } else {
2259            Size::new(actual_line_cross, final_used_main)
2260        };
2261        (sz, line_deps, line_min_aw)
2262    }
2263
2264    /// Executes uniform-column CSS Grid layout with row and column gaps in `ComputeSize` or `PerformLayout` mode.
2265    ///
2266    /// # Arguments
2267    ///
2268    /// - `&Self` - Mutable layout engine reference.
2269    /// - `&mut SceneTree` - Mutable scene tree.
2270    /// - `(usize, usize)` - Inclusive start and exclusive end indices into `flow_scratch`.
2271    /// - `ContainerFrame` - Grid container constraints and origin.
2272    /// - `LayoutRunMode` - `ComputeSize` probe vs `PerformLayout` placement mode.
2273    /// - `&mut LayoutStats` - Mutable telemetry counters.
2274    ///
2275    /// # Returns
2276    ///
2277    /// - `(Size, u8, f32)` - Aggregate grid content dimensions, dependency mask, and invariant `min_avail_w`.
2278    fn layout_grid(
2279        &mut self,
2280        tree: &mut SceneTree,
2281        flow_range: (usize, usize),
2282        frame: ContainerFrame,
2283        mode: LayoutRunMode,
2284        stats: &mut LayoutStats,
2285    ) -> (Size, u8, f32) {
2286        let (flow_start, flow_end): (usize, usize) = flow_range;
2287        if flow_start >= flow_end {
2288            return (Size::default(), LAYOUT_DEP_NONE, 0.0);
2289        }
2290        let parent_layout: LayoutStyle = frame.get_parent_layout();
2291        let inner_avail: Size = frame.get_inner_avail();
2292        let viewport: Size = frame.get_viewport();
2293        let content_origin: Point = frame.get_content_origin();
2294        let cols: usize = (parent_layout.get_grid_columns() as usize).max(1);
2295        let col_gap: f32 = parent_layout.get_column_gap();
2296        let row_gap: f32 = parent_layout.get_row_gap();
2297        let total_col_gaps: f32 = col_gap * ((cols.saturating_sub(1)) as f32);
2298        let col_w: f32 = ((inner_avail.get_width() - total_col_gaps) / (cols as f32)).max(0.0);
2299        let col_step: f32 = col_w + col_gap;
2300        let origin_x: f32 = content_origin.get_x();
2301        let origin_y: f32 = content_origin.get_y();
2302        let inner_h: f32 = inner_avail.get_height();
2303        let mut y_cursor: f32 = 0.0;
2304        let mut idx: usize = flow_start;
2305        let mut grid_deps: u8 = LAYOUT_DEP_AVAIL_W;
2306        while idx < flow_end {
2307            let row_end: usize = (idx + cols).min(flow_end);
2308            let mut row_h: f32 = 0.0;
2309            let mut min_row_h: f32 = f32::INFINITY;
2310            let y: f32 = origin_y + y_cursor;
2311            let mut x: f32 = origin_x;
2312            for pos in idx..row_end {
2313                let child_id: NodeId = self.get_flow_scratch()[pos];
2314                let auto_w: bool = tree.get_node(child_id).is_some_and(|n: &SceneNode| {
2315                    n.style_ref().layout_ref().get_width() == Length::Auto
2316                });
2317                let cell_space: AvailableSpace =
2318                    AvailableSpace::new(col_w, inner_h, viewport, x, y).with_stretch(auto_w, false);
2319                let (child_size, c_deps, _): (Size, u8, f32) =
2320                    self.layout_node_mode(tree, child_id, cell_space, mode, stats);
2321                grid_deps |= c_deps;
2322                if mode == LayoutRunMode::PerformLayout
2323                    && (child_size.get_width() - col_w).abs() > 0.001
2324                {
2325                    self.record_layout_snapshot(tree, child_id);
2326                    let adjusted_opt: Option<(Rect, Transform2D, bool)> =
2327                        if let Some(node) = tree.get_node_mut(child_id) {
2328                            let tr: Transform2D = node.style_ref().paint_ref().get_transform();
2329                            let clipped: bool = matches!(
2330                                node.style_ref().layout_ref().get_overflow(),
2331                                Overflow::Hidden | Overflow::Scroll
2332                            );
2333                            let mut b: Rect = node.get_layout_box().get_bounds();
2334                            b.set_width(col_w);
2335                            node.get_mut_layout_box().set_bounds(b);
2336                            Some((b, tr, clipped))
2337                        } else {
2338                            None
2339                        };
2340                    if let Some((b, tr, clipped)) = adjusted_opt {
2341                        let Self { split_cache, .. } = self;
2342                        split_cache.mark_post_stretched(child_id, b, tr, clipped);
2343                    }
2344                }
2345                let ch: f32 = child_size.get_height();
2346                row_h = row_h.max(ch);
2347                min_row_h = min_row_h.min(ch);
2348                x += col_step;
2349            }
2350            if mode == LayoutRunMode::PerformLayout && row_end - idx > 1 && min_row_h < row_h {
2351                for pos in idx..row_end {
2352                    let child_id: NodeId = self.get_flow_scratch()[pos];
2353                    let needs_stretch: bool =
2354                        tree.get_node(child_id).is_some_and(|n: &SceneNode| {
2355                            n.get_layout_box().get_bounds().get_height() < row_h
2356                        });
2357                    if needs_stretch {
2358                        self.record_layout_snapshot(tree, child_id);
2359                        let adjusted_opt: Option<(Rect, Transform2D, bool)> =
2360                            if let Some(node) = tree.get_node_mut(child_id) {
2361                                let tr: Transform2D = node.style_ref().paint_ref().get_transform();
2362                                let clipped: bool = matches!(
2363                                    node.style_ref().layout_ref().get_overflow(),
2364                                    Overflow::Hidden | Overflow::Scroll
2365                                );
2366                                let mut b: Rect = node.get_layout_box().get_bounds();
2367                                b.set_height(row_h);
2368                                node.get_mut_layout_box().set_bounds(b);
2369                                Some((b, tr, clipped))
2370                            } else {
2371                                None
2372                            };
2373                        if let Some((b, tr, clipped)) = adjusted_opt {
2374                            let Self { split_cache, .. } = self;
2375                            split_cache.mark_post_stretched(child_id, b, tr, clipped);
2376                        }
2377                    }
2378                }
2379            }
2380            y_cursor += row_h;
2381            if row_end < flow_end {
2382                y_cursor += row_gap;
2383            }
2384            idx = row_end;
2385        }
2386        (Size::new(inner_avail.get_width(), y_cursor), grid_deps, 0.0)
2387    }
2388
2389    /// Translates the cached layout geometry and SoA `SplitLayoutCache` bounds of `root_id` and non-fixed descendants by `(dx, dy)`.
2390    ///
2391    /// # Arguments
2392    ///
2393    /// - `&Self` - Mutable layout engine reference.
2394    /// - `&mut SceneTree` - Mutable retained scene tree.
2395    /// - `NodeId` - Root node of the clean subtree being shifted.
2396    /// - `f32` - Horizontal translation delta in logical pixels.
2397    /// - `f32` - Vertical translation delta in logical pixels.
2398    fn translate_subtree(&mut self, tree: &mut SceneTree, root_id: NodeId, dx: f32, dy: f32) {
2399        if dx == 0.0 && dy == 0.0 {
2400            return;
2401        }
2402        self.record_layout_snapshot(tree, root_id);
2403        let Some(root_node) = tree.get_node_mut(root_id) else {
2404            return;
2405        };
2406        let Style { layout, .. } = root_node.style_ref();
2407        let root_none_disp: bool = layout.get_display() == Display::None;
2408        if let Some(mut c) = root_node.cached_constraint() {
2409            c.set_origin_x(c.get_origin_x() + dx);
2410            c.set_origin_y(c.get_origin_y() + dy);
2411            root_node.set_last_constraint(Some(c));
2412        }
2413        if root_none_disp {
2414            let Self { split_cache, .. } = self;
2415            split_cache.translate_node_cache(root_id, dx, dy);
2416            return;
2417        }
2418        let mut root_bounds: Rect = root_node.get_layout_box().get_bounds();
2419        root_bounds.set_x(root_bounds.get_x() + dx);
2420        root_bounds.set_y(root_bounds.get_y() + dy);
2421        root_node.get_mut_layout_box().set_bounds(root_bounds);
2422        let mut root_content: Rect = root_node.get_layout_box().get_content_bounds();
2423        root_content.set_x(root_content.get_x() + dx);
2424        root_content.set_y(root_content.get_y() + dy);
2425        root_node
2426            .get_mut_layout_box()
2427            .set_content_bounds(root_content);
2428        let root_children_empty: bool = !tree.has_children(root_id);
2429        if !root_children_empty {
2430            self.get_mut_translate_scratch().clear();
2431            self.get_mut_translate_scratch()
2432                .extend(tree.children_iter(root_id));
2433        }
2434        {
2435            let Self { split_cache, .. } = self;
2436            split_cache.translate_node_cache(root_id, dx, dy);
2437        }
2438        if root_children_empty {
2439            return;
2440        }
2441        while let Some(nid) = self.get_mut_translate_scratch().pop() {
2442            let (is_fixed_pos, is_none_disp): (bool, bool) = match tree.get_node(nid) {
2443                Some(node) => {
2444                    let Style { layout, .. } = node.style_ref();
2445                    (
2446                        layout.get_position() == Position::Fixed,
2447                        layout.get_display() == Display::None,
2448                    )
2449                }
2450                None => continue,
2451            };
2452            if is_fixed_pos {
2453                continue;
2454            }
2455            if !is_none_disp {
2456                self.record_layout_snapshot(tree, nid);
2457            }
2458            let Some(node) = tree.get_node_mut(nid) else {
2459                continue;
2460            };
2461            if let Some(mut c) = node.cached_constraint() {
2462                c.set_origin_x(c.get_origin_x() + dx);
2463                c.set_origin_y(c.get_origin_y() + dy);
2464                node.set_last_constraint(Some(c));
2465            }
2466            if is_none_disp {
2467                let Self { split_cache, .. } = self;
2468                split_cache.translate_node_cache(nid, dx, dy);
2469                continue;
2470            }
2471            let mut bounds: Rect = node.get_layout_box().get_bounds();
2472            bounds.set_x(bounds.get_x() + dx);
2473            bounds.set_y(bounds.get_y() + dy);
2474            node.get_mut_layout_box().set_bounds(bounds);
2475            let mut content: Rect = node.get_layout_box().get_content_bounds();
2476            content.set_x(content.get_x() + dx);
2477            content.set_y(content.get_y() + dy);
2478            node.get_mut_layout_box().set_content_bounds(content);
2479            let has_children: bool = tree.has_children(nid);
2480            if has_children {
2481                self.get_mut_translate_scratch()
2482                    .extend(tree.children_iter(nid));
2483            }
2484            let Self { split_cache, .. } = self;
2485            split_cache.translate_node_cache(nid, dx, dy);
2486        }
2487    }
2488}