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