mgui-core 0.8.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
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
//! DT-03 统一帧时间线:把 CPU frame pipeline / GPU timestamp query 与
//! **任意扩展轨道**对齐到同一条单调时间轴。
//!
//! 框架只认识自己的两条轨道(CPU/GPU);扩展组件(如视频)用 [`push`] 以
//! 自带的名字注册轨道("VideoDecode" 之类),DevTools 只透传显示轨道名,
//! 不认识任何具体扩展 —— 组件是扩展,可观测设施是框架级,两边不互相定制。
//!
//! 存储基础设施复用 [`crate::devtools_trace::DevtoolsTrace`](三处 trace 共用同一套)。
//! 开关默认关闭;关闭时入口先做一次 thread-local 开关判断就返回,不拿锁、不构造记录。

use crate::devtools_trace::{now_ms, DevtoolsTrace};
use std::cell::Cell;
use std::sync::Mutex;

const CAPACITY: usize = 512;

/// 时间线条目类型。框架级只有 CPU/GPU 两条;扩展组件走 [`TimelineKind::Custom`],
/// 轨道名由调用方自带(见 [`TimelineEntry::track`])。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TimelineKind {
    /// CPU 帧管线一帧:六个阶段的完整统计
    CpuFrame,
    /// GPU 一次 render pass 的 timestamp query 结果
    GpuFrame,
    /// 扩展组件注册的轨道(视频、音频、任何长时间运行的子系统)。
    /// DevTools 只显示名字,不理解语义 —— 那是扩展自己的事。
    Custom,
}

/// 统一时间线的一条记录。
#[derive(Clone, Debug)]
pub struct TimelineEntry {
    pub timestamp_ms: u64,
    pub kind: TimelineKind,
    /// 扩展轨道的名字(`kind == Custom` 时由调用方给,如 `"VideoDecode"`)。
    /// 框架级两条轨道此字段为空串,`kind_label` 走固定名。
    pub track: &'static str,
    pub duration_ns: u64,
    /// CPU FrameStats 六阶段拆分(仅 CpuFrame 有意义;其他为 0)
    pub head_ns: u64,
    pub rebuild_ns: u64,
    pub after_tick_ns: u64,
    pub overlay_ns: u64,
    pub paint_ns: u64,
    pub layout_ns: u64,
    /// 本帧是否有全树 rebuild(CpuFrame)
    pub rebuilt: bool,
    /// 本帧 scoped dirty rebuild 的 element 数(CpuFrame)
    pub scoped_rebuilt: usize,
    /// 业务侧可选 detail(如 video session id / overlay name)
    pub detail: String,
}

impl TimelineEntry {
    pub fn kind_label(&self) -> &'static str {
        match self.kind {
            TimelineKind::CpuFrame => "CPU",
            TimelineKind::GpuFrame => "GPU",
            TimelineKind::Custom => {
                if self.track.is_empty() {
                    "custom"
                } else {
                    self.track
                }
            }
        }
    }
}

// ============================================================
// 线程级全局 trace(mgui 单 UI 线程模型,用 thread_local 零竞争)
// DevtoolsTrace 本身用 Mutex——单线程无竞争 ≈ RefCell
// ============================================================

thread_local! {
    /// 开关镜像:让关闭路径在拿 TRACE 锁之前就能返回。
    /// DevtoolsTrace 自己的 enabled 在锁内,只查它会先付出一次锁成本。
    static TRACE_ENABLED: Cell<bool> = const { Cell::new(false) };
    static TRACE: Mutex<DevtoolsTrace<TimelineEntry>> =
        std::sync::Mutex::new(DevtoolsTrace::new(CAPACITY));
}

/// 在 TRACE 上执行一个闭包。Mutex 保护单线程不会重入。
fn with_trace<R>(f: impl FnOnce(&DevtoolsTrace<TimelineEntry>) -> R) -> R {
    TRACE.with(|t| {
        let guard = t.lock().unwrap_or_else(|e| e.into_inner());
        f(&guard)
    })
}

// ============================================================
// 公共 API(与原 API 完全保持一致,调用方零改动)
// ============================================================

/// DT-03:开启/关闭 frame timeline 采集。默认关闭(零开销)。
pub fn set_enabled(on: bool) {
    TRACE_ENABLED.with(|c| c.set(on));
    with_trace(|t| t.set_enabled(on));
}

/// DT-03:是否正在采集 frame timeline。只读 thread-local 镜像,不拿锁。
pub fn enabled() -> bool {
    TRACE_ENABLED.with(|c| c.get())
}

/// DT-03:清空 timeline(切换窗口会话时)。
pub fn clear() {
    with_trace(|t| t.clear());
}

/// DT-03:记录一次完整的 CPU 帧管线统计(由 `run_frame` 末尾调)。
#[allow(clippy::too_many_arguments)]
pub fn push_cpu_frame(
    head_ns: u64,
    rebuild_ns: u64,
    after_tick_ns: u64,
    overlay_ns: u64,
    paint_ns: u64,
    layout_ns: u64,
    rebuilt: bool,
    scoped_rebuilt: usize,
) {
    if !enabled() {
        return;
    }
    with_trace(|t| {
        // 关闭时必须先返回,避免 now_ms / 结构体构造仍然发生。
        if !t.enabled() {
            return;
        }
        t.push(TimelineEntry {
            timestamp_ms: now_ms(),
            kind: TimelineKind::CpuFrame,
            track: "",
            duration_ns: head_ns
                .saturating_add(rebuild_ns)
                .saturating_add(after_tick_ns)
                .saturating_add(overlay_ns)
                .saturating_add(paint_ns),
            head_ns,
            rebuild_ns,
            after_tick_ns,
            overlay_ns,
            paint_ns,
            layout_ns,
            rebuilt,
            scoped_rebuilt,
            detail: String::new(),
        })
    });
}

/// DT-03:记录一次 GPU render pass timestamp query 结果(由 GpuProfiler.resolve 调)。
pub fn push_gpu_frame(gpu_ns: u64) {
    if !enabled() {
        return;
    }
    with_trace(|t| {
        if !t.enabled() {
            return;
        }
        t.push(TimelineEntry {
            timestamp_ms: now_ms(),
            kind: TimelineKind::GpuFrame,
            track: "",
            duration_ns: gpu_ns,
            head_ns: 0,
            rebuild_ns: 0,
            after_tick_ns: 0,
            overlay_ns: 0,
            paint_ns: 0,
            layout_ns: 0,
            rebuilt: false,
            scoped_rebuilt: 0,
            detail: String::new(),
        })
    });
}

/// DT-03:记录一条扩展轨道(由扩展组件调,如视频的 decode / take / input)。
///
/// `track` 是扩展自己起的名字(`'static` 是因为它是编译期常量标签,不入 detail 的
/// 运行时分配路径)。框架与 DevTools 都不解释它 —— 扩展组件换了名字,面板照常显示。
pub fn push(track: &'static str, duration_ns: u64, detail: impl Into<String>) {
    if !enabled() {
        return;
    }
    with_trace(|t| {
        if !t.enabled() {
            return;
        }
        t.push(TimelineEntry {
            timestamp_ms: now_ms(),
            kind: TimelineKind::Custom,
            track,
            duration_ns,
            head_ns: 0,
            rebuild_ns: 0,
            after_tick_ns: 0,
            overlay_ns: 0,
            paint_ns: 0,
            layout_ns: 0,
            rebuilt: false,
            scoped_rebuilt: 0,
            detail: detail.into(),
        })
    });
}

/// DT-03 导出:最近 `max` 条时间线的 JSON(`max == 0` = 全部)。
/// 手写序列化(本 crate 不加 serde):detail 里的引号/反斜杠/控制符必须转义,
/// 否则一条带特殊字符的会话名就能让整个导出成不了 JSON。
pub fn export_json(max: usize) -> String {
    let entries = peek(max);
    let mut out = String::from("[\n");
    for (i, e) in entries.iter().enumerate() {
        if i > 0 {
            out.push_str(",\n");
        }
        let _ = std::fmt::Write::write_fmt(
            &mut out,
            format_args!(
                "  {{\"t_ms\":{},\"track\":\"{}\",\"kind\":\"{}\",\"dur_ms\":{:.3},\"detail\":\"{}\"{}",
                e.timestamp_ms,
                escape_json(e.track),
                escape_json(e.kind_label()),
                e.duration_ns as f64 / 1_000_000.0,
                escape_json(&e.detail),
                cpu_breakdown_json(e),
            ),
        );
        out.push('}');
    }
    out.push_str("\n]\n");
    out
}

/// CpuFrame 的六阶段拆分(其他轨道这六项全 0,不输出假字段)。
fn cpu_breakdown_json(e: &TimelineEntry) -> String {
    if !matches!(e.kind, TimelineKind::CpuFrame) {
        return String::new();
    }
    format!(
        ",\"head_ms\":{:.3},\"rebuild_ms\":{:.3},\"after_tick_ms\":{:.3},\"overlay_ms\":{:.3},\"paint_ms\":{:.3},\"layout_ms\":{:.3},\"rebuilt\":{},\"scoped_rebuilt\":{}",
        e.head_ns as f64 / 1_000_000.0,
        e.rebuild_ns as f64 / 1_000_000.0,
        e.after_tick_ns as f64 / 1_000_000.0,
        e.overlay_ns as f64 / 1_000_000.0,
        e.paint_ns as f64 / 1_000_000.0,
        e.layout_ns as f64 / 1_000_000.0,
        e.rebuilt,
        e.scoped_rebuilt,
    )
}

/// DT-03 导出:最近 `max` 条时间线的 CSV(`max == 0` = 全部)。表头平铺六阶段,
/// 非 CPU 轨道留空 —— 与 JSON 的"不输出假字段"同一条纪律的 CSV 表达。
pub fn export_csv(max: usize) -> String {
    let entries = peek(max);
    let mut out = String::from(
        "t_ms,track,kind,dur_ms,detail,head_ms,rebuild_ms,after_tick_ms,overlay_ms,paint_ms,layout_ms,rebuilt,scoped_rebuilt\n",
    );
    for e in &entries {
        let cpu = if matches!(e.kind, TimelineKind::CpuFrame) {
            format!(
                "{:.3},{:.3},{:.3},{:.3},{:.3},{:.3},{},{}",
                e.head_ns as f64 / 1_000_000.0,
                e.rebuild_ns as f64 / 1_000_000.0,
                e.after_tick_ns as f64 / 1_000_000.0,
                e.overlay_ns as f64 / 1_000_000.0,
                e.paint_ns as f64 / 1_000_000.0,
                e.layout_ns as f64 / 1_000_000.0,
                e.rebuilt,
                e.scoped_rebuilt,
            )
        } else {
            String::from(",,,,,,,,")
        };
        let _ = std::fmt::Write::write_fmt(
            &mut out,
            format_args!(
                "{},{},{},{:.3},\"{}\",{}\n",
                e.timestamp_ms,
                csv_field(e.track),
                csv_field(e.kind_label()),
                e.duration_ns as f64 / 1_000_000.0,
                csv_field(&e.detail),
                cpu,
            ),
        );
    }
    out
}

/// JSON 字符串转义(引号、反斜杠、控制符;detail/track 是外部输入,不可信)。
fn escape_json(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            c if (c as u32) < 0x20 => {
                let _ = std::fmt::Write::write_fmt(&mut out, format_args!("\\u{:04x}", c as u32));
            }
            c => out.push(c),
        }
    }
    out
}

/// CSV 字段:含逗号/引号/换行的字段按 RFC 4180 加引号转义。
fn csv_field(s: &str) -> String {
    if s.contains([',', '"', '\n', '\r']) {
        format!("\"{}\"", s.replace('"', "\"\""))
    } else {
        s.to_owned()
    }
}

/// DT-03:取最近 `max` 条 timeline(不 drain,可重复调用)。关闭时返回空,不构造快照。
pub fn peek(max: usize) -> Vec<TimelineEntry> {
    if !enabled() {
        return Vec::new();
    }
    with_trace(|t| {
        if !t.enabled() {
            return Vec::new();
        }
        t.peek(max)
    })
}

// ============================================================
// 单元测试
// ============================================================

#[cfg(test)]
mod tests {
    use super::*;

    fn reset() {
        set_enabled(true);
        clear();
    }

    fn cleanup() {
        clear();
        set_enabled(false);
    }

    #[test]
    fn disabled_push_is_noop() {
        set_enabled(false);
        clear();
        push_cpu_frame(1, 2, 3, 4, 5, 1, false, 0);
        push_gpu_frame(100);
        assert!(peek(0).is_empty());
    }

    #[test]
    fn clear_works_while_disabled() {
        reset();
        push_cpu_frame(1, 2, 3, 4, 5, 1, false, 0);
        assert_eq!(peek(0).len(), 1);

        set_enabled(false);
        clear();
        set_enabled(true);
        assert!(peek(0).is_empty(), "关闭期间的显式 clear 必须生效");
        cleanup();
    }

    #[test]
    fn disabled_custom_push_does_not_materialize_detail() {
        use std::cell::Cell;
        use std::rc::Rc;

        struct LazyDetail(Rc<Cell<bool>>);

        impl From<LazyDetail> for String {
            fn from(v: LazyDetail) -> Self {
                v.0.set(true);
                String::from("materialized")
            }
        }

        set_enabled(false);
        clear();
        let called = Rc::new(Cell::new(false));
        push("VideoTake", 1, LazyDetail(called.clone()));
        push("VideoDecode", 1, LazyDetail(called.clone()));
        assert!(!called.get(), "关闭时不应构造扩展 detail");
        cleanup();
    }

    #[test]
    fn enabled_collects_cpu_and_gpu() {
        reset();
        push_cpu_frame(100, 200, 50, 100, 500, 80, false, 3);
        push_gpu_frame(300);
        push_cpu_frame(120, 250, 60, 90, 550, 90, true, 0);
        let snap = peek(0);
        assert_eq!(snap.len(), 3);
        assert!(matches!(snap[0].kind, TimelineKind::CpuFrame));
        assert_eq!(snap[0].duration_ns, 950); // 100+200+50+100+500
        assert!(matches!(snap[1].kind, TimelineKind::GpuFrame));
        assert_eq!(snap[1].duration_ns, 300);
        assert!(snap[2].rebuilt);
        assert_eq!(snap[2].scoped_rebuilt, 0);
        cleanup();
    }

    #[test]
    fn capacity_evicts_oldest() {
        reset();
        for i in 0..CAPACITY + 10 {
            push_cpu_frame(i as u64, 0, 0, 0, 0, 0, false, 0);
        }
        let snap = peek(0);
        assert_eq!(snap.len(), CAPACITY);
        assert_eq!(snap[0].head_ns, 10);
        cleanup();
    }

    #[test]
    fn max_truncates_recent() {
        reset();
        for i in 0..20 {
            push_cpu_frame(i, 0, 0, 0, 0, 0, false, 0);
        }
        let snap = peek(5);
        assert_eq!(snap.len(), 5);
        assert_eq!(snap[0].head_ns, 15);
        assert_eq!(snap[4].head_ns, 19);
        cleanup();
    }

    #[test]
    fn custom_tracks_recorded_with_their_own_names() {
        reset();
        // 扩展组件用自己的名字注册轨道;框架只保证它们同轴、同格式。
        push("VideoTake", 1500, "cam-01");
        push("VideoDecode", 25_000, "cam-01");
        push("VideoInput", 5_000, "cam-01");
        let snap = peek(0);
        assert_eq!(snap.len(), 3);
        assert!(matches!(snap[0].kind, TimelineKind::Custom));
        assert_eq!(snap[0].track, "VideoTake");
        assert_eq!(snap[0].kind_label(), "VideoTake");
        assert_eq!(snap[0].duration_ns, 1500);
        assert_eq!(snap[0].detail, "cam-01");
        assert_eq!(snap[1].track, "VideoDecode");
        assert_eq!(snap[2].track, "VideoInput");
        cleanup();
    }

    #[test]
    fn export_formats_escape_and_omit_fake_fields() {
        reset();
        push("VideoTake", 1_500_000, "cam-\"01\"");
        // 各段给足纳秒,毫秒三位小数不至于全舍成 0。
        push_cpu_frame(100_000, 200_000, 50_000, 100_000, 500_000, 80_000, true, 3);
        let json = export_json(0);
        assert!(json.starts_with("[\n"), "JSON 该以数组起头:{json}");
        assert!(json.contains("cam-\\\"01\\\""), "detail 里的引号必须转义:{json}");
        assert!(json.contains("\"rebuilt\":true"), "CpuFrame 要带六阶段与 rebuild 标记:{json}");
        let video_line = json.lines().find(|l| l.contains("VideoTake")).expect("有 VideoTake 行");
        assert!(!video_line.contains("head_ms"), "非 CPU 轨道不许输出假拆分:{video_line}");
        let csv = export_csv(0);
        let lines: Vec<&str> = csv.lines().collect();
        assert_eq!(lines.len(), 3, "表头 + 两条:{csv}");
        assert!(lines[1].contains("\"cam-\"\"01\"\""), "CSV 含引号的字段必须 RFC4180 引号包裹:{csv}");
        assert!(lines[2].contains("true,3"), "CpuFrame 行的 rebuilt/scoped 要落在末尾两列:{csv}");
        assert_eq!(export_json(1).matches("\"t_ms\"").count(), 1, "max 截断只留最近一条");
        cleanup();
    }

    #[test]
    fn clear_empties() {
        reset();
        for _ in 0..10 {
            push_cpu_frame(1, 0, 0, 0, 0, 0, false, 0);
        }
        clear();
        assert!(peek(0).is_empty());
        cleanup();
    }
}