mgui-core 0.8.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! UnconstrainedBox — child 用**无限约束**布局(取自然尺寸),自身被父约束夹紧
//!
//! 与 `ConstrainedBox` 相反:不向 child 施加任何上限,child 按内容自然尺寸布局;
//! 容器自身尺寸 = `constraints.constrain(child_size)`(通常被父约束夹紧),
//! 若 child 比容器大则**溢出**(paint/hit_test 不裁剪)。

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;

/// UnconstrainedBox RenderObject
pub struct UnconstrainedBoxRenderObject {
    pub alignment: Alignment,
    child: Option<SharedRO>,
    cached_size: Size,
    child_cached_size: Size,
    child_offset: Point,
}

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

impl RenderObject for UnconstrainedBoxRenderObject {
    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
        // 1. child 用无限约束布局 → 自然尺寸
        self.child_cached_size = if let Some(child) = &mut self.child {
            child.layout_cached(BoxConstraints::UNBOUNDED, ctx)
        } else {
            Size::ZERO
        };
        // 2. 自身尺寸 = 父约束夹紧后的 child 尺寸
        self.cached_size = constraints.constrain(self.child_cached_size);
        // 3. 按 alignment 摆位 child(允许负值 → 溢出)
        let delta_w = self.cached_size.width - self.child_cached_size.width;
        let delta_h = self.cached_size.height - self.child_cached_size.height;
        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> {
        self.child.as_ref().and_then(|c| {
            c.borrow().hit_test(position, Point::new(offset.x + self.child_offset.x, offset.y + self.child_offset.y))
        })
    }

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

/// UnconstrainedBox(child 不受约束,允许溢出)
#[derive(Debug)]
pub struct UnconstrainedBoxWidget {
    pub alignment: Alignment,
    pub child: Option<WidgetNode>,
}

impl UnconstrainedBoxWidget {
    pub fn new(child: impl Widget) -> Self {
        Self { alignment: Alignment::TOP_LEFT, child: Some(WidgetNode::new(child)) }
    }

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

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

    fn is_equivalent(&self, old: &dyn Widget) -> bool {
        old.as_any().downcast_ref::<UnconstrainedBoxWidget>().is_some_and(|o| {
            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(UnconstrainedBoxRenderObject::new(self.alignment, Some(child_ro)))
    }

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