mgui-core 0.5.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! FittedBox — 子节点按自然尺寸布局后**整体缩放**以适配容器(不重排)

use crate::id::ElementId;
use crate::paint::{LayerEffect, PaintList};
use crate::render_object::{
    inverse_apply_transform, make_ro_shared, BoxConstraints, LayoutContext, RRectRenderObject, RenderObject, SharedRO,
};
use crate::widget::{Widget, WidgetNode};
use crate::{BoxFit, Color, Point, Size, Transform2D};

use super::alignment::Alignment;

/// FittedBox RenderObject
///
/// 语义(对齐 Flutter `RenderFittedBox`):
/// - child 用**无限约束**布局 → 得到自然尺寸(不被父容器重排,这是与 SizedBox 的关键差异:
///   SizedBox 把容器尺寸压给 child,child 自己重新布局;FittedBox 保持 child 原有布局,
///   只把**绘制结果**整体缩放)
/// - 容器尺寸 = `constraints.constrain(child 自然尺寸)`;父给 tight 约束时 = 父给的盒子
/// - 按 `fit` 算缩放系数:`Contain` 等比放进盒子 / `Fill` 两轴独立铺满(可变形)
/// - `alignment` 决定缩放后内容在盒子内的摆放位置
///
/// 实现要点:缩放复用框架 layer 机制 —— 本 RO 是 **layer 边界**
/// (widget 侧 `is_repaint_boundary() = true`),`content_size()` 返回 child 自然尺寸
/// (layer 纹理必须装下**未缩放**的 child),`layer_effect()` 返回「绕 layer 中心
/// 缩放 + 平移」的 `Transform2D`,由 renderer 的 blit 阶段在 GPU 完成缩放。
/// 因此不需要在 paint 阶段改写几何命令,core ↔ runtime 边界保持干净。
pub struct FittedBoxRenderObject {
    pub fit: BoxFit,
    pub alignment: Alignment,
    child: Option<SharedRO>,
    /// 容器尺寸(父容器看到的布局尺寸)
    cached_size: Size,
    /// child 自然尺寸(层纹理尺寸 / content_size)
    child_size: Size,
    /// 缩放 + 摆位平移(layer blit 用)
    pub transform: Transform2D,
}

impl FittedBoxRenderObject {
    pub fn new(fit: BoxFit, alignment: Alignment, child: Option<Box<dyn RenderObject>>) -> Self {
        Self {
            fit,
            alignment,
            child: child.map(make_ro_shared),
            cached_size: Size::ZERO,
            child_size: Size::ZERO,
            transform: Transform2D::IDENTITY,
        }
    }
}

impl RenderObject for FittedBoxRenderObject {
    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
        // 1. child 按自然尺寸布局(无限约束 → 不受父容器影响)
        self.child_size = if let Some(child) = &mut self.child {
            child.layout_cached(
                BoxConstraints { min_width: 0.0, max_width: f32::INFINITY, min_height: 0.0, max_height: f32::INFINITY },
                ctx,
            )
        } else {
            Size::ZERO
        };

        // 2. 容器尺寸 = 父约束夹紧后的尺寸(父给 tight 时即父给的盒子)
        //
        // bugfix(层根重排塌缩 transform):`paint_layer_recursive` 会把每个 layer
        // root RO 用 **UNBOUNDED** 约束再 layout 一次(用于算层纹理尺寸 / 子层偏移)。
        // 此时 `constrain(child_size)` 恒等于 child 自然尺寸 → 缩放系数被错误算成
        // 1.0,把此前按父容器尺寸算出的 transform 覆盖成恒等(层 blit 不再缩放)。
        // 因此只在父给**有界**约束时更新容器尺寸;无界(层根重排)时沿用上一次
        // 已知容器尺寸,保证 transform 不被破坏。
        let bounded = constraints.max_width.is_finite() || constraints.max_height.is_finite();
        if bounded {
            self.cached_size = constraints.constrain(self.child_size);
        } else if self.cached_size.width <= 0.0 || self.cached_size.height <= 0.0 {
            // 从未拿到过容器尺寸(如 FittedBox 直接作为 root)→ 退化:盒子 = child 自然尺寸
            self.cached_size = self.child_size;
        }

        // 3. 缩放系数
        let cw = self.child_size.width;
        let ch = self.child_size.height;
        let bw = self.cached_size.width;
        let bh = self.cached_size.height;
        let (sx, sy) = if cw > 0.0 && ch > 0.0 && bw > 0.0 && bh > 0.0 {
            match self.fit {
                BoxFit::Fill => (bw / cw, bh / ch),
                BoxFit::Contain => {
                    let s = (bw / cw).min(bh / ch);
                    (s, s)
                }
            }
        } else {
            (1.0, 1.0)
        };

        // 4. 平移量:缩放后的内容左上角需落在盒子内 q = (bw - cw·sx)·align
        //    blit 公式(绕层中心 c):forward(p) = c + S·(p − c) + t
        //    令 p = (0, 0)(child 左上角,层内坐标)映射到 q:
        //    t = q − c + S·c  ⇒  t.x = q.x + (sx − 1)·cw/2
        let qx = (bw - cw * sx) * self.alignment.x;
        let qy = (bh - ch * sy) * self.alignment.y;
        self.transform = Transform2D {
            rotation: 0.0,
            scale_x: sx,
            scale_y: sy,
            translate: Point::new(qx + (sx - 1.0) * cw * 0.5, qy + (sy - 1.0) * ch * 0.5),
        };

        self.cached_size
    }

    fn paint(&self, _offset: Point, _painter: &mut PaintList) {
        // layer 边界 — paint noop,内容由本层纹理经 blit 缩放后画
    }

    fn paint_as_layer_root(&self, offset: Point, painter: &mut PaintList) {
        // 本层内容 = child 未缩放的绘制命令(child 在层内的原点即层原点)
        if let Some(c) = &self.child {
            c.borrow().paint(offset, painter);
        }
    }

    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
        // 反向变换:把世界坐标缩回 child 的未缩放坐标后再判命中
        let child = self.child.as_ref()?;
        let s = self.child_size;
        if s.width <= 0.0 || s.height <= 0.0 {
            return child.borrow().hit_test(position, offset);
        }
        let cx = offset.x + s.width * 0.5;
        let cy = offset.y + s.height * 0.5;
        let local = inverse_apply_transform(position, self.transform, cx, cy);
        child.borrow().hit_test(local, offset)
    }

    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
        if let (Some(child), Some(&cid)) = (self.child.as_mut(), child_ids.first()) {
            if let Some(new_ro) = stateful_ros.first_mut() {
                *child = new_ro.clone();
            }
            child.borrow_mut().set_element_id(cid);
        }
    }

    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
        self.child.as_ref().map(|c| vec![(Point::ZERO, c.clone())]).unwrap_or_default()
    }

    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
        if let Some(c) = &self.child {
            f(Point::ZERO, c);
        }
    }

    fn children_count(&self) -> usize {
        if self.child.is_some() {
            1
        } else {
            0
        }
    }

    /// 层纹理尺寸 = child 自然尺寸(必须装下未缩放的 child,缩放交给 blit)
    fn content_size(&self) -> Size {
        self.child_size
    }

    fn layer_layout_size(&self) -> Option<Size> {
        Some(self.cached_size)
    }

    fn layer_relayout_constraints(&self, layout_size: Size) -> BoxConstraints {
        // loose 会让 Fill 的高度收缩到 child 自然高度(scale_y→1),必须按已知盒子重排
        BoxConstraints::tight(layout_size)
    }

    fn layer_effect(&self) -> LayerEffect {
        LayerEffect::Transform(self.transform)
    }
}

/// FittedBox(按 fit 缩放子节点)
///
/// ```ignore
/// // 把固定尺寸的内容等比缩进 120×80 的盒子
/// SizedBox::sized(120.0, 80.0,
///     FittedBoxWidget::contain(my_fixed_size_content))
/// ```
#[derive(Debug)]
pub struct FittedBoxWidget {
    pub fit: BoxFit,
    pub alignment: Alignment,
    pub child: Option<WidgetNode>,
}

impl FittedBoxWidget {
    pub fn new(child: impl Widget, fit: BoxFit) -> Self {
        Self { fit, alignment: Alignment::CENTER, child: Some(WidgetNode::new(child)) }
    }

    /// 等比放进容器(默认,letterbox)
    pub fn contain(child: impl Widget) -> Self {
        Self::new(child, BoxFit::Contain)
    }

    /// 两轴独立拉伸铺满容器(可能变形)
    pub fn fill(child: impl Widget) -> Self {
        Self::new(child, BoxFit::Fill)
    }

    pub fn align(mut self, alignment: Alignment) -> Self {
        self.alignment = alignment;
        self
    }
}

impl Widget for FittedBoxWidget {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    /// 缩放依赖独立 layer:child 画进本层纹理,再由 blit 阶段缩放
    fn is_repaint_boundary(&self) -> bool {
        true
    }

    fn create_render_object(&self) -> Box<dyn RenderObject> {
        let child_ro = match &self.child {
            Some(c) => c.0.create_render_object(),
            None => Box::new(RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
        };
        Box::new(FittedBoxRenderObject::new(self.fit, self.alignment, Some(child_ro)))
    }

    fn children(&self) -> Vec<WidgetNode> {
        match &self.child {
            Some(c) => vec![c.clone()],
            None => vec![],
        }
    }
}