rgpui 1.3.0

GUI UI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! 检查器 —— 提供开发者调试工具,用于标识和检查视图元素树。

/// 可检查元素的唯一标识符。
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub struct InspectorElementId {
    /// ID 的稳定部分。
    #[cfg(any(feature = "inspector", debug_assertions))]
    pub path: std::rc::Rc<InspectorElementPath>,
    /// 区分具有相同路径的元素。
    #[cfg(any(feature = "inspector", debug_assertions))]
    pub instance_id: usize,
}

impl Into<InspectorElementId> for &InspectorElementId {
    fn into(self) -> InspectorElementId {
        self.clone()
    }
}

/// 检查器元素 id 的面板展示 helpers(I2 完整树行标签/展开键)。
#[cfg(any(feature = "inspector", debug_assertions))]
impl InspectorElementId {
    /// 行标签:全局路径末段 id;匿名元素退回源码文件名。
    pub fn short_label(&self) -> String {
        if let Some(last) = self.path.global_id.0.last() {
            last.to_string()
        } else {
            self.path.source_location.file().to_string()
        }
    }

    /// 源码位置标签(`文件:行`)。
    pub fn source_label(&self) -> String {
        let loc = self.path.source_location;
        format!("{}:{}", loc.file(), loc.line())
    }

    /// 跨帧稳定键:全局路径 + 实例号 + 源码位置(展开/折叠状态用)。
    pub fn tree_key(&self) -> String {
        let loc = self.path.source_location;
        format!(
            "{}#{}@{}:{}",
            self.path.global_id,
            self.instance_id,
            loc.file(),
            loc.line()
        )
    }
}

#[cfg(any(feature = "inspector", debug_assertions))]
pub use conditional::*;

#[cfg(any(feature = "inspector", debug_assertions))]
mod conditional {
    use super::*;
    use crate::collections::{FxHashMap, TypeIdHashMap};
    use crate::{AnyElement, App, Bounds, Context, Empty, IntoElement, Pixels, Render, Window};
    use std::any::{Any, TypeId};

    /// 由元素构造源位置限定的 `GlobalElementId`。
    #[derive(Debug, Eq, PartialEq, Hash)]
    pub struct InspectorElementPath {
        /// 到具有 `ElementId` 的最近祖先元素的路径。
        #[cfg(any(feature = "inspector", debug_assertions))]
        pub global_id: crate::GlobalElementId,
        /// 构造此元素的源位置。
        #[cfg(any(feature = "inspector", debug_assertions))]
        pub source_location: &'static std::panic::Location<'static>,
    }

    impl Clone for InspectorElementPath {
        fn clone(&self) -> Self {
            Self {
                global_id: self.global_id.clone(),
                source_location: self.source_location,
            }
        }
    }

    impl Into<InspectorElementPath> for &InspectorElementPath {
        fn into(self) -> InspectorElementPath {
            self.clone()
        }
    }

    /// 在 `App` 上设置的用于渲染检查器 UI 的函数。
    pub type InspectorRenderer =
        Box<dyn Fn(&mut Inspector, &mut Window, &mut Context<Inspector>) -> AnyElement>;

    /// 管理检查器状态 - 当前选中的元素以及检查器是否处于
    /// 拾取模式。
    pub struct Inspector {
        active_element: Option<InspectedElement>,
        pub(crate) pick_depth: Option<f32>,
    }

    struct InspectedElement {
        id: InspectorElementId,
        states: TypeIdHashMap<Box<dyn Any>>,
    }

    impl InspectedElement {
        fn new(id: InspectorElementId) -> Self {
            InspectedElement {
                id,
                states: Default::default(),
            }
        }
    }

    impl Inspector {
        pub(crate) fn new() -> Self {
            Self {
                active_element: None,
                pick_depth: Some(0.0),
            }
        }

        /// 选中指定元素并退出拾取模式。
        ///
        /// 公开给检查器面板调用(如树节点点击选中画布对应区域);
        /// 拾取点击路径内部同样复用此方法。
        pub fn select(&mut self, id: InspectorElementId, window: &mut Window) {
            self.set_active_element_id(id, window);
            self.pick_depth = None;
        }

        /// 按祖先层级上移选中(I1 双向映射)。
        ///
        /// `levels_up` 为从当前选中元素沿全局路径上移的层数:
        /// `0` 表示保持当前选中,`1` 为父级,依此类推。
        /// 在当前帧 `inspector_hitboxes` 注册表中按全局路径前缀反查祖先 id,
        /// 以 hitbox 包含关系消歧同路径多实例(取包含当前选中区域的最小祖先边界)。
        /// 成功时复用拾取高亮绘制选中区域,返回 `true`;无选中或越界返回 `false`。
        pub fn select_ancestor(&mut self, levels_up: usize, window: &mut Window) -> bool {
            let Some(active_id) = self.active_element_id().cloned() else {
                return false;
            };
            if levels_up == 0 {
                return true;
            }
            let active_global = active_id.path.global_id.clone();
            let active_len = active_global.0.len();
            if levels_up > active_len {
                return false;
            }
            let target_len = active_len - levels_up;
            let target_prefix = &active_global.0[..target_len];

            // 当前选中区域(优先已渲染帧,退回正在绘制帧),用于包含消歧。
            let active_bounds = window
                .inspector_bounds_for_id(&active_id)
                .or_else(|| window.next_inspector_bounds_for_id(&active_id));

            // 收集全局路径与目标前缀精确匹配的候选祖先。
            let mut candidates: Vec<(InspectorElementId, crate::Bounds<crate::Pixels>)> =
                Vec::new();
            for frame in [&window.rendered_frame, &window.next_frame] {
                for (hitbox_id, inspector_id) in frame.inspector_hitboxes.iter() {
                    if inspector_id.path.global_id.0.as_ref() != target_prefix {
                        continue;
                    }
                    if let Some(hitbox) =
                        frame.hitboxes.iter().find(|hitbox| hitbox.id == *hitbox_id)
                    {
                        candidates.push((inspector_id.clone(), hitbox.bounds));
                    }
                }
            }
            if candidates.is_empty() {
                return false;
            }

            // 以包含关系消歧:取包含当前选中区域的最小祖先边界;
            // 无选中区域或无包含者时退回首个候选。
            let chosen = if let Some(active_bounds) = active_bounds.as_ref() {
                candidates
                    .iter()
                    .filter(|(_, bounds)| bounds_contains(bounds, active_bounds))
                    .min_by(|a, b| {
                        bounds_area(&a.1)
                            .partial_cmp(&bounds_area(&b.1))
                            .unwrap_or(std::cmp::Ordering::Equal)
                    })
                    .map(|(id, _)| id.clone())
            } else {
                None
            };
            let chosen = chosen.unwrap_or_else(|| {
                // 去重后取首个(同一帧可能在 rendered/next 重复出现)。
                let mut seen = std::collections::HashSet::new();
                candidates
                    .into_iter()
                    .map(|(id, _)| id)
                    .find(|id| seen.insert(id.clone()))
                    .expect("候选非空")
            });

            self.select(chosen, window);
            true
        }

        pub(crate) fn hover(&mut self, id: InspectorElementId, window: &mut Window) {
            if self.is_picking() {
                let changed = self.set_active_element_id(id, window);
                if changed {
                    self.pick_depth = Some(0.0);
                }
            }
        }

        pub(crate) fn set_active_element_id(
            &mut self,
            id: InspectorElementId,
            window: &mut Window,
        ) -> bool {
            let changed = Some(&id) != self.active_element_id();
            if changed {
                self.active_element = Some(InspectedElement::new(id));
                window.refresh();
            }
            changed
        }

        /// 当前悬停或选中元素的 ID。
        pub fn active_element_id(&self) -> Option<&InspectorElementId> {
            self.active_element.as_ref().map(|e| &e.id)
        }

        pub(crate) fn with_active_element_state<T: 'static, R>(
            &mut self,
            window: &mut Window,
            f: impl FnOnce(&mut Option<T>, &mut Window) -> R,
        ) -> R {
            let Some(active_element) = &mut self.active_element else {
                return f(&mut None, window);
            };

            let type_id = TypeId::of::<T>();
            let mut inspector_state = active_element
                .states
                .remove(&type_id)
                .map(|state| *state.downcast().unwrap());

            let result = f(&mut inspector_state, window);

            if let Some(inspector_state) = inspector_state {
                active_element
                    .states
                    .insert(type_id, Box::new(inspector_state));
            }

            result
        }

        /// 启动元素拾取模式,允许用户通过点击选择元素。
        pub fn start_picking(&mut self) {
            self.pick_depth = Some(0.0);
        }

        /// 返回检查器当前是否处于拾取模式。
        pub fn is_picking(&self) -> bool {
            self.pick_depth.is_some()
        }

        /// 为活动检查器元素的所有已注册检查器状态渲染元素。
        pub fn render_inspector_states(
            &mut self,
            window: &mut Window,
            cx: &mut Context<Self>,
        ) -> Vec<AnyElement> {
            let mut elements = Vec::new();
            if let Some(active_element) = self.active_element.take() {
                for (type_id, state) in &active_element.states {
                    if let Some(render_inspector) = cx
                        .inspector_element_registry
                        .renderers_by_type_id
                        .remove(type_id)
                    {
                        let mut element = (render_inspector)(
                            active_element.id.clone(),
                            state.as_ref(),
                            window,
                            cx,
                        );
                        elements.push(element);
                        cx.inspector_element_registry
                            .renderers_by_type_id
                            .insert(*type_id, render_inspector);
                    }
                }

                self.active_element = Some(active_element);
            }

            elements
        }
    }

    impl Render for Inspector {
        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            if let Some(inspector_renderer) = cx.inspector_renderer.take() {
                let result = inspector_renderer(self, window, cx);
                cx.inspector_renderer = Some(inspector_renderer);
                result
            } else {
                Empty.into_any_element()
            }
        }
    }

    #[derive(Default)]
    pub(crate) struct InspectorElementRegistry {
        renderers_by_type_id: FxHashMap<
            TypeId,
            Box<dyn Fn(InspectorElementId, &dyn Any, &mut Window, &mut App) -> AnyElement>,
        >,
    }

    impl InspectorElementRegistry {
        pub fn register<T: 'static, R: IntoElement>(
            &mut self,
            f: impl 'static + Fn(InspectorElementId, &T, &mut Window, &mut App) -> R,
        ) {
            self.renderers_by_type_id.insert(
                TypeId::of::<T>(),
                Box::new(move |id, value, window, cx| {
                    let value = value.downcast_ref().unwrap();
                    f(id, value, window, cx).into_any_element()
                }),
            );
        }
    }

    /// 检查器元素树节点(I2 完整树)。
    ///
    /// prepaint 期按实际嵌套记录 parent→children,批量大时面板侧复用 `VirtualList`;
    /// 检查器关闭时不记录、不存储,零额外开销。
    #[derive(Debug, Clone, Default)]
    pub(crate) struct InspectorTreeNode {
        /// 父节点(根为 `None`,deferred/overlay 挂为独立根)。
        pub(crate) parent: Option<InspectorElementId>,
        /// 子节点(绘制顺序)。
        pub(crate) children: Vec<InspectorElementId>,
    }

    /// 崩溃快照里的单个节点(可序列化,事后回放/排查用)。
    #[derive(Debug, Clone, serde::Serialize)]
    pub struct SnapshotNode {
        /// 跨帧稳定键(同面板展开键)。
        pub key: String,
        /// 行标签(全局路径末段)。
        pub label: String,
        /// 源码位置(`文件:行`)。
        pub source: String,
        /// 实例号。
        pub instance: usize,
        /// 父节点键(根为 `None`)。
        pub parent: Option<String>,
        /// 边界(x/y/w/h 逻辑像素,无 hitbox 时为 `None`)。
        pub bounds: Option<[f32; 4]>,
    }

    /// 检查器崩溃快照(滚动写入 `last.json`,死后排查用)。
    ///
    /// 由 [`crate::Window::capture_inspector_snapshot`] 采集,
    /// `App::enable_crash_recorder` 开启后约 2 秒一写(原子替换),
    /// 配合 [`crate::runtime_stats::install_crash_hook`] 的 panic 日志食用。
    /// 注意快照随检查器门控:release 未开 `inspector` feature 时无此数据,
    /// 此时仅 panic 日志可用。
    #[derive(Debug, Clone, serde::Serialize)]
    pub struct InspectorSnapshot {
        /// 快照格式版本(当前 1)。
        pub version: u32,
        /// 采集时间(UNIX 毫秒)。
        pub timestamp_millis: u64,
        /// 当前选中。
        pub active: Option<SnapshotNode>,
        /// 选中祖先链(根在前)。
        pub ancestors: Vec<SnapshotNode>,
        /// 全树节点总数(`tree` 可能因截断少于此数)。
        pub tree_total: usize,
        /// 全树扁平节点(按键排序,截断 2000)。
        pub tree: Vec<SnapshotNode>,
        /// 错误环(序号升序)。
        pub errors: Vec<(u64, String)>,
        /// 视口尺寸(w/h 逻辑像素)。
        pub viewport: [f32; 2],
    }

    /// 判断外层边界是否包含内层边界(含相等,允许 1px 舍入误差)。
    fn bounds_contains(outer: &Bounds<Pixels>, inner: &Bounds<Pixels>) -> bool {
        const EPS: f32 = 1.0;
        let outer_right = outer.origin.x.as_f32() + outer.size.width.as_f32();
        let outer_bottom = outer.origin.y.as_f32() + outer.size.height.as_f32();
        let inner_right = inner.origin.x.as_f32() + inner.size.width.as_f32();
        let inner_bottom = inner.origin.y.as_f32() + inner.size.height.as_f32();
        outer.origin.x.as_f32() <= inner.origin.x.as_f32() + EPS
            && outer.origin.y.as_f32() <= inner.origin.y.as_f32() + EPS
            && outer_right + EPS >= inner_right
            && outer_bottom + EPS >= inner_bottom
    }

    /// 边界面积(用于包含消歧时取最小祖先)。
    fn bounds_area(bounds: &Bounds<Pixels>) -> f32 {
        bounds.size.width.as_f32() * bounds.size.height.as_f32()
    }

    /// 面板宽设置链路冒烟测试(set → draw → get,不断线)。
    #[crate::test]
    fn inspector_width_roundtrip(cx: &mut crate::TestAppContext) {
        use crate::{Context, IntoElement, Render, div};

        struct Probe;
        impl Render for Probe {
            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
                div()
            }
        }

        let (_view, cx) = cx.add_window_view(|_, _| Probe);
        cx.update(|window, cx| {
            assert!(window.inspector_width().is_none());
            window.set_inspector_width(Some(crate::px(400.0)));
            let _ = window.draw(cx);
            assert_eq!(window.inspector_width(), Some(crate::px(400.0)));
            window.set_inspector_width(None);
            assert!(window.inspector_width().is_none());
        });
    }
    /// 快照采集冒烟测试(打开检查器 → 绘制 → 快照非空)。
    #[crate::test]
    fn capture_snapshot_smoke(cx: &mut crate::TestAppContext) {
        use crate::{Context, IntoElement, Render, div};

        struct Probe;
        impl Render for Probe {
            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
                div()
            }
        }

        let (_view, cx) = cx.add_window_view(|_, _| Probe);
        cx.update(|window, cx| {
            window.toggle_inspector(cx);
            let _ = window.draw(cx);
            let snapshot = window
                .capture_inspector_snapshot(cx)
                .expect("检查器打开应有快照");
            assert_eq!(snapshot.version, 1);
            assert!(snapshot.viewport[0] > 0.0);
        });
    }

    /// 树文本导出冒烟测试(AI 可读:头部 + 节点行 + 选中标记)。
    #[crate::test]
    fn tree_text_marks_selected_with_source(cx: &mut crate::TestAppContext) {
        use crate::{Context, InteractiveElement as _, IntoElement, ParentElement, Render, div};

        struct Probe;
        impl Render for Probe {
            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
                div().id("probe-root").child(div().id("probe-leaf"))
            }
        }

        let (_view, cx) = cx.add_window_view(|_, _| Probe);
        cx.update(|window, cx| {
            window.toggle_inspector(cx);
            let _ = window.draw(cx);
            let text = window.inspector_tree_text(cx, 2000).unwrap();
            assert!(text.contains("# 检查器树"), "缺头部:{text}");
            assert!(text.contains("probe-leaf"), "缺叶子节点:{text}");
            // 递归找叶子并选中,应出现选中标记。
            fn find_leaf(
                window: &Window,
                id: &crate::InspectorElementId,
            ) -> Option<crate::InspectorElementId> {
                if id.short_label() == "probe-leaf" {
                    return Some(id.clone());
                }
                window
                    .inspector_tree_children(id)
                    .iter()
                    .find_map(|child| find_leaf(window, child))
            }
            let leaf = window
                .inspector_tree_roots()
                .iter()
                .find_map(|root| find_leaf(window, root))
                .expect("树中应有叶子");
            assert!(window.select_inspector_element(&leaf, cx));
            let _ = window.draw(cx);
            let text = window.inspector_tree_text(cx, 2000).unwrap();
            assert!(
                text.contains("[*]") && text.contains("probe-leaf"),
                "缺选中标记:{text}"
            );
        });
    }

    /// 快照 JSON 形状回归测试(字段改名即炸,提醒同步回放侧)。
    #[test]
    fn snapshot_serializes_stable_shape() {
        let snapshot = InspectorSnapshot {
            version: 1,
            timestamp_millis: 0,
            active: Some(SnapshotNode {
                key: "k".to_string(),
                label: "l".to_string(),
                source: "s:1".to_string(),
                instance: 0,
                parent: None,
                bounds: Some([0.0, 0.0, 10.0, 10.0]),
            }),
            ancestors: Vec::new(),
            tree_total: 1,
            tree: Vec::new(),
            errors: vec![(0, "boom".to_string())],
            viewport: [800.0, 600.0],
        };
        let json = serde_json::to_string(&snapshot).unwrap();
        for key in [
            "version",
            "timestamp_millis",
            "active",
            "ancestors",
            "tree_total",
            "tree",
            "errors",
            "viewport",
            "bounds",
            "source",
        ] {
            assert!(json.contains(key), "快照缺字段 {key}");
        }
    }
}

/// 提供 `#[derive_inspector_reflection]` 使用的定义。
#[cfg(any(feature = "inspector", debug_assertions))]
pub mod inspector_reflection {
    use std::any::Any;

    /// 具有签名 `fn some_fn(T) -> T` 的函数的具化。提供名称、
    /// 文档和调用函数的能力。
    #[derive(Clone, Copy)]
    pub struct FunctionReflection<T> {
        /// 函数的名称
        pub name: &'static str,
        /// 方法
        pub function: fn(Box<dyn Any>) -> Box<dyn Any>,
        /// 函数的文档
        pub documentation: Option<&'static str>,
        /// 参数和结果类型的 `PhantomData`
        pub _type: std::marker::PhantomData<T>,
    }

    impl<T: 'static> FunctionReflection<T> {
        /// 在值上调用此方法并返回结果。
        pub fn invoke(&self, value: T) -> T {
            let boxed = Box::new(value) as Box<dyn Any>;
            let result = (self.function)(boxed);
            *result
                .downcast::<T>()
                .expect("Type mismatch in reflection invoke")
        }
    }
}