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