Skip to main content

mgui_agent/
scenes.rs

1//! CLI 与真实窗口共享的内置场景集合。
2//!
3//! 场景只负责返回现有 `WidgetNode`;headless 快照与桌面 `AppSpec` 都从这里取,
4//! 避免“CLI 能跑 flagship,窗口里却拼了另一棵树”。
5
6use crate::{Scene, SceneRegistry};
7use mgui_components::{ButtonWidget, ColumnWidget, ContainerWidget, ListViewWidget, TextFieldWidget, TextWidget};
8use mgui_core::layout::SizedBoxWidget;
9use mgui_core::{single_width_signature, Color, InvalidationScope, MeasureKey, QueryCache, QueryKey, Size, WidgetNode};
10use mgui_runtime::app::{CommandId, CommandOutcome, CommandRouter};
11use mgui_text::{TextRuntime, TextRuntimeHandle};
12use std::cell::{Cell, RefCell};
13use std::rc::Rc;
14
15pub struct EmptyScene;
16impl Scene for EmptyScene {
17    fn name(&self) -> &'static str {
18        "empty"
19    }
20    fn build(&self) -> WidgetNode {
21        WidgetNode::new(ContainerWidget::new())
22    }
23}
24
25pub struct ButtonScene;
26impl Scene for ButtonScene {
27    fn name(&self) -> &'static str {
28        "button"
29    }
30    fn build(&self) -> WidgetNode {
31        WidgetNode::new(
32            ContainerWidget::new().child(ButtonWidget::new(Size::new(160.0, 48.0)).with_text("Hello", 16.0)),
33        )
34    }
35}
36
37/// 0.5 M0 旗舰场景骨架:真实组件组合,不是新树/新状态模型。
38pub struct FlagshipScene;
39impl Scene for FlagshipScene {
40    fn name(&self) -> &'static str {
41        "flagship"
42    }
43    fn build(&self) -> WidgetNode {
44        let list =
45            ListViewWidget::builder(10_000, |i| WidgetNode::new(TextWidget::new(format!("row {i}")).with_size(14.0)))
46                .with_item_height(24.0)
47                .with_height(280.0);
48        let video_tile = WidgetNode::new(mgui_core::RRectWidget::new(
49            Size::new(420.0, 160.0),
50            Color::rgba(0.10, 0.12, 0.16, 1.0),
51            4.0,
52        ));
53        let mut column = ColumnWidget::new(6.0);
54        column = column.push(TextWidget::new("mgui flagship skeleton").with_size(20.0));
55        column = column.push(ButtonWidget::new(Size::new(160.0, 40.0)).with_text("Open", 16.0));
56        column = column.push(video_tile);
57        column = column.push(SizedBoxWidget::sized(420.0, 280.0, list));
58        WidgetNode::new(ContainerWidget::new().child(column))
59    }
60}
61
62/// 0.6 M2A:grapheme / IME replay 的最小真实场景。
63///
64/// 用真实的 `TextFieldWidget`(而不是测试替身),脚本的指针/键盘/IME 事件
65/// 走与桌面相同的 shell → 焦点 → WidgetEvent 路由。
66pub struct TextEditingScene;
67impl Scene for TextEditingScene {
68    fn name(&self) -> &'static str {
69        "text_editing"
70    }
71    fn build(&self) -> WidgetNode {
72        let field = TextFieldWidget::new(360.0, 44.0).placeholder("IME replay").with_font_size(18.0);
73        WidgetNode::new(ContainerWidget::new().child(WidgetNode::new(field)))
74    }
75}
76
77/// 0.6 M3:命令路由 + 共享状态的语义 source。
78///
79/// 场景持有真实 `CommandRouter`(与桌面同一实现),`command` 脚本事件由宿主
80/// 投递到这里;处理器只改这个场景自己的共享状态,统计由 `Scene` 钩子写入 trace。
81pub struct CommandRouteScene {
82    router: RefCell<CommandRouter>,
83    shared: Rc<RefCell<RouteState>>,
84}
85
86#[derive(Default)]
87struct RouteState {
88    revision: u64,
89}
90
91impl Default for CommandRouteScene {
92    fn default() -> Self {
93        let shared = Rc::new(RefCell::new(RouteState::default()));
94        let mut router = CommandRouter::new();
95        let increment_shared = Rc::clone(&shared);
96        router.register(CommandId::new(1), move |_| {
97            let mut state = increment_shared.borrow_mut();
98            state.revision = state.revision.wrapping_add(1);
99            CommandOutcome::Consumed
100        });
101        router.register(CommandId::new(2), |_| CommandOutcome::PassThrough);
102        Self { router: RefCell::new(router), shared }
103    }
104}
105
106impl Scene for CommandRouteScene {
107    fn name(&self) -> &'static str {
108        "command_route"
109    }
110
111    fn build(&self) -> WidgetNode {
112        let column = ColumnWidget::new(8.0)
113            .push(TextWidget::new("command route / shared state").with_size(16.0))
114            .push(ButtonWidget::new(Size::new(220.0, 44.0)).with_text("increment (menu id=1)", 13.0))
115            .push(ButtonWidget::new(Size::new(220.0, 44.0)).with_text("passthrough (id=2)", 13.0));
116        WidgetNode::new(ContainerWidget::new().child(column))
117    }
118
119    fn command_router(&self) -> Option<&RefCell<CommandRouter>> {
120        Some(&self.router)
121    }
122
123    fn shared_state_summary(&self) -> Option<String> {
124        Some(format!("revision={}", self.shared.borrow().revision))
125    }
126}
127
128/// 0.6 M3 §8.5:Tab / Enter / Escape 的 L1 确定性 journey 场景。
129///
130/// 三个可聚焦按钮带稳定 `a11y_label`,焦点标签与语义 revision bump 由宿主
131/// 每帧写入 trace;`shared_state` 记录 Enter/Escape 的真实激活次数。
132pub struct A11yJourneyScene {
133    activations: Rc<Cell<u32>>,
134}
135
136impl Default for A11yJourneyScene {
137    fn default() -> Self {
138        Self { activations: Rc::new(Cell::new(0)) }
139    }
140}
141
142impl Scene for A11yJourneyScene {
143    fn name(&self) -> &'static str {
144        "a11y_journey"
145    }
146
147    fn build(&self) -> WidgetNode {
148        let button = |label: &'static str, activations: &Rc<Cell<u32>>| {
149            let counter = Rc::clone(activations);
150            ButtonWidget::new(Size::new(240.0, 44.0))
151                .with_text(label, 14.0)
152                .with_a11y_label(label)
153                .on_press(move || counter.set(counter.get() + 1))
154        };
155        let column = ColumnWidget::new(8.0)
156            .push(button("Journey A", &self.activations))
157            .push(button("Journey B", &self.activations))
158            .push(button("Journey C", &self.activations));
159        WidgetNode::new(ContainerWidget::new().child(column))
160    }
161
162    fn shared_state_summary(&self) -> Option<String> {
163        Some(format!("activations={}", self.activations.get()))
164    }
165}
166
167/// 0.7 M0:Text Runtime 隔离场景。两个应用级运行时各自持有字体栈/行高;
168/// command id=1 只改 primary,secondary generation 必须保持不动。
169pub struct TextRuntimeIsolationScene {
170    primary: TextRuntimeHandle,
171    secondary: TextRuntimeHandle,
172    router: RefCell<CommandRouter>,
173}
174
175impl Default for TextRuntimeIsolationScene {
176    fn default() -> Self {
177        let primary = TextRuntime::with_config("serif", 1.2);
178        let secondary = TextRuntime::with_config("sans-serif", 1.6);
179        let primary_for_command = primary.clone();
180        let mut router = CommandRouter::new();
181        router.register(CommandId::new(1), move |_| {
182            primary_for_command.set_line_height(1.8);
183            CommandOutcome::Consumed
184        });
185        Self { primary, secondary, router: RefCell::new(router) }
186    }
187}
188
189impl Scene for TextRuntimeIsolationScene {
190    fn name(&self) -> &'static str {
191        "text_runtime_isolation"
192    }
193
194    fn build(&self) -> WidgetNode {
195        let column = ColumnWidget::new(8.0)
196            .push(TextWidget::new("primary runtime / serif 1.2").with_size(16.0))
197            .push(TextWidget::new("secondary runtime / sans-serif 1.6").with_size(16.0));
198        WidgetNode::new(ContainerWidget::new().child(column))
199    }
200
201    fn command_router(&self) -> Option<&RefCell<CommandRouter>> {
202        Some(&self.router)
203    }
204
205    fn shared_state_summary(&self) -> Option<String> {
206        Some(format!(
207            "primary_stack={} primary_line_height={:.2} primary_gen={} secondary_gen={}",
208            self.primary.font_stack(),
209            self.primary.line_height(),
210            self.primary.style_generation(),
211            self.secondary.style_generation(),
212        ))
213    }
214
215    fn text_runtime_summary(&self) -> Option<String> {
216        Some(format!(
217            "primary_gen={} primary_dpr={:.2} secondary_gen={} secondary_dpr={:.2}",
218            self.primary.style_generation(),
219            self.primary.dpr(),
220            self.secondary.style_generation(),
221            self.secondary.dpr(),
222        ))
223    }
224}
225
226/// 0.7 M0:应用级缓存失效场景。command id=2 触发 lookup,id=1 按 Group(7) 标 stale。
227pub struct QueryCacheScene {
228    cache: QueryCache<u32>,
229    router: RefCell<CommandRouter>,
230}
231
232impl Default for QueryCacheScene {
233    fn default() -> Self {
234        let cache = QueryCache::new(8, 1024, |_| 4);
235        cache.insert(QueryKey::new(1), std::rc::Rc::new(1), 7);
236        cache.insert(QueryKey::new(2), std::rc::Rc::new(2), 8);
237        let lookup_cache = cache.clone();
238        let invalidate_cache = cache.clone();
239        let mut router = CommandRouter::new();
240        router.register(CommandId::new(1), move |_| {
241            invalidate_cache.invalidate(InvalidationScope::Group(7));
242            CommandOutcome::Consumed
243        });
244        router.register(CommandId::new(2), move |_| {
245            let _ = lookup_cache.lookup(QueryKey::new(1));
246            CommandOutcome::Consumed
247        });
248        Self { cache, router: RefCell::new(router) }
249    }
250}
251
252impl Scene for QueryCacheScene {
253    fn name(&self) -> &'static str {
254        "query_cache_invalidation"
255    }
256
257    fn build(&self) -> WidgetNode {
258        let column = ColumnWidget::new(8.0)
259            .push(TextWidget::new("query cache / group invalidation").with_size(16.0))
260            .push(ButtonWidget::new(Size::new(220.0, 44.0)).with_text("invalidate group 7", 13.0));
261        WidgetNode::new(ContainerWidget::new().child(column))
262    }
263
264    fn command_router(&self) -> Option<&RefCell<CommandRouter>> {
265        Some(&self.router)
266    }
267
268    fn shared_state_summary(&self) -> Option<String> {
269        let stats = self.cache.stats();
270        Some(format!(
271            "entries={} fresh_hits={} stale_hits={} invalidations={}",
272            self.cache.len(),
273            stats.fresh_hits,
274            stats.stale_hits,
275            stats.invalidations,
276        ))
277    }
278
279    fn cache_scope_summary(&self) -> Option<String> {
280        let stats = self.cache.stats();
281        Some(format!("scope=Group(7) entries={} invalidations={}", self.cache.len(), stats.invalidations,))
282    }
283}
284
285/// 0.9 M0:AppServices 用户入口 journey。
286///
287/// 不打开真实目录,不读墙钟;用确定性的内存摘要模拟设置 / 最近文件 / 崩溃记录,
288/// 验证菜单与面板入口提交后,shared_state 与 persistence 摘要能被 trace 定位。
289pub struct AppServicesJourneyScene {
290    settings: Rc<RefCell<Vec<(String, String)>>>,
291    recent: Rc<RefCell<Vec<String>>>,
292    crashes: Rc<RefCell<Vec<String>>>,
293    router: RefCell<CommandRouter>,
294}
295
296impl Default for AppServicesJourneyScene {
297    fn default() -> Self {
298        let settings = Rc::new(RefCell::new(vec![("showcase.high_contrast".into(), "0".into())]));
299        let recent = Rc::new(RefCell::new(Vec::new()));
300        let crashes = Rc::new(RefCell::new(Vec::new()));
301
302        let toggle_settings = Rc::clone(&settings);
303        let push_recent = Rc::clone(&recent);
304        let record_crash = Rc::clone(&crashes);
305        let clear_recent = Rc::clone(&recent);
306        let clear_crashes = Rc::clone(&crashes);
307
308        let mut router = CommandRouter::new();
309        router
310            .register(CommandId::new(1), move |_| {
311                let mut settings = toggle_settings.borrow_mut();
312                let current = settings[0].1 == "1";
313                settings[0].1 = if current { "0" } else { "1" }.into();
314                CommandOutcome::Consumed
315            })
316            .register(CommandId::new(2), move |_| {
317                let mut recent = push_recent.borrow_mut();
318                if !recent.first().map(|p| p == "doc.rs").unwrap_or(false) {
319                    recent.insert(0, "doc.rs".into());
320                }
321                CommandOutcome::Consumed
322            })
323            .register(CommandId::new(3), move |_| {
324                record_crash.borrow_mut().push("scene:summary".into());
325                CommandOutcome::Consumed
326            })
327            .register(CommandId::new(4), move |_| {
328                clear_recent.borrow_mut().clear();
329                CommandOutcome::Consumed
330            })
331            .register(CommandId::new(5), move |_| {
332                clear_crashes.borrow_mut().clear();
333                CommandOutcome::Consumed
334            });
335
336        Self { settings, recent, crashes, router: RefCell::new(router) }
337    }
338}
339
340impl AppServicesJourneyScene {
341    fn state_summary(&self) -> String {
342        let settings = self.settings.borrow();
343        let recent = self.recent.borrow();
344        let crashes = self.crashes.borrow();
345        let setting = settings.first().map(|(k, v)| format!("{k}={v}")).unwrap_or_else(|| "none".into());
346        format!("settings={setting} recent={} crashes={}", recent.len(), crashes.len())
347    }
348}
349
350impl Scene for AppServicesJourneyScene {
351    fn name(&self) -> &'static str {
352        "app_services_journey"
353    }
354
355    fn build(&self) -> WidgetNode {
356        let column = ColumnWidget::new(8.0)
357            .push(TextWidget::new("app services / typed user entries").with_size(16.0))
358            .push(TextWidget::new(self.state_summary()).with_size(13.0))
359            .push(ButtonWidget::new(Size::new(240.0, 44.0)).with_text("settings / recent / crashes", 13.0));
360        WidgetNode::new(ContainerWidget::new().child(column))
361    }
362
363    fn command_router(&self) -> Option<&RefCell<CommandRouter>> {
364        Some(&self.router)
365    }
366
367    fn shared_state_summary(&self) -> Option<String> {
368        Some(self.state_summary())
369    }
370
371    fn persistence_summary(&self) -> Option<String> {
372        Some(format!("schema=1 owner=held recovery=none {}", self.state_summary()))
373    }
374}
375
376/// 0.9 M0:双窗口不同 DPR + 跨屏移动。
377///
378/// 窗口 A 固定在 DPR 1.0,窗口 B 接受 DPR 变化;两者各自持有 `TextRuntimeHandle`
379/// 并生成 `MeasureKey`。这验证的是测量环境与命中测试的契约,不伪造物理显示器。
380pub struct MultiDprWindowsScene {
381    window_a: TextRuntimeHandle,
382    window_b: TextRuntimeHandle,
383    revision: Cell<u64>,
384}
385
386impl Default for MultiDprWindowsScene {
387    fn default() -> Self {
388        let window_a = TextRuntime::with_config("serif", 1.2);
389        let window_b = TextRuntime::with_config("sans-serif", 1.6);
390        window_a.set_dpr(1.0);
391        window_b.set_dpr(1.5);
392        Self { window_a, window_b, revision: Cell::new(0) }
393    }
394}
395
396impl MultiDprWindowsScene {
397    fn measure_key(runtime: &TextRuntimeHandle, width: f32, revision: u64) -> MeasureKey {
398        MeasureKey::new(single_width_signature(width), runtime.style_generation(), runtime.dpr(), revision)
399    }
400}
401
402impl Scene for MultiDprWindowsScene {
403    fn name(&self) -> &'static str {
404        "multi_dpr_windows"
405    }
406
407    fn build(&self) -> WidgetNode {
408        let column = ColumnWidget::new(8.0)
409            .push(TextWidget::new("window A / dpr 1.00").with_size(16.0))
410            .push(TextWidget::new("window B / dpr 1.50").with_size(16.0))
411            .push(TextWidget::new("cross-screen move updates B only").with_size(13.0));
412        WidgetNode::new(ContainerWidget::new().child(column))
413    }
414
415    fn shared_state_summary(&self) -> Option<String> {
416        Some(format!(
417            "window_a_dpr={:.2} window_b_dpr={:.2} revision={}",
418            self.window_a.dpr(),
419            self.window_b.dpr(),
420            self.revision.get(),
421        ))
422    }
423
424    fn text_runtime_summary(&self) -> Option<String> {
425        let revision = self.revision.get();
426        let a = Self::measure_key(&self.window_a, 800.0, revision);
427        let b = Self::measure_key(&self.window_b, 800.0, revision);
428        Some(format!("window_a_key={a:?} window_b_key={b:?}"))
429    }
430
431    fn on_scale_factor_changed(&self, dpr: f32) {
432        if (self.window_b.dpr() - dpr).abs() > f32::EPSILON {
433            self.window_b.set_dpr(dpr);
434            self.revision.set(self.revision.get() + 1);
435        }
436    }
437}
438
439/// 内置场景注册表,供 CLI 与桌面 `mgui::scene_app` 共享。
440pub fn builtin_scenes() -> SceneRegistry {
441    let mut registry = SceneRegistry::new();
442    registry.register(Box::new(EmptyScene));
443    registry.register(Box::new(ButtonScene));
444    registry.register(Box::new(FlagshipScene));
445    registry.register(Box::new(TextEditingScene));
446    registry.register(Box::new(CommandRouteScene::default()));
447    registry.register(Box::new(A11yJourneyScene::default()));
448    registry.register(Box::new(TextRuntimeIsolationScene::default()));
449    registry.register(Box::new(QueryCacheScene::default()));
450    registry.register(Box::new(AppServicesJourneyScene::default()));
451    registry.register(Box::new(MultiDprWindowsScene::default()));
452    registry
453}
454
455#[cfg(test)]
456mod tests {
457    use super::*;
458
459    #[test]
460    fn builtin_scenes_are_stably_named_and_buildable() {
461        let registry = builtin_scenes();
462        assert_eq!(
463            registry.names(),
464            vec![
465                "empty",
466                "button",
467                "flagship",
468                "text_editing",
469                "command_route",
470                "a11y_journey",
471                "text_runtime_isolation",
472                "query_cache_invalidation",
473                "app_services_journey",
474                "multi_dpr_windows",
475            ]
476        );
477        for name in registry.names() {
478            let _ = registry.build(name).unwrap_or_else(|e| panic!("scene {name}: {e}"));
479        }
480        assert!(registry.build("missing").is_err());
481    }
482}