Skip to main content

euv_core/layout/engine/
impl.rs

1use super::*;
2
3/// Core layout solver and hit-testing operations for `LayoutEngine`.
4impl LayoutEngine {
5    /// Computes layout for the entire `tree` within `viewport`, skipping clean cached subtrees.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Mutable layout engine.
10    /// - `&mut SceneTree` - Retained scene tree to lay out.
11    /// - `Size` - Logical viewport dimensions.
12    ///
13    /// # Returns
14    ///
15    /// - `LayoutStats` - Computed vs cached subtree counts.
16    pub fn compute(&mut self, tree: &mut SceneTree, viewport: Size) -> LayoutStats {
17        let root_id: NodeId = tree.get_root();
18        let space: AvailableSpace = AvailableSpace::root(viewport);
19        let mut stats: LayoutStats = LayoutStats::default();
20        self.layout_node(tree, root_id, space, &mut stats);
21        self.set_last_stats(stats);
22        stats
23    }
24
25    /// Performs recursive layout on `node_id` with O(1) clean-subtree caching.
26    ///
27    /// # Arguments
28    ///
29    /// - `&Self` - Layout engine reference.
30    /// - `&mut SceneTree` - Mutable scene tree.
31    /// - `NodeId` - Node handle to compute.
32    /// - `AvailableSpace` - Parent space constraint and origin.
33    /// - `&mut LayoutStats` - Mutable telemetry counters.
34    ///
35    /// # Returns
36    ///
37    /// - `Size` - Computed border-box dimensions of `node_id`.
38    fn layout_node(
39        &self,
40        tree: &mut SceneTree,
41        node_id: NodeId,
42        space: AvailableSpace,
43        stats: &mut LayoutStats,
44    ) -> Size {
45        if let Some(node) = tree.get_node(node_id) {
46            if !node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
47                && let Some(prev_space) = node.cached_constraint()
48            {
49                let same_size: bool = (prev_space.get_width() - space.get_width()).abs() <= 0.01
50                    && (prev_space.get_height() - space.get_height()).abs() <= 0.01
51                    && (prev_space.get_viewport().get_width() - space.get_viewport().get_width())
52                        .abs()
53                        <= 0.01
54                    && (prev_space.get_viewport().get_height() - space.get_viewport().get_height())
55                        .abs()
56                        <= 0.01
57                    && prev_space.get_stretch_width() == space.get_stretch_width()
58                    && prev_space.get_stretch_height() == space.get_stretch_height();
59                if same_size {
60                    let dx: f32 = space.get_origin_x() - prev_space.get_origin_x();
61                    let dy: f32 = space.get_origin_y() - prev_space.get_origin_y();
62                    let prev_bounds: Rect = node.get_layout_box().get_bounds();
63                    if dx.abs() > 0.001 || dy.abs() > 0.001 {
64                        self.translate_subtree(tree, node_id, dx, dy);
65                    }
66                    stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
67                    return Size::new(prev_bounds.get_width(), prev_bounds.get_height());
68                }
69            }
70        } else {
71            return Size::default();
72        }
73        let snapshot: Option<LayoutNodeSnapshot> =
74            tree.get_node(node_id).map(|node: &SceneNode| {
75                (
76                    node.get_style(),
77                    node.get_kind().clone(),
78                    node.get_dirty(),
79                    node.cached_constraint(),
80                    node.get_layout_box().get_bounds(),
81                    node.get_children().clone(),
82                )
83            });
84        let Some((style, kind, _, _, _, children)) = snapshot else {
85            return Size::default();
86        };
87        stats.set_nodes_computed(stats.get_nodes_computed() + 1);
88        let layout: LayoutStyle = style.get_layout();
89        if layout.get_display() == Display::None {
90            let mut stack: Vec<NodeId> = vec![node_id];
91            while let Some(hid) = stack.pop() {
92                if let Some(node) = tree.get_node_mut(hid) {
93                    node.get_mut_layout_box().set_bounds(Rect::default());
94                    node.get_mut_layout_box()
95                        .set_content_bounds(Rect::default());
96                    node.set_last_constraint(Some(space));
97                    node.get_mut_dirty().remove(DIRTY_LAYOUT_PASS_MASK);
98                    stack.extend(node.get_children().iter().copied());
99                }
100            }
101            return Size::default();
102        }
103        let padding: Edges = layout.get_padding();
104        let border_w: f32 = style.get_paint().get_border().get_width();
105        let chrome_h: f32 = padding.horizontal() + border_w * 2.0;
106        let chrome_v: f32 = padding.vertical() + border_w * 2.0;
107        let mut resolved_w: Option<f32> = layout
108            .get_width()
109            .resolve(space.get_width(), space.get_viewport());
110        let mut resolved_h: Option<f32> = layout
111            .get_height()
112            .resolve(space.get_height(), space.get_viewport());
113        if resolved_w.is_none() && space.get_stretch_width() {
114            resolved_w = Some(space.get_width());
115        }
116        if resolved_h.is_none() && space.get_stretch_height() {
117            resolved_h = Some(space.get_height());
118        }
119        let min_w: f32 = layout
120            .get_min_width()
121            .resolve(space.get_width(), space.get_viewport())
122            .unwrap_or(0.0);
123        let min_h: f32 = layout
124            .get_min_height()
125            .resolve(space.get_height(), space.get_viewport())
126            .unwrap_or(0.0);
127        let max_w: f32 = layout
128            .get_max_width()
129            .resolve(space.get_width(), space.get_viewport())
130            .unwrap_or(f32::INFINITY);
131        let max_h: f32 = layout
132            .get_max_height()
133            .resolve(space.get_height(), space.get_viewport())
134            .unwrap_or(f32::INFINITY);
135        if let Some(ratio) = layout.aspect_ratio_value()
136            && ratio > 0.0
137        {
138            if let Some(w) = resolved_w
139                && resolved_h.is_none()
140            {
141                resolved_h = Some(w.clamp(min_w, max_w) / ratio);
142            } else if let Some(h) = resolved_h
143                && resolved_w.is_none()
144            {
145                resolved_w = Some(h.clamp(min_h, max_h) * ratio);
146            }
147        }
148        let inner_avail_w: f32 =
149            (resolved_w.unwrap_or(space.get_width()).min(max_w) - chrome_h).max(0.0);
150        let inner_avail_h: f32 =
151            (resolved_h.unwrap_or(space.get_height()).min(max_h) - chrome_v).max(0.0);
152        let origin_x: f32 = space.get_origin_x();
153        let origin_y: f32 = space.get_origin_y();
154        let content_origin_x: f32 = origin_x + padding.get_left() + border_w;
155        let content_origin_y: f32 = origin_y + padding.get_top() + border_w;
156        let content_size: Size = match &kind {
157            NodeKind::Text(text) => {
158                let measured: TextLayoutResult = self.get_measurer().measure(
159                    text,
160                    style.get_text(),
161                    Some(inner_avail_w.max(1.0)),
162                );
163                measured.get_size()
164            }
165            NodeKind::Image(img) => Size::new(img.get_width() as f32, img.get_height() as f32),
166            NodeKind::Input(input_state) => {
167                let sample: &str = if input_state.get_value().is_empty() {
168                    input_state.get_placeholder().as_str()
169                } else {
170                    input_state.get_value().as_str()
171                };
172                let measured: TextLayoutResult = self.get_measurer().measure(
173                    sample,
174                    style.get_text(),
175                    Some(inner_avail_w.max(1.0)),
176                );
177                Size::new(
178                    measured.get_size().get_width().max(120.0),
179                    measured.get_size().get_height().max(20.0),
180                )
181            }
182            NodeKind::View
183            | NodeKind::ScrollView
184            | NodeKind::Portal
185            | NodeKind::Fragment
186            | NodeKind::Canvas => {
187                let frame: ContainerFrame = ContainerFrame::new(
188                    layout,
189                    Size::new(inner_avail_w, inner_avail_h),
190                    space.get_viewport(),
191                    Point::new(content_origin_x, content_origin_y),
192                    resolved_w.is_some(),
193                    resolved_h.is_some(),
194                );
195                self.layout_children(tree, &children, frame, stats)
196            }
197        };
198        let mut final_w: f32 = resolved_w.unwrap_or(content_size.get_width() + chrome_h);
199        let mut final_h: f32 = resolved_h.unwrap_or(content_size.get_height() + chrome_v);
200        if let Some(ratio) = layout.aspect_ratio_value()
201            && ratio > 0.0
202        {
203            if resolved_w.is_some() && resolved_h.is_none() {
204                final_h = final_w / ratio;
205            } else if resolved_h.is_some() && resolved_w.is_none() {
206                final_w = final_h * ratio;
207            }
208        }
209        final_w = final_w.clamp(min_w, max_w).max(0.0);
210        final_h = final_h.clamp(min_h, max_h).max(0.0);
211        let bounds: Rect = Rect::new(origin_x, origin_y, final_w, final_h);
212        let content_bounds: Rect = Rect::new(
213            content_origin_x,
214            content_origin_y,
215            (final_w - chrome_h).max(0.0),
216            (final_h - chrome_v).max(0.0),
217        );
218        if let Some(node) = tree.get_node_mut(node_id) {
219            node.get_mut_layout_box().set_bounds(bounds);
220            node.get_mut_layout_box().set_content_bounds(content_bounds);
221            node.get_mut_layout_box().set_content_size(content_size);
222            node.set_last_constraint(Some(space));
223            node.get_mut_dirty().remove(DIRTY_LAYOUT_PASS_MASK);
224        }
225        Size::new(final_w, final_h)
226    }
227
228    /// Lays out children according to Flex, Grid, or Block rules plus Absolute/Fixed overlays.
229    ///
230    /// # Arguments
231    ///
232    /// - `&Self` - Layout engine reference.
233    /// - `&mut SceneTree` - Mutable scene tree.
234    /// - `&[NodeId]` - Ordered child handles.
235    /// - `ContainerFrame` - Parent layout constraints and origin.
236    /// - `&mut LayoutStats` - Mutable telemetry counters.
237    ///
238    /// # Returns
239    ///
240    /// - `Size` - Intrinsic aggregate content size occupied by flow children.
241    fn layout_children(
242        &self,
243        tree: &mut SceneTree,
244        children: &[NodeId],
245        frame: ContainerFrame,
246        stats: &mut LayoutStats,
247    ) -> Size {
248        if children.is_empty() {
249            return Size::default();
250        }
251        let parent_layout: LayoutStyle = frame.get_parent_layout();
252        let inner_avail: Size = frame.get_inner_avail();
253        let viewport: Size = frame.get_viewport();
254        let content_origin: Point = frame.get_content_origin();
255        let mut flow_children: Vec<NodeId> = Vec::with_capacity(children.len());
256        let mut abs_children: Vec<NodeId> = Vec::new();
257        for child_id in children.iter().copied() {
258            if let Some(child_node) = tree.get_node(child_id) {
259                let child_layout: LayoutStyle = child_node.get_style().get_layout();
260                if child_layout.get_display() == Display::None {
261                    let _: Size = self.layout_node(
262                        tree,
263                        child_id,
264                        AvailableSpace::new(0.0, 0.0, viewport, 0.0, 0.0),
265                        stats,
266                    );
267                    continue;
268                }
269                match child_layout.get_position() {
270                    Position::Relative => flow_children.push(child_id),
271                    Position::Absolute | Position::Fixed => abs_children.push(child_id),
272                }
273            }
274        }
275        let flow_size: Size = match parent_layout.get_display() {
276            Display::Grid => self.layout_grid(tree, &flow_children, frame, stats),
277            Display::Block => {
278                self.layout_flex(tree, &flow_children, frame, FlexDirection::Column, stats)
279            }
280            Display::Flex | Display::None => self.layout_flex(
281                tree,
282                &flow_children,
283                frame,
284                parent_layout.get_flex_direction(),
285                stats,
286            ),
287        };
288        for abs_id in abs_children.into_iter() {
289            let child_layout_opt: Option<LayoutStyle> = tree
290                .get_node(abs_id)
291                .map(|node: &SceneNode| node.get_style().get_layout());
292            let Some(child_layout) = child_layout_opt else {
293                continue;
294            };
295            let is_fixed: bool = child_layout.get_position() == Position::Fixed;
296            let ref_origin: Point = if is_fixed {
297                Point::new(0.0, 0.0)
298            } else {
299                content_origin
300            };
301            let ref_size: Size = if is_fixed { viewport } else { inner_avail };
302            let resolved_w: Option<f32> = child_layout
303                .get_width()
304                .resolve(ref_size.get_width(), viewport);
305            let resolved_h: Option<f32> = child_layout
306                .get_height()
307                .resolve(ref_size.get_height(), viewport);
308            let needs_intrinsic: bool = (resolved_w.is_none()
309                && child_layout.left_offset().is_none()
310                && child_layout.right_offset().is_some())
311                || (resolved_h.is_none()
312                    && child_layout.top_offset().is_none()
313                    && child_layout.bottom_offset().is_some());
314            let probed: Size = if needs_intrinsic {
315                let probe_space: AvailableSpace = AvailableSpace::new(
316                    ref_size.get_width(),
317                    ref_size.get_height(),
318                    viewport,
319                    ref_origin.get_x(),
320                    ref_origin.get_y(),
321                );
322                self.layout_node(tree, abs_id, probe_space, stats)
323            } else {
324                Size::new(ref_size.get_width(), ref_size.get_height())
325            };
326            let child_w: f32 = resolved_w.unwrap_or(probed.get_width());
327            let child_h: f32 = resolved_h.unwrap_or(probed.get_height());
328            let x: f32 = if let Some(left) = child_layout.left_offset() {
329                ref_origin.get_x() + left
330            } else if let Some(right) = child_layout.right_offset() {
331                ref_origin.get_x() + (ref_size.get_width() - child_w - right)
332            } else {
333                ref_origin.get_x()
334            };
335            let y: f32 = if let Some(top) = child_layout.top_offset() {
336                ref_origin.get_y() + top
337            } else if let Some(bottom) = child_layout.bottom_offset() {
338                ref_origin.get_y() + (ref_size.get_height() - child_h - bottom)
339            } else {
340                ref_origin.get_y()
341            };
342            let abs_space: AvailableSpace =
343                AvailableSpace::new(ref_size.get_width(), ref_size.get_height(), viewport, x, y);
344            let _: Size = self.layout_node(tree, abs_id, abs_space, stats);
345        }
346        flow_size
347    }
348
349    /// Executes single-line or multi-line Flexbox layout with grow, gap, justification, and alignment.
350    ///
351    /// # Arguments
352    ///
353    /// - `&Self` - Layout engine reference.
354    /// - `&mut SceneTree` - Mutable scene tree.
355    /// - `&[NodeId]` - Normal-flow children.
356    /// - `ContainerFrame` - Container constraints and origin.
357    /// - `FlexDirection` - Effective main-axis direction.
358    /// - `&mut LayoutStats` - Mutable telemetry counters.
359    ///
360    /// # Returns
361    ///
362    /// - `Size` - Aggregate content size of all flex lines.
363    fn layout_flex(
364        &self,
365        tree: &mut SceneTree,
366        children: &[NodeId],
367        frame: ContainerFrame,
368        direction: FlexDirection,
369        stats: &mut LayoutStats,
370    ) -> Size {
371        if children.is_empty() {
372            return Size::default();
373        }
374        let parent_layout: LayoutStyle = frame.get_parent_layout();
375        let inner_avail: Size = frame.get_inner_avail();
376        let viewport: Size = frame.get_viewport();
377        let content_origin: Point = frame.get_content_origin();
378        let is_row: bool = matches!(direction, FlexDirection::Row | FlexDirection::RowReverse);
379        let is_reverse: bool = matches!(
380            direction,
381            FlexDirection::RowReverse | FlexDirection::ColumnReverse
382        );
383        let main_gap: f32 = if is_row {
384            parent_layout.get_column_gap()
385        } else {
386            parent_layout.get_row_gap()
387        };
388        let cross_gap: f32 = if is_row {
389            parent_layout.get_row_gap()
390        } else {
391            parent_layout.get_column_gap()
392        };
393        let main_avail: f32 = if is_row {
394            inner_avail.get_width()
395        } else {
396            inner_avail.get_height()
397        };
398        let cross_avail: f32 = if is_row {
399            inner_avail.get_height()
400        } else {
401            inner_avail.get_width()
402        };
403        let mut measured_sizes: Vec<(NodeId, Size, LayoutStyle)> =
404            Vec::with_capacity(children.len());
405        let mut ordered: Vec<NodeId> = children.to_vec();
406        if is_reverse {
407            ordered.reverse();
408        }
409        let wrap_enabled: bool = parent_layout.get_flex_wrap() == FlexWrap::Wrap;
410        if !wrap_enabled
411            && !is_reverse
412            && parent_layout.get_justify_content() == JustifyContent::Start
413        {
414            let mut single_pass_ok: bool = true;
415            let mut has_stretched_auto: bool = false;
416            for child_id in ordered.iter().copied() {
417                let child_layout: LayoutStyle = tree
418                    .get_node(child_id)
419                    .map(|node: &SceneNode| node.get_style().get_layout())
420                    .unwrap_or_default();
421                if child_layout.get_flex_grow() > 0.0 {
422                    single_pass_ok = false;
423                    break;
424                }
425                let align: AlignItems = match child_layout.get_align_self() {
426                    AlignSelf::Auto => parent_layout.get_align_items(),
427                    AlignSelf::Stretch => AlignItems::Stretch,
428                    AlignSelf::Start => AlignItems::Start,
429                    AlignSelf::Center => AlignItems::Center,
430                    AlignSelf::End => AlignItems::End,
431                };
432                if matches!(align, AlignItems::Center | AlignItems::End) {
433                    single_pass_ok = false;
434                    break;
435                }
436                if align == AlignItems::Stretch {
437                    if is_row {
438                        if child_layout.get_height() == Length::Auto
439                            && parent_layout.get_height() == Length::Auto
440                        {
441                            single_pass_ok = false;
442                            break;
443                        }
444                    } else if child_layout.get_width() == Length::Auto {
445                        has_stretched_auto = true;
446                    }
447                }
448            }
449            if single_pass_ok {
450                let mut main_cursor: f32 = 0.0;
451                let mut max_cross: f32 = 0.0;
452                let count: usize = ordered.len();
453                let mut child_records: Vec<(NodeId, LayoutStyle, Size)> = if has_stretched_auto {
454                    Vec::with_capacity(count)
455                } else {
456                    Vec::new()
457                };
458                for (idx, child_id) in ordered.iter().copied().enumerate() {
459                    let child_layout: LayoutStyle = tree
460                        .get_node(child_id)
461                        .map(|node: &SceneNode| node.get_style().get_layout())
462                        .unwrap_or_default();
463                    let margin: Edges = child_layout.get_margin();
464                    let align: AlignItems = match child_layout.get_align_self() {
465                        AlignSelf::Auto => parent_layout.get_align_items(),
466                        AlignSelf::Stretch => AlignItems::Stretch,
467                        AlignSelf::Start => AlignItems::Start,
468                        AlignSelf::Center => AlignItems::Center,
469                        AlignSelf::End => AlignItems::End,
470                    };
471                    let (x, y): (f32, f32) = if is_row {
472                        (
473                            content_origin.get_x() + main_cursor + margin.get_left(),
474                            content_origin.get_y() + margin.get_top(),
475                        )
476                    } else {
477                        (
478                            content_origin.get_x() + margin.get_left(),
479                            content_origin.get_y() + main_cursor + margin.get_top(),
480                        )
481                    };
482                    let stretch_w: bool = !is_row
483                        && align == AlignItems::Stretch
484                        && child_layout.get_width() == Length::Auto;
485                    let stretch_h: bool = is_row
486                        && align == AlignItems::Stretch
487                        && child_layout.get_height() == Length::Auto;
488                    let space_w: f32 = if stretch_w {
489                        (inner_avail.get_width() - margin.horizontal()).max(0.0)
490                    } else {
491                        inner_avail.get_width()
492                    };
493                    let space_h: f32 = if stretch_h {
494                        (inner_avail.get_height() - margin.vertical()).max(0.0)
495                    } else {
496                        inner_avail.get_height()
497                    };
498                    let final_space: AvailableSpace =
499                        AvailableSpace::new(space_w, space_h, viewport, x, y)
500                            .with_stretch(stretch_w, stretch_h);
501                    let placed: Size = self.layout_node(tree, child_id, final_space, stats);
502                    let target_w: f32 = if stretch_w {
503                        space_w.max(placed.get_width())
504                    } else {
505                        placed.get_width()
506                    };
507                    let target_h: f32 = if stretch_h {
508                        space_h.max(placed.get_height())
509                    } else {
510                        placed.get_height()
511                    };
512                    if ((stretch_w && target_w > placed.get_width() + 0.01)
513                        || (stretch_h && target_h > placed.get_height() + 0.01))
514                        && let Some(node) = tree.get_node_mut(child_id)
515                    {
516                        let mut b: Rect = node.get_layout_box().get_bounds();
517                        b.set_width(target_w);
518                        b.set_height(target_h);
519                        node.get_mut_layout_box().set_bounds(b);
520                    }
521                    if has_stretched_auto {
522                        child_records.push((child_id, child_layout, Size::new(target_w, target_h)));
523                    }
524                    if is_row {
525                        main_cursor += target_w + margin.horizontal();
526                        max_cross = max_cross.max(target_h + margin.vertical());
527                    } else {
528                        main_cursor += target_h + margin.vertical();
529                        max_cross = max_cross.max(target_w + margin.horizontal());
530                    }
531                    if idx + 1 < count {
532                        main_cursor += main_gap;
533                    }
534                }
535                if has_stretched_auto && max_cross > cross_avail + 0.5 {
536                    for (child_id, child_layout, child_size) in child_records.into_iter() {
537                        let align: AlignItems = match child_layout.get_align_self() {
538                            AlignSelf::Auto => parent_layout.get_align_items(),
539                            AlignSelf::Stretch => AlignItems::Stretch,
540                            AlignSelf::Start => AlignItems::Start,
541                            AlignSelf::Center => AlignItems::Center,
542                            AlignSelf::End => AlignItems::End,
543                        };
544                        if align == AlignItems::Stretch && child_layout.get_width() == Length::Auto
545                        {
546                            let widened: f32 = (max_cross - child_layout.get_margin().horizontal())
547                                .max(child_size.get_width());
548                            if let Some(node) = tree.get_node_mut(child_id) {
549                                let mut b: Rect = node.get_layout_box().get_bounds();
550                                b.set_width(widened);
551                                node.get_mut_layout_box().set_bounds(b);
552                            }
553                        }
554                    }
555                }
556                return if is_row {
557                    Size::new(main_cursor, max_cross)
558                } else {
559                    Size::new(max_cross, main_cursor)
560                };
561            }
562        }
563        let mut total_grow: f32 = 0.0;
564        for child_id in ordered.iter().copied() {
565            let child_layout: LayoutStyle = tree
566                .get_node(child_id)
567                .map(|node: &SceneNode| node.get_style().get_layout())
568                .unwrap_or_default();
569            let grow: f32 = child_layout.get_flex_grow();
570            total_grow += grow;
571            let zero_basis_grow: bool = !wrap_enabled
572                && grow > 0.0
573                && if is_row {
574                    child_layout.get_width() == Length::Auto
575                } else {
576                    child_layout.get_height() == Length::Auto
577                };
578            let child_size: Size = if zero_basis_grow {
579                if is_row {
580                    let h: f32 = child_layout
581                        .get_height()
582                        .resolve(cross_avail, viewport)
583                        .unwrap_or(0.0);
584                    Size::new(0.0, h)
585                } else {
586                    let w: f32 = child_layout
587                        .get_width()
588                        .resolve(cross_avail, viewport)
589                        .unwrap_or(0.0);
590                    Size::new(w, 0.0)
591                }
592            } else {
593                let probe_space: AvailableSpace = AvailableSpace::new(
594                    inner_avail.get_width(),
595                    inner_avail.get_height(),
596                    viewport,
597                    content_origin.get_x(),
598                    content_origin.get_y(),
599                );
600                self.layout_node(tree, child_id, probe_space, stats)
601            };
602            measured_sizes.push((child_id, child_size, child_layout));
603        }
604        let mut lines: Vec<Vec<(NodeId, Size, LayoutStyle)>> = Vec::new();
605        let mut current_line: Vec<(NodeId, Size, LayoutStyle)> = Vec::new();
606        let mut line_main: f32 = 0.0;
607        for item in measured_sizes.into_iter() {
608            let item_main: f32 = if is_row {
609                item.1.get_width() + item.2.get_margin().horizontal()
610            } else {
611                item.1.get_height() + item.2.get_margin().vertical()
612            };
613            let needed: f32 = if current_line.is_empty() {
614                item_main
615            } else {
616                line_main + main_gap + item_main
617            };
618            if wrap_enabled && !current_line.is_empty() && needed > main_avail && main_avail > 0.0 {
619                lines.push(take(&mut current_line));
620                line_main = item_main;
621                current_line.push(item);
622            } else {
623                line_main = needed;
624                current_line.push(item);
625            }
626        }
627        if !current_line.is_empty() {
628            lines.push(current_line);
629        }
630        let mut cross_cursor: f32 = 0.0;
631        let mut max_main_extent: f32 = 0.0;
632        let line_count: usize = lines.len();
633        for (line_idx, mut line) in lines.into_iter().enumerate() {
634            let count: usize = line.len();
635            let gaps_total: f32 = if count > 1 {
636                main_gap * ((count - 1) as f32)
637            } else {
638                0.0
639            };
640            let used_main: f32 =
641                line.iter()
642                    .fold(0.0_f32, |acc: f32, item: &(NodeId, Size, LayoutStyle)| {
643                        let sz: f32 = if is_row {
644                            item.1.get_width() + item.2.get_margin().horizontal()
645                        } else {
646                            item.1.get_height() + item.2.get_margin().vertical()
647                        };
648                        acc + sz
649                    })
650                    + gaps_total;
651            let has_definite_or_grow: bool = frame.get_definite_width() || total_grow > 0.0;
652            let effective_main_avail: f32 = if is_row {
653                if has_definite_or_grow || wrap_enabled {
654                    main_avail
655                } else {
656                    parent_layout
657                        .get_min_width()
658                        .resolve(viewport.get_width(), viewport)
659                        .map(|mw: f32| (mw - parent_layout.get_padding().horizontal()).max(0.0))
660                        .unwrap_or(0.0)
661                }
662            } else if frame.get_definite_height() {
663                main_avail
664            } else {
665                parent_layout
666                    .get_min_height()
667                    .resolve(viewport.get_height(), viewport)
668                    .map(|mh: f32| (mh - parent_layout.get_padding().vertical()).max(0.0))
669                    .unwrap_or(0.0)
670            };
671            let free_main: f32 = (effective_main_avail - used_main).max(0.0);
672            if total_grow > 0.0 && free_main > 0.0 && !wrap_enabled {
673                for item in line.iter_mut() {
674                    let grow: f32 = item.2.get_flex_grow();
675                    if grow > 0.0 {
676                        let extra: f32 = free_main * (grow / total_grow);
677                        if is_row {
678                            item.1.set_width(item.1.get_width() + extra);
679                        } else {
680                            item.1.set_height(item.1.get_height() + extra);
681                        }
682                    }
683                }
684            }
685            if !wrap_enabled {
686                for item in line.iter_mut() {
687                    let auto_cross: bool = item.2.get_flex_grow() > 0.0
688                        && if is_row {
689                            item.2.get_height() == Length::Auto
690                        } else {
691                            item.2.get_width() == Length::Auto
692                        };
693                    if auto_cross {
694                        let probe_w: f32 = if is_row {
695                            item.1.get_width()
696                        } else {
697                            cross_avail
698                        };
699                        let probe_h: f32 = if is_row {
700                            cross_avail
701                        } else {
702                            item.1.get_height()
703                        };
704                        let probe_sp: AvailableSpace = AvailableSpace::new(
705                            probe_w,
706                            probe_h,
707                            viewport,
708                            content_origin.get_x(),
709                            content_origin.get_y(),
710                        );
711                        let measured: Size = self.layout_node(tree, item.0, probe_sp, stats);
712                        if is_row {
713                            item.1.set_height(measured.get_height());
714                        } else {
715                            item.1.set_width(measured.get_width());
716                        }
717                    }
718                }
719            }
720            let final_used_main: f32 =
721                line.iter()
722                    .fold(0.0_f32, |acc: f32, item: &(NodeId, Size, LayoutStyle)| {
723                        let sz: f32 = if is_row {
724                            item.1.get_width() + item.2.get_margin().horizontal()
725                        } else {
726                            item.1.get_height() + item.2.get_margin().vertical()
727                        };
728                        acc + sz
729                    })
730                    + gaps_total;
731            let rem: f32 = (effective_main_avail - final_used_main).max(0.0);
732            let (mut main_cursor, extra_step): (f32, f32) =
733                match parent_layout.get_justify_content() {
734                    JustifyContent::Start => (0.0, 0.0),
735                    JustifyContent::Center => (rem * 0.5, 0.0),
736                    JustifyContent::End => (rem, 0.0),
737                    JustifyContent::SpaceBetween => {
738                        if count > 1 {
739                            (0.0, rem / ((count - 1) as f32))
740                        } else {
741                            (0.0, 0.0)
742                        }
743                    }
744                    JustifyContent::SpaceAround => {
745                        let slot: f32 = rem / (count.max(1) as f32);
746                        (slot * 0.5, slot)
747                    }
748                    JustifyContent::SpaceEvenly => {
749                        let slot: f32 = rem / ((count + 1) as f32);
750                        (slot, slot)
751                    }
752                };
753            let line_cross: f32 =
754                line.iter()
755                    .fold(0.0_f32, |acc: f32, item: &(NodeId, Size, LayoutStyle)| {
756                        let c: f32 = if is_row {
757                            item.1.get_height() + item.2.get_margin().vertical()
758                        } else {
759                            item.1.get_width() + item.2.get_margin().horizontal()
760                        };
761                        acc.max(c)
762                    });
763            let definite_cross: bool = !is_row || frame.get_definite_height();
764            let effective_line_cross: f32 = if line_count == 1 && !wrap_enabled && definite_cross {
765                line_cross.max(cross_avail)
766            } else {
767                line_cross
768            };
769            let mut actual_line_cross: f32 = line_cross;
770            for (idx, (child_id, child_size, child_layout)) in line.into_iter().enumerate() {
771                let margin: Edges = child_layout.get_margin();
772                let item_cross: f32 = if is_row {
773                    child_size.get_height()
774                } else {
775                    child_size.get_width()
776                };
777                let align: AlignItems = match child_layout.get_align_self() {
778                    AlignSelf::Auto => parent_layout.get_align_items(),
779                    AlignSelf::Stretch => AlignItems::Stretch,
780                    AlignSelf::Start => AlignItems::Start,
781                    AlignSelf::Center => AlignItems::Center,
782                    AlignSelf::End => AlignItems::End,
783                };
784                let avail_item_cross: f32 = (effective_line_cross
785                    - if is_row {
786                        margin.vertical()
787                    } else {
788                        margin.horizontal()
789                    })
790                .max(0.0);
791                let cross_offset: f32 = match align {
792                    AlignItems::Start | AlignItems::Stretch => 0.0,
793                    AlignItems::Center => ((avail_item_cross - item_cross) * 0.5).max(0.0),
794                    AlignItems::End => (avail_item_cross - item_cross).max(0.0),
795                };
796                let auto_cross_grow: bool = !wrap_enabled
797                    && child_layout.get_flex_grow() > 0.0
798                    && if is_row {
799                        child_layout.get_height() == Length::Auto
800                    } else {
801                        child_layout.get_width() == Length::Auto
802                    };
803                let target_w: f32 = if !is_row
804                    && align == AlignItems::Stretch
805                    && child_layout.get_width() == Length::Auto
806                {
807                    avail_item_cross.max(child_size.get_width())
808                } else {
809                    child_size.get_width()
810                };
811                let target_h: f32 = if is_row
812                    && align == AlignItems::Stretch
813                    && child_layout.get_height() == Length::Auto
814                {
815                    avail_item_cross.max(child_size.get_height())
816                } else {
817                    child_size.get_height()
818                };
819                let (x, y): (f32, f32) = if is_row {
820                    (
821                        content_origin.get_x() + main_cursor + margin.get_left(),
822                        content_origin.get_y() + cross_cursor + cross_offset + margin.get_top(),
823                    )
824                } else {
825                    (
826                        content_origin.get_x() + cross_cursor + cross_offset + margin.get_left(),
827                        content_origin.get_y() + main_cursor + margin.get_top(),
828                    )
829                };
830                let space_w: f32 = if matches!(child_layout.get_width(), Length::Percent(_)) {
831                    inner_avail.get_width()
832                } else if auto_cross_grow && !is_row {
833                    cross_avail
834                } else {
835                    target_w
836                };
837                let space_h: f32 = if matches!(child_layout.get_height(), Length::Percent(_)) {
838                    inner_avail.get_height()
839                } else if auto_cross_grow && is_row {
840                    cross_avail
841                } else {
842                    target_h
843                };
844                let stretch_child_w: bool = !(auto_cross_grow && !is_row)
845                    && ((!is_row
846                        && align == AlignItems::Stretch
847                        && child_layout.get_width() == Length::Auto)
848                        || (is_row
849                            && child_layout.get_flex_grow() > 0.0
850                            && child_layout.get_width() == Length::Auto));
851                let stretch_child_h: bool = !(auto_cross_grow && is_row)
852                    && ((is_row
853                        && align == AlignItems::Stretch
854                        && child_layout.get_height() == Length::Auto)
855                        || (!is_row
856                            && child_layout.get_flex_grow() > 0.0
857                            && child_layout.get_height() == Length::Auto));
858                let final_space: AvailableSpace =
859                    AvailableSpace::new(space_w, space_h, viewport, x, y)
860                        .with_stretch(stretch_child_w, stretch_child_h);
861                let placed: Size = self.layout_node(tree, child_id, final_space, stats);
862                if let Some(node) = tree.get_node_mut(child_id) {
863                    let mut b: Rect = node.get_layout_box().get_bounds();
864                    let is_clipped: bool = matches!(
865                        child_layout.get_overflow(),
866                        Overflow::Hidden | Overflow::Scroll
867                    );
868                    if auto_cross_grow {
869                        if is_row {
870                            b.set_width(target_w);
871                            b.set_height(placed.get_height());
872                            actual_line_cross =
873                                actual_line_cross.max(placed.get_height() + margin.vertical());
874                        } else {
875                            b.set_width(placed.get_width());
876                            b.set_height(target_h);
877                            actual_line_cross =
878                                actual_line_cross.max(placed.get_width() + margin.horizontal());
879                        }
880                    } else if is_clipped || child_layout.get_flex_grow() > 0.0 {
881                        b.set_width(target_w);
882                        b.set_height(target_h);
883                    } else {
884                        b.set_width(target_w.max(placed.get_width()));
885                        b.set_height(target_h.max(placed.get_height()));
886                    }
887                    node.get_mut_layout_box().set_bounds(b);
888                }
889                let advance: f32 = if is_row {
890                    target_w + margin.horizontal()
891                } else {
892                    target_h + margin.vertical()
893                };
894                main_cursor += advance;
895                if idx + 1 < count {
896                    main_cursor += main_gap + extra_step;
897                }
898            }
899            max_main_extent = max_main_extent.max(final_used_main);
900            cross_cursor += actual_line_cross;
901            if line_idx + 1 < line_count {
902                cross_cursor += cross_gap;
903            }
904        }
905        if is_row {
906            Size::new(max_main_extent, cross_cursor)
907        } else {
908            Size::new(cross_cursor, max_main_extent)
909        }
910    }
911
912    /// Executes uniform-column CSS Grid layout with row and column gaps.
913    ///
914    /// # Arguments
915    ///
916    /// - `&Self` - Layout engine reference.
917    /// - `&mut SceneTree` - Mutable scene tree.
918    /// - `&[NodeId]` - Grid child handles.
919    /// - `ContainerFrame` - Grid container constraints and origin.
920    /// - `&mut LayoutStats` - Mutable telemetry counters.
921    ///
922    /// # Returns
923    ///
924    /// - `Size` - Aggregate grid content dimensions.
925    fn layout_grid(
926        &self,
927        tree: &mut SceneTree,
928        children: &[NodeId],
929        frame: ContainerFrame,
930        stats: &mut LayoutStats,
931    ) -> Size {
932        if children.is_empty() {
933            return Size::default();
934        }
935        let parent_layout: LayoutStyle = frame.get_parent_layout();
936        let inner_avail: Size = frame.get_inner_avail();
937        let viewport: Size = frame.get_viewport();
938        let content_origin: Point = frame.get_content_origin();
939        let cols: usize = (parent_layout.get_grid_columns() as usize).max(1);
940        let col_gap: f32 = parent_layout.get_column_gap();
941        let row_gap: f32 = parent_layout.get_row_gap();
942        let total_col_gaps: f32 = col_gap * ((cols.saturating_sub(1)) as f32);
943        let col_w: f32 = ((inner_avail.get_width() - total_col_gaps) / (cols as f32)).max(0.0);
944        let mut y_cursor: f32 = 0.0;
945        let mut idx: usize = 0;
946        while idx < children.len() {
947            let row_end: usize = (idx + cols).min(children.len());
948            let mut row_h: f32 = 0.0;
949            for (col_idx, child_id) in children[idx..row_end].iter().copied().enumerate() {
950                let x: f32 = content_origin.get_x() + (col_idx as f32) * (col_w + col_gap);
951                let y: f32 = content_origin.get_y() + y_cursor;
952                let auto_w: bool = tree
953                    .get_node(child_id)
954                    .map(|n: &SceneNode| n.get_style().get_layout().get_width() == Length::Auto)
955                    .unwrap_or(false);
956                let cell_space: AvailableSpace =
957                    AvailableSpace::new(col_w, inner_avail.get_height(), viewport, x, y)
958                        .with_stretch(auto_w, false);
959                let child_size: Size = self.layout_node(tree, child_id, cell_space, stats);
960                if let Some(node) = tree.get_node_mut(child_id) {
961                    let mut b: Rect = node.get_layout_box().get_bounds();
962                    b.set_width(col_w);
963                    node.get_mut_layout_box().set_bounds(b);
964                }
965                row_h = row_h.max(child_size.get_height());
966            }
967            for child_id in children[idx..row_end].iter().copied() {
968                if let Some(node) = tree.get_node_mut(child_id) {
969                    let mut b: Rect = node.get_layout_box().get_bounds();
970                    if b.get_height() < row_h {
971                        b.set_height(row_h);
972                        node.get_mut_layout_box().set_bounds(b);
973                    }
974                }
975            }
976            y_cursor += row_h;
977            if row_end < children.len() {
978                y_cursor += row_gap;
979            }
980            idx = row_end;
981        }
982        Size::new(inner_avail.get_width(), y_cursor)
983    }
984
985    /// Translates the cached layout geometry of `root_id` and all non-fixed descendants by `(dx, dy)` in O(subtree) without re-running layout or text measurement.
986    ///
987    /// # Arguments
988    ///
989    /// - `&Self` - Layout engine reference.
990    /// - `&mut SceneTree` - Mutable retained scene tree.
991    /// - `NodeId` - Root node of the clean subtree being shifted.
992    /// - `f32` - Horizontal translation delta in logical pixels.
993    /// - `f32` - Vertical translation delta in logical pixels.
994    fn translate_subtree(&self, tree: &mut SceneTree, root_id: NodeId, dx: f32, dy: f32) {
995        let mut stack: Vec<(NodeId, bool)> = vec![(root_id, true)];
996        while let Some((nid, is_root)) = stack.pop() {
997            let children_to_visit: Vec<NodeId> = {
998                let Some(node) = tree.get_node_mut(nid) else {
999                    continue;
1000                };
1001                let layout: LayoutStyle = node.get_style().get_layout();
1002                if !is_root && layout.get_position() == Position::Fixed {
1003                    continue;
1004                }
1005                if let Some(mut c) = node.cached_constraint() {
1006                    c.set_origin_x(c.get_origin_x() + dx);
1007                    c.set_origin_y(c.get_origin_y() + dy);
1008                    node.set_last_constraint(Some(c));
1009                }
1010                if layout.get_display() == Display::None {
1011                    continue;
1012                }
1013                let mut bounds: Rect = node.get_layout_box().get_bounds();
1014                bounds.set_x(bounds.get_x() + dx);
1015                bounds.set_y(bounds.get_y() + dy);
1016                node.get_mut_layout_box().set_bounds(bounds);
1017                let mut content: Rect = node.get_layout_box().get_content_bounds();
1018                content.set_x(content.get_x() + dx);
1019                content.set_y(content.get_y() + dy);
1020                node.get_mut_layout_box().set_content_bounds(content);
1021                node.get_children().clone()
1022            };
1023            for child_id in children_to_visit.into_iter() {
1024                stack.push((child_id, false));
1025            }
1026        }
1027    }
1028}