mgui-core 0.6.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! SizedBox — 固定尺寸或宽/高单边强制的单 child 容器

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};

/// SizedBox RenderObject
///
/// 语义:
/// - `width=None, height=None` → child 透传约束(等价于 Padding 0)
/// - `width=Some(w)` → 强制 child width=w(用 tight 约束);height 取 child height
/// - `height=Some(h)` → 强制 child height=h;height 取 child height;width 取 child width
/// - 两者都 Some → tight(w, h)
pub struct SizedBoxRenderObject {
    pub width: Option<f32>,
    pub height: Option<f32>,
    child: Option<SharedRO>,
    cached_size: Size,
    child_cached_size: Size,
}

impl SizedBoxRenderObject {
    pub fn new(width: Option<f32>, height: Option<f32>, child: Option<Box<dyn RenderObject>>) -> Self {
        Self { width, height, child: child.map(make_ro_shared), cached_size: Size::ZERO, child_cached_size: Size::ZERO }
    }
}

impl RenderObject for SizedBoxRenderObject {
    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
        // 构造传给 child 的约束
        let child_constraints = match (self.width, self.height) {
            (Some(w), Some(h)) => BoxConstraints::tight(Size::new(w, h)),
            (Some(w), None) => BoxConstraints {
                min_width: w,
                max_width: w,
                min_height: constraints.min_height,
                max_height: constraints.max_height,
            },
            (None, Some(h)) => BoxConstraints {
                min_width: constraints.min_width,
                max_width: constraints.max_width,
                min_height: h,
                max_height: h,
            },
            (None, None) => constraints,
        };

        self.child_cached_size =
            if let Some(child) = &mut self.child { child.layout_cached(child_constraints, ctx) } else { Size::ZERO };

        let w = self.width.unwrap_or(self.child_cached_size.width);
        let h = self.height.unwrap_or(self.child_cached_size.height);
        self.cached_size = Size::new(w, h);
        constraints.constrain(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(offset, painter);
        }
    }

    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
        if let Some(child) = &self.child {
            child.borrow().hit_test(position, offset)
        } 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![(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
        }
    }
}

/// SizedBox(固定尺寸或宽/高单边强制)
#[derive(Debug)]
pub struct SizedBoxWidget {
    pub width: Option<f32>,
    pub height: Option<f32>,
    pub child: Option<WidgetNode>,
}

impl SizedBoxWidget {
    pub fn new(width: Option<f32>, height: Option<f32>, child: impl Widget) -> Self {
        Self { width, height, child: Some(WidgetNode::new(child)) }
    }

    pub fn sized(width: f32, height: f32, child: impl Widget) -> Self {
        Self::new(Some(width), Some(height), child)
    }

    pub fn width(w: f32, child: impl Widget) -> Self {
        Self::new(Some(w), None, child)
    }

    pub fn height(h: f32, child: impl Widget) -> Self {
        Self::new(None, Some(h), child)
    }

    /// 让 child 填满父约束(passthrough,等价于 Flutter 的 SizedBox.expand)
    pub fn expand(child: impl Widget) -> Self {
        Self::new(None, None, child)
    }
}

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

    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(SizedBoxRenderObject::new(self.width, self.height, Some(child_ro)))
    }

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

    fn is_equivalent(&self, old: &dyn Widget) -> bool {
        let Some(o) = old.as_any().downcast_ref::<SizedBoxWidget>() else {
            return false;
        };
        self.width == o.width
            && self.height == o.height
            && crate::widget::optional_child_equivalent(&self.child, &o.child)
    }
}