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