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