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                    || matches!(child_layout.get_min_width(), Length::Percent(_))
1581                    || matches!(child_layout.get_max_width(), Length::Percent(_))
1582                {
1583                    f |= FLEX_ITEM_WIDTH_PERCENT;
1584                }
1585                if matches!(height_len, Length::Percent(_))
1586                    || matches!(child_layout.get_min_height(), Length::Percent(_))
1587                    || matches!(child_layout.get_max_height(), Length::Percent(_))
1588                {
1589                    f |= FLEX_ITEM_HEIGHT_PERCENT;
1590                }
1591                let zero_basis: bool =
1592                    !wrap_enabled && grow > 0.0 && if is_row { width_auto } else { height_auto };
1593                if zero_basis {
1594                    if is_row {
1595                        if matches!(height_len, Length::Percent(_)) {
1596                            pass1_deps |= LAYOUT_DEP_AVAIL_H;
1597                        }
1598                        if Self::is_viewport_length(height_len) {
1599                            pass1_deps |= LAYOUT_DEP_VIEWPORT;
1600                        }
1601                        let h: f32 = height_len.resolve(cross_avail, viewport).unwrap_or(0.0);
1602                        zero_basis_size = Some(Size::new(0.0, h));
1603                    } else {
1604                        if matches!(width_len, Length::Percent(_)) {
1605                            pass1_deps |= LAYOUT_DEP_AVAIL_W;
1606                        }
1607                        if Self::is_viewport_length(width_len) {
1608                            pass1_deps |= LAYOUT_DEP_VIEWPORT;
1609                        }
1610                        let w: f32 = width_len.resolve(cross_avail, viewport).unwrap_or(0.0);
1611                        zero_basis_size = Some(Size::new(w, 0.0));
1612                    }
1613                }
1614                let _: &mut FlexItemRecord = rec.set_margin(child_layout.get_margin());
1615                let _: &mut FlexItemRecord = rec.set_flex_grow(grow);
1616                let _: &mut FlexItemRecord = rec.set_flex_shrink(shrink);
1617                let _: &mut FlexItemRecord = rec.set_align_self(child_layout.get_align_self());
1618                let _: &mut FlexItemRecord = rec.set_overflow(child_layout.get_overflow());
1619                let _: &mut FlexItemRecord = rec.set_flags(f);
1620            }
1621            total_grow += rec.get_flex_grow();
1622            let child_size: Size = if let Some(zb) = zero_basis_size {
1623                zb
1624            } else {
1625                let (measured, c_deps, c_min_aw): (Size, u8, f32) = self.layout_node_mode(
1626                    tree,
1627                    child_id,
1628                    probe_template,
1629                    LayoutRunMode::ComputeSize,
1630                    stats,
1631                );
1632                pass1_deps |= c_deps;
1633                if c_min_aw > 0.0 {
1634                    pass1_min_aw = pass1_min_aw.max(c_min_aw + rec.get_margin().horizontal());
1635                }
1636                measured
1637            };
1638            let resolved_min_main: f32 = if let Some(explicit_min) = explicit_min_main {
1639                explicit_min.max(0.0)
1640            } else if rec.get_overflow() == Overflow::Scroll
1641                || (rec.get_overflow() == Overflow::Hidden && !has_px_main)
1642            {
1643                0.0
1644            } else if is_row {
1645                if is_unwrapped_clip_text {
1646                    child_size.get_width()
1647                } else {
1648                    0.0
1649                }
1650            } else {
1651                child_size.get_height()
1652            };
1653            let _: &mut FlexItemRecord = rec.set_min_main(resolved_min_main);
1654            if !wrap_enabled {
1655                if is_row {
1656                    single_line_main += child_size.get_width() + rec.get_margin().horizontal();
1657                    single_line_cross = single_line_cross
1658                        .max(child_size.get_height() + rec.get_margin().vertical());
1659                } else {
1660                    single_line_main += child_size.get_height() + rec.get_margin().vertical();
1661                    single_line_cross = single_line_cross
1662                        .max(child_size.get_width() + rec.get_margin().horizontal());
1663                }
1664            }
1665            let _: &mut FlexItemRecord = rec.set_size(child_size);
1666            self.get_mut_flex_items_scratch().push(rec);
1667        }
1668        let items_end: usize = self.get_flex_items_scratch().len();
1669        if !wrap_enabled {
1670            let mut line_ctx: FlexLineContext = FlexLineContext::new(
1671                frame,
1672                is_row,
1673                main_gap,
1674                main_avail,
1675                cross_avail,
1676                total_grow,
1677                mode,
1678            );
1679            let _: &mut FlexLineContext = line_ctx.set_line_count(1);
1680            let (line_size, line_deps, line_min_aw): (Size, u8, f32) = self.layout_flex_line(
1681                tree,
1682                (items_start, items_end),
1683                0.0,
1684                Some((single_line_main, single_line_cross)),
1685                line_ctx,
1686                stats,
1687            );
1688            self.get_mut_flex_items_scratch().truncate(items_start);
1689            return (
1690                line_size,
1691                pass1_deps | line_deps,
1692                pass1_min_aw.max(line_min_aw),
1693            );
1694        }
1695        let lines_start: usize = self.get_flex_lines_scratch().len();
1696        let mut cur_line_start: usize = items_start;
1697        let mut line_main: f32 = 0.0;
1698        for item_idx in items_start..items_end {
1699            let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1700            let item_main: f32 = if is_row {
1701                item.get_size().get_width() + item.get_margin().horizontal()
1702            } else {
1703                item.get_size().get_height() + item.get_margin().vertical()
1704            };
1705            let line_empty: bool = item_idx == cur_line_start;
1706            let needed: f32 = if line_empty {
1707                item_main
1708            } else {
1709                line_main + main_gap + item_main
1710            };
1711            if !line_empty && needed > main_avail && main_avail > 0.0 {
1712                self.get_mut_flex_lines_scratch()
1713                    .push((cur_line_start, item_idx));
1714                cur_line_start = item_idx;
1715                line_main = item_main;
1716            } else {
1717                line_main = needed;
1718            }
1719        }
1720        if cur_line_start < items_end {
1721            self.get_mut_flex_lines_scratch()
1722                .push((cur_line_start, items_end));
1723        }
1724        let lines_end: usize = self.get_flex_lines_scratch().len();
1725        let mut cross_cursor: f32 = 0.0;
1726        let mut max_main_extent: f32 = 0.0;
1727        let line_count: usize = lines_end.saturating_sub(lines_start);
1728        let mut wrap_deps: u8 = pass1_deps;
1729        let mut wrap_min_aw: f32 = pass1_min_aw;
1730        if is_row {
1731            if line_count > 1 {
1732                wrap_deps |= LAYOUT_DEP_AVAIL_W;
1733            } else {
1734                wrap_min_aw = wrap_min_aw.max(line_main + 0.5);
1735            }
1736        } else {
1737            wrap_deps |= LAYOUT_DEP_AVAIL_H;
1738        }
1739        for line_offset in 0..line_count {
1740            let line_range: (usize, usize) =
1741                self.get_flex_lines_scratch()[lines_start + line_offset];
1742            let mut line_grow: f32 = 0.0;
1743            for item_idx in line_range.0..line_range.1 {
1744                line_grow += self.get_flex_items_scratch()[item_idx].get_flex_grow();
1745            }
1746            let mut line_ctx: FlexLineContext = FlexLineContext::new(
1747                frame,
1748                is_row,
1749                main_gap,
1750                main_avail,
1751                cross_avail,
1752                line_grow,
1753                mode,
1754            );
1755            let _: &mut FlexLineContext = line_ctx.set_wrap_enabled(true);
1756            let _: &mut FlexLineContext = line_ctx.set_line_count(line_count);
1757            let (line_size, l_deps, l_min_aw): (Size, u8, f32) =
1758                self.layout_flex_line(tree, line_range, cross_cursor, None, line_ctx, stats);
1759            wrap_deps |= l_deps;
1760            wrap_min_aw = wrap_min_aw.max(l_min_aw);
1761            if is_row {
1762                max_main_extent = max_main_extent.max(line_size.get_width());
1763                cross_cursor += line_size.get_height();
1764            } else {
1765                max_main_extent = max_main_extent.max(line_size.get_height());
1766                cross_cursor += line_size.get_width();
1767            }
1768            if line_offset + 1 < line_count {
1769                cross_cursor += cross_gap;
1770            }
1771        }
1772        self.get_mut_flex_lines_scratch().truncate(lines_start);
1773        self.get_mut_flex_items_scratch().truncate(items_start);
1774        let out_size: Size = if is_row {
1775            Size::new(max_main_extent, cross_cursor)
1776        } else {
1777            Size::new(cross_cursor, max_main_extent)
1778        };
1779        (out_size, wrap_deps, wrap_min_aw)
1780    }
1781
1782    /// Resolves flex-grow and places a single flex line slice `[line_start..line_end)`, skipping Pass 3 in `ComputeSize` mode.
1783    ///
1784    /// # Arguments
1785    ///
1786    /// - `&Self` - Mutable layout engine reference.
1787    /// - `&mut SceneTree` - Mutable scene tree.
1788    /// - `(usize, usize)` - Inclusive start and exclusive end indices into `flex_items_scratch`.
1789    /// - `f32` - Cross-axis cursor offset where this line begins.
1790    /// - `Option<(f32, f32)>` - Optional pre-accumulated `(items_main_sum, line_cross)` for unwrapped single-line passes.
1791    /// - `FlexLineContext` - Enclosing container axis, gap, and execution mode parameters.
1792    /// - `&mut LayoutStats` - Mutable telemetry counters.
1793    ///
1794    /// # Returns
1795    ///
1796    /// - `(Size, u8, f32)` - Occupied `(width, height)` extent, dependency mask, and invariant `min_avail_w`.
1797    #[inline(always)]
1798    fn layout_flex_line(
1799        &mut self,
1800        tree: &mut SceneTree,
1801        line_range: (usize, usize),
1802        cross_cursor: f32,
1803        precomputed: Option<(f32, f32)>,
1804        ctx: FlexLineContext,
1805        stats: &mut LayoutStats,
1806    ) -> (Size, u8, f32) {
1807        let (line_start, line_end): (usize, usize) = line_range;
1808        let frame: ContainerFrame = ctx.get_frame();
1809        let is_row: bool = ctx.get_is_row();
1810        let wrap_enabled: bool = ctx.get_wrap_enabled();
1811        let main_gap: f32 = ctx.get_main_gap();
1812        let main_avail: f32 = ctx.get_main_avail();
1813        let cross_avail: f32 = ctx.get_cross_avail();
1814        let total_grow: f32 = ctx.get_total_grow();
1815        let line_count: usize = ctx.get_line_count();
1816        let mode: LayoutRunMode = ctx.get_mode();
1817        let parent_layout: LayoutStyle = frame.get_parent_layout();
1818        let inner_avail: Size = frame.get_inner_avail();
1819        let viewport: Size = frame.get_viewport();
1820        let content_origin: Point = frame.get_content_origin();
1821        let count: usize = line_end.saturating_sub(line_start);
1822        let gaps_total: f32 = if count > 1 {
1823            main_gap * ((count - 1) as f32)
1824        } else {
1825            0.0
1826        };
1827        let mut line_deps: u8 = LAYOUT_DEP_NONE;
1828        let mut line_min_aw: f32 = 0.0;
1829        let has_definite_or_grow: bool = frame.get_definite_width() || total_grow > 0.0;
1830        let effective_main_avail: f32 = if is_row {
1831            if has_definite_or_grow || wrap_enabled {
1832                if total_grow > 0.0 {
1833                    line_deps |= LAYOUT_DEP_AVAIL_W;
1834                }
1835                main_avail
1836            } else {
1837                let min_w_len: Length = parent_layout.get_min_width();
1838                if matches!(min_w_len, Length::Percent(_)) || Self::is_viewport_length(min_w_len) {
1839                    line_deps |= LAYOUT_DEP_VIEWPORT;
1840                }
1841                frame.get_min_inner_size().get_width()
1842            }
1843        } else if frame.get_definite_height() {
1844            if total_grow > 0.0 {
1845                line_deps |= LAYOUT_DEP_AVAIL_H;
1846            }
1847            main_avail
1848        } else {
1849            let min_h_len: Length = parent_layout.get_min_height();
1850            if matches!(min_h_len, Length::Percent(_)) || Self::is_viewport_length(min_h_len) {
1851                line_deps |= LAYOUT_DEP_VIEWPORT;
1852            }
1853            frame.get_min_inner_size().get_height()
1854        };
1855        let has_main_cap: bool = parent_layout.get_overflow() != Overflow::Scroll
1856            && if is_row {
1857                frame.get_definite_width() || parent_layout.get_max_width() != Length::Auto
1858            } else {
1859                frame.get_definite_height() || parent_layout.get_max_height() != Length::Auto
1860            };
1861        let pre_overflows: bool = !wrap_enabled
1862            && has_main_cap
1863            && precomputed
1864                .map(|(items_main, _): (f32, f32)| items_main + gaps_total > main_avail + 0.5)
1865                .unwrap_or(false);
1866        let mut line_shrunk: bool = false;
1867        let (final_used_main, line_cross): (f32, f32) = if let Some((items_main, pre_cross)) =
1868            precomputed
1869            && total_grow == 0.0
1870            && !pre_overflows
1871        {
1872            (items_main + gaps_total, pre_cross)
1873        } else {
1874            let used_main: f32 = if let Some((items_main, _)) = precomputed {
1875                items_main + gaps_total
1876            } else {
1877                let mut acc: f32 = gaps_total;
1878                for item_idx in line_start..line_end {
1879                    let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1880                    let sz: f32 = if is_row {
1881                        item.get_size().get_width() + item.get_margin().horizontal()
1882                    } else {
1883                        item.get_size().get_height() + item.get_margin().vertical()
1884                    };
1885                    acc += sz;
1886                }
1887                acc
1888            };
1889            let free_main: f32 = (effective_main_avail - used_main).max(0.0);
1890            let mut any_main_resized: bool = false;
1891            if total_grow > 0.0 && free_main > 0.0 {
1892                for item_idx in line_start..line_end {
1893                    let item: &mut FlexItemRecord =
1894                        &mut self.get_mut_flex_items_scratch()[item_idx];
1895                    let grow: f32 = item.get_flex_grow();
1896                    if grow > 0.0 {
1897                        let extra: f32 = free_main * (grow / total_grow);
1898                        if is_row {
1899                            let next_w: f32 = item.get_size().get_width() + extra;
1900                            item.get_mut_size().set_width(next_w);
1901                        } else {
1902                            let next_h: f32 = item.get_size().get_height() + extra;
1903                            item.get_mut_size().set_height(next_h);
1904                        }
1905                        any_main_resized = true;
1906                    }
1907                }
1908            } else if !wrap_enabled && has_main_cap && used_main > main_avail + 0.5 {
1909                line_deps |= if is_row {
1910                    LAYOUT_DEP_AVAIL_W
1911                } else {
1912                    LAYOUT_DEP_AVAIL_H
1913                };
1914                let mut rem_overflow: f32 = used_main - main_avail;
1915                for _ in 0..4usize {
1916                    if rem_overflow <= 0.05 {
1917                        break;
1918                    }
1919                    let mut weighted_sum: f32 = 0.0;
1920                    for item_idx in line_start..line_end {
1921                        let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1922                        let cur_main: f32 = if is_row {
1923                            item.get_size().get_width()
1924                        } else {
1925                            item.get_size().get_height()
1926                        };
1927                        if item.get_flex_shrink() > 0.0 && cur_main > item.get_min_main() + 0.05 {
1928                            weighted_sum += item.get_flex_shrink() * cur_main.max(1.0);
1929                        }
1930                    }
1931                    if weighted_sum <= 0.0 {
1932                        break;
1933                    }
1934                    let pass_overflow: f32 = rem_overflow;
1935                    let mut absorbed: f32 = 0.0;
1936                    for item_idx in line_start..line_end {
1937                        let item: &mut FlexItemRecord =
1938                            &mut self.get_mut_flex_items_scratch()[item_idx];
1939                        let cur_main: f32 = if is_row {
1940                            item.get_size().get_width()
1941                        } else {
1942                            item.get_size().get_height()
1943                        };
1944                        let min_m: f32 = item.get_min_main();
1945                        let shrink_f: f32 = item.get_flex_shrink();
1946                        if shrink_f > 0.0 && cur_main > min_m + 0.05 {
1947                            let w: f32 = shrink_f * cur_main.max(1.0);
1948                            let raw_cut: f32 = pass_overflow * (w / weighted_sum);
1949                            let next_main: f32 = (cur_main - raw_cut).max(min_m);
1950                            let cut: f32 = cur_main - next_main;
1951                            if cut > 0.01 {
1952                                if is_row {
1953                                    item.get_mut_size().set_width(next_main);
1954                                } else {
1955                                    item.get_mut_size().set_height(next_main);
1956                                }
1957                                absorbed += cut;
1958                                any_main_resized = true;
1959                                line_shrunk = true;
1960                            }
1961                        }
1962                    }
1963                    if absorbed <= 0.01 {
1964                        break;
1965                    }
1966                    rem_overflow = (rem_overflow - absorbed).max(0.0);
1967                }
1968            }
1969            if total_grow > 0.0 || any_main_resized {
1970                for item_idx in line_start..line_end {
1971                    let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1972                    let resized_item: bool = item.get_flex_grow() > 0.0 || any_main_resized;
1973                    let auto_cross: bool = resized_item
1974                        && if is_row {
1975                            (item.get_flags() & FLEX_ITEM_HEIGHT_AUTO) != 0
1976                        } else {
1977                            (item.get_flags() & FLEX_ITEM_WIDTH_AUTO) != 0
1978                        };
1979                    if auto_cross {
1980                        let probe_w: f32 = if is_row {
1981                            item.get_size().get_width()
1982                        } else {
1983                            cross_avail
1984                        };
1985                        let probe_h: f32 = if is_row {
1986                            cross_avail
1987                        } else {
1988                            item.get_size().get_height()
1989                        };
1990                        let stretch_pw: bool =
1991                            is_row && (item.get_flags() & FLEX_ITEM_WIDTH_AUTO) != 0;
1992                        let stretch_ph: bool =
1993                            !is_row && (item.get_flags() & FLEX_ITEM_HEIGHT_AUTO) != 0;
1994                        let probe_sp: AvailableSpace = AvailableSpace::new(
1995                            probe_w,
1996                            probe_h,
1997                            viewport,
1998                            content_origin.get_x(),
1999                            content_origin.get_y(),
2000                        )
2001                        .with_stretch(stretch_pw, stretch_ph);
2002                        let (measured, c_deps, c_min_aw): (Size, u8, f32) = self.layout_node_mode(
2003                            tree,
2004                            item.get_node_id(),
2005                            probe_sp,
2006                            LayoutRunMode::ComputeSize,
2007                            stats,
2008                        );
2009                        line_deps |= c_deps;
2010                        if c_min_aw > 0.0 {
2011                            line_min_aw =
2012                                line_min_aw.max(c_min_aw + item.get_margin().horizontal());
2013                        }
2014                        let slot: &mut FlexItemRecord =
2015                            &mut self.get_mut_flex_items_scratch()[item_idx];
2016                        if is_row {
2017                            slot.get_mut_size().set_height(measured.get_height());
2018                        } else {
2019                            slot.get_mut_size().set_width(measured.get_width());
2020                        }
2021                    }
2022                }
2023            }
2024            let mut sum_main: f32 = gaps_total;
2025            let mut max_cross: f32 = 0.0;
2026            for item_idx in line_start..line_end {
2027                let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
2028                if is_row {
2029                    sum_main += item.get_size().get_width() + item.get_margin().horizontal();
2030                    max_cross =
2031                        max_cross.max(item.get_size().get_height() + item.get_margin().vertical());
2032                } else {
2033                    sum_main += item.get_size().get_height() + item.get_margin().vertical();
2034                    max_cross =
2035                        max_cross.max(item.get_size().get_width() + item.get_margin().horizontal());
2036                }
2037            }
2038            (sum_main, max_cross)
2039        };
2040        if mode == LayoutRunMode::ComputeSize {
2041            let sz: Size = if is_row {
2042                Size::new(final_used_main, line_cross)
2043            } else {
2044                Size::new(line_cross, final_used_main)
2045            };
2046            return (sz, line_deps, line_min_aw);
2047        }
2048        let rem: f32 = (effective_main_avail - final_used_main).max(0.0);
2049        let (mut main_cursor, extra_step): (f32, f32) = match parent_layout.get_justify_content() {
2050            JustifyContent::Start => (0.0, 0.0),
2051            JustifyContent::Center => (rem * 0.5, 0.0),
2052            JustifyContent::End => (rem, 0.0),
2053            JustifyContent::SpaceBetween => {
2054                if count > 1 {
2055                    (0.0, rem / ((count - 1) as f32))
2056                } else {
2057                    (0.0, 0.0)
2058                }
2059            }
2060            JustifyContent::SpaceAround => {
2061                let slot: f32 = rem / (count.max(1) as f32);
2062                (slot * 0.5, slot)
2063            }
2064            JustifyContent::SpaceEvenly => {
2065                let slot: f32 = rem / ((count + 1) as f32);
2066                (slot, slot)
2067            }
2068        };
2069        let min_cross: f32 = if is_row {
2070            frame.get_min_inner_size().get_height()
2071        } else {
2072            frame.get_min_inner_size().get_width()
2073        };
2074        let definite_cross: bool = !is_row || frame.get_definite_height();
2075        let effective_line_cross: f32 = if line_count == 1 {
2076            let floor_cross: f32 = if definite_cross && (!wrap_enabled || is_row) {
2077                cross_avail.max(min_cross)
2078            } else {
2079                min_cross
2080            };
2081            line_cross.max(floor_cross)
2082        } else {
2083            line_cross
2084        };
2085        let mut actual_line_cross: f32 = line_cross;
2086        let parent_align: AlignItems = parent_layout.get_align_items();
2087        for idx in 0..count {
2088            let rec: FlexItemRecord = self.get_flex_items_scratch()[line_start + idx];
2089            let child_id: NodeId = rec.get_node_id();
2090            let child_size: Size = rec.get_size();
2091            let margin: Edges = rec.get_margin();
2092            let width_auto: bool = (rec.get_flags() & FLEX_ITEM_WIDTH_AUTO) != 0;
2093            let height_auto: bool = (rec.get_flags() & FLEX_ITEM_HEIGHT_AUTO) != 0;
2094            let item_cross: f32 = if is_row {
2095                child_size.get_height()
2096            } else {
2097                child_size.get_width()
2098            };
2099            let align: AlignItems = match rec.get_align_self() {
2100                AlignSelf::Auto => parent_align,
2101                AlignSelf::Stretch => AlignItems::Stretch,
2102                AlignSelf::Start => AlignItems::Start,
2103                AlignSelf::Center => AlignItems::Center,
2104                AlignSelf::End => AlignItems::End,
2105            };
2106            let avail_item_cross: f32 = (effective_line_cross
2107                - if is_row {
2108                    margin.vertical()
2109                } else {
2110                    margin.horizontal()
2111                })
2112            .max(0.0);
2113            let cross_offset: f32 = match align {
2114                AlignItems::Start | AlignItems::Stretch => 0.0,
2115                AlignItems::Center => ((avail_item_cross - item_cross) * 0.5).max(0.0),
2116                AlignItems::End => (avail_item_cross - item_cross).max(0.0),
2117            };
2118            let main_resized_item: bool = rec.get_flex_grow() > 0.0 || line_shrunk;
2119            let auto_cross_grow: bool =
2120                main_resized_item && if is_row { height_auto } else { width_auto };
2121            let target_w: f32 = if !is_row && align == AlignItems::Stretch && width_auto {
2122                avail_item_cross.max(child_size.get_width())
2123            } else {
2124                child_size.get_width()
2125            };
2126            let target_h: f32 = if is_row && align == AlignItems::Stretch && height_auto {
2127                avail_item_cross.max(child_size.get_height())
2128            } else {
2129                child_size.get_height()
2130            };
2131            let (x, y): (f32, f32) = if is_row {
2132                (
2133                    content_origin.get_x() + main_cursor + margin.get_left(),
2134                    content_origin.get_y() + cross_cursor + cross_offset + margin.get_top(),
2135                )
2136            } else {
2137                (
2138                    content_origin.get_x() + cross_cursor + cross_offset + margin.get_left(),
2139                    content_origin.get_y() + main_cursor + margin.get_top(),
2140                )
2141            };
2142            let stretch_child_w: bool = !(auto_cross_grow && !is_row)
2143                && ((!is_row && align == AlignItems::Stretch && width_auto)
2144                    || (is_row && main_resized_item && width_auto));
2145            let stretch_child_h: bool = !(auto_cross_grow && is_row)
2146                && ((is_row && align == AlignItems::Stretch && height_auto)
2147                    || (!is_row && main_resized_item && height_auto));
2148            let space_w: f32 =
2149                if !stretch_child_w && (rec.get_flags() & FLEX_ITEM_WIDTH_PERCENT) != 0 {
2150                    inner_avail.get_width()
2151                } else if auto_cross_grow && !is_row {
2152                    cross_avail
2153                } else {
2154                    target_w
2155                };
2156            let space_h: f32 =
2157                if !stretch_child_h && (rec.get_flags() & FLEX_ITEM_HEIGHT_PERCENT) != 0 {
2158                    inner_avail.get_height()
2159                } else if auto_cross_grow && is_row {
2160                    cross_avail
2161                } else {
2162                    target_h
2163                };
2164            let final_space: AvailableSpace = AvailableSpace::new(space_w, space_h, viewport, x, y)
2165                .with_stretch(stretch_child_w, stretch_child_h);
2166            let (placed, _, _): (Size, u8, f32) = self.layout_node_mode(
2167                tree,
2168                child_id,
2169                final_space,
2170                LayoutRunMode::PerformLayout,
2171                stats,
2172            );
2173            let is_clipped: bool =
2174                matches!(rec.get_overflow(), Overflow::Hidden | Overflow::Scroll);
2175            let mut placed_final: Size = placed;
2176            if auto_cross_grow && matches!(align, AlignItems::Center | AlignItems::End) {
2177                let actual_item_cross: f32 = if is_row {
2178                    placed_final.get_height()
2179                } else {
2180                    placed_final.get_width()
2181                };
2182                let refined_offset: f32 = match align {
2183                    AlignItems::Center => ((avail_item_cross - actual_item_cross) * 0.5).max(0.0),
2184                    AlignItems::End => (avail_item_cross - actual_item_cross).max(0.0),
2185                    AlignItems::Start | AlignItems::Stretch => cross_offset,
2186                };
2187                let delta_cross: f32 = refined_offset - cross_offset;
2188                if delta_cross.abs() > 0.001 {
2189                    let (next_x, next_y): (f32, f32) = if is_row {
2190                        (x, y + delta_cross)
2191                    } else {
2192                        (x + delta_cross, y)
2193                    };
2194                    let shifted_space: AvailableSpace =
2195                        AvailableSpace::new(space_w, space_h, viewport, next_x, next_y)
2196                            .with_stretch(stretch_child_w, stretch_child_h);
2197                    let (re_placed, _, _): (Size, u8, f32) = self.layout_node_mode(
2198                        tree,
2199                        child_id,
2200                        shifted_space,
2201                        LayoutRunMode::PerformLayout,
2202                        stats,
2203                    );
2204                    placed_final = re_placed;
2205                }
2206            }
2207            let (desired_w, desired_h): (f32, f32) = if auto_cross_grow {
2208                if is_row {
2209                    actual_line_cross =
2210                        actual_line_cross.max(placed_final.get_height() + margin.vertical());
2211                    (target_w, placed_final.get_height())
2212                } else {
2213                    actual_line_cross =
2214                        actual_line_cross.max(placed_final.get_width() + margin.horizontal());
2215                    (placed_final.get_width(), target_h)
2216                }
2217            } else if is_clipped || main_resized_item {
2218                (target_w, target_h)
2219            } else {
2220                (
2221                    target_w.max(placed_final.get_width()),
2222                    target_h.max(placed_final.get_height()),
2223                )
2224            };
2225            let needs_box_adjust: bool = tree.get_node(child_id).is_some_and(|n: &SceneNode| {
2226                let b: Rect = n.get_layout_box().get_bounds();
2227                (b.get_width() - desired_w).abs() > 0.001
2228                    || (b.get_height() - desired_h).abs() > 0.001
2229            });
2230            if needs_box_adjust {
2231                self.record_layout_snapshot(tree, child_id);
2232                let adjusted_opt: Option<(Rect, Transform2D)> =
2233                    if let Some(node) = tree.get_node_mut(child_id) {
2234                        let pad: Edges = node.style_ref().layout_ref().get_padding();
2235                        let bw: f32 = node.style_ref().paint_ref().get_border().get_width();
2236                        let tr: Transform2D = node.style_ref().paint_ref().get_transform();
2237                        let mut b: Rect = node.get_layout_box().get_bounds();
2238                        b.set_width(desired_w);
2239                        b.set_height(desired_h);
2240                        let mut cb: Rect = node.get_layout_box().get_content_bounds();
2241                        cb.set_width((desired_w - pad.horizontal() - bw * 2.0).max(0.0));
2242                        cb.set_height((desired_h - pad.vertical() - bw * 2.0).max(0.0));
2243                        node.get_mut_layout_box().set_bounds(b);
2244                        node.get_mut_layout_box().set_content_bounds(cb);
2245                        Some((b, tr))
2246                    } else {
2247                        None
2248                    };
2249                if let Some((b, tr)) = adjusted_opt {
2250                    let Self { split_cache, .. } = self;
2251                    split_cache.mark_post_stretched(child_id, b, tr, is_clipped);
2252                }
2253            }
2254            let advance: f32 = if is_row {
2255                target_w + margin.horizontal()
2256            } else {
2257                target_h + margin.vertical()
2258            };
2259            main_cursor += advance;
2260            if idx + 1 < count {
2261                main_cursor += main_gap + extra_step;
2262            }
2263        }
2264        let sz: Size = if is_row {
2265            Size::new(final_used_main, actual_line_cross)
2266        } else {
2267            Size::new(actual_line_cross, final_used_main)
2268        };
2269        (sz, line_deps, line_min_aw)
2270    }
2271
2272    /// Executes uniform-column CSS Grid layout with row and column gaps in `ComputeSize` or `PerformLayout` mode.
2273    ///
2274    /// # Arguments
2275    ///
2276    /// - `&Self` - Mutable layout engine reference.
2277    /// - `&mut SceneTree` - Mutable scene tree.
2278    /// - `(usize, usize)` - Inclusive start and exclusive end indices into `flow_scratch`.
2279    /// - `ContainerFrame` - Grid container constraints and origin.
2280    /// - `LayoutRunMode` - `ComputeSize` probe vs `PerformLayout` placement mode.
2281    /// - `&mut LayoutStats` - Mutable telemetry counters.
2282    ///
2283    /// # Returns
2284    ///
2285    /// - `(Size, u8, f32)` - Aggregate grid content dimensions, dependency mask, and invariant `min_avail_w`.
2286    fn layout_grid(
2287        &mut self,
2288        tree: &mut SceneTree,
2289        flow_range: (usize, usize),
2290        frame: ContainerFrame,
2291        mode: LayoutRunMode,
2292        stats: &mut LayoutStats,
2293    ) -> (Size, u8, f32) {
2294        let (flow_start, flow_end): (usize, usize) = flow_range;
2295        if flow_start >= flow_end {
2296            return (Size::default(), LAYOUT_DEP_NONE, 0.0);
2297        }
2298        let parent_layout: LayoutStyle = frame.get_parent_layout();
2299        let inner_avail: Size = frame.get_inner_avail();
2300        let viewport: Size = frame.get_viewport();
2301        let content_origin: Point = frame.get_content_origin();
2302        let cols: usize = (parent_layout.get_grid_columns() as usize).max(1);
2303        let col_gap: f32 = parent_layout.get_column_gap();
2304        let row_gap: f32 = parent_layout.get_row_gap();
2305        let total_col_gaps: f32 = col_gap * ((cols.saturating_sub(1)) as f32);
2306        let col_w: f32 = ((inner_avail.get_width() - total_col_gaps) / (cols as f32)).max(0.0);
2307        let col_step: f32 = col_w + col_gap;
2308        let origin_x: f32 = content_origin.get_x();
2309        let origin_y: f32 = content_origin.get_y();
2310        let inner_h: f32 = inner_avail.get_height();
2311        let mut y_cursor: f32 = 0.0;
2312        let mut idx: usize = flow_start;
2313        let mut grid_deps: u8 = LAYOUT_DEP_AVAIL_W;
2314        while idx < flow_end {
2315            let row_end: usize = (idx + cols).min(flow_end);
2316            let mut row_h: f32 = 0.0;
2317            let mut min_row_h: f32 = f32::INFINITY;
2318            let y: f32 = origin_y + y_cursor;
2319            let mut x: f32 = origin_x;
2320            for pos in idx..row_end {
2321                let child_id: NodeId = self.get_flow_scratch()[pos];
2322                let auto_w: bool = tree.get_node(child_id).is_some_and(|n: &SceneNode| {
2323                    n.style_ref().layout_ref().get_width() == Length::Auto
2324                });
2325                let cell_space: AvailableSpace =
2326                    AvailableSpace::new(col_w, inner_h, viewport, x, y).with_stretch(auto_w, false);
2327                let (child_size, c_deps, _): (Size, u8, f32) =
2328                    self.layout_node_mode(tree, child_id, cell_space, mode, stats);
2329                grid_deps |= c_deps;
2330                if mode == LayoutRunMode::PerformLayout
2331                    && (child_size.get_width() - col_w).abs() > 0.001
2332                {
2333                    self.record_layout_snapshot(tree, child_id);
2334                    let adjusted_opt: Option<(Rect, Transform2D, bool)> =
2335                        if let Some(node) = tree.get_node_mut(child_id) {
2336                            let tr: Transform2D = node.style_ref().paint_ref().get_transform();
2337                            let clipped: bool = matches!(
2338                                node.style_ref().layout_ref().get_overflow(),
2339                                Overflow::Hidden | Overflow::Scroll
2340                            );
2341                            let mut b: Rect = node.get_layout_box().get_bounds();
2342                            b.set_width(col_w);
2343                            node.get_mut_layout_box().set_bounds(b);
2344                            Some((b, tr, clipped))
2345                        } else {
2346                            None
2347                        };
2348                    if let Some((b, tr, clipped)) = adjusted_opt {
2349                        let Self { split_cache, .. } = self;
2350                        split_cache.mark_post_stretched(child_id, b, tr, clipped);
2351                    }
2352                }
2353                let ch: f32 = child_size.get_height();
2354                row_h = row_h.max(ch);
2355                min_row_h = min_row_h.min(ch);
2356                x += col_step;
2357            }
2358            if mode == LayoutRunMode::PerformLayout && row_end - idx > 1 && min_row_h < row_h {
2359                for pos in idx..row_end {
2360                    let child_id: NodeId = self.get_flow_scratch()[pos];
2361                    let needs_stretch: bool =
2362                        tree.get_node(child_id).is_some_and(|n: &SceneNode| {
2363                            n.get_layout_box().get_bounds().get_height() < row_h
2364                        });
2365                    if needs_stretch {
2366                        self.record_layout_snapshot(tree, child_id);
2367                        let adjusted_opt: Option<(Rect, Transform2D, bool)> =
2368                            if let Some(node) = tree.get_node_mut(child_id) {
2369                                let tr: Transform2D = node.style_ref().paint_ref().get_transform();
2370                                let clipped: bool = matches!(
2371                                    node.style_ref().layout_ref().get_overflow(),
2372                                    Overflow::Hidden | Overflow::Scroll
2373                                );
2374                                let mut b: Rect = node.get_layout_box().get_bounds();
2375                                b.set_height(row_h);
2376                                node.get_mut_layout_box().set_bounds(b);
2377                                Some((b, tr, clipped))
2378                            } else {
2379                                None
2380                            };
2381                        if let Some((b, tr, clipped)) = adjusted_opt {
2382                            let Self { split_cache, .. } = self;
2383                            split_cache.mark_post_stretched(child_id, b, tr, clipped);
2384                        }
2385                    }
2386                }
2387            }
2388            y_cursor += row_h;
2389            if row_end < flow_end {
2390                y_cursor += row_gap;
2391            }
2392            idx = row_end;
2393        }
2394        (Size::new(inner_avail.get_width(), y_cursor), grid_deps, 0.0)
2395    }
2396
2397    /// Translates the cached layout geometry and SoA `SplitLayoutCache` bounds of `root_id` and non-fixed descendants by `(dx, dy)`.
2398    ///
2399    /// # Arguments
2400    ///
2401    /// - `&Self` - Mutable layout engine reference.
2402    /// - `&mut SceneTree` - Mutable retained scene tree.
2403    /// - `NodeId` - Root node of the clean subtree being shifted.
2404    /// - `f32` - Horizontal translation delta in logical pixels.
2405    /// - `f32` - Vertical translation delta in logical pixels.
2406    fn translate_subtree(&mut self, tree: &mut SceneTree, root_id: NodeId, dx: f32, dy: f32) {
2407        if dx == 0.0 && dy == 0.0 {
2408            return;
2409        }
2410        self.record_layout_snapshot(tree, root_id);
2411        let Some(root_node) = tree.get_node_mut(root_id) else {
2412            return;
2413        };
2414        let Style { layout, .. } = root_node.style_ref();
2415        let root_none_disp: bool = layout.get_display() == Display::None;
2416        if let Some(mut c) = root_node.cached_constraint() {
2417            c.set_origin_x(c.get_origin_x() + dx);
2418            c.set_origin_y(c.get_origin_y() + dy);
2419            root_node.set_last_constraint(Some(c));
2420        }
2421        if root_none_disp {
2422            let Self { split_cache, .. } = self;
2423            split_cache.translate_node_cache(root_id, dx, dy);
2424            return;
2425        }
2426        let mut root_bounds: Rect = root_node.get_layout_box().get_bounds();
2427        root_bounds.set_x(root_bounds.get_x() + dx);
2428        root_bounds.set_y(root_bounds.get_y() + dy);
2429        root_node.get_mut_layout_box().set_bounds(root_bounds);
2430        let mut root_content: Rect = root_node.get_layout_box().get_content_bounds();
2431        root_content.set_x(root_content.get_x() + dx);
2432        root_content.set_y(root_content.get_y() + dy);
2433        root_node
2434            .get_mut_layout_box()
2435            .set_content_bounds(root_content);
2436        let root_children_empty: bool = !tree.has_children(root_id);
2437        if !root_children_empty {
2438            self.get_mut_translate_scratch().clear();
2439            self.get_mut_translate_scratch()
2440                .extend(tree.children_iter(root_id));
2441        }
2442        {
2443            let Self { split_cache, .. } = self;
2444            split_cache.translate_node_cache(root_id, dx, dy);
2445        }
2446        if root_children_empty {
2447            return;
2448        }
2449        while let Some(nid) = self.get_mut_translate_scratch().pop() {
2450            let (is_fixed_pos, is_none_disp): (bool, bool) = match tree.get_node(nid) {
2451                Some(node) => {
2452                    let Style { layout, .. } = node.style_ref();
2453                    (
2454                        layout.get_position() == Position::Fixed,
2455                        layout.get_display() == Display::None,
2456                    )
2457                }
2458                None => continue,
2459            };
2460            if is_fixed_pos {
2461                continue;
2462            }
2463            if !is_none_disp {
2464                self.record_layout_snapshot(tree, nid);
2465            }
2466            let Some(node) = tree.get_node_mut(nid) else {
2467                continue;
2468            };
2469            if let Some(mut c) = node.cached_constraint() {
2470                c.set_origin_x(c.get_origin_x() + dx);
2471                c.set_origin_y(c.get_origin_y() + dy);
2472                node.set_last_constraint(Some(c));
2473            }
2474            if is_none_disp {
2475                let Self { split_cache, .. } = self;
2476                split_cache.translate_node_cache(nid, dx, dy);
2477                continue;
2478            }
2479            let mut bounds: Rect = node.get_layout_box().get_bounds();
2480            bounds.set_x(bounds.get_x() + dx);
2481            bounds.set_y(bounds.get_y() + dy);
2482            node.get_mut_layout_box().set_bounds(bounds);
2483            let mut content: Rect = node.get_layout_box().get_content_bounds();
2484            content.set_x(content.get_x() + dx);
2485            content.set_y(content.get_y() + dy);
2486            node.get_mut_layout_box().set_content_bounds(content);
2487            let has_children: bool = tree.has_children(nid);
2488            if has_children {
2489                self.get_mut_translate_scratch()
2490                    .extend(tree.children_iter(nid));
2491            }
2492            let Self { split_cache, .. } = self;
2493            split_cache.translate_node_cache(nid, dx, dy);
2494        }
2495    }
2496}