mgui-core 0.2.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
use super::*;

/// 阶段 5:Opacity 容器 RO(整体 alpha 乘)
pub struct OpacityRenderObject {
    pub child: Option<SharedRO>,
    pub element_id: Option<ElementId>,
    pub size: Size,
    /// 整体 alpha 乘(0.0 完全透明,1.0 不透明)
    pub opacity: f32,
}

impl OpacityRenderObject {
    pub fn new(child: Box<dyn RenderObject>, opacity: f32) -> Self {
        Self {
            child: Some(make_ro_shared(child)),
            element_id: None,
            size: Size::ZERO,
            opacity: opacity.clamp(0.0, 1.0),
        }
    }
    pub fn empty(opacity: f32) -> Self {
        Self { child: None, element_id: None, size: Size::ZERO, opacity: opacity.clamp(0.0, 1.0) }
    }
}

impl RenderObject for OpacityRenderObject {
    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
        self.size = self.child.as_mut().map(|c| c.layout_cached(constraints, ctx)).unwrap_or(Size::ZERO);
        self.size
    }
    fn paint(&self, _offset: Point, _painter: &mut PaintList) {
        // layer 边界,paint noop
    }
    fn paint_as_layer_root(&self, offset: Point, painter: &mut PaintList) {
        // 本层内容 = child 的绘制命令(见 trait 文档:非 boundary child 无自己的
        // layer,必须画进本层,否则 cmds=0 整层不可见)
        if let Some(c) = &self.child {
            c.borrow().paint(offset, painter);
        }
    }
    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
        // 阶段 5:opacity=0 完全透明 → 没有命中;否则透传到 child
        if self.opacity <= 0.0 {
            return None;
        }
        self.child.as_ref()?.borrow().hit_test(position, offset)
    }
    fn set_element_id(&mut self, _id: ElementId) {
        // noop
    }
    /// 阶段 2-E:element_origin 遍历用 — 透传 child
    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 propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
        if let (Some(child_ro), Some(&cid)) = (self.child.as_mut(), child_ids.first()) {
            if let Some(new_ro) = stateful_ros.first_mut() {
                *child_ro = new_ro.clone();
            }
            child_ro.borrow_mut().set_element_id(cid);
        }
    }
    fn content_size(&self) -> Size {
        self.size
    }
    fn layer_layout_size(&self) -> Option<Size> {
        Some(self.size)
    }
    fn push_child(&mut self, _offset: Point, _child: SharedRO) {
        // noop
    }
    fn children_count(&self) -> usize {
        if self.child.is_some() {
            1
        } else {
            0
        }
    }
    fn layer_effect(&self) -> crate::paint::LayerEffect {
        crate::paint::LayerEffect::Opacity(self.opacity)
    }
}