mgui-agent 0.8.0

mgui 0.4 Headless/Agent 工具链:命名 scene + 软件快照 PNG + 语义树 JSON + 脚本回放与 motion trace
Documentation
//! 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::{Color, InvalidationScope, 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(),
        ))
    }
}

/// 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,
        ))
    }
}

/// 内置场景注册表,供 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
}

#[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",
            ]
        );
        for name in registry.names() {
            let _ = registry.build(name).unwrap_or_else(|e| panic!("scene {name}: {e}"));
        }
        assert!(registry.build("missing").is_err());
    }
}