mgui-core 0.2.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! DecoratedBox / BoxDecoration — 背景色 + 圆角 + 边框 + 阴影
//!
//! `BoxDecoration` 是装饰描述数据;`DecoratedBoxRenderObject` 按层叠顺序绘制:
//! 阴影(GPU SDF blur)→ 背景色 → 边框环 → child。
//! 无 stroke 绘制原语,边框用「外圈实心 + 内圈填背景色」模拟描边(与 Button ghost / BorderRO 同原理)。

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

/// 盒子阴影规格(复用 `PaintList::box_shadow` 的 GPU SDF blur 通道)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BoxShadowSpec {
    pub offset: Point,
    pub blur_radius: f32,
    pub spread: f32,
    pub color: Color,
}

impl BoxShadowSpec {
    pub fn new(offset: Point, blur_radius: f32, color: Color) -> Self {
        Self { offset, blur_radius, spread: 0.0, color }
    }

    pub fn spread(mut self, spread: f32) -> Self {
        self.spread = spread;
        self
    }
}

/// 装饰描述(颜色 / 圆角 / 边框 / 阴影)
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct BoxDecoration {
    pub color: Option<Color>,
    pub radius: f32,
    pub border: Option<Border>,
    pub shadow: Option<BoxShadowSpec>,
}

impl BoxDecoration {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    pub fn radius(mut self, radius: f32) -> Self {
        self.radius = radius;
        self
    }

    pub fn border(mut self, border: Border) -> Self {
        self.border = Some(border);
        self
    }

    pub fn shadow(mut self, shadow: BoxShadowSpec) -> Self {
        self.shadow = Some(shadow);
        self
    }
}

/// DecoratedBox RenderObject
pub struct DecoratedBoxRenderObject {
    pub decoration: BoxDecoration,
    child: Option<SharedRO>,
    cached_size: Size,
    child_cached_size: Size,
}

impl DecoratedBoxRenderObject {
    pub fn new(decoration: BoxDecoration, child: Option<Box<dyn RenderObject>>) -> Self {
        Self { decoration, child: child.map(make_ro_shared), cached_size: Size::ZERO, child_cached_size: Size::ZERO }
    }
}

impl RenderObject for DecoratedBoxRenderObject {
    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
        // 透传约束(装饰不改变 child 布局),自身尺寸 = child 尺寸
        self.child_cached_size =
            if let Some(child) = &mut self.child { child.layout_cached(constraints, ctx) } else { Size::ZERO };
        self.cached_size = constraints.constrain(self.child_cached_size);
        self.cached_size
    }

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

    fn paint(&self, offset: Point, painter: &mut PaintList) {
        let rect = Rect::new(offset.x, offset.y, self.cached_size.width, self.cached_size.height);
        let radius = self.decoration.radius;

        // 1. 阴影(最底层)
        if let Some(sh) = self.decoration.shadow {
            painter.box_shadow(rect, sh.offset, sh.blur_radius, sh.spread, sh.color, radius);
        }
        // 2. 背景色
        if let Some(color) = self.decoration.color {
            painter.rounded_rect(rect, color, radius);
        }
        // 3. 边框环(外圈实心 + 内圈填背景色)
        if let Some(border) = self.decoration.border {
            let inner_bg = self.decoration.color.unwrap_or(Color::TRANSPARENT);
            border.paint_ring(rect, inner_bg, painter);
        }
        // 4. child
        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
        }
    }
}

/// DecoratedBox(给 child 加背景装饰)
#[derive(Debug)]
pub struct DecoratedBoxWidget {
    pub decoration: BoxDecoration,
    pub child: Option<WidgetNode>,
}

impl DecoratedBoxWidget {
    pub fn new(decoration: BoxDecoration, child: impl Widget) -> Self {
        Self { decoration, child: Some(WidgetNode::new(child)) }
    }
}

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

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

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