Skip to main content

mgui_runtime/
app.rs

1//! 平台无关 Runner API —— 应用只依赖本模块,不直接接触 winit/wgpu。
2//!
3//! 桌面事件循环、窗口/GPU/AccessKit 由 `mgui-shell-desktop` host 实现;
4//! 本模块只定义:
5//! - [`RunnerConfig`] / [`RunnerApp`] 生命周期
6//! - [`AppContext`](WindowShell + 中性后端查询 + 任务执行器)
7//! - [`SoftwareBackend`] 软件回退契约(窗口句柄由 shell 层提供)
8
9use std::path::PathBuf;
10
11use mgui_core::element::ElementTree;
12use mgui_core::{FramePaint, Size};
13
14use crate::renderer::{PresentStats, RenderStats};
15use crate::task::TaskExecutor;
16use crate::ImageTextureStats;
17
18pub mod commands;
19pub use commands::{CommandId, CommandOutcome, CommandRouter, CommandScope, CommandSource, CommandStats};
20
21pub use mgui_shell::{
22    ClipboardHandle, ClipboardImage, FileDialogOptions, FileDragOptions, FileDragOutcome, GlobalShortcut, IconImage,
23    ImeEvent, NativeMenu, NativeMenuBar, NativeMenuCommand, NativeMenuController, NativeMenuItem, Notification,
24    NotificationLevel, NotificationTimeout, ResizeDirection, ShellEvent, ShellMetrics, Shortcut, ShortcutKey,
25    SingleInstanceConfig, TrayConfig, TrayEvent, TrayMenuItem, WindowCommand, WindowCommandBus, WindowCorners,
26    WindowIcon, WindowShell, WindowState,
27};
28
29// =================================================================
30// 配置 / 上下文
31// =================================================================
32
33/// 窗口启动配置
34#[derive(Clone, Debug)]
35pub struct RunnerConfig {
36    pub title: String,
37    /// 窗口初始尺寸;默认按逻辑像素解释,`physical_size = true` 时按物理像素
38    pub inner_size: Size,
39    /// `inner_size` 是否按物理像素解释(L2 GPU 性能验收用于精确指定 1080p/4K)
40    pub physical_size: bool,
41    /// 强制走软件光栅器(不尝试 wgpu;用于 VM/远程桌面验证与无 GPU 环境)
42    pub prefer_software: bool,
43    /// 启动冒烟:窗口放到屏幕外,校验「首帧先于显示 / a11y 树在可见后推送」后自动退出
44    pub startup_smoke: bool,
45    /// 是否创建系统标题栏/边框;false 用于程序自绘菜单标题栏。
46    pub decorations: bool,
47    /// 窗口图标(small=标题栏,large=任务栏/切换器);None = 系统/exe 默认
48    pub window_icon: Option<WindowIcon>,
49    /// 桌面应用 id(Linux 关联 `.desktop`;Windows 预留给 AUMID,当前未使用)
50    pub app_id: Option<String>,
51    /// 窗口几何持久化文件;Some 时启动自动恢复、关闭时自动保存。
52    /// 启动冒烟/物理像素模式不读写该文件。
53    pub window_state_path: Option<PathBuf>,
54    /// 单实例守卫;None = 允许同时运行多个实例。启动冒烟模式跳过。
55    pub single_instance: Option<SingleInstanceConfig>,
56    /// 系统托盘;None = 不创建。启动冒烟模式跳过创建。
57    pub tray: Option<TrayConfig>,
58    /// 原生应用菜单栏;None = 不安装。当前 Windows/macOS 支持,Linux 忽略并告警。
59    /// 启动冒烟模式跳过安装。
60    pub native_menu: Option<NativeMenuBar>,
61    /// 进程级全局快捷键。启动冒烟模式跳过注册(避免占用系统快捷键)。
62    pub global_shortcuts: Vec<GlobalShortcut>,
63}
64
65impl RunnerConfig {
66    pub fn new(title: impl Into<String>, width: f32, height: f32) -> Self {
67        Self {
68            title: title.into(),
69            inner_size: Size::new(width, height),
70            physical_size: false,
71            prefer_software: false,
72            startup_smoke: false,
73            decorations: true,
74            window_icon: None,
75            app_id: None,
76            window_state_path: None,
77            single_instance: None,
78            tray: None,
79            native_menu: None,
80            global_shortcuts: Vec::new(),
81        }
82    }
83
84    /// 将 `inner_size` 解释为物理像素(默认逻辑像素)。
85    pub fn with_physical_size(mut self, physical: bool) -> Self {
86        self.physical_size = physical;
87        self
88    }
89
90    /// 强制软件渲染(桌面应用需实现 `mgui-shell-desktop::DesktopRunnerApp::create_software_backend`)
91    pub fn with_prefer_software(mut self, prefer: bool) -> Self {
92        self.prefer_software = prefer;
93        self
94    }
95
96    /// 启动冒烟模式:完成首帧 + 初始 a11y 树后自动退出,顺序不符则启动失败
97    pub fn with_startup_smoke(mut self, smoke: bool) -> Self {
98        self.startup_smoke = smoke;
99        self
100    }
101
102    /// 是否使用系统标题栏/边框(默认 true)。false 时配合
103    /// [`WindowShell::start_dragging`] / [`WindowShell::start_resize`] 自绘标题栏。
104    pub fn with_decorations(mut self, decorations: bool) -> Self {
105        self.decorations = decorations;
106        self
107    }
108
109    /// 设置窗口图标(small 用于标题栏,large 用于任务栏/窗口切换器)。
110    pub fn with_window_icon(mut self, icon: WindowIcon) -> Self {
111        self.window_icon = Some(icon);
112        self
113    }
114
115    /// 设置桌面应用 id;Linux 下应与安装的 `.desktop` 文件名一致。
116    pub fn with_app_id(mut self, id: impl Into<String>) -> Self {
117        self.app_id = Some(id.into());
118        self
119    }
120
121    /// 窗口大小/位置/最大化状态持久化到指定文件。
122    pub fn with_window_state_path(mut self, path: impl Into<PathBuf>) -> Self {
123        self.window_state_path = Some(path.into());
124        self
125    }
126
127    /// 启用单实例。第二实例把命令行参数转发给第一实例并直接退出;文件关联
128    /// 打开可把文件路径作为参数传入。启动冒烟模式跳过。
129    pub fn with_single_instance(mut self, id: impl Into<String>) -> Self {
130        self.single_instance = Some(SingleInstanceConfig::new(id));
131        self
132    }
133
134    /// 使用完整单实例配置(可关闭参数转发)。
135    pub fn with_single_instance_config(mut self, config: SingleInstanceConfig) -> Self {
136        self.single_instance = Some(config);
137        self
138    }
139
140    /// 创建系统托盘;菜单点击与图标单击回调 [`RunnerApp::on_tray_event`]。
141    ///
142    /// Linux 使用 StatusNotifierItem(需要桌面支持 AppIndicator/SNI);
143    /// 托盘创建失败不会阻止应用启动,只记录警告。
144    pub fn with_tray(mut self, tray: TrayConfig) -> Self {
145        self.tray = Some(tray);
146        self
147    }
148
149    /// 安装原生应用菜单栏(Windows/macOS)。菜单命令经
150    /// [`RunnerApp::on_native_menu_command`] 回调;菜单项上的加速键由宿主处理。
151    pub fn with_native_menu(mut self, menu: NativeMenuBar) -> Self {
152        self.native_menu = Some(menu);
153        self
154    }
155
156    /// 注册一组进程级全局快捷键。
157    pub fn with_global_shortcuts(mut self, shortcuts: Vec<GlobalShortcut>) -> Self {
158        self.global_shortcuts = shortcuts;
159        self
160    }
161
162    /// 追加一个进程级全局快捷键。
163    pub fn with_global_shortcut(mut self, shortcut: GlobalShortcut) -> Self {
164        self.global_shortcuts.push(shortcut);
165        self
166    }
167}
168
169/// 软件回退后端:无 GPU 时 Runner 用它上屏。
170///
171/// 由应用提供(通常直接包一层 `mgui_software::SoftwarePresenter`),
172/// 这样 `mgui-runtime` 不必反向依赖软件光栅器。
173pub trait SoftwareBackend {
174    /// 渲染并 present 一帧 `FramePaint`
175    fn present(&mut self, frame: &FramePaint) -> Result<(), String>;
176    fn set_scale_factor(&mut self, scale_factor: f32);
177    fn set_logical_size(&mut self, size: Size);
178}
179
180/// 中性后端能力 —— 由 desktop host 实现,应用侧不接触 GpuState/Renderer。
181#[doc(hidden)]
182pub trait RunnerBackend {
183    fn is_software(&self) -> bool;
184    fn image_texture_stats(&self) -> ImageTextureStats;
185    fn resolve_gpu_profile(&mut self) -> Option<u32>;
186    /// P2-1.5:上一帧 draw calls / segment / scratch 内存统计
187    fn render_stats(&self) -> RenderStats;
188    /// 上一段 present 的读数(等 vsync / 提交 / 相邻间隔)。
189    ///
190    /// **默认实现给全零而不是 panic**:这条是诊断读数,实现者里软件回退与测试宿主根本
191    /// 不 present 到屏幕。但读到的 `presents == 0` 必须被当成"没量到",不是"节奏完美" ——
192    /// 与 `FrameStats::COLLECTING`、`StageCounters::frames_measured` 同一条家规。
193    fn present_stats(&self) -> PresentStats {
194        PresentStats::default()
195    }
196}
197
198/// 应用回调可用的运行时句柄(由 Runner 持有)。
199///
200/// 应用侧不暴露 wgpu/winit 类型:GPU 相关能力通过中性的统计/查询方法提供。
201pub struct AppContext<'a> {
202    /// 窗口/DPI/IME 能力 —— 应用不直接依赖 winit
203    pub shell: &'a dyn WindowShell,
204    backend: &'a mut dyn RunnerBackend,
205    /// UI 线程任务执行器:应用可 spawn 异步任务,回调在 UI 线程执行
206    pub tasks: &'a TaskExecutor,
207}
208
209impl<'a> AppContext<'a> {
210    /// desktop host 内部构造入口(应用不应调用)。
211    #[doc(hidden)]
212    pub fn new(shell: &'a dyn WindowShell, backend: &'a mut dyn RunnerBackend, tasks: &'a TaskExecutor) -> Self {
213        Self { shell, backend, tasks }
214    }
215}
216
217impl AppContext<'_> {
218    pub fn is_software(&self) -> bool {
219        self.backend.is_software()
220    }
221
222    pub fn metrics(&self) -> ShellMetrics {
223        self.shell.metrics()
224    }
225
226    /// DPR(文字/布局的物理像素比)
227    pub fn scale_factor(&self) -> f32 {
228        self.metrics().scale_factor
229    }
230
231    /// 当前逻辑尺寸(由窗口物理尺寸与 DPR 推导)
232    pub fn logical_size(&self) -> Size {
233        self.metrics().logical_size
234    }
235
236    /// 请求下一帧重绘。
237    pub fn request_redraw(&self) {
238        self.shell.request_redraw();
239    }
240
241    /// 图片纹理占用快照(软件回退时为默认值)。
242    pub fn image_texture_stats(&self) -> ImageTextureStats {
243        self.backend.image_texture_stats()
244    }
245
246    /// 解析 GPU timestamp(仅 GPU 后端且 profiler 可用时返回)。
247    pub fn resolve_gpu_profile(&mut self) -> Option<u32> {
248        self.backend.resolve_gpu_profile()
249    }
250
251    /// P2-1.5:上一帧绘制统计(draw calls / segments / scratch 内存)
252    pub fn render_stats(&self) -> RenderStats {
253        self.backend.render_stats()
254    }
255
256    /// 上一段 present 的读数(含**实际生效**的 `present_mode` 与 `max_frame_latency`)。
257    ///
258    /// 应用侧读它是为了把"呈现节奏不匀"拆成两件不同的事:等 vsync 的时间(配额)与
259    /// 相邻两次 present 的间隔(节奏)。软件回退那一路不 present 到屏幕,所以
260    /// `presents == 0` —— 那是"没量到",不是"节奏完美"。
261    pub fn present_stats(&self) -> PresentStats {
262        self.backend.present_stats()
263    }
264}
265
266// =================================================================
267// 应用接口
268// =================================================================
269
270/// 窗口应用需要实现的最小生命周期。
271///
272/// 所有带默认实现的方法都是可选的;`tree_mut` / `mark_redraw` / `frame`
273/// 是必需的。
274pub trait RunnerApp {
275    /// Runner 构建语义树、路由 AccessKit action 时使用
276    fn tree_mut(&mut self) -> &mut ElementTree;
277
278    /// Runner 内部触发重绘(a11y action 等)时调用,应用据此标记 needs_redraw
279    fn mark_redraw(&mut self);
280
281    /// 异步任务完成后调用:默认仅重绘;需要重建 widget 树的应用可覆盖
282    /// (例如占位图 → 真图需要重新执行 build 才能替换 ImageWidget)。
283    fn mark_rebuild(&mut self) {
284        self.mark_redraw();
285    }
286
287    /// 绘制一帧的 CPU 部分;返回 `None` 表示本帧无需重绘。
288    ///
289    /// 推荐委托给 `mgui_core::frame::run_frame`(固定
290    /// drain → rebuild → pending pointer → tick → build requests → overlay → paint
291    /// 顺序),宿主只提供 `FrameHost` 的 build_root / pending pointer / after_tick 钩子,
292    /// 避免各示例与 headless 自行拼帧序导致 tick/overlay 语义漂移。
293    ///
294    /// Runner 负责 surface 获取、GPU 提交、present、a11y 推送与首帧显示。
295    fn frame(&mut self, ctx: &mut AppContext<'_>) -> Option<FramePaint>;
296
297    /// 帧已 present 后调用(profile 上报、fps 角标等)
298    fn after_present(&mut self, _ctx: &mut AppContext<'_>) {}
299
300    /// 窗口关闭请求。返回 false 可阻止关闭(如未保存确认);默认允许。
301    ///
302    /// 应用拒绝后可在确认完成时调用 `ctx.shell.request_close()` 再次触发。
303    fn on_close_requested(&mut self, _ctx: &mut AppContext<'_>) -> bool {
304        true
305    }
306
307    /// 平台无关输入事件(鼠标/键盘/滚轮/IME/焦点)。
308    ///
309    /// 坐标已换算为逻辑像素;应用不再依赖 winit 的 `WindowEvent`。
310    fn on_event(&mut self, _ctx: &mut AppContext<'_>, _event: &ShellEvent) {}
311
312    /// 系统托盘事件(图标单击 / 菜单项激活)。
313    ///
314    /// 在事件循环线程回调;返回后 Runner 自动标记重绘。
315    fn on_tray_event(&mut self, _ctx: &mut AppContext<'_>, _event: &TrayEvent) {}
316
317    /// 原生菜单命令被激活(鼠标选择或菜单加速键)。
318    ///
319    /// 在事件循环线程回调;返回后 Runner 自动标记重绘。
320    fn on_native_menu_command(&mut self, _ctx: &mut AppContext<'_>, _id: u64) {}
321
322    /// 第二个实例把命令行参数转发到当前实例(单实例模式)。
323    ///
324    /// `args` 不含 exe 路径;文件关联打开可直接把它当作文件路径处理。
325    /// 回调后 Runner 自动标记重绘;窗口显示/聚焦由应用决定。
326    fn on_second_instance(&mut self, _ctx: &mut AppContext<'_>, _args: &[String]) {}
327
328    /// 全局快捷键按下。仅报告按下边沿(长按不重复)。
329    ///
330    /// 在事件循环线程回调;返回后 Runner 自动标记重绘。
331    fn on_global_shortcut(&mut self, _ctx: &mut AppContext<'_>, _id: u64) {}
332
333    /// 每个配置的全局快捷键注册结果(启动阶段回调一次)。
334    ///
335    /// `Err` 表示组合非法/被系统或其他应用占用;应用可据此更新 UI。
336    fn on_global_shortcut_registered(&mut self, _ctx: &mut AppContext<'_>, _id: u64, _result: Result<(), String>) {}
337
338    /// 物理尺寸变化(Runner 已完成 gpu.resize)
339    fn on_resized(&mut self, _ctx: &mut AppContext<'_>, _logical_size: Size) {}
340
341    /// DPI 变化(Runner 已完成 gpu.set_scale_factor + 文字 DPR 更新)
342    fn on_scale_factor_changed(&mut self, _ctx: &mut AppContext<'_>) {}
343
344    /// 事件循环空闲时调用;返回 true 表示需要继续重绘(动画/待处理 tick)
345    fn on_about_to_wait(&mut self, _ctx: &mut AppContext<'_>) -> bool {
346        false
347    }
348
349    /// 离散动画的下一次唤醒延迟(光标闪烁等)。
350    ///
351    /// `on_about_to_wait` 返回 false 后,Runner 据此使用 `WaitUntil` 而非无限
352    /// 休眠;None 表示没有定时任务。
353    fn next_wake(&mut self, _ctx: &mut AppContext<'_>) -> Option<std::time::Duration> {
354        None
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361
362    #[test]
363    fn tray_is_opt_in_and_preserves_config() {
364        let config = RunnerConfig::new("test", 320.0, 200.0);
365        assert!(config.decorations, "默认使用系统标题栏");
366        assert!(config.single_instance.is_none(), "默认允许多实例");
367        assert!(config.tray.is_none(), "默认不创建托盘");
368        assert!(config.native_menu.is_none(), "默认不安装原生菜单");
369        assert!(config.global_shortcuts.is_empty(), "默认无全局快捷键");
370
371        let tray = TrayConfig::new("mgui")
372            .with_menu_item(TrayMenuItem::item(1, "Show"))
373            .with_menu_item(TrayMenuItem::separator());
374        let menu = NativeMenuBar::new().with_menu(
375            NativeMenu::new("File")
376                .with_item(NativeMenuCommand::new(1, "Quit").with_shortcut(Shortcut::command(ShortcutKey::Char('q')))),
377        );
378        let global = GlobalShortcut::new(7, Shortcut::ctrl_alt(ShortcutKey::Char('m')));
379        let config = config
380            .with_decorations(false)
381            .with_single_instance("studio.test.single")
382            .with_tray(tray.clone())
383            .with_native_menu(menu.clone())
384            .with_global_shortcut(global.clone());
385        assert!(!config.decorations);
386        assert_eq!(config.single_instance.as_ref().map(|instance| instance.id.as_str()), Some("studio.test.single"));
387        assert_eq!(config.tray, Some(tray));
388        assert_eq!(config.native_menu, Some(menu));
389        assert_eq!(config.global_shortcuts, vec![global]);
390    }
391}