Skip to main content

mgui_runtime/app/
commands.rs

1//! 统一命令路由 —— 菜单、托盘、全局快捷键、第二实例共用 `CommandId` 空间。
2//!
3//! 命令来源是日志/计数口径,不改变业务语义:同一 `CommandId` 无论从菜单还是
4//! 全局快捷键触发,都落到同一个处理器。`CommandRouter` 每应用实例一份,
5//! 不是全局状态;`CommandScope` 是窄上下文,不暴露 wgpu/winit。
6//!
7//! 投递统计:`delivered = consumed + passthrough`,供 trace 与 Agent replay 对账;
8//! 同一命令被投递两次是宿主缺陷,不是路由器的责任。
9
10use std::collections::HashMap;
11
12use mgui_app_lifecycle::FeatureLifecycle;
13use mgui_core::element::ElementTree;
14use mgui_shell::WindowShell;
15
16/// 统一命令 ID。菜单、托盘、全局快捷键共用同一 ID 空间。
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18pub struct CommandId(pub u64);
19
20impl CommandId {
21    pub const fn new(id: u64) -> Self {
22        Self(id)
23    }
24}
25
26/// 命令来源。只用于 trace 与投递计数,不参与业务分发。
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum CommandSource {
29    Menu,
30    TrayMenu,
31    TrayClick,
32    GlobalShortcut,
33    SecondInstance,
34}
35
36impl CommandSource {
37    pub fn as_str(self) -> &'static str {
38        match self {
39            Self::Menu => "menu",
40            Self::TrayMenu => "tray_menu",
41            Self::TrayClick => "tray_click",
42            Self::GlobalShortcut => "global_shortcut",
43            Self::SecondInstance => "second_instance",
44        }
45    }
46}
47
48/// 命令处理结果。`PassThrough` 继续走默认事件路由,与 `on_event` 的 `false` 同义。
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum CommandOutcome {
51    Consumed,
52    PassThrough,
53}
54
55/// 命令处理器的窄上下文:暴露 shell/树/生命周期/参数,不暴露 wgpu/winit。
56pub struct CommandScope<'a> {
57    shell: &'a dyn WindowShell,
58    tree: &'a mut ElementTree,
59    lifecycle: Option<&'a FeatureLifecycle>,
60    args: &'a [String],
61    source: CommandSource,
62    needs_redraw: Option<&'a mut bool>,
63    needs_rebuild: Option<&'a mut bool>,
64}
65
66impl<'a> CommandScope<'a> {
67    /// 构造命令上下文。`needs_redraw` / `needs_rebuild` 可为 `None`:
68    /// 自定义 `RunnerApp` 没有这两个标志时,按 `CommandOutcome` 自行调用 `ctx.request_redraw()`。
69    pub fn new(
70        shell: &'a dyn WindowShell,
71        tree: &'a mut ElementTree,
72        lifecycle: Option<&'a FeatureLifecycle>,
73        args: &'a [String],
74        source: CommandSource,
75        needs_redraw: Option<&'a mut bool>,
76        needs_rebuild: Option<&'a mut bool>,
77    ) -> Self {
78        Self { shell, tree, lifecycle, args, source, needs_redraw, needs_rebuild }
79    }
80
81    pub fn shell(&self) -> &dyn WindowShell {
82        self.shell
83    }
84
85    pub fn tree_mut(&mut self) -> &mut ElementTree {
86        self.tree
87    }
88
89    pub fn lifecycle(&self) -> Option<&FeatureLifecycle> {
90        self.lifecycle
91    }
92
93    pub fn source(&self) -> CommandSource {
94        self.source
95    }
96
97    /// 仅 `SecondInstance` 携带命令行参数(不含 exe 路径),其余来源为空。
98    pub fn args(&self) -> &[String] {
99        self.args
100    }
101
102    pub fn request_redraw(&mut self) {
103        if let Some(flag) = self.needs_redraw.as_deref_mut() {
104            *flag = true;
105        }
106    }
107
108    pub fn request_rebuild(&mut self) {
109        if let Some(flag) = self.needs_rebuild.as_deref_mut() {
110            *flag = true;
111        }
112        self.request_redraw();
113    }
114}
115
116/// 命令路由投递统计。
117#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
118pub struct CommandStats {
119    pub delivered: u64,
120    pub consumed: u64,
121    pub passthrough: u64,
122    pub menu: u64,
123    pub tray_menu: u64,
124    pub tray_click: u64,
125    pub global_shortcut: u64,
126    pub second_instance: u64,
127}
128
129type CommandHandler = Box<dyn FnMut(&mut CommandScope<'_>) -> CommandOutcome>;
130
131/// 声明式命令路由。每应用实例一份,不引入全局状态。
132#[derive(Default)]
133pub struct CommandRouter {
134    handlers: HashMap<CommandId, CommandHandler>,
135    stats: CommandStats,
136}
137
138impl std::fmt::Debug for CommandRouter {
139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        f.debug_struct("CommandRouter").field("registered", &self.handlers.len()).field("stats", &self.stats).finish()
141    }
142}
143
144impl CommandRouter {
145    pub fn new() -> Self {
146        Self::default()
147    }
148
149    /// 注册命令处理器;重复注册同一 ID 覆盖旧处理器(构建期行为)。
150    pub fn register<F>(&mut self, id: CommandId, handler: F) -> &mut Self
151    where
152        F: FnMut(&mut CommandScope<'_>) -> CommandOutcome + 'static,
153    {
154        self.handlers.insert(id, Box::new(handler));
155        self
156    }
157
158    pub fn registered(&self) -> usize {
159        self.handlers.len()
160    }
161
162    pub fn stats(&self) -> CommandStats {
163        self.stats
164    }
165
166    /// 投递命令。未注册 ID 返回 `PassThrough`,计入 `delivered/passthrough`。
167    pub fn dispatch(&mut self, scope: &mut CommandScope<'_>, id: CommandId) -> CommandOutcome {
168        let source = scope.source;
169        self.stats.delivered += 1;
170        match source {
171            CommandSource::Menu => self.stats.menu += 1,
172            CommandSource::TrayMenu => self.stats.tray_menu += 1,
173            CommandSource::TrayClick => self.stats.tray_click += 1,
174            CommandSource::GlobalShortcut => self.stats.global_shortcut += 1,
175            CommandSource::SecondInstance => self.stats.second_instance += 1,
176        }
177        match self.handlers.get_mut(&id) {
178            Some(handler) => {
179                let outcome = handler(scope);
180                if outcome == CommandOutcome::Consumed {
181                    self.stats.consumed += 1;
182                } else {
183                    self.stats.passthrough += 1;
184                }
185                outcome
186            }
187            None => {
188                self.stats.passthrough += 1;
189                CommandOutcome::PassThrough
190            }
191        }
192    }
193}