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。
56///
57/// `S` 是应用持有的命令状态类型,默认 `()` 保持 0.6 的无状态用法。类型化状态由
58/// [`CommandScope::with_state`] 显式注入;`CommandScope::new` 只构造 `S = ()`
59/// 的兼容上下文,不提供 `app_state_mut()`。
60pub struct CommandScope<'a, S = ()> {
61    shell: &'a dyn WindowShell,
62    tree: &'a mut ElementTree,
63    lifecycle: Option<&'a FeatureLifecycle>,
64    args: &'a [String],
65    source: CommandSource,
66    needs_redraw: Option<&'a mut bool>,
67    needs_rebuild: Option<&'a mut bool>,
68    app_state: Option<&'a mut S>,
69}
70
71impl<'a> CommandScope<'a, ()> {
72    /// 构造无状态命令上下文。`needs_redraw` / `needs_rebuild` 可为 `None`:
73    /// 自定义 `RunnerApp` 没有这两个标志时,按 `CommandOutcome` 自行调用 `ctx.request_redraw()`。
74    pub fn new(
75        shell: &'a dyn WindowShell,
76        tree: &'a mut ElementTree,
77        lifecycle: Option<&'a FeatureLifecycle>,
78        args: &'a [String],
79        source: CommandSource,
80        needs_redraw: Option<&'a mut bool>,
81        needs_rebuild: Option<&'a mut bool>,
82    ) -> Self {
83        Self { shell, tree, lifecycle, args, source, needs_redraw, needs_rebuild, app_state: None }
84    }
85}
86
87impl<'a, S> CommandScope<'a, S> {
88    /// 构造带类型化应用状态的命令上下文。状态所有权在 App 层,这里只借可变引用。
89    #[allow(clippy::too_many_arguments)]
90    pub fn with_state(
91        shell: &'a dyn WindowShell,
92        tree: &'a mut ElementTree,
93        lifecycle: Option<&'a FeatureLifecycle>,
94        args: &'a [String],
95        source: CommandSource,
96        needs_redraw: Option<&'a mut bool>,
97        needs_rebuild: Option<&'a mut bool>,
98        app_state: &'a mut S,
99    ) -> Self {
100        Self { shell, tree, lifecycle, args, source, needs_redraw, needs_rebuild, app_state: Some(app_state) }
101    }
102
103    /// 命令处理器访问类型化应用状态。无状态上下文调用会 panic,调用方必须先确认
104    /// 自己注册的是 `CommandRouter<S>` 且由 `with_state` 投递。
105    pub fn app_state_mut(&mut self) -> &mut S {
106        self.app_state.as_deref_mut().expect("CommandScope 未注入类型化应用状态")
107    }
108
109    pub fn try_app_state_mut(&mut self) -> Option<&mut S> {
110        self.app_state.as_deref_mut()
111    }
112
113    pub fn shell(&self) -> &dyn WindowShell {
114        self.shell
115    }
116
117    pub fn tree_mut(&mut self) -> &mut ElementTree {
118        self.tree
119    }
120
121    pub fn lifecycle(&self) -> Option<&FeatureLifecycle> {
122        self.lifecycle
123    }
124
125    pub fn source(&self) -> CommandSource {
126        self.source
127    }
128
129    /// 仅 `SecondInstance` 携带命令行参数(不含 exe 路径),其余来源为空。
130    pub fn args(&self) -> &[String] {
131        self.args
132    }
133
134    pub fn request_redraw(&mut self) {
135        if let Some(flag) = self.needs_redraw.as_deref_mut() {
136            *flag = true;
137        }
138    }
139
140    pub fn request_rebuild(&mut self) {
141        if let Some(flag) = self.needs_rebuild.as_deref_mut() {
142            *flag = true;
143        }
144        self.request_redraw();
145    }
146}
147
148/// 命令路由投递统计。
149#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
150pub struct CommandStats {
151    pub delivered: u64,
152    pub consumed: u64,
153    pub passthrough: u64,
154    pub menu: u64,
155    pub tray_menu: u64,
156    pub tray_click: u64,
157    pub global_shortcut: u64,
158    pub second_instance: u64,
159}
160
161type CommandHandler<S> = Box<dyn FnMut(&mut CommandScope<'_, S>) -> CommandOutcome>;
162
163/// 声明式命令路由。每应用实例一份,不引入全局状态。
164///
165/// `S = ()` 保持 0.6 的无状态用法;`S != ()` 时处理器通过
166/// [`CommandScope::app_state_mut`] 修改应用持有的类型化状态。
167pub struct CommandRouter<S = ()> {
168    handlers: HashMap<CommandId, CommandHandler<S>>,
169    stats: CommandStats,
170}
171
172impl<S> Default for CommandRouter<S> {
173    fn default() -> Self {
174        Self { handlers: HashMap::new(), stats: CommandStats::default() }
175    }
176}
177
178impl<S> std::fmt::Debug for CommandRouter<S> {
179    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180        f.debug_struct("CommandRouter").field("registered", &self.handlers.len()).field("stats", &self.stats).finish()
181    }
182}
183
184impl<S> CommandRouter<S> {
185    pub fn new() -> Self {
186        Self::default()
187    }
188
189    /// 注册命令处理器;重复注册同一 ID 覆盖旧处理器(构建期行为)。
190    pub fn register<F>(&mut self, id: CommandId, handler: F) -> &mut Self
191    where
192        F: FnMut(&mut CommandScope<'_, S>) -> CommandOutcome + 'static,
193    {
194        self.handlers.insert(id, Box::new(handler));
195        self
196    }
197
198    pub fn registered(&self) -> usize {
199        self.handlers.len()
200    }
201
202    pub fn stats(&self) -> CommandStats {
203        self.stats
204    }
205
206    /// 投递命令。未注册 ID 返回 `PassThrough`,计入 `delivered/passthrough`。
207    pub fn dispatch(&mut self, scope: &mut CommandScope<'_, S>, id: CommandId) -> CommandOutcome {
208        let source = scope.source;
209        self.stats.delivered += 1;
210        match source {
211            CommandSource::Menu => self.stats.menu += 1,
212            CommandSource::TrayMenu => self.stats.tray_menu += 1,
213            CommandSource::TrayClick => self.stats.tray_click += 1,
214            CommandSource::GlobalShortcut => self.stats.global_shortcut += 1,
215            CommandSource::SecondInstance => self.stats.second_instance += 1,
216        }
217        match self.handlers.get_mut(&id) {
218            Some(handler) => {
219                let outcome = handler(scope);
220                if outcome == CommandOutcome::Consumed {
221                    self.stats.consumed += 1;
222                } else {
223                    self.stats.passthrough += 1;
224                }
225                outcome
226            }
227            None => {
228                self.stats.passthrough += 1;
229                CommandOutcome::PassThrough
230            }
231        }
232    }
233}