mgui-core 0.7.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! 只读 introspection — 供 Inspector / 诊断工具读取 Element、Layer 与 bounds。
//!
//! 全部是快照式只读 API,不触发 layout/paint,不影响正常渲染路径。

use crate::element::ElementTree;
use crate::geometry::{Point, Rect, Size};
use crate::id::{ElementId, LayerId};
use crate::paint::LayerEffect;
use crate::render_object::BoxConstraints;

/// 图片纹理占用快照(Inspector/诊断用)。
///
/// 定义放在 core 而不是 `mgui-runtime`:这只是三个后端无关的计数,
/// Inspector 读它不需要把整个 wgpu runtime 拉进依赖树。`mgui-runtime`
/// 在 crate 根与 `renderer` 模块保留同名 re-export,旧路径继续可用。
#[derive(Clone, Copy, Debug, Default)]
pub struct ImageTextureStats {
    pub count: usize,
    pub bytes: u64,
    pub budget_bytes: u64,
}

/// Element 树一行(深度优先,父在前)
#[derive(Clone, Copy, Debug)]
pub struct ElementInfo {
    pub id: ElementId,
    pub parent: Option<ElementId>,
    /// 相对根的深度(根 = 0)
    pub depth: usize,
    pub type_name: &'static str,
    pub dirty: bool,
    pub active: bool,
    pub stateful: bool,
    /// state 当前是否在动画(帧内持续标脏的直接原因)
    pub animating: bool,
}

/// 拾取/布局 overlay 用的单元素只读详情(一次取齐 Inspector 需要的信息)。
///
/// 与 [`ElementInfo`] 的区别:后者是「整棵树的行」,不含几何;本类型是「一个元素」,
/// 含 bounds 与上一次 layout 的约束,供元素拾取与布局 overlay 使用。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ElementDetail {
    pub id: ElementId,
    pub parent: Option<ElementId>,
    /// 相对根的深度(根 = 0)
    pub depth: usize,
    pub type_name: &'static str,
    /// root layer 逻辑坐标下的占据区域。
    ///
    /// 优先用 RO 的 `content_size()`;容器 RO 返回零尺寸时退回到 layout 结果尺寸,
    /// 这样拾取高亮不会显示成 0×0。
    pub bounds: Rect,
    /// 父元素占据区域,用于观察 margin/溢出;根元素为 None
    pub parent_bounds: Option<Rect>,
    /// 上一次 layout 收到的约束(从未布局过为 None)
    pub constraints: Option<BoxConstraints>,
    /// 上一次 layout 返回的尺寸(从未布局过为 None)
    pub layout_size: Option<Size>,
    pub dirty: bool,
    pub stateful: bool,
    pub animating: bool,
    pub focusable: bool,
    pub focused: bool,
}

/// Layer 快照(依赖上一次 paint 后的状态)
#[derive(Clone, Copy, Debug)]
pub struct LayerInfo {
    pub id: LayerId,
    pub parent: Option<LayerId>,
    pub root_element: ElementId,
    pub root_type: &'static str,
    pub z_order: u32,
    pub dirty: bool,
    /// 累计 paint 次数
    pub paint_count: u32,
    /// 缓存 PaintList 的命令数(上次绘制结果)
    pub cmds: usize,
    pub offset: Point,
    pub size: Option<Size>,
    pub effect: LayerEffect,
}

impl ElementTree {
    /// 按树序快照最多 `limit` 个 active element(深度优先,父在前)。
    pub fn inspect_elements(&self, limit: usize) -> Vec<ElementInfo> {
        let mut out = Vec::new();
        let Some(root) = self.root else { return out };
        let mut stack = vec![(root, 0usize)];
        while let Some((id, depth)) = stack.pop() {
            let Some(el) = self.elements.get(id) else { continue };
            if !el.active {
                continue;
            }
            out.push(ElementInfo {
                id,
                parent: el.parent,
                depth,
                type_name: el.widget.0.type_name(),
                dirty: el.dirty,
                active: el.active,
                stateful: el.widget.0.is_stateful(),
                animating: el.state.as_ref().is_some_and(|s| s.is_animating()),
            });
            if out.len() >= limit {
                break;
            }
            for &child in el.children.iter().rev() {
                stack.push((child, depth + 1));
            }
        }
        out
    }

    /// (active element 数, 总 element 数)
    pub fn inspect_counts(&self) -> (usize, usize) {
        let active = self.elements.iter().filter(|(_, e)| e.active).count();
        (active, self.elements.len())
    }

    /// 所有真实 layer(不含虚拟 root),按 z_order 升序。
    pub fn inspect_layers(&self) -> Vec<LayerInfo> {
        let mut out: Vec<LayerInfo> = self
            .layer_tree
            .layers
            .iter()
            .filter(|(id, _)| Some(*id) != self.layer_tree.root)
            .map(|(id, layer)| LayerInfo {
                id,
                parent: layer.parent,
                root_element: layer.root_element,
                root_type: self.elements.get(layer.root_element).map(|e| e.widget.0.type_name()).unwrap_or("?"),
                z_order: layer.z_order,
                dirty: layer.dirty,
                paint_count: layer.paint_count,
                cmds: layer.cached_paint_list.as_ref().map(|p| p.len()).unwrap_or(0),
                offset: layer.offset,
                size: layer.size,
                effect: layer.effect,
            })
            .collect();
        out.sort_by_key(|l| l.z_order);
        out
    }

    /// element 在 root layer 逻辑坐标下的 bounds(origin + RO content_size)。
    ///
    /// 容器 RO 若不实现 `content_size`(返回 ZERO),bounds 会是零尺寸;
    /// Inspector 会显示 origin + "0×0"。
    pub fn element_bounds(&self, id: ElementId) -> Option<Rect> {
        let origin = self.element_origin(id)?;
        let el = self.elements.get(id)?;
        let size = el.render_object.borrow().content_size();
        Some(Rect::new(origin.x, origin.y, size.width, size.height))
    }

    /// element 实际占据的区域:RO `content_size()` 为零(常见于容器 RO)时,
    /// 退回到上一次 layout 的结果尺寸,避免拾取高亮显示成 0×0。
    fn element_occupied(&self, id: ElementId) -> Option<Rect> {
        let origin = self.element_origin(id)?;
        let el = self.elements.get(id)?;
        let content = el.render_object.borrow().content_size();
        let size = if content.width > 0.0 && content.height > 0.0 {
            content
        } else {
            el.render_object.layout_snapshot().map(|(_, s)| s)?
        };
        Some(Rect::new(origin.x, origin.y, size.width, size.height))
    }

    /// 单个 element 的拾取详情(bounds + 布局约束 + 焦点态)。
    ///
    /// `id` 不存在或已非 active 时返回 None;纯只读,不触发 layout/paint。
    pub fn element_detail(&self, id: ElementId) -> Option<ElementDetail> {
        let el = self.elements.get(id)?;
        if !el.active {
            return None;
        }
        let bounds = self.element_occupied(id)?;
        let parent = el.parent;
        let parent_bounds = parent.and_then(|p| self.element_occupied(p));
        let mut depth = 0usize;
        let mut cursor = parent;
        while let Some(p) = cursor {
            depth += 1;
            cursor = self.elements.get(p).and_then(|e| e.parent);
        }
        let (constraints, layout_size) = match el.render_object.layout_snapshot() {
            Some((c, s)) => (Some(c), Some(s)),
            None => (None, None),
        };
        Some(ElementDetail {
            id,
            parent,
            depth,
            type_name: el.widget.0.type_name(),
            bounds,
            parent_bounds,
            constraints,
            layout_size,
            dirty: el.dirty,
            stateful: el.widget.0.is_stateful(),
            animating: el.state.as_ref().is_some_and(|s| s.is_animating()),
            focusable: el.widget.0.is_focusable(),
            focused: self.focused_element() == Some(id),
        })
    }

    /// 窗口坐标 → 最深命中元素的拾取详情(Inspector 元素拾取入口)。
    ///
    /// 与事件路由共用 [`ElementTree::hit_test`](含 overlay 优先与 RO 命中),
    /// 因此拾取高亮的就是实际点击目标;只读,不改变捕获或焦点。
    pub fn hit_test_detail(&self, position: Point) -> Option<ElementDetail> {
        let id = self.hit_test(position)?;
        self.element_detail(id)
    }
}

// ================================================================
// DT-02:Signal 依赖图
// ================================================================

/// DT-02:一次 Signal 触发事件的 ElementId 映射快照。
///
/// `subscriber_elements` 里 Some = element subscriber(映射到 ElementId),
/// None = Memo/Effect subscriber(不在本 ElementTree 里)。
#[derive(Clone, Debug)]
pub struct SignalEventView {
    pub timestamp_ms: u64,
    pub signal_id: crate::reactive::SignalId,
    pub peeked: bool,
    pub subscriber_elements: Vec<Option<ElementId>>,
}

/// DT-02:本树当前 scope 内的 dirty subscriber → ElementId 映射。
#[derive(Clone, Debug)]
pub struct SignalDirtyView {
    pub subscriber_id: crate::reactive::SubscriberId,
    pub element_id: Option<ElementId>,
    pub dirty: bool,
}

impl ElementTree {
    /// DT-02:取最近 N 条 Signal trace 并把 subscriber 映射到本树 ElementId。
    pub fn inspect_signal_trace(&self, max: usize) -> Vec<SignalEventView> {
        let trace = crate::reactive::peek_signal_trace(max);
        trace
            .into_iter()
            .map(|entry| SignalEventView {
                timestamp_ms: entry.timestamp_ms,
                signal_id: entry.signal_id,
                peeked: entry.peeked,
                subscriber_elements: entry
                    .subscribers
                    .into_iter()
                    .map(|sid| self.subscriber_to_element.get(&sid).copied())
                    .collect(),
            })
            .collect()
    }

    /// DT-02:枚举本树所有 registered subscriber(通过 subscriber_to_element)
    /// 并标记哪些当前处于 dirty 状态。
    pub fn inspect_signal_dirty(&self) -> Vec<SignalDirtyView> {
        let dirty_set = crate::reactive::peek_dirty_for_scope(self.reactive_scope);
        let mut out = Vec::with_capacity(self.subscriber_to_element.len());
        for (&sub_id, &element_id) in &self.subscriber_to_element {
            out.push(SignalDirtyView {
                subscriber_id: sub_id,
                element_id: Some(element_id),
                dirty: dirty_set.contains(&sub_id),
            });
        }
        // 把本树 scope 里 dirty 但不在 subscriber_to_element 的也补上
        for sub_id in dirty_set {
            if !self.subscriber_to_element.contains_key(&sub_id) {
                out.push(SignalDirtyView { subscriber_id: sub_id, element_id: None, dirty: true });
            }
        }
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::widget::{RRectWidget, WidgetNode};
    use crate::StackWidget;
    use crate::{paint_frame, Color};

    #[test]
    fn inspect_elements_and_bounds() {
        let mut tree = ElementTree::new();
        let root = StackWidget::new()
            .push(Point::ZERO, RRectWidget::new(Size::new(100.0, 50.0), Color::WHITE, 0.0))
            .push(Point::ZERO, RRectWidget::new(Size::new(20.0, 20.0), Color::WHITE, 4.0));
        tree.mount(WidgetNode::new(root));
        tree.set_viewport_size(Size::new(200.0, 100.0));
        let _ = paint_frame(&mut tree);

        let rows = tree.inspect_elements(100);
        assert!(!rows.is_empty(), "应能列出 element");
        assert_eq!(rows[0].depth, 0, "根 depth=0");
        assert!(rows.iter().any(|r| r.type_name.contains("RRect")), "应包含 RRect 叶子");
        let (active, total) = tree.inspect_counts();
        assert_eq!(active, total, "无 inactive 时 active=total");
        assert!(active >= 3);

        let leaf = rows.iter().find(|r| r.type_name.contains("RRect")).unwrap();
        let bounds = tree.element_bounds(leaf.id).expect("leaf bounds");
        assert!(bounds.width > 0.0 && bounds.height > 0.0, "叶子应有尺寸: {bounds:?}");

        let limited = tree.inspect_elements(2);
        assert_eq!(limited.len(), 2, "limit 生效");
    }

    #[test]
    fn element_detail_picks_deepest_hit_with_layout_info() {
        let mut tree = ElementTree::new();
        let inner = StackWidget::new()
            .push(Point::new(100.0, 50.0), RRectWidget::new(Size::new(60.0, 40.0), Color::WHITE, 0.0));
        let root = StackWidget::new().push(Point::ZERO, inner);
        tree.mount(WidgetNode::new(root));
        tree.set_viewport_size(Size::new(200.0, 100.0));
        let _ = paint_frame(&mut tree);

        // 命中内层叶子:拾取结果应与实际点击目标一致(最内层)
        let picked = tree.hit_test_detail(Point::new(120.0, 60.0)).expect("应命中内层 RRect");
        assert!(picked.type_name.contains("RRect"), "应给出最内层: {}", picked.type_name);
        assert!((picked.bounds.x - 100.0).abs() < 0.5 && (picked.bounds.y - 50.0).abs() < 0.5, "{:?}", picked.bounds);
        assert!(
            (picked.bounds.width - 60.0).abs() < 0.5 && (picked.bounds.height - 40.0).abs() < 0.5,
            "{:?}",
            picked.bounds
        );
        assert!(picked.depth >= 2, "叶子深度: {}", picked.depth);
        assert!(picked.parent.is_some(), "叶子应有父");
        assert!(picked.constraints.is_some() && picked.layout_size.is_some(), "布局后应能读到约束与尺寸");
        let c = picked.constraints.unwrap();
        assert!(c.min_width <= 60.0 && c.max_width >= 60.0, "约束应覆盖结果宽度: {c:?}");
        let s = picked.layout_size.unwrap();
        assert!((s.width - 60.0).abs() < 0.5 && (s.height - 40.0).abs() < 0.5, "{s:?}");
        assert!(!picked.focused, "未设置焦点时 focused=false");

        // 容器 RO 的 content_size 为 ZERO → bounds 退回 layout 尺寸,而不是 0×0
        let container = tree
            .inspect_elements(200)
            .into_iter()
            .find(|e| e.depth == 1 && !e.type_name.contains("RRect"))
            .expect("中间层容器");
        let detail = tree.element_detail(container.id).expect("容器详情");
        assert!(
            detail.bounds.width > 0.0 && detail.bounds.height > 0.0,
            "容器 bounds 应退回布局尺寸: {:?}",
            detail.bounds
        );

        // 空白处不应拾到内层叶子
        let far = tree.hit_test_detail(Point::new(8.0, 8.0));
        assert!(!far.is_some_and(|d| d.type_name.contains("RRect")), "空白处不应拾到内层 RRect");
    }

    #[test]
    fn inspect_layers_reports_paint_stats() {
        // 无 RepaintBoundary 时只有虚拟 root,列表应为空
        let mut tree = ElementTree::new();
        let root = StackWidget::new().push(Point::ZERO, RRectWidget::new(Size::new(10.0, 10.0), Color::WHITE, 0.0));
        tree.mount(WidgetNode::new(root));
        tree.set_viewport_size(Size::new(100.0, 100.0));
        let _ = paint_frame(&mut tree);
        let layers = tree.inspect_layers();
        assert!(!layers.is_empty(), "主树至少有一个内容 layer");
        assert!(layers.iter().all(|l| !l.root_type.is_empty()), "layer 应关联 root widget 类型");
    }
}