mgui-runtime 0.3.0

mgui 运行时:AppRunner、GPU/软件渲染后端、窗口/无障碍/异步任务集成
Documentation
//! 启动顺序埋点与冒烟校验。
//!
//! `AppRunner` 在关键节点记录 [`StartupStep`](启动/窗口/AccessKit/后端/首帧/可见/
//! 初始语义树),`--startup-smoke` 模式跑一遍隐藏(屏幕外)窗口后校验:
//! **首帧 present 必须先于 `set_visible`**,**初始 a11y 树必须在可见后的第一帧推送**。
//! 纯结构校验可单测,CI 无 GPU 时也能跑(配合软件回退)。

/// 启动阶段(按期望发生顺序排列)
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StartupStep {
    Resumed,
    WindowCreated,
    AccessKitReady,
    /// GPU Renderer 或软件回退后端就绪
    BackendReady,
    /// 首帧已成功 present(窗口仍不可见)
    FirstFramePresented,
    /// 调用 `set_visible(true)`(冒烟模式窗口位于屏幕外)
    WindowVisible,
    /// 可见后推送第一棵 AccessKit 语义树
    A11yInitialPushed,
}

impl StartupStep {
    pub fn as_str(self) -> &'static str {
        match self {
            StartupStep::Resumed => "resumed",
            StartupStep::WindowCreated => "window_created",
            StartupStep::AccessKitReady => "accesskit_ready",
            StartupStep::BackendReady => "backend_ready",
            StartupStep::FirstFramePresented => "first_frame_presented",
            StartupStep::WindowVisible => "window_visible",
            StartupStep::A11yInitialPushed => "a11y_initial_pushed",
        }
    }
}

/// 启动顺序记录(步骤 + 自启动起的毫秒数)
#[derive(Clone, Debug, Default)]
pub struct StartupTrace {
    steps: Vec<(StartupStep, u64)>,
}

impl StartupTrace {
    pub fn new() -> Self {
        Self::default()
    }

    /// 记录一个阶段;同一步骤只记第一次(阶段是单向的)
    pub fn record(&mut self, step: StartupStep, elapsed_ms: u64) {
        if !self.has(step) {
            self.steps.push((step, elapsed_ms));
        }
    }

    pub fn has(&self, step: StartupStep) -> bool {
        self.steps.iter().any(|(s, _)| *s == step)
    }

    pub fn steps(&self) -> &[(StartupStep, u64)] {
        &self.steps
    }

    /// 校验关键顺序:
    /// 1. 六个阶段齐全;
    /// 2. `FirstFramePresented` 早于 `WindowVisible`(禁止白屏);
    /// 3. `A11yInitialPushed` 晚于 `WindowVisible`(可见后首帧才推树)。
    pub fn validate(&self) -> Result<(), String> {
        let pos = |step: StartupStep| self.steps.iter().position(|(s, _)| *s == step);
        let mut missing = Vec::new();
        for step in [
            StartupStep::Resumed,
            StartupStep::WindowCreated,
            StartupStep::AccessKitReady,
            StartupStep::BackendReady,
            StartupStep::FirstFramePresented,
            StartupStep::WindowVisible,
            StartupStep::A11yInitialPushed,
        ] {
            if pos(step).is_none() {
                missing.push(step.as_str());
            }
        }
        if !missing.is_empty() {
            return Err(format!("缺少启动阶段: {}", missing.join(", ")));
        }

        let present = pos(StartupStep::FirstFramePresented).unwrap();
        let visible = pos(StartupStep::WindowVisible).unwrap();
        let a11y = pos(StartupStep::A11yInitialPushed).unwrap();
        if present > visible {
            return Err("首帧 present 晚于窗口显示(会白屏)".into());
        }
        if a11y < visible {
            return Err("初始 a11y 树早于窗口显示(adapter 可能未激活)".into());
        }
        Ok(())
    }

    /// 冒烟报告:`first_frame=84ms window_visible=...;...`
    pub fn report(&self) -> String {
        self.steps.iter().map(|(s, ms)| format!("{}={}ms", s.as_str(), ms)).collect::<Vec<_>>().join(" ")
    }
}

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

    fn valid_trace() -> StartupTrace {
        let mut t = StartupTrace::new();
        for (i, step) in [
            StartupStep::Resumed,
            StartupStep::WindowCreated,
            StartupStep::AccessKitReady,
            StartupStep::BackendReady,
            StartupStep::FirstFramePresented,
            StartupStep::WindowVisible,
            StartupStep::A11yInitialPushed,
        ]
        .into_iter()
        .enumerate()
        {
            t.record(step, i as u64 * 10);
        }
        t
    }

    #[test]
    fn valid_order_passes() {
        assert!(valid_trace().validate().is_ok());
    }

    #[test]
    fn visible_before_first_frame_is_rejected() {
        let mut t = StartupTrace::new();
        for step in [
            StartupStep::Resumed,
            StartupStep::WindowCreated,
            StartupStep::AccessKitReady,
            StartupStep::BackendReady,
            StartupStep::WindowVisible, // 抢在首帧前显示 → 白屏
            StartupStep::FirstFramePresented,
            StartupStep::A11yInitialPushed,
        ] {
            t.record(step, 0);
        }
        let err = t.validate().unwrap_err();
        assert!(err.contains("白屏"), "错误信息应指出白屏: {err}");
    }

    #[test]
    fn a11y_before_visible_is_rejected() {
        let mut t2 = StartupTrace::new();
        for step in [
            StartupStep::Resumed,
            StartupStep::WindowCreated,
            StartupStep::AccessKitReady,
            StartupStep::BackendReady,
            StartupStep::FirstFramePresented,
            StartupStep::A11yInitialPushed,
            StartupStep::WindowVisible,
        ] {
            t2.record(step, 0);
        }
        let err = t2.validate().unwrap_err();
        assert!(err.contains("a11y"), "错误信息应指出 a11y 顺序: {err}");
    }

    #[test]
    fn missing_steps_are_reported() {
        let mut t = StartupTrace::new();
        t.record(StartupStep::Resumed, 0);
        t.record(StartupStep::WindowCreated, 1);
        let err = t.validate().unwrap_err();
        assert!(err.contains("缺少启动阶段"), "{err}");
        assert!(err.contains("first_frame_presented"), "{err}");
    }

    #[test]
    fn duplicate_step_keeps_first_timestamp() {
        let mut t = StartupTrace::new();
        t.record(StartupStep::Resumed, 5);
        t.record(StartupStep::Resumed, 99);
        assert_eq!(t.steps(), &[(StartupStep::Resumed, 5)]);
    }
}