Skip to main content

mgui_core/layout/
fitted_box.rs

1//! FittedBox — 子节点按自然尺寸布局后**整体缩放**以适配容器(不重排)
2
3use crate::id::ElementId;
4use crate::paint::{LayerEffect, PaintList};
5use crate::render_object::{
6    inverse_apply_transform, make_ro_shared, BoxConstraints, LayoutContext, RRectRenderObject, RenderObject, SharedRO,
7};
8use crate::widget::{Widget, WidgetNode};
9use crate::{BoxFit, Color, Point, Size, Transform2D};
10
11use super::alignment::Alignment;
12
13/// FittedBox RenderObject
14///
15/// 语义(对齐 Flutter `RenderFittedBox`):
16/// - child 用**无限约束**布局 → 得到自然尺寸(不被父容器重排,这是与 SizedBox 的关键差异:
17///   SizedBox 把容器尺寸压给 child,child 自己重新布局;FittedBox 保持 child 原有布局,
18///   只把**绘制结果**整体缩放)
19/// - 容器尺寸 = `constraints.constrain(child 自然尺寸)`;父给 tight 约束时 = 父给的盒子
20/// - 按 `fit` 算缩放系数:`Contain` 等比放进盒子 / `Fill` 两轴独立铺满(可变形)
21/// - `alignment` 决定缩放后内容在盒子内的摆放位置
22///
23/// 实现要点:缩放复用框架 layer 机制 —— 本 RO 是 **layer 边界**
24/// (widget 侧 `is_repaint_boundary() = true`),`content_size()` 返回 child 自然尺寸
25/// (layer 纹理必须装下**未缩放**的 child),`layer_effect()` 返回「绕 layer 中心
26/// 缩放 + 平移」的 `Transform2D`,由 renderer 的 blit 阶段在 GPU 完成缩放。
27/// 因此不需要在 paint 阶段改写几何命令,core ↔ runtime 边界保持干净。
28pub struct FittedBoxRenderObject {
29    pub fit: BoxFit,
30    pub alignment: Alignment,
31    child: Option<SharedRO>,
32    /// 容器尺寸(父容器看到的布局尺寸)
33    cached_size: Size,
34    /// child 自然尺寸(层纹理尺寸 / content_size)
35    child_size: Size,
36    /// 缩放 + 摆位平移(layer blit 用)
37    pub transform: Transform2D,
38}
39
40impl FittedBoxRenderObject {
41    pub fn new(fit: BoxFit, alignment: Alignment, child: Option<Box<dyn RenderObject>>) -> Self {
42        Self {
43            fit,
44            alignment,
45            child: child.map(make_ro_shared),
46            cached_size: Size::ZERO,
47            child_size: Size::ZERO,
48            transform: Transform2D::IDENTITY,
49        }
50    }
51}
52
53impl RenderObject for FittedBoxRenderObject {
54    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
55        // 1. child 按自然尺寸布局(无限约束 → 不受父容器影响)
56        self.child_size = if let Some(child) = &mut self.child {
57            child.layout_cached(
58                BoxConstraints { min_width: 0.0, max_width: f32::INFINITY, min_height: 0.0, max_height: f32::INFINITY },
59                ctx,
60            )
61        } else {
62            Size::ZERO
63        };
64
65        // 2. 容器尺寸 = 父约束夹紧后的尺寸(父给 tight 时即父给的盒子)
66        //
67        // bugfix(层根重排塌缩 transform):`paint_layer_recursive` 会把每个 layer
68        // root RO 用 **UNBOUNDED** 约束再 layout 一次(用于算层纹理尺寸 / 子层偏移)。
69        // 此时 `constrain(child_size)` 恒等于 child 自然尺寸 → 缩放系数被错误算成
70        // 1.0,把此前按父容器尺寸算出的 transform 覆盖成恒等(层 blit 不再缩放)。
71        // 因此只在父给**有界**约束时更新容器尺寸;无界(层根重排)时沿用上一次
72        // 已知容器尺寸,保证 transform 不被破坏。
73        let bounded = constraints.max_width.is_finite() || constraints.max_height.is_finite();
74        if bounded {
75            self.cached_size = constraints.constrain(self.child_size);
76        } else if self.cached_size.width <= 0.0 || self.cached_size.height <= 0.0 {
77            // 从未拿到过容器尺寸(如 FittedBox 直接作为 root)→ 退化:盒子 = child 自然尺寸
78            self.cached_size = self.child_size;
79        }
80
81        // 3. 缩放系数
82        let cw = self.child_size.width;
83        let ch = self.child_size.height;
84        let bw = self.cached_size.width;
85        let bh = self.cached_size.height;
86        let (sx, sy) = if cw > 0.0 && ch > 0.0 && bw > 0.0 && bh > 0.0 {
87            match self.fit {
88                BoxFit::Fill => (bw / cw, bh / ch),
89                BoxFit::Contain => {
90                    let s = (bw / cw).min(bh / ch);
91                    (s, s)
92                }
93            }
94        } else {
95            (1.0, 1.0)
96        };
97
98        // 4. 平移量:缩放后的内容左上角需落在盒子内 q = (bw - cw·sx)·align
99        //    blit 公式(绕层中心 c):forward(p) = c + S·(p − c) + t
100        //    令 p = (0, 0)(child 左上角,层内坐标)映射到 q:
101        //    t = q − c + S·c  ⇒  t.x = q.x + (sx − 1)·cw/2
102        let qx = (bw - cw * sx) * self.alignment.x;
103        let qy = (bh - ch * sy) * self.alignment.y;
104        self.transform = Transform2D {
105            rotation: 0.0,
106            scale_x: sx,
107            scale_y: sy,
108            translate: Point::new(qx + (sx - 1.0) * cw * 0.5, qy + (sy - 1.0) * ch * 0.5),
109        };
110
111        self.cached_size
112    }
113
114    fn paint(&self, _offset: Point, _painter: &mut PaintList) {
115        // layer 边界 — paint noop,内容由本层纹理经 blit 缩放后画
116    }
117
118    fn paint_as_layer_root(&self, offset: Point, painter: &mut PaintList) {
119        // 本层内容 = child 未缩放的绘制命令(child 在层内的原点即层原点)
120        if let Some(c) = &self.child {
121            c.borrow().paint(offset, painter);
122        }
123    }
124
125    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
126        // 反向变换:把世界坐标缩回 child 的未缩放坐标后再判命中
127        let child = self.child.as_ref()?;
128        let s = self.child_size;
129        if s.width <= 0.0 || s.height <= 0.0 {
130            return child.borrow().hit_test(position, offset);
131        }
132        let cx = offset.x + s.width * 0.5;
133        let cy = offset.y + s.height * 0.5;
134        let local = inverse_apply_transform(position, self.transform, cx, cy);
135        child.borrow().hit_test(local, offset)
136    }
137
138    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
139        if let (Some(child), Some(&cid)) = (self.child.as_mut(), child_ids.first()) {
140            if let Some(new_ro) = stateful_ros.first_mut() {
141                *child = new_ro.clone();
142            }
143            child.borrow_mut().set_element_id(cid);
144        }
145    }
146
147    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
148        self.child.as_ref().map(|c| vec![(Point::ZERO, c.clone())]).unwrap_or_default()
149    }
150
151    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
152        if let Some(c) = &self.child {
153            f(Point::ZERO, c);
154        }
155    }
156
157    fn children_count(&self) -> usize {
158        if self.child.is_some() {
159            1
160        } else {
161            0
162        }
163    }
164
165    /// 层纹理尺寸 = child 自然尺寸(必须装下未缩放的 child,缩放交给 blit)
166    fn content_size(&self) -> Size {
167        self.child_size
168    }
169
170    fn layer_layout_size(&self) -> Option<Size> {
171        Some(self.cached_size)
172    }
173
174    fn layer_relayout_constraints(&self, layout_size: Size) -> BoxConstraints {
175        // loose 会让 Fill 的高度收缩到 child 自然高度(scale_y→1),必须按已知盒子重排
176        BoxConstraints::tight(layout_size)
177    }
178
179    fn layer_effect(&self) -> LayerEffect {
180        LayerEffect::Transform(self.transform)
181    }
182}
183
184/// FittedBox(按 fit 缩放子节点)
185///
186/// ```ignore
187/// // 把固定尺寸的内容等比缩进 120×80 的盒子
188/// SizedBox::sized(120.0, 80.0,
189///     FittedBoxWidget::contain(my_fixed_size_content))
190/// ```
191#[derive(Debug)]
192pub struct FittedBoxWidget {
193    pub fit: BoxFit,
194    pub alignment: Alignment,
195    pub child: Option<WidgetNode>,
196}
197
198impl FittedBoxWidget {
199    pub fn new(child: impl Widget, fit: BoxFit) -> Self {
200        Self { fit, alignment: Alignment::CENTER, child: Some(WidgetNode::new(child)) }
201    }
202
203    /// 等比放进容器(默认,letterbox)
204    pub fn contain(child: impl Widget) -> Self {
205        Self::new(child, BoxFit::Contain)
206    }
207
208    /// 两轴独立拉伸铺满容器(可能变形)
209    pub fn fill(child: impl Widget) -> Self {
210        Self::new(child, BoxFit::Fill)
211    }
212
213    pub fn align(mut self, alignment: Alignment) -> Self {
214        self.alignment = alignment;
215        self
216    }
217}
218
219impl Widget for FittedBoxWidget {
220    fn as_any(&self) -> &dyn std::any::Any {
221        self
222    }
223
224    /// 缩放依赖独立 layer:child 画进本层纹理,再由 blit 阶段缩放
225    fn is_repaint_boundary(&self) -> bool {
226        true
227    }
228
229    fn create_render_object(&self) -> Box<dyn RenderObject> {
230        let child_ro = match &self.child {
231            Some(c) => c.0.create_render_object(),
232            None => Box::new(RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
233        };
234        Box::new(FittedBoxRenderObject::new(self.fit, self.alignment, Some(child_ro)))
235    }
236
237    fn children(&self) -> Vec<WidgetNode> {
238        match &self.child {
239            Some(c) => vec![c.clone()],
240            None => vec![],
241        }
242    }
243}