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::{Color, InvalidationScope, 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
216/// 0.7 M0:应用级缓存失效场景。command id=2 触发 lookup,id=1 按 Group(7) 标 stale。
217pub struct QueryCacheScene {
218    cache: QueryCache<u32>,
219    router: RefCell<CommandRouter>,
220}
221
222impl Default for QueryCacheScene {
223    fn default() -> Self {
224        let cache = QueryCache::new(8, 1024, |_| 4);
225        cache.insert(QueryKey::new(1), std::rc::Rc::new(1), 7);
226        cache.insert(QueryKey::new(2), std::rc::Rc::new(2), 8);
227        let lookup_cache = cache.clone();
228        let invalidate_cache = cache.clone();
229        let mut router = CommandRouter::new();
230        router.register(CommandId::new(1), move |_| {
231            invalidate_cache.invalidate(InvalidationScope::Group(7));
232            CommandOutcome::Consumed
233        });
234        router.register(CommandId::new(2), move |_| {
235            let _ = lookup_cache.lookup(QueryKey::new(1));
236            CommandOutcome::Consumed
237        });
238        Self { cache, router: RefCell::new(router) }
239    }
240}
241
242impl Scene for QueryCacheScene {
243    fn name(&self) -> &'static str {
244        "query_cache_invalidation"
245    }
246
247    fn build(&self) -> WidgetNode {
248        let column = ColumnWidget::new(8.0)
249            .push(TextWidget::new("query cache / group invalidation").with_size(16.0))
250            .push(ButtonWidget::new(Size::new(220.0, 44.0)).with_text("invalidate group 7", 13.0));
251        WidgetNode::new(ContainerWidget::new().child(column))
252    }
253
254    fn command_router(&self) -> Option<&RefCell<CommandRouter>> {
255        Some(&self.router)
256    }
257
258    fn shared_state_summary(&self) -> Option<String> {
259        let stats = self.cache.stats();
260        Some(format!(
261            "entries={} fresh_hits={} stale_hits={} invalidations={}",
262            self.cache.len(),
263            stats.fresh_hits,
264            stats.stale_hits,
265            stats.invalidations,
266        ))
267    }
268}
269
270/// 内置场景注册表,供 CLI 与桌面 `mgui::scene_app` 共享。
271pub fn builtin_scenes() -> SceneRegistry {
272    let mut registry = SceneRegistry::new();
273    registry.register(Box::new(EmptyScene));
274    registry.register(Box::new(ButtonScene));
275    registry.register(Box::new(FlagshipScene));
276    registry.register(Box::new(TextEditingScene));
277    registry.register(Box::new(CommandRouteScene::default()));
278    registry.register(Box::new(A11yJourneyScene::default()));
279    registry.register(Box::new(TextRuntimeIsolationScene::default()));
280    registry.register(Box::new(QueryCacheScene::default()));
281    registry
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287
288    #[test]
289    fn builtin_scenes_are_stably_named_and_buildable() {
290        let registry = builtin_scenes();
291        assert_eq!(
292            registry.names(),
293            vec![
294                "empty",
295                "button",
296                "flagship",
297                "text_editing",
298                "command_route",
299                "a11y_journey",
300                "text_runtime_isolation",
301                "query_cache_invalidation",
302            ]
303        );
304        for name in registry.names() {
305            let _ = registry.build(name).unwrap_or_else(|e| panic!("scene {name}: {e}"));
306        }
307        assert!(registry.build("missing").is_err());
308    }
309}