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