mgui-core 0.7.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! FractionallySizedBox — 按**父可用空间的比例**决定子节点尺寸

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

use super::alignment::Alignment;

/// FractionallySizedBox RenderObject
///
/// 语义(对齐 Flutter `RenderFractionallySizedOverflowBox`):
/// - `width_factor` / `height_factor` 为 `Some` 时,该轴给 child 的约束被收紧为
///   **父可用空间 × factor** 的 tight 值(父约束该轴无界时比例无意义,退回透传)
/// - 自身尺寸 = 父约束在该轴的最大值(填满父可用空间);父该轴无界时退回 child 尺寸
/// - `alignment` 决定 child 在自身盒子内的摆放位置
///
/// 与 [`super::align`] 的 `width_factor` 的区别:**此处比例相对父可用空间**,
/// 而 `AlignWidget` 的 factor 是相对 child 自身尺寸。
pub struct FractionallySizedBoxRenderObject {
    pub width_factor: Option<f32>,
    pub height_factor: Option<f32>,
    pub alignment: Alignment,
    child: Option<SharedRO>,
    cached_size: Size,
    /// child 实际布局尺寸(受 width/height_factor 收紧后的结果)
    pub child_size: Size,
    /// child 相对自身原点(左上角)的摆放偏移
    pub child_offset: Point,
}

impl FractionallySizedBoxRenderObject {
    pub fn new(
        width_factor: Option<f32>,
        height_factor: Option<f32>,
        alignment: Alignment,
        child: Option<Box<dyn RenderObject>>,
    ) -> Self {
        Self {
            width_factor,
            height_factor,
            alignment,
            child: child.map(make_ro_shared),
            cached_size: Size::ZERO,
            child_size: Size::ZERO,
            child_offset: Point::ZERO,
        }
    }

    /// 由父约束 + factor 推导传给 child 的约束
    fn child_constraints(&self, c: BoxConstraints) -> BoxConstraints {
        let (mut min_w, mut max_w) = (c.min_width, c.max_width);
        if let Some(wf) = self.width_factor {
            // 无界轴上比例无意义 → 保持透传
            if c.max_width.is_finite() {
                let w = c.max_width * wf;
                min_w = w;
                max_w = w;
            }
        }
        let (mut min_h, mut max_h) = (c.min_height, c.max_height);
        if let Some(hf) = self.height_factor {
            if c.max_height.is_finite() {
                let h = c.max_height * hf;
                min_h = h;
                max_h = h;
            }
        }
        BoxConstraints { min_width: min_w, max_width: max_w, min_height: min_h, max_height: max_h }
    }
}

impl RenderObject for FractionallySizedBoxRenderObject {
    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
        // 1. child 用「父可用空间 × factor」的 tight 约束布局
        let inner = self.child_constraints(constraints);
        self.child_size = if let Some(child) = &mut self.child { child.layout_cached(inner, ctx) } else { Size::ZERO };

        // 2. 自身尺寸 = 父该轴可用的最大值(填满可用空间);无界轴退回 child 尺寸
        let self_w = if constraints.max_width.is_finite() { constraints.max_width } else { self.child_size.width };
        let self_h = if constraints.max_height.is_finite() { constraints.max_height } else { self.child_size.height };
        self.cached_size = constraints.constrain(Size::new(self_w, self_h));

        // 3. child 按 alignment 摆在自身盒子内(尺寸差为负时保持左上角)
        let delta_w = (self.cached_size.width - self.child_size.width).max(0.0);
        let delta_h = (self.cached_size.height - self.child_size.height).max(0.0);
        self.child_offset = Point::new(self.alignment.x * delta_w, self.alignment.y * delta_h);

        self.cached_size
    }

    fn content_size(&self) -> Size {
        self.cached_size
    }

    fn paint(&self, offset: Point, painter: &mut PaintList) {
        if let Some(child) = &self.child {
            child.borrow().paint(Point::new(offset.x + self.child_offset.x, offset.y + self.child_offset.y), painter);
        }
    }

    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
        if let Some(child) = &self.child {
            child
                .borrow()
                .hit_test(position, Point::new(offset.x + self.child_offset.x, offset.y + self.child_offset.y))
        } else {
            None
        }
    }

    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
        if let Some(child) = &mut self.child {
            if let Some(&cid) = 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![(self.child_offset, c.clone())]).unwrap_or_default()
    }

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

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

/// FractionallySizedBox(按父可用空间比例定尺寸)
///
/// ```ignore
/// // 在父容器内占 50% × 50% 的居中内容
/// FractionallySizedBoxWidget::new(content)
///      .width_factor(0.5)
///      .height_factor(0.5)
///      .align(Alignment::CENTER)
/// ```
#[derive(Debug)]
pub struct FractionallySizedBoxWidget {
    pub width_factor: Option<f32>,
    pub height_factor: Option<f32>,
    pub alignment: Alignment,
    pub child: Option<WidgetNode>,
}

impl FractionallySizedBoxWidget {
    pub fn new(child: impl Widget) -> Self {
        Self {
            width_factor: None,
            height_factor: None,
            alignment: Alignment::CENTER,
            child: Some(WidgetNode::new(child)),
        }
    }

    /// 宽度占父可用空间比例(1.0 = 铺满)
    pub fn width_factor(mut self, f: f32) -> Self {
        self.width_factor = Some(f);
        self
    }

    /// 高度占父可用空间比例(1.0 = 铺满)
    pub fn height_factor(mut self, f: f32) -> Self {
        self.height_factor = Some(f);
        self
    }

    /// 两轴使用同一比例
    pub fn fraction(mut self, f: f32) -> Self {
        self.width_factor = Some(f);
        self.height_factor = Some(f);
        self
    }

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

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

    fn is_equivalent(&self, old: &dyn Widget) -> bool {
        old.as_any().downcast_ref::<FractionallySizedBoxWidget>().is_some_and(|o| {
            self.width_factor == o.width_factor
                && self.height_factor == o.height_factor
                && self.alignment == o.alignment
                && crate::widget::optional_child_equivalent(&self.child, &o.child)
        })
    }

    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(FractionallySizedBoxRenderObject::new(
            self.width_factor,
            self.height_factor,
            self.alignment,
            Some(child_ro),
        ))
    }

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