Skip to main content

mgui_core/
inspect.rs

1//! 只读 introspection — 供 Inspector / 诊断工具读取 Element、Layer 与 bounds。
2//!
3//! 全部是快照式只读 API,不触发 layout/paint,不影响正常渲染路径。
4
5use crate::element::ElementTree;
6use crate::geometry::{Point, Rect, Size};
7use crate::id::{ElementId, LayerId};
8use crate::paint::LayerEffect;
9use crate::render_object::BoxConstraints;
10
11/// 图片纹理占用快照(Inspector/诊断用)。
12///
13/// 定义放在 core 而不是 `mgui-runtime`:这只是三个后端无关的计数,
14/// Inspector 读它不需要把整个 wgpu runtime 拉进依赖树。`mgui-runtime`
15/// 在 crate 根与 `renderer` 模块保留同名 re-export,旧路径继续可用。
16#[derive(Clone, Copy, Debug, Default)]
17pub struct ImageTextureStats {
18    pub count: usize,
19    pub bytes: u64,
20    pub budget_bytes: u64,
21}
22
23/// Element 树一行(深度优先,父在前)
24#[derive(Clone, Copy, Debug)]
25pub struct ElementInfo {
26    pub id: ElementId,
27    pub parent: Option<ElementId>,
28    /// 相对根的深度(根 = 0)
29    pub depth: usize,
30    pub type_name: &'static str,
31    pub dirty: bool,
32    pub active: bool,
33    pub stateful: bool,
34    /// state 当前是否在动画(帧内持续标脏的直接原因)
35    pub animating: bool,
36}
37
38/// 拾取/布局 overlay 用的单元素只读详情(一次取齐 Inspector 需要的信息)。
39///
40/// 与 [`ElementInfo`] 的区别:后者是「整棵树的行」,不含几何;本类型是「一个元素」,
41/// 含 bounds 与上一次 layout 的约束,供元素拾取与布局 overlay 使用。
42#[derive(Clone, Copy, Debug, PartialEq)]
43pub struct ElementDetail {
44    pub id: ElementId,
45    pub parent: Option<ElementId>,
46    /// 相对根的深度(根 = 0)
47    pub depth: usize,
48    pub type_name: &'static str,
49    /// root layer 逻辑坐标下的占据区域。
50    ///
51    /// 优先用 RO 的 `content_size()`;容器 RO 返回零尺寸时退回到 layout 结果尺寸,
52    /// 这样拾取高亮不会显示成 0×0。
53    pub bounds: Rect,
54    /// 父元素占据区域,用于观察 margin/溢出;根元素为 None
55    pub parent_bounds: Option<Rect>,
56    /// 上一次 layout 收到的约束(从未布局过为 None)
57    pub constraints: Option<BoxConstraints>,
58    /// 上一次 layout 返回的尺寸(从未布局过为 None)
59    pub layout_size: Option<Size>,
60    pub dirty: bool,
61    pub stateful: bool,
62    pub animating: bool,
63    pub focusable: bool,
64    pub focused: bool,
65}
66
67/// Layer 快照(依赖上一次 paint 后的状态)
68#[derive(Clone, Copy, Debug)]
69pub struct LayerInfo {
70    pub id: LayerId,
71    pub parent: Option<LayerId>,
72    pub root_element: ElementId,
73    pub root_type: &'static str,
74    pub z_order: u32,
75    pub dirty: bool,
76    /// 累计 paint 次数
77    pub paint_count: u32,
78    /// 缓存 PaintList 的命令数(上次绘制结果)
79    pub cmds: usize,
80    pub offset: Point,
81    pub size: Option<Size>,
82    pub effect: LayerEffect,
83}
84
85impl ElementTree {
86    /// 按树序快照最多 `limit` 个 active element(深度优先,父在前)。
87    pub fn inspect_elements(&self, limit: usize) -> Vec<ElementInfo> {
88        let mut out = Vec::new();
89        let Some(root) = self.root else { return out };
90        let mut stack = vec![(root, 0usize)];
91        while let Some((id, depth)) = stack.pop() {
92            let Some(el) = self.elements.get(id) else { continue };
93            if !el.active {
94                continue;
95            }
96            out.push(ElementInfo {
97                id,
98                parent: el.parent,
99                depth,
100                type_name: el.widget.0.type_name(),
101                dirty: el.dirty,
102                active: el.active,
103                stateful: el.widget.0.is_stateful(),
104                animating: el.state.as_ref().is_some_and(|s| s.is_animating()),
105            });
106            if out.len() >= limit {
107                break;
108            }
109            for &child in el.children.iter().rev() {
110                stack.push((child, depth + 1));
111            }
112        }
113        out
114    }
115
116    /// (active element 数, 总 element 数)
117    pub fn inspect_counts(&self) -> (usize, usize) {
118        let active = self.elements.iter().filter(|(_, e)| e.active).count();
119        (active, self.elements.len())
120    }
121
122    /// 所有真实 layer(不含虚拟 root),按 z_order 升序。
123    pub fn inspect_layers(&self) -> Vec<LayerInfo> {
124        let mut out: Vec<LayerInfo> = self
125            .layer_tree
126            .layers
127            .iter()
128            .filter(|(id, _)| Some(*id) != self.layer_tree.root)
129            .map(|(id, layer)| LayerInfo {
130                id,
131                parent: layer.parent,
132                root_element: layer.root_element,
133                root_type: self.elements.get(layer.root_element).map(|e| e.widget.0.type_name()).unwrap_or("?"),
134                z_order: layer.z_order,
135                dirty: layer.dirty,
136                paint_count: layer.paint_count,
137                cmds: layer.cached_paint_list.as_ref().map(|p| p.len()).unwrap_or(0),
138                offset: layer.offset,
139                size: layer.size,
140                effect: layer.effect,
141            })
142            .collect();
143        out.sort_by_key(|l| l.z_order);
144        out
145    }
146
147    /// element 在 root layer 逻辑坐标下的 bounds(origin + RO content_size)。
148    ///
149    /// 容器 RO 若不实现 `content_size`(返回 ZERO),bounds 会是零尺寸;
150    /// Inspector 会显示 origin + "0×0"。
151    pub fn element_bounds(&self, id: ElementId) -> Option<Rect> {
152        let origin = self.element_origin(id)?;
153        let el = self.elements.get(id)?;
154        let size = el.render_object.borrow().content_size();
155        Some(Rect::new(origin.x, origin.y, size.width, size.height))
156    }
157
158    /// element 实际占据的区域:RO `content_size()` 为零(常见于容器 RO)时,
159    /// 退回到上一次 layout 的结果尺寸,避免拾取高亮显示成 0×0。
160    fn element_occupied(&self, id: ElementId) -> Option<Rect> {
161        let origin = self.element_origin(id)?;
162        let el = self.elements.get(id)?;
163        let content = el.render_object.borrow().content_size();
164        let size = if content.width > 0.0 && content.height > 0.0 {
165            content
166        } else {
167            el.render_object.layout_snapshot().map(|(_, s)| s)?
168        };
169        Some(Rect::new(origin.x, origin.y, size.width, size.height))
170    }
171
172    /// 单个 element 的拾取详情(bounds + 布局约束 + 焦点态)。
173    ///
174    /// `id` 不存在或已非 active 时返回 None;纯只读,不触发 layout/paint。
175    pub fn element_detail(&self, id: ElementId) -> Option<ElementDetail> {
176        let el = self.elements.get(id)?;
177        if !el.active {
178            return None;
179        }
180        let bounds = self.element_occupied(id)?;
181        let parent = el.parent;
182        let parent_bounds = parent.and_then(|p| self.element_occupied(p));
183        let mut depth = 0usize;
184        let mut cursor = parent;
185        while let Some(p) = cursor {
186            depth += 1;
187            cursor = self.elements.get(p).and_then(|e| e.parent);
188        }
189        let (constraints, layout_size) = match el.render_object.layout_snapshot() {
190            Some((c, s)) => (Some(c), Some(s)),
191            None => (None, None),
192        };
193        Some(ElementDetail {
194            id,
195            parent,
196            depth,
197            type_name: el.widget.0.type_name(),
198            bounds,
199            parent_bounds,
200            constraints,
201            layout_size,
202            dirty: el.dirty,
203            stateful: el.widget.0.is_stateful(),
204            animating: el.state.as_ref().is_some_and(|s| s.is_animating()),
205            focusable: el.widget.0.is_focusable(),
206            focused: self.focused_element() == Some(id),
207        })
208    }
209
210    /// 窗口坐标 → 最深命中元素的拾取详情(Inspector 元素拾取入口)。
211    ///
212    /// 与事件路由共用 [`ElementTree::hit_test`](含 overlay 优先与 RO 命中),
213    /// 因此拾取高亮的就是实际点击目标;只读,不改变捕获或焦点。
214    pub fn hit_test_detail(&self, position: Point) -> Option<ElementDetail> {
215        let id = self.hit_test(position)?;
216        self.element_detail(id)
217    }
218}
219
220// ================================================================
221// DT-02:Signal 依赖图
222// ================================================================
223
224/// DT-02:一次 Signal 触发事件的 ElementId 映射快照。
225///
226/// `subscriber_elements` 里 Some = element subscriber(映射到 ElementId),
227/// None = Memo/Effect subscriber(不在本 ElementTree 里)。
228#[derive(Clone, Debug)]
229pub struct SignalEventView {
230    pub timestamp_ms: u64,
231    pub signal_id: crate::reactive::SignalId,
232    pub peeked: bool,
233    pub subscriber_elements: Vec<Option<ElementId>>,
234}
235
236/// DT-02:本树当前 scope 内的 dirty subscriber → ElementId 映射。
237#[derive(Clone, Debug)]
238pub struct SignalDirtyView {
239    pub subscriber_id: crate::reactive::SubscriberId,
240    pub element_id: Option<ElementId>,
241    pub dirty: bool,
242}
243
244impl ElementTree {
245    /// DT-02:取最近 N 条 Signal trace 并把 subscriber 映射到本树 ElementId。
246    pub fn inspect_signal_trace(&self, max: usize) -> Vec<SignalEventView> {
247        let trace = crate::reactive::peek_signal_trace(max);
248        trace
249            .into_iter()
250            .map(|entry| SignalEventView {
251                timestamp_ms: entry.timestamp_ms,
252                signal_id: entry.signal_id,
253                peeked: entry.peeked,
254                subscriber_elements: entry
255                    .subscribers
256                    .into_iter()
257                    .map(|sid| self.subscriber_to_element.get(&sid).copied())
258                    .collect(),
259            })
260            .collect()
261    }
262
263    /// DT-02:枚举本树所有 registered subscriber(通过 subscriber_to_element)
264    /// 并标记哪些当前处于 dirty 状态。
265    pub fn inspect_signal_dirty(&self) -> Vec<SignalDirtyView> {
266        let dirty_set = crate::reactive::peek_dirty_for_scope(self.reactive_scope);
267        let mut out = Vec::with_capacity(self.subscriber_to_element.len());
268        for (&sub_id, &element_id) in &self.subscriber_to_element {
269            out.push(SignalDirtyView {
270                subscriber_id: sub_id,
271                element_id: Some(element_id),
272                dirty: dirty_set.contains(&sub_id),
273            });
274        }
275        // 把本树 scope 里 dirty 但不在 subscriber_to_element 的也补上
276        for sub_id in dirty_set {
277            if !self.subscriber_to_element.contains_key(&sub_id) {
278                out.push(SignalDirtyView { subscriber_id: sub_id, element_id: None, dirty: true });
279            }
280        }
281        out
282    }
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288    use crate::widget::{RRectWidget, WidgetNode};
289    use crate::StackWidget;
290    use crate::{paint_frame, Color};
291
292    #[test]
293    fn inspect_elements_and_bounds() {
294        let mut tree = ElementTree::new();
295        let root = StackWidget::new()
296            .push(Point::ZERO, RRectWidget::new(Size::new(100.0, 50.0), Color::WHITE, 0.0))
297            .push(Point::ZERO, RRectWidget::new(Size::new(20.0, 20.0), Color::WHITE, 4.0));
298        tree.mount(WidgetNode::new(root));
299        tree.set_viewport_size(Size::new(200.0, 100.0));
300        let _ = paint_frame(&mut tree);
301
302        let rows = tree.inspect_elements(100);
303        assert!(!rows.is_empty(), "应能列出 element");
304        assert_eq!(rows[0].depth, 0, "根 depth=0");
305        assert!(rows.iter().any(|r| r.type_name.contains("RRect")), "应包含 RRect 叶子");
306        let (active, total) = tree.inspect_counts();
307        assert_eq!(active, total, "无 inactive 时 active=total");
308        assert!(active >= 3);
309
310        let leaf = rows.iter().find(|r| r.type_name.contains("RRect")).unwrap();
311        let bounds = tree.element_bounds(leaf.id).expect("leaf bounds");
312        assert!(bounds.width > 0.0 && bounds.height > 0.0, "叶子应有尺寸: {bounds:?}");
313
314        let limited = tree.inspect_elements(2);
315        assert_eq!(limited.len(), 2, "limit 生效");
316    }
317
318    #[test]
319    fn element_detail_picks_deepest_hit_with_layout_info() {
320        let mut tree = ElementTree::new();
321        let inner = StackWidget::new()
322            .push(Point::new(100.0, 50.0), RRectWidget::new(Size::new(60.0, 40.0), Color::WHITE, 0.0));
323        let root = StackWidget::new().push(Point::ZERO, inner);
324        tree.mount(WidgetNode::new(root));
325        tree.set_viewport_size(Size::new(200.0, 100.0));
326        let _ = paint_frame(&mut tree);
327
328        // 命中内层叶子:拾取结果应与实际点击目标一致(最内层)
329        let picked = tree.hit_test_detail(Point::new(120.0, 60.0)).expect("应命中内层 RRect");
330        assert!(picked.type_name.contains("RRect"), "应给出最内层: {}", picked.type_name);
331        assert!((picked.bounds.x - 100.0).abs() < 0.5 && (picked.bounds.y - 50.0).abs() < 0.5, "{:?}", picked.bounds);
332        assert!(
333            (picked.bounds.width - 60.0).abs() < 0.5 && (picked.bounds.height - 40.0).abs() < 0.5,
334            "{:?}",
335            picked.bounds
336        );
337        assert!(picked.depth >= 2, "叶子深度: {}", picked.depth);
338        assert!(picked.parent.is_some(), "叶子应有父");
339        assert!(picked.constraints.is_some() && picked.layout_size.is_some(), "布局后应能读到约束与尺寸");
340        let c = picked.constraints.unwrap();
341        assert!(c.min_width <= 60.0 && c.max_width >= 60.0, "约束应覆盖结果宽度: {c:?}");
342        let s = picked.layout_size.unwrap();
343        assert!((s.width - 60.0).abs() < 0.5 && (s.height - 40.0).abs() < 0.5, "{s:?}");
344        assert!(!picked.focused, "未设置焦点时 focused=false");
345
346        // 容器 RO 的 content_size 为 ZERO → bounds 退回 layout 尺寸,而不是 0×0
347        let container = tree
348            .inspect_elements(200)
349            .into_iter()
350            .find(|e| e.depth == 1 && !e.type_name.contains("RRect"))
351            .expect("中间层容器");
352        let detail = tree.element_detail(container.id).expect("容器详情");
353        assert!(
354            detail.bounds.width > 0.0 && detail.bounds.height > 0.0,
355            "容器 bounds 应退回布局尺寸: {:?}",
356            detail.bounds
357        );
358
359        // 空白处不应拾到内层叶子
360        let far = tree.hit_test_detail(Point::new(8.0, 8.0));
361        assert!(!far.is_some_and(|d| d.type_name.contains("RRect")), "空白处不应拾到内层 RRect");
362    }
363
364    #[test]
365    fn inspect_layers_reports_paint_stats() {
366        // 无 RepaintBoundary 时只有虚拟 root,列表应为空
367        let mut tree = ElementTree::new();
368        let root = StackWidget::new().push(Point::ZERO, RRectWidget::new(Size::new(10.0, 10.0), Color::WHITE, 0.0));
369        tree.mount(WidgetNode::new(root));
370        tree.set_viewport_size(Size::new(100.0, 100.0));
371        let _ = paint_frame(&mut tree);
372        let layers = tree.inspect_layers();
373        assert!(!layers.is_empty(), "主树至少有一个内容 layer");
374        assert!(layers.iter().all(|l| !l.root_type.is_empty()), "layer 应关联 root widget 类型");
375    }
376}