Skip to main content

mgui_shell/
lib.rs

1//! mgui-shell — 平台无关的 Shell 抽象。
2//!
3//! 这里是 desktop / headless 共享的最小契约:
4//! - [`Clock`]:帧循环、动画与 IME 闪烁的时间来源
5//! - [`ShellMetrics`]:逻辑尺寸 + DPR
6//! - [`ClipboardProvider`]:复用 core 的剪贴板契约
7//!
8//! 窗口创建、原生输入、present 等 desktop 专属能力后续在其上继续分层;
9//! 无窗口环境请使用 `mgui-shell-headless`。
10
11#![forbid(unsafe_code)]
12
13use std::cell::Cell;
14use std::path::{Path, PathBuf};
15use std::rc::Rc;
16use std::time::Instant;
17
18use mgui_core::{KeyCode, KeyModifiers, MouseButton, Point, Rect, Size};
19
20pub use mgui_core::{ClipboardHandle, ClipboardImage, ClipboardProvider, NoopClipboard};
21
22pub mod icon;
23pub use icon::{IconImage, WindowIcon};
24
25/// 平台无关窗口 ID。
26#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
27pub struct ShellWindowId(pub u64);
28
29/// Shell 的尺寸与 DPI。
30#[derive(Clone, Copy, Debug, PartialEq)]
31pub struct ShellMetrics {
32    pub logical_size: Size,
33    /// 物理像素 / 逻辑像素
34    pub scale_factor: f32,
35}
36
37impl ShellMetrics {
38    pub fn new(logical_size: Size, scale_factor: f32) -> Self {
39        Self {
40            logical_size: Size::new(logical_size.width.max(1.0), logical_size.height.max(1.0)),
41            scale_factor: scale_factor.max(0.01),
42        }
43    }
44
45    /// 从物理像素尺寸与 DPR 推导逻辑尺寸。
46    pub fn from_physical(physical_width: u32, physical_height: u32, scale_factor: f32) -> Self {
47        let scale_factor = scale_factor.max(0.01);
48        Self::new(Size::new(physical_width as f32 / scale_factor, physical_height as f32 / scale_factor), scale_factor)
49    }
50}
51
52impl Default for ShellMetrics {
53    fn default() -> Self {
54        Self::new(Size::new(800.0, 600.0), 1.0)
55    }
56}
57
58/// 平台无关光标形状。
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60pub enum CursorIcon {
61    #[default]
62    Default,
63    Pointer,
64    Text,
65    Crosshair,
66    Move,
67    NotAllowed,
68    Wait,
69    Progress,
70    Help,
71    Grab,
72    Grabbing,
73    ZoomIn,
74    ZoomOut,
75    ResizeHorizontal,
76    ResizeVertical,
77    ResizeNwSe,
78    ResizeNeSw,
79    ResizeAll,
80    ColumnResize,
81    RowResize,
82}
83
84/// 自定义标题栏的边缘缩放方向。
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub enum ResizeDirection {
87    East,
88    North,
89    NorthEast,
90    NorthWest,
91    South,
92    SouthEast,
93    SouthWest,
94    West,
95}
96
97impl ResizeDirection {
98    /// 按窗口逻辑尺寸与边缘厚度做命中测试;用于自绘标题栏/无边框窗口。
99    ///
100    /// 角落优先于边;位置在窗口外或 `margin <= 0` 时返回 None。
101    pub fn hit_test(position: Point, size: Size, margin: f32) -> Option<Self> {
102        if !(margin.is_finite() && margin > 0.0)
103            || !(size.width.is_finite() && size.height.is_finite() && size.width > 0.0 && size.height > 0.0)
104            || !(position.x.is_finite() && position.y.is_finite())
105        {
106            return None;
107        }
108        if position.x < 0.0 || position.y < 0.0 || position.x >= size.width || position.y >= size.height {
109            return None;
110        }
111        let mx = margin.min(size.width / 2.0);
112        let my = margin.min(size.height / 2.0);
113        let left = position.x < mx;
114        let right = position.x > size.width - mx;
115        let top = position.y < my;
116        let bottom = position.y > size.height - my;
117        match (top, bottom, left, right) {
118            (true, _, true, _) => Some(Self::NorthWest),
119            (true, _, _, true) => Some(Self::NorthEast),
120            (_, true, true, _) => Some(Self::SouthWest),
121            (_, true, _, true) => Some(Self::SouthEast),
122            (true, _, _, _) => Some(Self::North),
123            (_, true, _, _) => Some(Self::South),
124            (_, _, true, _) => Some(Self::West),
125            (_, _, _, true) => Some(Self::East),
126            _ => None,
127        }
128    }
129}
130
131/// 无边框/自绘标题栏窗口的角样式(Windows 11;其他平台 no-op)。
132#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
133pub enum WindowCorners {
134    /// 交给系统决定。
135    #[default]
136    Default,
137    /// 直角。
138    Square,
139    /// 系统圆角(DWM)。
140    Rounded,
141}
142
143/// 可持久化的窗口几何状态(逻辑像素)。
144#[derive(Clone, Copy, Debug, PartialEq)]
145pub struct WindowState {
146    pub size: Size,
147    /// 窗口左上角(逻辑像素);None = 未知/平台不支持
148    pub position: Option<(f32, f32)>,
149    pub maximized: bool,
150}
151
152impl WindowState {
153    pub fn new(size: Size) -> Self {
154        Self { size: Size::new(size.width.max(1.0), size.height.max(1.0)), position: None, maximized: false }
155    }
156
157    pub fn encode(&self) -> String {
158        let mut out = String::from("mgui-window-state=1\n");
159        out.push_str(&format!("width={}\nheight={}\n", self.size.width, self.size.height));
160        if let Some((x, y)) = self.position {
161            out.push_str(&format!("x={x}\ny={y}\n"));
162        }
163        out.push_str(&format!("maximized={}\n", self.maximized));
164        out
165    }
166
167    pub fn parse(text: &str) -> Option<Self> {
168        let mut version = None;
169        let mut width = None;
170        let mut height = None;
171        let mut x = None;
172        let mut y = None;
173        let mut maximized = false;
174        for line in text.lines() {
175            let Some((key, value)) = line.split_once('=') else { continue };
176            let key = key.trim();
177            let value = value.trim();
178            match key {
179                "mgui-window-state" => version = value.parse::<u32>().ok(),
180                "width" => width = value.parse::<f32>().ok(),
181                "height" => height = value.parse::<f32>().ok(),
182                "x" => x = value.parse::<f32>().ok(),
183                "y" => y = value.parse::<f32>().ok(),
184                "maximized" => maximized = matches!(value, "1" | "true"),
185                _ => {}
186            }
187        }
188        if version != Some(1) {
189            return None;
190        }
191        let width = width.filter(|v| v.is_finite() && *v >= 1.0)?;
192        let height = height.filter(|v| v.is_finite() && *v >= 1.0)?;
193        let position = match (x, y) {
194            (Some(x), Some(y)) if x.is_finite() && y.is_finite() => Some((x, y)),
195            _ => None,
196        };
197        Some(Self { size: Size::new(width, height), position, maximized })
198    }
199
200    pub fn load(path: impl AsRef<Path>) -> Option<Self> {
201        let text = std::fs::read_to_string(path).ok()?;
202        Self::parse(&text)
203    }
204
205    pub fn save(&self, path: impl AsRef<Path>) -> Result<(), String> {
206        let path = path.as_ref();
207        if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
208            std::fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?;
209        }
210        std::fs::write(path, self.encode()).map_err(|e| format!("write {}: {e}", path.display()))
211    }
212}
213
214/// 系统外观主题。
215#[derive(Clone, Copy, Debug, PartialEq, Eq)]
216pub enum SystemTheme {
217    Light,
218    Dark,
219}
220
221/// 文件对话框的扩展名过滤器。
222#[derive(Clone, Debug, PartialEq, Eq)]
223pub struct FileDialogFilter {
224    pub name: String,
225    pub extensions: Vec<String>,
226}
227
228impl FileDialogFilter {
229    pub fn new<I, S>(name: impl Into<String>, extensions: I) -> Self
230    where
231        I: IntoIterator<Item = S>,
232        S: Into<String>,
233    {
234        Self { name: name.into(), extensions: extensions.into_iter().map(Into::into).collect() }
235    }
236}
237
238/// 原生文件对话框参数。所有字段都是可选提示,shell 可忽略不支持的部分。
239#[derive(Clone, Debug, Default, PartialEq, Eq)]
240pub struct FileDialogOptions {
241    pub title: String,
242    pub directory: Option<PathBuf>,
243    pub file_name: Option<String>,
244    pub filters: Vec<FileDialogFilter>,
245}
246
247impl FileDialogOptions {
248    pub fn new(title: impl Into<String>) -> Self {
249        Self { title: title.into(), ..Self::default() }
250    }
251
252    pub fn with_directory(mut self, directory: impl Into<PathBuf>) -> Self {
253        self.directory = Some(directory.into());
254        self
255    }
256
257    pub fn with_file_name(mut self, name: impl Into<String>) -> Self {
258        self.file_name = Some(name.into());
259        self
260    }
261
262    pub fn with_filter<I, S>(mut self, name: impl Into<String>, extensions: I) -> Self
263    where
264        I: IntoIterator<Item = S>,
265        S: Into<String>,
266    {
267        self.filters.push(FileDialogFilter::new(name, extensions));
268        self
269    }
270}
271
272/// 系统通知的重要级别。平台实现可把 `Critical` 映射为常驻提醒。
273#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
274pub enum NotificationLevel {
275    Low,
276    #[default]
277    Normal,
278    Critical,
279}
280
281/// 通知自动消失时间。
282#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
283pub enum NotificationTimeout {
284    /// 使用系统默认时长。
285    #[default]
286    Default,
287    /// 常驻,直到用户主动关闭。
288    Never,
289    /// 指定毫秒数(系统可能忽略或截断)。
290    Milliseconds(u32),
291}
292
293/// 平台无关的系统通知。
294///
295/// `app_id` 在 Windows 上对应 AUMID:打包应用应传入安装时注册的 id,
296/// 未注册的 id 可能让通知不显示。`app_name` 主要用于 Linux 通知中心分组。
297#[derive(Clone, Debug, PartialEq, Eq)]
298pub struct Notification {
299    pub title: String,
300    pub body: String,
301    pub app_name: Option<String>,
302    pub app_id: Option<String>,
303    pub level: NotificationLevel,
304    pub silent: bool,
305    pub timeout: NotificationTimeout,
306    /// Linux 图标名/绝对路径;其他平台可忽略。
307    pub icon: Option<String>,
308}
309
310impl Notification {
311    pub fn new(title: impl Into<String>) -> Self {
312        Self {
313            title: title.into(),
314            body: String::new(),
315            app_name: None,
316            app_id: None,
317            level: NotificationLevel::Normal,
318            silent: false,
319            timeout: NotificationTimeout::Default,
320            icon: None,
321        }
322    }
323
324    pub fn with_body(mut self, body: impl Into<String>) -> Self {
325        self.body = body.into();
326        self
327    }
328
329    pub fn with_app_name(mut self, name: impl Into<String>) -> Self {
330        self.app_name = Some(name.into());
331        self
332    }
333
334    pub fn with_app_id(mut self, id: impl Into<String>) -> Self {
335        self.app_id = Some(id.into());
336        self
337    }
338
339    pub fn with_level(mut self, level: NotificationLevel) -> Self {
340        self.level = level;
341        self
342    }
343
344    pub fn with_silent(mut self, silent: bool) -> Self {
345        self.silent = silent;
346        self
347    }
348
349    pub fn with_timeout(mut self, timeout: NotificationTimeout) -> Self {
350        self.timeout = timeout;
351        self
352    }
353
354    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
355        self.icon = Some(icon.into());
356        self
357    }
358}
359
360/// 托盘菜单项。
361///
362/// `id` 由应用定义,菜单点击通过 [`TrayEvent::Menu`] 原样返回;
363/// 框架不解释 id 语义。
364#[derive(Clone, Debug, PartialEq, Eq)]
365pub enum TrayMenuItem {
366    Item { id: u64, label: String, enabled: bool },
367    Separator,
368    Submenu { label: String, items: Vec<TrayMenuItem> },
369}
370
371impl TrayMenuItem {
372    pub fn item(id: u64, label: impl Into<String>) -> Self {
373        Self::Item { id, label: label.into(), enabled: true }
374    }
375
376    pub fn item_enabled(id: u64, label: impl Into<String>, enabled: bool) -> Self {
377        Self::Item { id, label: label.into(), enabled }
378    }
379
380    pub fn separator() -> Self {
381        Self::Separator
382    }
383
384    pub fn submenu(label: impl Into<String>, items: Vec<TrayMenuItem>) -> Self {
385        Self::Submenu { label: label.into(), items }
386    }
387}
388
389/// 托盘图标配置。
390///
391/// 图标复用 [`IconImage`](RGBA8);建议提供 32×32 或平台面板原生尺寸。
392/// `icon = None` 时桌面宿主会尝试复用 Runner 的窗口小图标。
393/// Linux 使用 StatusNotifierItem,`open_menu_on_left_click` 仅 Windows/macOS 生效。
394#[derive(Clone, Debug, Default, PartialEq, Eq)]
395pub struct TrayConfig {
396    pub tooltip: String,
397    pub icon: Option<IconImage>,
398    pub menu: Vec<TrayMenuItem>,
399    pub open_menu_on_left_click: bool,
400}
401
402impl TrayConfig {
403    pub fn new(tooltip: impl Into<String>) -> Self {
404        Self { tooltip: tooltip.into(), ..Self::default() }
405    }
406
407    pub fn with_icon(mut self, icon: IconImage) -> Self {
408        self.icon = Some(icon);
409        self
410    }
411
412    pub fn with_menu(mut self, items: Vec<TrayMenuItem>) -> Self {
413        self.menu = items;
414        self
415    }
416
417    pub fn with_menu_item(mut self, item: TrayMenuItem) -> Self {
418        self.menu.push(item);
419        self
420    }
421
422    pub fn with_open_menu_on_left_click(mut self, open: bool) -> Self {
423        self.open_menu_on_left_click = open;
424        self
425    }
426}
427
428/// 托盘事件(在 UI/事件循环线程回调)。
429#[derive(Clone, Copy, Debug, PartialEq, Eq)]
430pub enum TrayEvent {
431    /// 单击托盘图标。`open_menu_on_left_click` 为 true 时左键可能只弹菜单。
432    Click { button: MouseButton },
433    /// 菜单项被激活;`id` 与 [`TrayMenuItem`] 中定义的一致。
434    Menu { id: u64 },
435}
436
437/// 快捷键主键(不包含修饰键)。
438///
439/// `Char` 只支持 ASCII 字母、数字与常见标点;名称键覆盖导航/编辑/F1–F24。
440#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
441pub enum ShortcutKey {
442    Char(char),
443    Enter,
444    Escape,
445    Tab,
446    Space,
447    Backspace,
448    Delete,
449    Insert,
450    Left,
451    Right,
452    Up,
453    Down,
454    Home,
455    End,
456    PageUp,
457    PageDown,
458    /// F1–F24;非法范围在注册/构建菜单时返回错误。
459    F(u8),
460}
461
462/// 键位组合。用于原生菜单加速键与全局快捷键。
463#[derive(Clone, Copy, Debug, PartialEq, Eq)]
464pub struct Shortcut {
465    pub modifiers: KeyModifiers,
466    pub key: ShortcutKey,
467}
468
469impl Shortcut {
470    pub const fn new(modifiers: KeyModifiers, key: ShortcutKey) -> Self {
471        Self { modifiers, key }
472    }
473
474    /// 平台「命令键」:macOS ⌘,Windows/Linux Ctrl。
475    pub fn command(key: ShortcutKey) -> Self {
476        Self::new(KeyModifiers::command_only(), key)
477    }
478
479    pub fn ctrl(key: ShortcutKey) -> Self {
480        Self::new(KeyModifiers::ctrl_only(), key)
481    }
482
483    pub fn shift(key: ShortcutKey) -> Self {
484        Self::new(KeyModifiers::shift_only(), key)
485    }
486
487    pub fn ctrl_shift(key: ShortcutKey) -> Self {
488        Self::new(KeyModifiers(KeyModifiers::CTRL | KeyModifiers::SHIFT), key)
489    }
490
491    pub fn ctrl_alt(key: ShortcutKey) -> Self {
492        Self::new(KeyModifiers(KeyModifiers::CTRL | KeyModifiers::ALT), key)
493    }
494
495    pub fn alt(key: ShortcutKey) -> Self {
496        Self::new(KeyModifiers(KeyModifiers::ALT), key)
497    }
498}
499
500/// 单实例配置。
501///
502/// 第一个实例持有本地 socket;后续实例把命令行参数转发给它后立即退出,
503/// 由第一个实例的 `RunnerApp::on_second_instance` 处理(例如文件关联打开)。
504/// `id` 必须在同一应用的所有版本/会话中保持稳定,建议直接用 `app_id`。
505#[derive(Clone, Debug, PartialEq, Eq)]
506pub struct SingleInstanceConfig {
507    pub id: String,
508    /// 第二实例是否把命令行参数转发给第一实例;false 时只退出。
509    pub forward_args: bool,
510}
511
512impl SingleInstanceConfig {
513    pub fn new(id: impl Into<String>) -> Self {
514        Self { id: id.into(), forward_args: true }
515    }
516
517    pub fn with_forward_args(mut self, forward: bool) -> Self {
518        self.forward_args = forward;
519        self
520    }
521}
522
523/// 进程级全局快捷键。`id` 由应用定义,按下时原样回调给应用。
524///
525/// 全局快捷键必须至少包含一个修饰键(Shift/Ctrl/Alt/Meta),避免抢占普通输入。
526#[derive(Clone, Debug, PartialEq, Eq)]
527pub struct GlobalShortcut {
528    pub id: u64,
529    pub shortcut: Shortcut,
530}
531
532impl GlobalShortcut {
533    pub fn new(id: u64, shortcut: Shortcut) -> Self {
534        Self { id, shortcut }
535    }
536}
537
538/// 原生菜单命令。
539#[derive(Clone, Debug, PartialEq, Eq)]
540pub struct NativeMenuCommand {
541    pub id: u64,
542    pub label: String,
543    pub shortcut: Option<Shortcut>,
544    pub enabled: bool,
545    /// None = 普通项;Some = 可勾选项及初始状态。
546    pub checked: Option<bool>,
547}
548
549impl NativeMenuCommand {
550    pub fn new(id: u64, label: impl Into<String>) -> Self {
551        Self { id, label: label.into(), shortcut: None, enabled: true, checked: None }
552    }
553
554    pub fn with_shortcut(mut self, shortcut: Shortcut) -> Self {
555        self.shortcut = Some(shortcut);
556        self
557    }
558
559    pub fn with_enabled(mut self, enabled: bool) -> Self {
560        self.enabled = enabled;
561        self
562    }
563
564    pub fn with_checked(mut self, checked: bool) -> Self {
565        self.checked = Some(checked);
566        self
567    }
568}
569
570/// 原生菜单项:命令 / 分隔线 / 子菜单。
571#[derive(Clone, Debug, PartialEq, Eq)]
572pub enum NativeMenuItem {
573    Command(NativeMenuCommand),
574    Separator,
575    Submenu(NativeMenu),
576}
577
578impl NativeMenuItem {
579    pub fn separator() -> Self {
580        Self::Separator
581    }
582}
583
584impl From<NativeMenuCommand> for NativeMenuItem {
585    fn from(command: NativeMenuCommand) -> Self {
586        Self::Command(command)
587    }
588}
589
590impl From<NativeMenu> for NativeMenuItem {
591    fn from(menu: NativeMenu) -> Self {
592        Self::Submenu(menu)
593    }
594}
595
596/// 一个顶层下拉菜单(如 File / Edit)。
597#[derive(Clone, Debug, PartialEq, Eq)]
598pub struct NativeMenu {
599    pub title: String,
600    pub items: Vec<NativeMenuItem>,
601}
602
603impl NativeMenu {
604    pub fn new(title: impl Into<String>) -> Self {
605        Self { title: title.into(), items: Vec::new() }
606    }
607
608    pub fn with_item(mut self, item: impl Into<NativeMenuItem>) -> Self {
609        self.items.push(item.into());
610        self
611    }
612
613    pub fn with_separator(mut self) -> Self {
614        self.items.push(NativeMenuItem::Separator);
615        self
616    }
617}
618
619/// 原生应用菜单栏。
620///
621/// Windows/macOS 由桌面宿主安装为系统菜单;Linux 当前没有统一原生菜单栏,
622/// 宿主会记录警告并忽略(应用可继续使用框架内 Menu 组件)。
623#[derive(Clone, Debug, Default, PartialEq, Eq)]
624pub struct NativeMenuBar {
625    pub menus: Vec<NativeMenu>,
626}
627
628impl NativeMenuBar {
629    pub fn new() -> Self {
630        Self::default()
631    }
632
633    pub fn with_menu(mut self, menu: NativeMenu) -> Self {
634        self.menus.push(menu);
635        self
636    }
637
638    /// 收集所有命令 id(含嵌套子菜单)。
639    pub fn command_ids(&self) -> Vec<u64> {
640        fn collect(menu: &NativeMenu, out: &mut Vec<u64>) {
641            for item in &menu.items {
642                match item {
643                    NativeMenuItem::Command(command) => out.push(command.id),
644                    NativeMenuItem::Submenu(submenu) => collect(submenu, out),
645                    NativeMenuItem::Separator => {}
646                }
647            }
648        }
649        let mut out = Vec::new();
650        for menu in &self.menus {
651            collect(menu, &mut out);
652        }
653        out
654    }
655
656    /// 收集所有命令的加速键(含嵌套子菜单),供宿主在不转发菜单加速键时使用。
657    pub fn accelerators(&self) -> Vec<(u64, Shortcut)> {
658        fn collect(menu: &NativeMenu, out: &mut Vec<(u64, Shortcut)>) {
659            for item in &menu.items {
660                match item {
661                    NativeMenuItem::Command(command) => {
662                        if let Some(shortcut) = command.shortcut {
663                            out.push((command.id, shortcut));
664                        }
665                    }
666                    NativeMenuItem::Submenu(submenu) => collect(submenu, out),
667                    NativeMenuItem::Separator => {}
668                }
669            }
670        }
671        let mut out = Vec::new();
672        for menu in &self.menus {
673            collect(menu, &mut out);
674        }
675        out
676    }
677}
678
679/// 拖出文件的结果。
680#[derive(Clone, Copy, Debug, PartialEq, Eq)]
681pub enum FileDragOutcome {
682    Dropped,
683    Cancelled,
684}
685
686/// 从窗口拖出文件的选项。
687#[derive(Clone, Debug, PartialEq, Eq)]
688pub struct FileDragOptions {
689    /// 拖拽预览图路径;None = 尝试使用第一个文件(不是图片时无预览)。
690    pub preview: Option<PathBuf>,
691    /// true = 复制(默认);false = 移动。
692    pub copy: bool,
693}
694
695impl Default for FileDragOptions {
696    fn default() -> Self {
697        Self { preview: None, copy: true }
698    }
699}
700
701impl FileDragOptions {
702    pub fn new() -> Self {
703        Self::default()
704    }
705
706    pub fn with_preview(mut self, path: impl Into<PathBuf>) -> Self {
707        self.preview = Some(path.into());
708        self
709    }
710
711    pub fn with_copy(mut self, copy: bool) -> Self {
712        self.copy = copy;
713        self
714    }
715}
716
717/// 已安装原生菜单的运行期控制器。
718///
719/// 由 [`WindowShell::native_menu`] 返回;未知 id 应被忽略而不是 panic。
720pub trait NativeMenuController {
721    fn set_item_enabled(&self, id: u64, enabled: bool);
722    fn set_item_checked(&self, id: u64, checked: bool);
723    /// 显示/隐藏菜单栏。Windows 为真正移除/重新挂载;macOS 会安装空菜单
724    /// (系统全局菜单栏无法完全隐藏)。
725    fn set_visible(&self, visible: bool);
726}
727
728/// 窗口/DPI/IME/平台服务能力——应用只依赖此接口,不直接依赖 winit。
729///
730/// 逻辑坐标约定:`set_ime_cursor_area` 接收 root layer 逻辑坐标(与布局一致),
731/// 由具体 shell 负责换算成平台需要的物理/逻辑单位。
732pub trait WindowShell {
733    fn metrics(&self) -> ShellMetrics;
734    fn request_redraw(&self);
735    fn set_title(&self, title: &str);
736    fn set_visible(&self, visible: bool);
737    /// 窗口当前是否可见;默认 true(headless/未知)。
738    fn is_visible(&self) -> bool {
739        true
740    }
741    fn set_ime_allowed(&self, allowed: bool);
742    fn set_ime_cursor_area(&self, rect: Rect);
743
744    /// 光标形状;默认 no-op。
745    fn set_cursor(&self, _cursor: CursorIcon) {}
746    /// 进入/退出全屏(当前显示器无边框全屏);默认 no-op。
747    fn set_fullscreen(&self, _fullscreen: bool) {}
748    fn is_fullscreen(&self) -> bool {
749        false
750    }
751    /// 最小化 / 还原;默认 no-op。
752    fn set_minimized(&self, _minimized: bool) {}
753    /// 最大化 / 还原;默认 no-op。
754    fn set_maximized(&self, _maximized: bool) {}
755    fn is_maximized(&self) -> bool {
756        false
757    }
758    /// 请求系统把键盘焦点移到此窗口;默认 no-op。
759    fn focus_window(&self) {}
760    /// 显示/隐藏系统标题栏与边框;默认 no-op。
761    fn set_decorations(&self, _decorations: bool) {}
762    /// 最大化与还原之间切换。默认基于 [`WindowShell::is_maximized`] /
763    /// [`WindowShell::set_maximized`] 实现。
764    fn toggle_maximized(&self) {
765        self.set_maximized(!self.is_maximized());
766    }
767    /// 开始拖动窗口(用于自绘标题栏)。由左键按下事件触发,系统接管直到释放。
768    /// 默认返回不支持错误(headless / 平台无此能力)。
769    fn start_dragging(&self) -> Result<(), String> {
770        Err("当前 shell 不支持窗口拖拽".to_string())
771    }
772    /// 开始拖动窗口边缘缩放(用于无边框/自绘标题栏)。
773    ///
774    /// macOS 的 winit 不支持此调用,会返回错误;应用可回退到系统边框或自行实现。
775    fn start_resize(&self, _direction: ResizeDirection) -> Result<(), String> {
776        Err("当前 shell 不支持窗口边缘缩放".to_string())
777    }
778    /// 是否允许用户拖拽调整窗口大小;默认 no-op。
779    fn set_resizable(&self, _resizable: bool) {}
780    /// 置顶 / 取消置顶;默认 no-op。
781    fn set_always_on_top(&self, _on_top: bool) {}
782    /// 设置客户区逻辑尺寸;默认 no-op。
783    fn set_size(&self, _size: Size) {}
784    /// 设置窗口左上角逻辑位置;默认 no-op。
785    fn set_position(&self, _x: f32, _y: f32) {}
786
787    /// 请求关闭当前窗口。应用在 `on_close_requested` 里确认后调用;
788    /// 默认 no-op(headless / 不支持关闭的 shell)。
789    fn request_close(&self) {}
790
791    /// 当前系统明暗主题;None = 平台不支持或未知。
792    fn system_theme(&self) -> Option<SystemTheme> {
793        None
794    }
795
796    /// 系统剪贴板句柄(可克隆,支持文本/HTML/图片/文件列表)。
797    ///
798    /// 默认返回无操作句柄(headless / 不支持剪贴板的 shell)。
799    fn clipboard(&self) -> ClipboardHandle {
800        ClipboardHandle::noop()
801    }
802
803    /// 已安装的原生菜单控制器;None = 未安装/平台不支持。
804    fn native_menu(&self) -> Option<Rc<dyn NativeMenuController>> {
805        None
806    }
807
808    /// 无边框窗口是否启用系统投影(Windows 10 2004+;其他平台 no-op)。
809    ///
810    /// 必须在窗口创建后调用才会显示;不会改变 DWM 圆角/贴靠布局行为。
811    fn set_undecorated_shadow(&self, _shadow: bool) {}
812
813    /// 当前系统是否启用高对比度(Windows 读取注册表;其他平台暂返回 false)。
814    ///
815    /// 应用可在启动与主题变化时查询,并切换到
816    /// [`ThemeData::high_contrast`](https://docs.rs/mgui-core) 等对比度更高的配色。
817    fn high_contrast(&self) -> bool {
818        false
819    }
820
821    /// 设置窗口圆角样式(Windows 11+;其他平台 no-op)。
822    ///
823    /// 无边框窗口默认可能保持直角;在首帧显示前设置为 [`WindowCorners::Rounded`]
824    /// 可让 DWM 绘制系统圆角。该设置不影响贴靠布局(Snap Layouts)。
825    fn set_window_corners(&self, _corners: WindowCorners) {}
826
827    /// 当前窗口几何状态;None = 平台不支持(headless / 尚未创建)。
828    fn window_state(&self) -> Option<WindowState> {
829        None
830    }
831
832    /// 原生“打开文件”对话框。**阻塞调用**,应在 UI 线程直接调用并处理返回值。
833    /// 默认 None(headless / 不支持)。
834    fn pick_file(&self, _options: &FileDialogOptions) -> Option<PathBuf> {
835        None
836    }
837
838    /// 原生“打开多个文件”对话框。
839    fn pick_files(&self, _options: &FileDialogOptions) -> Option<Vec<PathBuf>> {
840        None
841    }
842
843    /// 原生“选择文件夹”对话框。
844    fn pick_folder(&self, _options: &FileDialogOptions) -> Option<PathBuf> {
845        None
846    }
847
848    /// 原生“保存文件”对话框。
849    fn save_file(&self, _options: &FileDialogOptions) -> Option<PathBuf> {
850        None
851    }
852
853    /// 从窗口拖出文件(资源管理器/Finder/文件接收应用)。
854    ///
855    /// **阻塞**直到用户放下或取消;路径应为绝对路径。Windows/macOS 支持,
856    /// Linux 当前返回不支持错误。
857    fn start_file_drag(&self, _paths: &[PathBuf], _options: &FileDragOptions) -> Result<FileDragOutcome, String> {
858        Err("当前 shell 不支持拖出文件".to_string())
859    }
860
861    /// 发送系统通知。同步调用,通常在毫秒级完成;通知服务不可用时返回错误。
862    /// 默认返回不支持错误(headless / 无通知服务的 shell)。
863    fn show_notification(&self, _notification: &Notification) -> Result<(), String> {
864        Err("当前 shell 不支持系统通知".to_string())
865    }
866}
867
868/// 平台无关输入事件 —— 桌面 shell 把原生事件翻译成此类型后再交给应用。
869///
870/// 坐标语义:全部为 **root layer 逻辑坐标**(已按 DPR 换算)。
871#[derive(Clone, Debug, PartialEq)]
872pub enum ShellEvent {
873    CursorMoved {
874        position: Point,
875    },
876    MouseInput {
877        position: Point,
878        button: MouseButton,
879        pressed: bool,
880        modifiers: KeyModifiers,
881    },
882    /// 光标离开窗口客户区(没有按键捕获时)
883    CursorLeft,
884    /// 滚轮/触控板:delta 已归一化为逻辑像素(约 16px/行)。
885    Wheel {
886        position: Point,
887        delta: Point,
888        modifiers: KeyModifiers,
889    },
890    ModifiersChanged(KeyModifiers),
891    Keyboard {
892        key: KeyCode,
893        pressed: bool,
894        repeat: bool,
895        modifiers: KeyModifiers,
896    },
897    Focused(bool),
898    Ime(ImeEvent),
899    /// 文件被拖入窗口(每个文件一次)。
900    FileHovered(PathBuf),
901    /// 拖入的文件离开窗口。
902    FileHoverCancelled,
903    /// 文件在窗口内释放。
904    FileDropped(PathBuf),
905    /// 系统明暗主题变化。
906    ThemeChanged(SystemTheme),
907}
908
909/// 平台无关 IME 事件。
910#[derive(Clone, Debug, PartialEq, Eq)]
911pub enum ImeEvent {
912    Enabled,
913    Disabled,
914    Preedit(String, Option<(usize, usize)>),
915    Commit(String),
916}
917
918/// 帧循环 / 动画使用的单调毫秒时钟。
919pub trait Clock {
920    fn now_ms(&self) -> u64;
921}
922
923/// 手动推进的确定性时钟 —— headless 测试 / 回放用。
924#[derive(Clone, Debug)]
925pub struct ManualClock {
926    now_ms: Cell<u64>,
927}
928
929impl ManualClock {
930    pub fn new(start_ms: u64) -> Self {
931        Self { now_ms: Cell::new(start_ms) }
932    }
933
934    pub fn set(&self, now_ms: u64) {
935        self.now_ms.set(now_ms);
936    }
937
938    pub fn advance(&self, delta_ms: u64) -> u64 {
939        let next = self.now_ms.get().saturating_add(delta_ms);
940        self.now_ms.set(next);
941        next
942    }
943}
944
945impl Default for ManualClock {
946    fn default() -> Self {
947        Self::new(0)
948    }
949}
950
951impl Clock for ManualClock {
952    fn now_ms(&self) -> u64 {
953        self.now_ms.get()
954    }
955}
956
957/// 真实系统时钟(桌面 / 集成环境用)。
958#[derive(Debug)]
959pub struct SystemClock {
960    start: Instant,
961}
962
963impl SystemClock {
964    pub fn new() -> Self {
965        Self { start: Instant::now() }
966    }
967}
968
969impl Default for SystemClock {
970    fn default() -> Self {
971        Self::new()
972    }
973}
974
975impl Clock for SystemClock {
976    fn now_ms(&self) -> u64 {
977        self.start.elapsed().as_millis() as u64
978    }
979}
980
981#[cfg(test)]
982mod tests {
983    use super::*;
984
985    #[test]
986    fn manual_clock_is_deterministic() {
987        let clock = ManualClock::new(100);
988        assert_eq!(clock.now_ms(), 100);
989        assert_eq!(clock.advance(16), 116);
990        clock.set(500);
991        assert_eq!(clock.now_ms(), 500);
992    }
993
994    #[test]
995    fn metrics_clamp_invalid_values() {
996        let m = ShellMetrics::new(Size::new(0.0, -5.0), 0.0);
997        assert_eq!(m.logical_size, Size::new(1.0, 1.0));
998        assert_eq!(m.scale_factor, 0.01);
999    }
1000
1001    #[test]
1002    fn metrics_from_physical_divides_by_dpr() {
1003        let m = ShellMetrics::from_physical(1920, 1080, 2.0);
1004        assert_eq!(m.logical_size, Size::new(960.0, 540.0));
1005        assert_eq!(m.scale_factor, 2.0);
1006    }
1007
1008    #[test]
1009    fn window_state_roundtrip_and_validation() {
1010        let state = WindowState { size: Size::new(1024.0, 720.0), position: Some((120.0, 80.0)), maximized: true };
1011        let parsed = WindowState::parse(&state.encode()).expect("parse roundtrip");
1012        assert_eq!(parsed, state);
1013
1014        // 无 position / 旧版本 / 非法尺寸
1015        let compact = WindowState::parse("mgui-window-state=1\nwidth=800\nheight=600\n").expect("compact");
1016        assert_eq!(compact.position, None);
1017        assert!(!compact.maximized);
1018        assert!(WindowState::parse("mgui-window-state=2\nwidth=800\nheight=600").is_none());
1019        assert!(WindowState::parse("mgui-window-state=1\nwidth=0\nheight=600").is_none());
1020    }
1021
1022    #[test]
1023    fn window_state_file_roundtrip() {
1024        let path = std::env::temp_dir().join(format!(
1025            "mgui-window-state-{}-{}.txt",
1026            std::process::id(),
1027            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)
1028        ));
1029        let state = WindowState { size: Size::new(1280.0, 800.0), position: Some((10.0, 20.0)), maximized: false };
1030        state.save(&path).expect("save state");
1031        assert_eq!(WindowState::load(&path), Some(state));
1032        let _ = std::fs::remove_file(path);
1033    }
1034
1035    #[test]
1036    fn file_dialog_options_builder() {
1037        let options = FileDialogOptions::new("Open")
1038            .with_directory("/tmp")
1039            .with_file_name("notes.txt")
1040            .with_filter("Text", ["txt", "md"])
1041            .with_filter("All", ["*"]);
1042        assert_eq!(options.title, "Open");
1043        assert_eq!(options.directory.as_deref(), Some(std::path::Path::new("/tmp")));
1044        assert_eq!(options.file_name.as_deref(), Some("notes.txt"));
1045        assert_eq!(options.filters.len(), 2);
1046        assert_eq!(options.filters[0].name, "Text");
1047        assert_eq!(options.filters[0].extensions, vec!["txt", "md"]);
1048    }
1049
1050    #[test]
1051    fn notification_builder_defaults_and_overrides() {
1052        let n = Notification::new("Build finished");
1053        assert_eq!(n.title, "Build finished");
1054        assert!(n.body.is_empty());
1055        assert_eq!(n.level, NotificationLevel::Normal);
1056        assert_eq!(n.timeout, NotificationTimeout::Default);
1057        assert!(!n.silent);
1058
1059        let n = n
1060            .with_body("all green")
1061            .with_app_id("studio.qianbai.mgui")
1062            .with_level(NotificationLevel::Critical)
1063            .with_timeout(NotificationTimeout::Never)
1064            .with_silent(true)
1065            .with_icon("dialog-information");
1066        assert_eq!(n.body, "all green");
1067        assert_eq!(n.app_id.as_deref(), Some("studio.qianbai.mgui"));
1068        assert_eq!(n.level, NotificationLevel::Critical);
1069        assert_eq!(n.timeout, NotificationTimeout::Never);
1070        assert!(n.silent);
1071        assert_eq!(n.icon.as_deref(), Some("dialog-information"));
1072    }
1073
1074    #[test]
1075    fn tray_config_keeps_menu_order() {
1076        let icon = IconImage::from_rgba(2, 2, vec![255; 16]).expect("valid icon");
1077        let tray = TrayConfig::new("mgui")
1078            .with_icon(icon)
1079            .with_menu_item(TrayMenuItem::item(1, "Show"))
1080            .with_menu_item(TrayMenuItem::separator())
1081            .with_menu_item(TrayMenuItem::submenu("More", vec![TrayMenuItem::item_enabled(2, "Disabled", false)]))
1082            .with_open_menu_on_left_click(true);
1083        assert_eq!(tray.tooltip, "mgui");
1084        assert!(tray.icon.is_some());
1085        assert_eq!(tray.menu.len(), 3);
1086        assert!(matches!(tray.menu[0], TrayMenuItem::Item { id: 1, ref label, enabled: true } if label == "Show"));
1087        assert_eq!(tray.menu[1], TrayMenuItem::Separator);
1088        assert!(matches!(tray.menu[2], TrayMenuItem::Submenu { ref label, .. } if label == "More"));
1089        assert!(tray.open_menu_on_left_click);
1090    }
1091
1092    #[test]
1093    fn tray_event_is_comparable() {
1094        assert_eq!(TrayEvent::Menu { id: 7 }, TrayEvent::Menu { id: 7 });
1095        assert_ne!(TrayEvent::Click { button: MouseButton::Left }, TrayEvent::Click { button: MouseButton::Right });
1096    }
1097
1098    #[test]
1099    fn shortcut_helpers_set_expected_modifiers() {
1100        assert_eq!(Shortcut::command(ShortcutKey::Char('s')).modifiers, KeyModifiers::command_only());
1101        assert_eq!(Shortcut::ctrl(ShortcutKey::Char('s')).modifiers, KeyModifiers::ctrl_only());
1102        assert_eq!(
1103            Shortcut::ctrl_shift(ShortcutKey::F(5)).modifiers,
1104            KeyModifiers(KeyModifiers::CTRL | KeyModifiers::SHIFT)
1105        );
1106        assert_eq!(Shortcut::alt(ShortcutKey::Left).key, ShortcutKey::Left);
1107    }
1108
1109    #[test]
1110    fn native_menu_builder_collects_nested_accelerators() {
1111        let menu = NativeMenuBar::new()
1112            .with_menu(
1113                NativeMenu::new("File")
1114                    .with_item(
1115                        NativeMenuCommand::new(1, "New").with_shortcut(Shortcut::command(ShortcutKey::Char('n'))),
1116                    )
1117                    .with_item(NativeMenuItem::separator())
1118                    .with_item(
1119                        NativeMenuCommand::new(2, "Exit").with_shortcut(Shortcut::command(ShortcutKey::Char('q'))),
1120                    )
1121                    .with_item(
1122                        NativeMenu::new("More").with_item(
1123                            NativeMenuCommand::new(3, "Deep")
1124                                .with_shortcut(Shortcut::ctrl_shift(ShortcutKey::F(7)))
1125                                .with_checked(true),
1126                        ),
1127                    ),
1128            )
1129            .with_menu(NativeMenu::new("Help"));
1130        let accelerators = menu.accelerators();
1131        assert_eq!(accelerators.len(), 3);
1132        assert_eq!(accelerators[0].0, 1);
1133        assert_eq!(accelerators[1].0, 2);
1134        assert_eq!(accelerators[2].0, 3);
1135        assert_eq!(accelerators[2].1.key, ShortcutKey::F(7));
1136        assert_eq!(menu.menus.len(), 2);
1137        assert_eq!(menu.command_ids(), vec![1, 2, 3]);
1138    }
1139
1140    #[test]
1141    fn global_shortcut_keeps_id_and_combo() {
1142        let shortcut = Shortcut::ctrl_alt(ShortcutKey::Char('m'));
1143        let global = GlobalShortcut::new(42, shortcut);
1144        assert_eq!(global.id, 42);
1145        assert_eq!(global.shortcut, shortcut);
1146    }
1147
1148    #[test]
1149    fn single_instance_config_defaults_to_forwarding() {
1150        let config = SingleInstanceConfig::new("studio.example.app");
1151        assert_eq!(config.id, "studio.example.app");
1152        assert!(config.forward_args);
1153        assert!(!config.with_forward_args(false).forward_args);
1154    }
1155
1156    #[test]
1157    fn file_drag_options_default_to_copy() {
1158        let options = FileDragOptions::new().with_preview("/tmp/a.png").with_copy(false);
1159        assert_eq!(options.preview.as_deref(), Some(std::path::Path::new("/tmp/a.png")));
1160        assert!(!options.copy);
1161        assert!(FileDragOptions::default().copy);
1162    }
1163
1164    #[test]
1165    fn resize_direction_hit_test_prioritizes_corners() {
1166        let size = Size::new(200.0, 100.0);
1167        assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 2.0), size, 6.0), Some(ResizeDirection::NorthWest));
1168        assert_eq!(ResizeDirection::hit_test(Point::new(198.0, 2.0), size, 6.0), Some(ResizeDirection::NorthEast));
1169        assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 98.0), size, 6.0), Some(ResizeDirection::SouthWest));
1170        assert_eq!(ResizeDirection::hit_test(Point::new(100.0, 98.0), size, 6.0), Some(ResizeDirection::South));
1171        assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 50.0), size, 6.0), Some(ResizeDirection::West));
1172        assert_eq!(ResizeDirection::hit_test(Point::new(100.0, 50.0), size, 6.0), None);
1173        assert_eq!(ResizeDirection::hit_test(Point::new(-1.0, 50.0), size, 6.0), None);
1174        assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 2.0), size, 0.0), None);
1175    }
1176}