mgui-agent 1.0.0

mgui 0.4 Headless/Agent 工具链:命名 scene + 软件快照 PNG + 语义树 JSON + 脚本回放与 motion trace
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
//! CLI 与真实窗口共享的内置场景集合。
//!
//! 场景只负责返回现有 `WidgetNode`;headless 快照与桌面 `AppSpec` 都从这里取,
//! 避免“CLI 能跑 flagship,窗口里却拼了另一棵树”。

use crate::{Scene, SceneRegistry};
use mgui_components::{ButtonWidget, ColumnWidget, ContainerWidget, ListViewWidget, TextFieldWidget, TextWidget};
use mgui_core::layout::SizedBoxWidget;
use mgui_core::{single_width_signature, Color, InvalidationScope, MeasureKey, QueryCache, QueryKey, Size, WidgetNode};
use mgui_runtime::app::{CommandId, CommandOutcome, CommandRouter};
use mgui_text::{TextRuntime, TextRuntimeHandle};
use std::cell::{Cell, RefCell};
use std::rc::Rc;

pub struct EmptyScene;
impl Scene for EmptyScene {
    fn name(&self) -> &'static str {
        "empty"
    }
    fn build(&self) -> WidgetNode {
        WidgetNode::new(ContainerWidget::new())
    }
}

pub struct ButtonScene;
impl Scene for ButtonScene {
    fn name(&self) -> &'static str {
        "button"
    }
    fn build(&self) -> WidgetNode {
        WidgetNode::new(
            ContainerWidget::new().child(ButtonWidget::new(Size::new(160.0, 48.0)).with_text("Hello", 16.0)),
        )
    }
}

/// 0.5 M0 旗舰场景骨架:真实组件组合,不是新树/新状态模型。
pub struct FlagshipScene;
impl Scene for FlagshipScene {
    fn name(&self) -> &'static str {
        "flagship"
    }
    fn build(&self) -> WidgetNode {
        let list =
            ListViewWidget::builder(10_000, |i| WidgetNode::new(TextWidget::new(format!("row {i}")).with_size(14.0)))
                .with_item_height(24.0)
                .with_height(280.0);
        let video_tile = WidgetNode::new(mgui_core::RRectWidget::new(
            Size::new(420.0, 160.0),
            Color::rgba(0.10, 0.12, 0.16, 1.0),
            4.0,
        ));
        let mut column = ColumnWidget::new(6.0);
        column = column.push(TextWidget::new("mgui flagship skeleton").with_size(20.0));
        column = column.push(ButtonWidget::new(Size::new(160.0, 40.0)).with_text("Open", 16.0));
        column = column.push(video_tile);
        column = column.push(SizedBoxWidget::sized(420.0, 280.0, list));
        WidgetNode::new(ContainerWidget::new().child(column))
    }
}

/// 0.6 M2A:grapheme / IME replay 的最小真实场景。
///
/// 用真实的 `TextFieldWidget`(而不是测试替身),脚本的指针/键盘/IME 事件
/// 走与桌面相同的 shell → 焦点 → WidgetEvent 路由。
pub struct TextEditingScene;
impl Scene for TextEditingScene {
    fn name(&self) -> &'static str {
        "text_editing"
    }
    fn build(&self) -> WidgetNode {
        let field = TextFieldWidget::new(360.0, 44.0).placeholder("IME replay").with_font_size(18.0);
        WidgetNode::new(ContainerWidget::new().child(WidgetNode::new(field)))
    }
}

/// 0.6 M3:命令路由 + 共享状态的语义 source。
///
/// 场景持有真实 `CommandRouter`(与桌面同一实现),`command` 脚本事件由宿主
/// 投递到这里;处理器只改这个场景自己的共享状态,统计由 `Scene` 钩子写入 trace。
pub struct CommandRouteScene {
    router: RefCell<CommandRouter>,
    shared: Rc<RefCell<RouteState>>,
}

#[derive(Default)]
struct RouteState {
    revision: u64,
}

impl Default for CommandRouteScene {
    fn default() -> Self {
        let shared = Rc::new(RefCell::new(RouteState::default()));
        let mut router = CommandRouter::new();
        let increment_shared = Rc::clone(&shared);
        router.register(CommandId::new(1), move |_| {
            let mut state = increment_shared.borrow_mut();
            state.revision = state.revision.wrapping_add(1);
            CommandOutcome::Consumed
        });
        router.register(CommandId::new(2), |_| CommandOutcome::PassThrough);
        Self { router: RefCell::new(router), shared }
    }
}

impl Scene for CommandRouteScene {
    fn name(&self) -> &'static str {
        "command_route"
    }

    fn build(&self) -> WidgetNode {
        let column = ColumnWidget::new(8.0)
            .push(TextWidget::new("command route / shared state").with_size(16.0))
            .push(ButtonWidget::new(Size::new(220.0, 44.0)).with_text("increment (menu id=1)", 13.0))
            .push(ButtonWidget::new(Size::new(220.0, 44.0)).with_text("passthrough (id=2)", 13.0));
        WidgetNode::new(ContainerWidget::new().child(column))
    }

    fn command_router(&self) -> Option<&RefCell<CommandRouter>> {
        Some(&self.router)
    }

    fn shared_state_summary(&self) -> Option<String> {
        Some(format!("revision={}", self.shared.borrow().revision))
    }
}

/// 0.6 M3 §8.5:Tab / Enter / Escape 的 L1 确定性 journey 场景。
///
/// 三个可聚焦按钮带稳定 `a11y_label`,焦点标签与语义 revision bump 由宿主
/// 每帧写入 trace;`shared_state` 记录 Enter/Escape 的真实激活次数。
pub struct A11yJourneyScene {
    activations: Rc<Cell<u32>>,
}

impl Default for A11yJourneyScene {
    fn default() -> Self {
        Self { activations: Rc::new(Cell::new(0)) }
    }
}

impl Scene for A11yJourneyScene {
    fn name(&self) -> &'static str {
        "a11y_journey"
    }

    fn build(&self) -> WidgetNode {
        let button = |label: &'static str, activations: &Rc<Cell<u32>>| {
            let counter = Rc::clone(activations);
            ButtonWidget::new(Size::new(240.0, 44.0))
                .with_text(label, 14.0)
                .with_a11y_label(label)
                .on_press(move || counter.set(counter.get() + 1))
        };
        let column = ColumnWidget::new(8.0)
            .push(button("Journey A", &self.activations))
            .push(button("Journey B", &self.activations))
            .push(button("Journey C", &self.activations));
        WidgetNode::new(ContainerWidget::new().child(column))
    }

    fn shared_state_summary(&self) -> Option<String> {
        Some(format!("activations={}", self.activations.get()))
    }
}

/// 0.7 M0:Text Runtime 隔离场景。两个应用级运行时各自持有字体栈/行高;
/// command id=1 只改 primary,secondary generation 必须保持不动。
pub struct TextRuntimeIsolationScene {
    primary: TextRuntimeHandle,
    secondary: TextRuntimeHandle,
    router: RefCell<CommandRouter>,
}

impl Default for TextRuntimeIsolationScene {
    fn default() -> Self {
        let primary = TextRuntime::with_config("serif", 1.2);
        let secondary = TextRuntime::with_config("sans-serif", 1.6);
        let primary_for_command = primary.clone();
        let mut router = CommandRouter::new();
        router.register(CommandId::new(1), move |_| {
            primary_for_command.set_line_height(1.8);
            CommandOutcome::Consumed
        });
        Self { primary, secondary, router: RefCell::new(router) }
    }
}

impl Scene for TextRuntimeIsolationScene {
    fn name(&self) -> &'static str {
        "text_runtime_isolation"
    }

    fn build(&self) -> WidgetNode {
        let column = ColumnWidget::new(8.0)
            .push(TextWidget::new("primary runtime / serif 1.2").with_size(16.0))
            .push(TextWidget::new("secondary runtime / sans-serif 1.6").with_size(16.0));
        WidgetNode::new(ContainerWidget::new().child(column))
    }

    fn command_router(&self) -> Option<&RefCell<CommandRouter>> {
        Some(&self.router)
    }

    fn shared_state_summary(&self) -> Option<String> {
        Some(format!(
            "primary_stack={} primary_line_height={:.2} primary_gen={} secondary_gen={}",
            self.primary.font_stack(),
            self.primary.line_height(),
            self.primary.style_generation(),
            self.secondary.style_generation(),
        ))
    }

    fn text_runtime_summary(&self) -> Option<String> {
        Some(format!(
            "primary_gen={} primary_dpr={:.2} secondary_gen={} secondary_dpr={:.2}",
            self.primary.style_generation(),
            self.primary.dpr(),
            self.secondary.style_generation(),
            self.secondary.dpr(),
        ))
    }
}

/// 0.7 M0:应用级缓存失效场景。command id=2 触发 lookup,id=1 按 Group(7) 标 stale。
pub struct QueryCacheScene {
    cache: QueryCache<u32>,
    router: RefCell<CommandRouter>,
}

impl Default for QueryCacheScene {
    fn default() -> Self {
        let cache = QueryCache::new(8, 1024, |_| 4);
        cache.insert(QueryKey::new(1), std::rc::Rc::new(1), 7);
        cache.insert(QueryKey::new(2), std::rc::Rc::new(2), 8);
        let lookup_cache = cache.clone();
        let invalidate_cache = cache.clone();
        let mut router = CommandRouter::new();
        router.register(CommandId::new(1), move |_| {
            invalidate_cache.invalidate(InvalidationScope::Group(7));
            CommandOutcome::Consumed
        });
        router.register(CommandId::new(2), move |_| {
            let _ = lookup_cache.lookup(QueryKey::new(1));
            CommandOutcome::Consumed
        });
        Self { cache, router: RefCell::new(router) }
    }
}

impl Scene for QueryCacheScene {
    fn name(&self) -> &'static str {
        "query_cache_invalidation"
    }

    fn build(&self) -> WidgetNode {
        let column = ColumnWidget::new(8.0)
            .push(TextWidget::new("query cache / group invalidation").with_size(16.0))
            .push(ButtonWidget::new(Size::new(220.0, 44.0)).with_text("invalidate group 7", 13.0));
        WidgetNode::new(ContainerWidget::new().child(column))
    }

    fn command_router(&self) -> Option<&RefCell<CommandRouter>> {
        Some(&self.router)
    }

    fn shared_state_summary(&self) -> Option<String> {
        let stats = self.cache.stats();
        Some(format!(
            "entries={} fresh_hits={} stale_hits={} invalidations={}",
            self.cache.len(),
            stats.fresh_hits,
            stats.stale_hits,
            stats.invalidations,
        ))
    }

    fn cache_scope_summary(&self) -> Option<String> {
        let stats = self.cache.stats();
        Some(format!("scope=Group(7) entries={} invalidations={}", self.cache.len(), stats.invalidations,))
    }
}

/// 0.9 M0:AppServices 用户入口 journey。
///
/// 不打开真实目录,不读墙钟;用确定性的内存摘要模拟设置 / 最近文件 / 崩溃记录,
/// 验证菜单与面板入口提交后,shared_state 与 persistence 摘要能被 trace 定位。
pub struct AppServicesJourneyScene {
    settings: Rc<RefCell<Vec<(String, String)>>>,
    recent: Rc<RefCell<Vec<String>>>,
    crashes: Rc<RefCell<Vec<String>>>,
    router: RefCell<CommandRouter>,
}

impl Default for AppServicesJourneyScene {
    fn default() -> Self {
        let settings = Rc::new(RefCell::new(vec![("showcase.high_contrast".into(), "0".into())]));
        let recent = Rc::new(RefCell::new(Vec::new()));
        let crashes = Rc::new(RefCell::new(Vec::new()));

        let toggle_settings = Rc::clone(&settings);
        let push_recent = Rc::clone(&recent);
        let record_crash = Rc::clone(&crashes);
        let clear_recent = Rc::clone(&recent);
        let clear_crashes = Rc::clone(&crashes);

        let mut router = CommandRouter::new();
        router
            .register(CommandId::new(1), move |_| {
                let mut settings = toggle_settings.borrow_mut();
                let current = settings[0].1 == "1";
                settings[0].1 = if current { "0" } else { "1" }.into();
                CommandOutcome::Consumed
            })
            .register(CommandId::new(2), move |_| {
                let mut recent = push_recent.borrow_mut();
                if !recent.first().map(|p| p == "doc.rs").unwrap_or(false) {
                    recent.insert(0, "doc.rs".into());
                }
                CommandOutcome::Consumed
            })
            .register(CommandId::new(3), move |_| {
                record_crash.borrow_mut().push("scene:summary".into());
                CommandOutcome::Consumed
            })
            .register(CommandId::new(4), move |_| {
                clear_recent.borrow_mut().clear();
                CommandOutcome::Consumed
            })
            .register(CommandId::new(5), move |_| {
                clear_crashes.borrow_mut().clear();
                CommandOutcome::Consumed
            });

        Self { settings, recent, crashes, router: RefCell::new(router) }
    }
}

impl AppServicesJourneyScene {
    fn state_summary(&self) -> String {
        let settings = self.settings.borrow();
        let recent = self.recent.borrow();
        let crashes = self.crashes.borrow();
        let setting = settings.first().map(|(k, v)| format!("{k}={v}")).unwrap_or_else(|| "none".into());
        format!("settings={setting} recent={} crashes={}", recent.len(), crashes.len())
    }
}

impl Scene for AppServicesJourneyScene {
    fn name(&self) -> &'static str {
        "app_services_journey"
    }

    fn build(&self) -> WidgetNode {
        let column = ColumnWidget::new(8.0)
            .push(TextWidget::new("app services / typed user entries").with_size(16.0))
            .push(TextWidget::new(self.state_summary()).with_size(13.0))
            .push(ButtonWidget::new(Size::new(240.0, 44.0)).with_text("settings / recent / crashes", 13.0));
        WidgetNode::new(ContainerWidget::new().child(column))
    }

    fn command_router(&self) -> Option<&RefCell<CommandRouter>> {
        Some(&self.router)
    }

    fn shared_state_summary(&self) -> Option<String> {
        Some(self.state_summary())
    }

    fn persistence_summary(&self) -> Option<String> {
        Some(format!("schema=1 owner=held recovery=none {}", self.state_summary()))
    }
}

/// 0.9 M0:双窗口不同 DPR + 跨屏移动。
///
/// 窗口 A 固定在 DPR 1.0,窗口 B 接受 DPR 变化;两者各自持有 `TextRuntimeHandle`
/// 并生成 `MeasureKey`。这验证的是测量环境与命中测试的契约,不伪造物理显示器。
pub struct MultiDprWindowsScene {
    window_a: TextRuntimeHandle,
    window_b: TextRuntimeHandle,
    revision: Cell<u64>,
}

impl Default for MultiDprWindowsScene {
    fn default() -> Self {
        let window_a = TextRuntime::with_config("serif", 1.2);
        let window_b = TextRuntime::with_config("sans-serif", 1.6);
        window_a.set_dpr(1.0);
        window_b.set_dpr(1.5);
        Self { window_a, window_b, revision: Cell::new(0) }
    }
}

impl MultiDprWindowsScene {
    fn measure_key(runtime: &TextRuntimeHandle, width: f32, revision: u64) -> MeasureKey {
        MeasureKey::new(single_width_signature(width), runtime.style_generation(), runtime.dpr(), revision)
    }
}

impl Scene for MultiDprWindowsScene {
    fn name(&self) -> &'static str {
        "multi_dpr_windows"
    }

    fn build(&self) -> WidgetNode {
        let column = ColumnWidget::new(8.0)
            .push(TextWidget::new("window A / dpr 1.00").with_size(16.0))
            .push(TextWidget::new("window B / dpr 1.50").with_size(16.0))
            .push(TextWidget::new("cross-screen move updates B only").with_size(13.0));
        WidgetNode::new(ContainerWidget::new().child(column))
    }

    fn shared_state_summary(&self) -> Option<String> {
        Some(format!(
            "window_a_dpr={:.2} window_b_dpr={:.2} revision={}",
            self.window_a.dpr(),
            self.window_b.dpr(),
            self.revision.get(),
        ))
    }

    fn text_runtime_summary(&self) -> Option<String> {
        let revision = self.revision.get();
        let a = Self::measure_key(&self.window_a, 800.0, revision);
        let b = Self::measure_key(&self.window_b, 800.0, revision);
        Some(format!("window_a_key={a:?} window_b_key={b:?}"))
    }

    fn on_scale_factor_changed(&self, dpr: f32) {
        if (self.window_b.dpr() - dpr).abs() > f32::EPSILON {
            self.window_b.set_dpr(dpr);
            self.revision.set(self.revision.get() + 1);
        }
    }
}

/// 内置场景注册表,供 CLI 与桌面 `mgui::scene_app` 共享。
pub fn builtin_scenes() -> SceneRegistry {
    let mut registry = SceneRegistry::new();
    registry.register(Box::new(EmptyScene));
    registry.register(Box::new(ButtonScene));
    registry.register(Box::new(FlagshipScene));
    registry.register(Box::new(TextEditingScene));
    registry.register(Box::new(CommandRouteScene::default()));
    registry.register(Box::new(A11yJourneyScene::default()));
    registry.register(Box::new(TextRuntimeIsolationScene::default()));
    registry.register(Box::new(QueryCacheScene::default()));
    registry.register(Box::new(AppServicesJourneyScene::default()));
    registry.register(Box::new(MultiDprWindowsScene::default()));
    registry
}

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

    #[test]
    fn builtin_scenes_are_stably_named_and_buildable() {
        let registry = builtin_scenes();
        assert_eq!(
            registry.names(),
            vec![
                "empty",
                "button",
                "flagship",
                "text_editing",
                "command_route",
                "a11y_journey",
                "text_runtime_isolation",
                "query_cache_invalidation",
                "app_services_journey",
                "multi_dpr_windows",
            ]
        );
        for name in registry.names() {
            let _ = registry.build(name).unwrap_or_else(|e| panic!("scene {name}: {e}"));
        }
        assert!(registry.build("missing").is_err());
    }
}