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