mgui-runtime 0.7.0

mgui 运行时:AppRunner、GPU/软件渲染后端、窗口/无障碍/异步任务集成
Documentation
//! 统一命令路由 —— 菜单、托盘、全局快捷键、第二实例共用 `CommandId` 空间。
//!
//! 命令来源是日志/计数口径,不改变业务语义:同一 `CommandId` 无论从菜单还是
//! 全局快捷键触发,都落到同一个处理器。`CommandRouter` 每应用实例一份,
//! 不是全局状态;`CommandScope` 是窄上下文,不暴露 wgpu/winit。
//!
//! 投递统计:`delivered = consumed + passthrough`,供 trace 与 Agent replay 对账;
//! 同一命令被投递两次是宿主缺陷,不是路由器的责任。

use std::collections::HashMap;

use mgui_app_lifecycle::FeatureLifecycle;
use mgui_core::element::ElementTree;
use mgui_shell::WindowShell;

/// 统一命令 ID。菜单、托盘、全局快捷键共用同一 ID 空间。
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct CommandId(pub u64);

impl CommandId {
    pub const fn new(id: u64) -> Self {
        Self(id)
    }
}

/// 命令来源。只用于 trace 与投递计数,不参与业务分发。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CommandSource {
    Menu,
    TrayMenu,
    TrayClick,
    GlobalShortcut,
    SecondInstance,
}

impl CommandSource {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Menu => "menu",
            Self::TrayMenu => "tray_menu",
            Self::TrayClick => "tray_click",
            Self::GlobalShortcut => "global_shortcut",
            Self::SecondInstance => "second_instance",
        }
    }
}

/// 命令处理结果。`PassThrough` 继续走默认事件路由,与 `on_event` 的 `false` 同义。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CommandOutcome {
    Consumed,
    PassThrough,
}

/// 命令处理器的窄上下文:暴露 shell/树/生命周期/参数,不暴露 wgpu/winit。
///
/// `S` 是应用持有的命令状态类型,默认 `()` 保持 0.6 的无状态用法。类型化状态由
/// [`CommandScope::with_state`] 显式注入;`CommandScope::new` 只构造 `S = ()`
/// 的兼容上下文,不提供 `app_state_mut()`。
pub struct CommandScope<'a, S = ()> {
    shell: &'a dyn WindowShell,
    tree: &'a mut ElementTree,
    lifecycle: Option<&'a FeatureLifecycle>,
    args: &'a [String],
    source: CommandSource,
    needs_redraw: Option<&'a mut bool>,
    needs_rebuild: Option<&'a mut bool>,
    app_state: Option<&'a mut S>,
}

impl<'a> CommandScope<'a, ()> {
    /// 构造无状态命令上下文。`needs_redraw` / `needs_rebuild` 可为 `None`:
    /// 自定义 `RunnerApp` 没有这两个标志时,按 `CommandOutcome` 自行调用 `ctx.request_redraw()`。
    pub fn new(
        shell: &'a dyn WindowShell,
        tree: &'a mut ElementTree,
        lifecycle: Option<&'a FeatureLifecycle>,
        args: &'a [String],
        source: CommandSource,
        needs_redraw: Option<&'a mut bool>,
        needs_rebuild: Option<&'a mut bool>,
    ) -> Self {
        Self { shell, tree, lifecycle, args, source, needs_redraw, needs_rebuild, app_state: None }
    }
}

impl<'a, S> CommandScope<'a, S> {
    /// 构造带类型化应用状态的命令上下文。状态所有权在 App 层,这里只借可变引用。
    #[allow(clippy::too_many_arguments)]
    pub fn with_state(
        shell: &'a dyn WindowShell,
        tree: &'a mut ElementTree,
        lifecycle: Option<&'a FeatureLifecycle>,
        args: &'a [String],
        source: CommandSource,
        needs_redraw: Option<&'a mut bool>,
        needs_rebuild: Option<&'a mut bool>,
        app_state: &'a mut S,
    ) -> Self {
        Self { shell, tree, lifecycle, args, source, needs_redraw, needs_rebuild, app_state: Some(app_state) }
    }

    /// 命令处理器访问类型化应用状态。无状态上下文调用会 panic,调用方必须先确认
    /// 自己注册的是 `CommandRouter<S>` 且由 `with_state` 投递。
    pub fn app_state_mut(&mut self) -> &mut S {
        self.app_state.as_deref_mut().expect("CommandScope 未注入类型化应用状态")
    }

    pub fn try_app_state_mut(&mut self) -> Option<&mut S> {
        self.app_state.as_deref_mut()
    }

    pub fn shell(&self) -> &dyn WindowShell {
        self.shell
    }

    pub fn tree_mut(&mut self) -> &mut ElementTree {
        self.tree
    }

    pub fn lifecycle(&self) -> Option<&FeatureLifecycle> {
        self.lifecycle
    }

    pub fn source(&self) -> CommandSource {
        self.source
    }

    /// 仅 `SecondInstance` 携带命令行参数(不含 exe 路径),其余来源为空。
    pub fn args(&self) -> &[String] {
        self.args
    }

    pub fn request_redraw(&mut self) {
        if let Some(flag) = self.needs_redraw.as_deref_mut() {
            *flag = true;
        }
    }

    pub fn request_rebuild(&mut self) {
        if let Some(flag) = self.needs_rebuild.as_deref_mut() {
            *flag = true;
        }
        self.request_redraw();
    }
}

/// 命令路由投递统计。
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CommandStats {
    pub delivered: u64,
    pub consumed: u64,
    pub passthrough: u64,
    pub menu: u64,
    pub tray_menu: u64,
    pub tray_click: u64,
    pub global_shortcut: u64,
    pub second_instance: u64,
}

type CommandHandler<S> = Box<dyn FnMut(&mut CommandScope<'_, S>) -> CommandOutcome>;

/// 声明式命令路由。每应用实例一份,不引入全局状态。
///
/// `S = ()` 保持 0.6 的无状态用法;`S != ()` 时处理器通过
/// [`CommandScope::app_state_mut`] 修改应用持有的类型化状态。
pub struct CommandRouter<S = ()> {
    handlers: HashMap<CommandId, CommandHandler<S>>,
    stats: CommandStats,
}

impl<S> Default for CommandRouter<S> {
    fn default() -> Self {
        Self { handlers: HashMap::new(), stats: CommandStats::default() }
    }
}

impl<S> std::fmt::Debug for CommandRouter<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CommandRouter").field("registered", &self.handlers.len()).field("stats", &self.stats).finish()
    }
}

impl<S> CommandRouter<S> {
    pub fn new() -> Self {
        Self::default()
    }

    /// 注册命令处理器;重复注册同一 ID 覆盖旧处理器(构建期行为)。
    pub fn register<F>(&mut self, id: CommandId, handler: F) -> &mut Self
    where
        F: FnMut(&mut CommandScope<'_, S>) -> CommandOutcome + 'static,
    {
        self.handlers.insert(id, Box::new(handler));
        self
    }

    pub fn registered(&self) -> usize {
        self.handlers.len()
    }

    pub fn stats(&self) -> CommandStats {
        self.stats
    }

    /// 投递命令。未注册 ID 返回 `PassThrough`,计入 `delivered/passthrough`。
    pub fn dispatch(&mut self, scope: &mut CommandScope<'_, S>, id: CommandId) -> CommandOutcome {
        let source = scope.source;
        self.stats.delivered += 1;
        match source {
            CommandSource::Menu => self.stats.menu += 1,
            CommandSource::TrayMenu => self.stats.tray_menu += 1,
            CommandSource::TrayClick => self.stats.tray_click += 1,
            CommandSource::GlobalShortcut => self.stats.global_shortcut += 1,
            CommandSource::SecondInstance => self.stats.second_instance += 1,
        }
        match self.handlers.get_mut(&id) {
            Some(handler) => {
                let outcome = handler(scope);
                if outcome == CommandOutcome::Consumed {
                    self.stats.consumed += 1;
                } else {
                    self.stats.passthrough += 1;
                }
                outcome
            }
            None => {
                self.stats.passthrough += 1;
                CommandOutcome::PassThrough
            }
        }
    }
}