mgui-core 0.5.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
use crate::render_object::{RRectRenderObject, RenderObject, StackRenderObject};
use crate::{Color, Point, Size};

use super::{Widget, WidgetNode};

// =================================================================
// 叶子 Widget
// =================================================================

/// 圆角矩形
#[derive(Debug, Clone)]
pub struct RRectWidget {
    pub size: Size,
    pub color: Color,
    pub radius: f32,
}

impl RRectWidget {
    pub fn new(size: Size, color: Color, radius: f32) -> Self {
        Self { size, color, radius }
    }
}

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

    fn create_render_object(&self) -> Box<dyn RenderObject> {
        Box::new(RRectRenderObject::new(self.size, self.color, self.radius))
    }

    fn is_equivalent(&self, old: &dyn Widget) -> bool {
        old.as_any()
            .downcast_ref::<RRectWidget>()
            .is_some_and(|o| self.size == o.size && self.color == o.color && self.radius == o.radius)
    }
}

// =================================================================
// 容器 Widget
// =================================================================

/// Stack(多子节点按各自 offset 叠加)
#[derive(Debug, Default)]
pub struct StackWidget {
    pub children: Vec<(Point, WidgetNode)>,
}

impl StackWidget {
    pub fn new() -> Self {
        Self { children: Vec::new() }
    }

    pub fn push(mut self, offset: Point, child: impl Widget) -> Self {
        self.children.push((offset, WidgetNode::new(child)));
        self
    }
}

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

    fn create_render_object(&self) -> Box<dyn RenderObject> {
        let mut stack = StackRenderObject::new();
        for (offset, child) in &self.children {
            stack = stack.push(*offset, child.0.create_render_object());
        }
        Box::new(stack)
    }
    fn children(&self) -> Vec<WidgetNode> {
        self.children.iter().map(|(_, n)| n.clone()).collect()
    }

    /// 阶段 4-D:Stack 知道每个 child 在父内的 position
    /// (WidgetNode 的 RO paint 时通过 StackRenderObject 的 push 传 offset)
    fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
        self.children.clone()
    }

    fn is_equivalent(&self, old: &dyn Widget) -> bool {
        let Some(o) = old.as_any().downcast_ref::<StackWidget>() else {
            return false;
        };
        self.children.len() == o.children.len()
            && self.children.iter().zip(&o.children).all(|((pa, wa), (pb, wb))| pa == pb && wa.is_equivalent(wb))
    }

    fn semantics(&self) -> Option<crate::semantics::WidgetSemantics> {
        Some(crate::semantics::WidgetSemantics::new(crate::semantics::SemanticsRole::Container).non_focusable())
    }
}