mgui-core 0.5.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! ConstrainedBox — 附加约束(与父约束相交)的单 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};

/// ConstrainedBox RenderObject — 附加约束(与父约束相交)
pub struct ConstrainedBoxRenderObject {
    pub min_width: f32,
    pub max_width: f32,
    pub min_height: f32,
    pub max_height: f32,
    child: Option<SharedRO>,
    cached_size: Size,
    child_cached_size: Size,
}

impl ConstrainedBoxRenderObject {
    pub fn new(
        min_width: f32,
        max_width: f32,
        min_height: f32,
        max_height: f32,
        child: Option<Box<dyn RenderObject>>,
    ) -> Self {
        Self {
            min_width,
            max_width,
            min_height,
            max_height,
            child: child.map(make_ro_shared),
            cached_size: Size::ZERO,
            child_cached_size: Size::ZERO,
        }
    }

    /// 计算附加约束与父约束的相交,并夹紧 min ≤ max 避免产生无效约束
    fn intersect(&self, parent: BoxConstraints) -> BoxConstraints {
        let mut result = BoxConstraints {
            min_width: parent.min_width.max(self.min_width),
            max_width: parent.max_width.min(self.max_width),
            min_height: parent.min_height.max(self.min_height),
            max_height: parent.max_height.min(self.max_height),
        };
        // 夹紧:相交后可能出现 min > max(父 min 比 self max 还大),非法
        result.min_width = result.min_width.min(result.max_width);
        result.min_height = result.min_height.min(result.max_height);
        result
    }
}

impl RenderObject for ConstrainedBoxRenderObject {
    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
        let child_constraints = self.intersect(constraints);
        self.child_cached_size =
            if let Some(child) = &mut self.child { child.layout_cached(child_constraints, ctx) } else { Size::ZERO };
        self.cached_size = self.child_cached_size;
        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> {
        self.child.as_ref().and_then(|c| c.borrow().hit_test(position, offset))
    }

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

/// ConstrainedBox(附加约束,与父约束相交)
///
/// 例: `ConstrainedBox::new().min_w(200.0).max_w(400.0).child(button)`
///   → button width 永远在 200..400 之间
#[derive(Debug)]
pub struct ConstrainedBoxWidget {
    pub min_width: f32,
    pub max_width: f32,
    pub min_height: f32,
    pub max_height: f32,
    pub child: Option<WidgetNode>,
}

impl ConstrainedBoxWidget {
    /// 最大 — 不附加任何约束,只限制上限
    pub fn big(child: impl Widget) -> Self {
        Self {
            min_width: 0.0,
            max_width: f32::INFINITY,
            min_height: 0.0,
            max_height: f32::INFINITY,
            child: Some(WidgetNode::new(child)),
        }
    }

    pub fn min_w(mut self, w: f32) -> Self {
        self.min_width = w;
        self
    }
    pub fn max_w(mut self, w: f32) -> Self {
        self.max_width = w;
        self
    }
    pub fn min_h(mut self, h: f32) -> Self {
        self.min_height = h;
        self
    }
    pub fn max_h(mut self, h: f32) -> Self {
        self.max_height = h;
        self
    }

    pub fn min(mut self, size: Size) -> Self {
        self.min_width = size.width;
        self.min_height = size.height;
        self
    }
    pub fn max(mut self, size: Size) -> Self {
        self.max_width = size.width;
        self.max_height = size.height;
        self
    }
}

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

    fn is_equivalent(&self, old: &dyn Widget) -> bool {
        old.as_any().downcast_ref::<ConstrainedBoxWidget>().is_some_and(|o| {
            self.min_width == o.min_width
                && self.max_width == o.max_width
                && self.min_height == o.min_height
                && self.max_height == o.max_height
                && 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(ConstrainedBoxRenderObject::new(
            self.min_width,
            self.max_width,
            self.min_height,
            self.max_height,
            Some(child_ro),
        ))
    }

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