mgui-shell 0.5.0

平台无关 Shell 抽象:Clock / ShellMetrics / Clipboard 能力契约
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
//! mgui-shell — 平台无关的 Shell 抽象。
//!
//! 这里是 desktop / headless 共享的最小契约:
//! - [`Clock`]:帧循环、动画与 IME 闪烁的时间来源
//! - [`ShellMetrics`]:逻辑尺寸 + DPR
//! - [`ClipboardProvider`]:复用 core 的剪贴板契约
//!
//! 窗口创建、原生输入、present 等 desktop 专属能力后续在其上继续分层;
//! 无窗口环境请使用 `mgui-shell-headless`。

#![forbid(unsafe_code)]

use std::cell::Cell;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::time::Instant;

use mgui_core::{KeyCode, KeyModifiers, MouseButton, Point, Rect, Size};

pub use mgui_core::{ClipboardHandle, ClipboardImage, ClipboardProvider, NoopClipboard};

pub mod dispatch;
pub use dispatch::dispatch_shell_event;
pub mod icon;
pub use icon::{IconImage, WindowIcon};
pub mod window_command;
pub use window_command::{route_window_commands, WindowCommand, WindowCommandBus};

/// 平台无关窗口 ID。
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ShellWindowId(pub u64);

/// Shell 的尺寸与 DPI。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ShellMetrics {
    pub logical_size: Size,
    /// 物理像素 / 逻辑像素
    pub scale_factor: f32,
}

impl ShellMetrics {
    pub fn new(logical_size: Size, scale_factor: f32) -> Self {
        Self {
            logical_size: Size::new(logical_size.width.max(1.0), logical_size.height.max(1.0)),
            scale_factor: scale_factor.max(0.01),
        }
    }

    /// 从物理像素尺寸与 DPR 推导逻辑尺寸。
    pub fn from_physical(physical_width: u32, physical_height: u32, scale_factor: f32) -> Self {
        let scale_factor = scale_factor.max(0.01);
        Self::new(Size::new(physical_width as f32 / scale_factor, physical_height as f32 / scale_factor), scale_factor)
    }
}

impl Default for ShellMetrics {
    fn default() -> Self {
        Self::new(Size::new(800.0, 600.0), 1.0)
    }
}

/// 平台无关光标形状。
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CursorIcon {
    #[default]
    Default,
    Pointer,
    Text,
    Crosshair,
    Move,
    NotAllowed,
    Wait,
    Progress,
    Help,
    Grab,
    Grabbing,
    ZoomIn,
    ZoomOut,
    ResizeHorizontal,
    ResizeVertical,
    ResizeNwSe,
    ResizeNeSw,
    ResizeAll,
    ColumnResize,
    RowResize,
}

/// 自定义标题栏的边缘缩放方向。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResizeDirection {
    East,
    North,
    NorthEast,
    NorthWest,
    South,
    SouthEast,
    SouthWest,
    West,
}

impl ResizeDirection {
    /// 按窗口逻辑尺寸与边缘厚度做命中测试;用于自绘标题栏/无边框窗口。
    ///
    /// 角落优先于边;位置在窗口外或 `margin <= 0` 时返回 None。
    pub fn hit_test(position: Point, size: Size, margin: f32) -> Option<Self> {
        if !(margin.is_finite() && margin > 0.0)
            || !(size.width.is_finite() && size.height.is_finite() && size.width > 0.0 && size.height > 0.0)
            || !(position.x.is_finite() && position.y.is_finite())
        {
            return None;
        }
        if position.x < 0.0 || position.y < 0.0 || position.x >= size.width || position.y >= size.height {
            return None;
        }
        let mx = margin.min(size.width / 2.0);
        let my = margin.min(size.height / 2.0);
        let left = position.x < mx;
        let right = position.x > size.width - mx;
        let top = position.y < my;
        let bottom = position.y > size.height - my;
        match (top, bottom, left, right) {
            (true, _, true, _) => Some(Self::NorthWest),
            (true, _, _, true) => Some(Self::NorthEast),
            (_, true, true, _) => Some(Self::SouthWest),
            (_, true, _, true) => Some(Self::SouthEast),
            (true, _, _, _) => Some(Self::North),
            (_, true, _, _) => Some(Self::South),
            (_, _, true, _) => Some(Self::West),
            (_, _, _, true) => Some(Self::East),
            _ => None,
        }
    }
}

/// 无边框/自绘标题栏窗口的角样式(Windows 11;其他平台 no-op)。
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WindowCorners {
    /// 交给系统决定。
    #[default]
    Default,
    /// 直角。
    Square,
    /// 系统圆角(DWM)。
    Rounded,
}

/// 可持久化的窗口几何状态(逻辑像素)。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WindowState {
    pub size: Size,
    /// 窗口左上角(逻辑像素);None = 未知/平台不支持
    pub position: Option<(f32, f32)>,
    pub maximized: bool,
}

impl WindowState {
    pub fn new(size: Size) -> Self {
        Self { size: Size::new(size.width.max(1.0), size.height.max(1.0)), position: None, maximized: false }
    }

    pub fn encode(&self) -> String {
        let mut out = String::from("mgui-window-state=1\n");
        out.push_str(&format!("width={}\nheight={}\n", self.size.width, self.size.height));
        if let Some((x, y)) = self.position {
            out.push_str(&format!("x={x}\ny={y}\n"));
        }
        out.push_str(&format!("maximized={}\n", self.maximized));
        out
    }

    pub fn parse(text: &str) -> Option<Self> {
        let mut version = None;
        let mut width = None;
        let mut height = None;
        let mut x = None;
        let mut y = None;
        let mut maximized = false;
        for line in text.lines() {
            let Some((key, value)) = line.split_once('=') else { continue };
            let key = key.trim();
            let value = value.trim();
            match key {
                "mgui-window-state" => version = value.parse::<u32>().ok(),
                "width" => width = value.parse::<f32>().ok(),
                "height" => height = value.parse::<f32>().ok(),
                "x" => x = value.parse::<f32>().ok(),
                "y" => y = value.parse::<f32>().ok(),
                "maximized" => maximized = matches!(value, "1" | "true"),
                _ => {}
            }
        }
        if version != Some(1) {
            return None;
        }
        let width = width.filter(|v| v.is_finite() && *v >= 1.0)?;
        let height = height.filter(|v| v.is_finite() && *v >= 1.0)?;
        let position = match (x, y) {
            (Some(x), Some(y)) if x.is_finite() && y.is_finite() => Some((x, y)),
            _ => None,
        };
        Some(Self { size: Size::new(width, height), position, maximized })
    }

    pub fn load(path: impl AsRef<Path>) -> Option<Self> {
        let text = std::fs::read_to_string(path).ok()?;
        Self::parse(&text)
    }

    pub fn save(&self, path: impl AsRef<Path>) -> Result<(), String> {
        let path = path.as_ref();
        if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
            std::fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?;
        }
        std::fs::write(path, self.encode()).map_err(|e| format!("write {}: {e}", path.display()))
    }
}

/// 系统外观主题。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SystemTheme {
    Light,
    Dark,
}

/// 文件对话框的扩展名过滤器。
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileDialogFilter {
    pub name: String,
    pub extensions: Vec<String>,
}

impl FileDialogFilter {
    pub fn new<I, S>(name: impl Into<String>, extensions: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self { name: name.into(), extensions: extensions.into_iter().map(Into::into).collect() }
    }
}

/// 原生文件对话框参数。所有字段都是可选提示,shell 可忽略不支持的部分。
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FileDialogOptions {
    pub title: String,
    pub directory: Option<PathBuf>,
    pub file_name: Option<String>,
    pub filters: Vec<FileDialogFilter>,
}

impl FileDialogOptions {
    pub fn new(title: impl Into<String>) -> Self {
        Self { title: title.into(), ..Self::default() }
    }

    pub fn with_directory(mut self, directory: impl Into<PathBuf>) -> Self {
        self.directory = Some(directory.into());
        self
    }

    pub fn with_file_name(mut self, name: impl Into<String>) -> Self {
        self.file_name = Some(name.into());
        self
    }

    pub fn with_filter<I, S>(mut self, name: impl Into<String>, extensions: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.filters.push(FileDialogFilter::new(name, extensions));
        self
    }
}

/// 系统通知的重要级别。平台实现可把 `Critical` 映射为常驻提醒。
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NotificationLevel {
    Low,
    #[default]
    Normal,
    Critical,
}

/// 通知自动消失时间。
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NotificationTimeout {
    /// 使用系统默认时长。
    #[default]
    Default,
    /// 常驻,直到用户主动关闭。
    Never,
    /// 指定毫秒数(系统可能忽略或截断)。
    Milliseconds(u32),
}

/// 平台无关的系统通知。
///
/// `app_id` 在 Windows 上对应 AUMID:打包应用应传入安装时注册的 id,
/// 未注册的 id 可能让通知不显示。`app_name` 主要用于 Linux 通知中心分组。
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Notification {
    pub title: String,
    pub body: String,
    pub app_name: Option<String>,
    pub app_id: Option<String>,
    pub level: NotificationLevel,
    pub silent: bool,
    pub timeout: NotificationTimeout,
    /// Linux 图标名/绝对路径;其他平台可忽略。
    pub icon: Option<String>,
}

impl Notification {
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            body: String::new(),
            app_name: None,
            app_id: None,
            level: NotificationLevel::Normal,
            silent: false,
            timeout: NotificationTimeout::Default,
            icon: None,
        }
    }

    pub fn with_body(mut self, body: impl Into<String>) -> Self {
        self.body = body.into();
        self
    }

    pub fn with_app_name(mut self, name: impl Into<String>) -> Self {
        self.app_name = Some(name.into());
        self
    }

    pub fn with_app_id(mut self, id: impl Into<String>) -> Self {
        self.app_id = Some(id.into());
        self
    }

    pub fn with_level(mut self, level: NotificationLevel) -> Self {
        self.level = level;
        self
    }

    pub fn with_silent(mut self, silent: bool) -> Self {
        self.silent = silent;
        self
    }

    pub fn with_timeout(mut self, timeout: NotificationTimeout) -> Self {
        self.timeout = timeout;
        self
    }

    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
        self.icon = Some(icon.into());
        self
    }
}

/// 托盘菜单项。
///
/// `id` 由应用定义,菜单点击通过 [`TrayEvent::Menu`] 原样返回;
/// 框架不解释 id 语义。
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TrayMenuItem {
    Item { id: u64, label: String, enabled: bool },
    Separator,
    Submenu { label: String, items: Vec<TrayMenuItem> },
}

impl TrayMenuItem {
    pub fn item(id: u64, label: impl Into<String>) -> Self {
        Self::Item { id, label: label.into(), enabled: true }
    }

    pub fn item_enabled(id: u64, label: impl Into<String>, enabled: bool) -> Self {
        Self::Item { id, label: label.into(), enabled }
    }

    pub fn separator() -> Self {
        Self::Separator
    }

    pub fn submenu(label: impl Into<String>, items: Vec<TrayMenuItem>) -> Self {
        Self::Submenu { label: label.into(), items }
    }
}

/// 托盘图标配置。
///
/// 图标复用 [`IconImage`](RGBA8);建议提供 32×32 或平台面板原生尺寸。
/// `icon = None` 时桌面宿主会尝试复用 Runner 的窗口小图标。
/// Linux 使用 StatusNotifierItem,`open_menu_on_left_click` 仅 Windows/macOS 生效。
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TrayConfig {
    pub tooltip: String,
    pub icon: Option<IconImage>,
    pub menu: Vec<TrayMenuItem>,
    pub open_menu_on_left_click: bool,
}

impl TrayConfig {
    pub fn new(tooltip: impl Into<String>) -> Self {
        Self { tooltip: tooltip.into(), ..Self::default() }
    }

    pub fn with_icon(mut self, icon: IconImage) -> Self {
        self.icon = Some(icon);
        self
    }

    pub fn with_menu(mut self, items: Vec<TrayMenuItem>) -> Self {
        self.menu = items;
        self
    }

    pub fn with_menu_item(mut self, item: TrayMenuItem) -> Self {
        self.menu.push(item);
        self
    }

    pub fn with_open_menu_on_left_click(mut self, open: bool) -> Self {
        self.open_menu_on_left_click = open;
        self
    }
}

/// 托盘事件(在 UI/事件循环线程回调)。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TrayEvent {
    /// 单击托盘图标。`open_menu_on_left_click` 为 true 时左键可能只弹菜单。
    Click { button: MouseButton },
    /// 菜单项被激活;`id` 与 [`TrayMenuItem`] 中定义的一致。
    Menu { id: u64 },
}

/// 快捷键主键(不包含修饰键)。
///
/// `Char` 只支持 ASCII 字母、数字与常见标点;名称键覆盖导航/编辑/F1–F24。
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ShortcutKey {
    Char(char),
    Enter,
    Escape,
    Tab,
    Space,
    Backspace,
    Delete,
    Insert,
    Left,
    Right,
    Up,
    Down,
    Home,
    End,
    PageUp,
    PageDown,
    /// F1–F24;非法范围在注册/构建菜单时返回错误。
    F(u8),
}

/// 键位组合。用于原生菜单加速键与全局快捷键。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Shortcut {
    pub modifiers: KeyModifiers,
    pub key: ShortcutKey,
}

impl Shortcut {
    pub const fn new(modifiers: KeyModifiers, key: ShortcutKey) -> Self {
        Self { modifiers, key }
    }

    /// 平台「命令键」:macOS ⌘,Windows/Linux Ctrl。
    pub fn command(key: ShortcutKey) -> Self {
        Self::new(KeyModifiers::command_only(), key)
    }

    pub fn ctrl(key: ShortcutKey) -> Self {
        Self::new(KeyModifiers::ctrl_only(), key)
    }

    pub fn shift(key: ShortcutKey) -> Self {
        Self::new(KeyModifiers::shift_only(), key)
    }

    pub fn ctrl_shift(key: ShortcutKey) -> Self {
        Self::new(KeyModifiers(KeyModifiers::CTRL | KeyModifiers::SHIFT), key)
    }

    pub fn ctrl_alt(key: ShortcutKey) -> Self {
        Self::new(KeyModifiers(KeyModifiers::CTRL | KeyModifiers::ALT), key)
    }

    pub fn alt(key: ShortcutKey) -> Self {
        Self::new(KeyModifiers(KeyModifiers::ALT), key)
    }
}

/// 单实例配置。
///
/// 第一个实例持有本地 socket;后续实例把命令行参数转发给它后立即退出,
/// 由第一个实例的 `RunnerApp::on_second_instance` 处理(例如文件关联打开)。
/// `id` 必须在同一应用的所有版本/会话中保持稳定,建议直接用 `app_id`。
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SingleInstanceConfig {
    pub id: String,
    /// 第二实例是否把命令行参数转发给第一实例;false 时只退出。
    pub forward_args: bool,
}

impl SingleInstanceConfig {
    pub fn new(id: impl Into<String>) -> Self {
        Self { id: id.into(), forward_args: true }
    }

    pub fn with_forward_args(mut self, forward: bool) -> Self {
        self.forward_args = forward;
        self
    }
}

/// 进程级全局快捷键。`id` 由应用定义,按下时原样回调给应用。
///
/// 全局快捷键必须至少包含一个修饰键(Shift/Ctrl/Alt/Meta),避免抢占普通输入。
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GlobalShortcut {
    pub id: u64,
    pub shortcut: Shortcut,
}

impl GlobalShortcut {
    pub fn new(id: u64, shortcut: Shortcut) -> Self {
        Self { id, shortcut }
    }
}

/// 原生菜单命令。
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NativeMenuCommand {
    pub id: u64,
    pub label: String,
    pub shortcut: Option<Shortcut>,
    pub enabled: bool,
    /// None = 普通项;Some = 可勾选项及初始状态。
    pub checked: Option<bool>,
}

impl NativeMenuCommand {
    pub fn new(id: u64, label: impl Into<String>) -> Self {
        Self { id, label: label.into(), shortcut: None, enabled: true, checked: None }
    }

    pub fn with_shortcut(mut self, shortcut: Shortcut) -> Self {
        self.shortcut = Some(shortcut);
        self
    }

    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    pub fn with_checked(mut self, checked: bool) -> Self {
        self.checked = Some(checked);
        self
    }
}

/// 原生菜单项:命令 / 分隔线 / 子菜单。
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NativeMenuItem {
    Command(NativeMenuCommand),
    Separator,
    Submenu(NativeMenu),
}

impl NativeMenuItem {
    pub fn separator() -> Self {
        Self::Separator
    }
}

impl From<NativeMenuCommand> for NativeMenuItem {
    fn from(command: NativeMenuCommand) -> Self {
        Self::Command(command)
    }
}

impl From<NativeMenu> for NativeMenuItem {
    fn from(menu: NativeMenu) -> Self {
        Self::Submenu(menu)
    }
}

/// 一个顶层下拉菜单(如 File / Edit)。
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NativeMenu {
    pub title: String,
    pub items: Vec<NativeMenuItem>,
}

impl NativeMenu {
    pub fn new(title: impl Into<String>) -> Self {
        Self { title: title.into(), items: Vec::new() }
    }

    pub fn with_item(mut self, item: impl Into<NativeMenuItem>) -> Self {
        self.items.push(item.into());
        self
    }

    pub fn with_separator(mut self) -> Self {
        self.items.push(NativeMenuItem::Separator);
        self
    }
}

/// 原生应用菜单栏。
///
/// Windows/macOS 由桌面宿主安装为系统菜单;Linux 当前没有统一原生菜单栏,
/// 宿主会记录警告并忽略(应用可继续使用框架内 Menu 组件)。
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NativeMenuBar {
    pub menus: Vec<NativeMenu>,
}

impl NativeMenuBar {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_menu(mut self, menu: NativeMenu) -> Self {
        self.menus.push(menu);
        self
    }

    /// 收集所有命令 id(含嵌套子菜单)。
    pub fn command_ids(&self) -> Vec<u64> {
        fn collect(menu: &NativeMenu, out: &mut Vec<u64>) {
            for item in &menu.items {
                match item {
                    NativeMenuItem::Command(command) => out.push(command.id),
                    NativeMenuItem::Submenu(submenu) => collect(submenu, out),
                    NativeMenuItem::Separator => {}
                }
            }
        }
        let mut out = Vec::new();
        for menu in &self.menus {
            collect(menu, &mut out);
        }
        out
    }

    /// 收集所有命令的加速键(含嵌套子菜单),供宿主在不转发菜单加速键时使用。
    pub fn accelerators(&self) -> Vec<(u64, Shortcut)> {
        fn collect(menu: &NativeMenu, out: &mut Vec<(u64, Shortcut)>) {
            for item in &menu.items {
                match item {
                    NativeMenuItem::Command(command) => {
                        if let Some(shortcut) = command.shortcut {
                            out.push((command.id, shortcut));
                        }
                    }
                    NativeMenuItem::Submenu(submenu) => collect(submenu, out),
                    NativeMenuItem::Separator => {}
                }
            }
        }
        let mut out = Vec::new();
        for menu in &self.menus {
            collect(menu, &mut out);
        }
        out
    }
}

/// 拖出文件的结果。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FileDragOutcome {
    Dropped,
    Cancelled,
}

/// 从窗口拖出文件的选项。
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileDragOptions {
    /// 拖拽预览图路径;None = 尝试使用第一个文件(不是图片时无预览)。
    pub preview: Option<PathBuf>,
    /// true = 复制(默认);false = 移动。
    pub copy: bool,
}

impl Default for FileDragOptions {
    fn default() -> Self {
        Self { preview: None, copy: true }
    }
}

impl FileDragOptions {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_preview(mut self, path: impl Into<PathBuf>) -> Self {
        self.preview = Some(path.into());
        self
    }

    pub fn with_copy(mut self, copy: bool) -> Self {
        self.copy = copy;
        self
    }
}

/// 已安装原生菜单的运行期控制器。
///
/// 由 [`WindowShell::native_menu`] 返回;未知 id 应被忽略而不是 panic。
pub trait NativeMenuController {
    fn set_item_enabled(&self, id: u64, enabled: bool);
    fn set_item_checked(&self, id: u64, checked: bool);
    /// 显示/隐藏菜单栏。Windows 为真正移除/重新挂载;macOS 会安装空菜单
    /// (系统全局菜单栏无法完全隐藏)。
    fn set_visible(&self, visible: bool);
}

/// 窗口/DPI/IME/平台服务能力——应用只依赖此接口,不直接依赖 winit。
///
/// 逻辑坐标约定:`set_ime_cursor_area` 接收 root layer 逻辑坐标(与布局一致),
/// 由具体 shell 负责换算成平台需要的物理/逻辑单位。
pub trait WindowShell {
    fn metrics(&self) -> ShellMetrics;
    fn request_redraw(&self);
    fn set_title(&self, title: &str);
    fn set_visible(&self, visible: bool);
    /// 窗口当前是否可见;默认 true(headless/未知)。
    fn is_visible(&self) -> bool {
        true
    }
    fn set_ime_allowed(&self, allowed: bool);
    fn set_ime_cursor_area(&self, rect: Rect);

    /// 光标形状;默认 no-op。
    fn set_cursor(&self, _cursor: CursorIcon) {}
    /// 进入/退出全屏(当前显示器无边框全屏);默认 no-op。
    fn set_fullscreen(&self, _fullscreen: bool) {}
    fn is_fullscreen(&self) -> bool {
        false
    }
    /// 最小化 / 还原;默认 no-op。
    fn set_minimized(&self, _minimized: bool) {}
    /// 最大化 / 还原;默认 no-op。
    fn set_maximized(&self, _maximized: bool) {}
    fn is_maximized(&self) -> bool {
        false
    }
    /// 请求系统把键盘焦点移到此窗口;默认 no-op。
    fn focus_window(&self) {}
    /// 显示/隐藏系统标题栏与边框;默认 no-op。
    fn set_decorations(&self, _decorations: bool) {}
    /// 最大化与还原之间切换。默认基于 [`WindowShell::is_maximized`] /
    /// [`WindowShell::set_maximized`] 实现。
    fn toggle_maximized(&self) {
        self.set_maximized(!self.is_maximized());
    }
    /// 开始拖动窗口(用于自绘标题栏)。由左键按下事件触发,系统接管直到释放。
    /// 默认返回不支持错误(headless / 平台无此能力)。
    fn start_dragging(&self) -> Result<(), String> {
        Err("当前 shell 不支持窗口拖拽".to_string())
    }
    /// 开始拖动窗口边缘缩放(用于无边框/自绘标题栏)。
    ///
    /// macOS 的 winit 不支持此调用,会返回错误;应用可回退到系统边框或自行实现。
    fn start_resize(&self, _direction: ResizeDirection) -> Result<(), String> {
        Err("当前 shell 不支持窗口边缘缩放".to_string())
    }
    /// 是否允许用户拖拽调整窗口大小;默认 no-op。
    fn set_resizable(&self, _resizable: bool) {}
    /// 置顶 / 取消置顶;默认 no-op。
    fn set_always_on_top(&self, _on_top: bool) {}
    /// 设置客户区逻辑尺寸;默认 no-op。
    fn set_size(&self, _size: Size) {}
    /// 设置窗口左上角逻辑位置;默认 no-op。
    fn set_position(&self, _x: f32, _y: f32) {}

    /// 请求关闭当前窗口。应用在 `on_close_requested` 里确认后调用;
    /// 默认 no-op(headless / 不支持关闭的 shell)。
    fn request_close(&self) {}

    /// 本进程是否真的有一个可用的系统托盘图标。默认 `false`(headless / 未配置托盘)。
    ///
    /// 给"点 ✕ 收进托盘"这类**否决关闭**的用法当安全阀:Linux 上没有 SNI watcher 时
    /// `with_tray` 会创建失败(宿主只记警告、应用继续运行),此时如果还把关闭翻译成
    /// `set_visible(false)`,用户就得到一个看不见窗口、也没有图标可以唤回的进程。
    /// 所以应用应当先问这一句:没有托盘就放行关闭。
    fn tray_available(&self) -> bool {
        false
    }

    /// 本窗口在 `MultiWindowConfig` 里的名字(`WindowSpec::with_name`)。
    /// 单窗口 / headless 默认 `None`。
    fn window_name(&self) -> Option<String> {
        None
    }

    /// 向**同一次 `run_multi_app` 里的另一个窗口**投递命令(按窗口名寻址)。
    ///
    /// 用于 F3 唤回被关掉的 DevTools 面板窗口、或主窗改完数据后唤醒背景里的
    /// 从窗(Windows 上不保证未聚焦窗口会收到 `RedrawRequested`)。
    /// 命令在下一轮宿主循环里被消费。单窗口宿主 / headless 默认不支持。
    fn send_window_command(&self, _window: &str, _command: WindowCommand) -> Result<(), String> {
        Err("当前 shell 不支持跨窗口命令(只有 run_multi_app 宿主支持)".to_string())
    }

    /// 当前系统明暗主题;None = 平台不支持或未知。
    fn system_theme(&self) -> Option<SystemTheme> {
        None
    }

    /// 系统剪贴板句柄(可克隆,支持文本/HTML/图片/文件列表)。
    ///
    /// 默认返回无操作句柄(headless / 不支持剪贴板的 shell)。
    fn clipboard(&self) -> ClipboardHandle {
        ClipboardHandle::noop()
    }

    /// 已安装的原生菜单控制器;None = 未安装/平台不支持。
    fn native_menu(&self) -> Option<Rc<dyn NativeMenuController>> {
        None
    }

    /// 无边框窗口是否启用系统投影(Windows 10 2004+;其他平台 no-op)。
    ///
    /// 必须在窗口创建后调用才会显示;不会改变 DWM 圆角/贴靠布局行为。
    fn set_undecorated_shadow(&self, _shadow: bool) {}

    /// 当前系统是否启用高对比度(Windows 读取注册表;其他平台暂返回 false)。
    ///
    /// 应用可在启动与主题变化时查询,并切换到
    /// [`ThemeData::high_contrast`](https://docs.rs/mgui-core) 等对比度更高的配色。
    fn high_contrast(&self) -> bool {
        false
    }

    /// 设置窗口圆角样式(Windows 11+;其他平台 no-op)。
    ///
    /// 无边框窗口默认可能保持直角;在首帧显示前设置为 [`WindowCorners::Rounded`]
    /// 可让 DWM 绘制系统圆角。该设置不影响贴靠布局(Snap Layouts)。
    fn set_window_corners(&self, _corners: WindowCorners) {}

    /// 当前窗口几何状态;None = 平台不支持(headless / 尚未创建)。
    fn window_state(&self) -> Option<WindowState> {
        None
    }

    /// 原生“打开文件”对话框。**阻塞调用**,应在 UI 线程直接调用并处理返回值。
    /// 默认 None(headless / 不支持)。
    fn pick_file(&self, _options: &FileDialogOptions) -> Option<PathBuf> {
        None
    }

    /// 原生“打开多个文件”对话框。
    fn pick_files(&self, _options: &FileDialogOptions) -> Option<Vec<PathBuf>> {
        None
    }

    /// 原生“选择文件夹”对话框。
    fn pick_folder(&self, _options: &FileDialogOptions) -> Option<PathBuf> {
        None
    }

    /// 原生“保存文件”对话框。
    fn save_file(&self, _options: &FileDialogOptions) -> Option<PathBuf> {
        None
    }

    /// 从窗口拖出文件(资源管理器/Finder/文件接收应用)。
    ///
    /// **阻塞**直到用户放下或取消;路径应为绝对路径。Windows/macOS 支持,
    /// Linux 当前返回不支持错误。
    fn start_file_drag(&self, _paths: &[PathBuf], _options: &FileDragOptions) -> Result<FileDragOutcome, String> {
        Err("当前 shell 不支持拖出文件".to_string())
    }

    /// 发送系统通知。同步调用,通常在毫秒级完成;通知服务不可用时返回错误。
    /// 默认返回不支持错误(headless / 无通知服务的 shell)。
    fn show_notification(&self, _notification: &Notification) -> Result<(), String> {
        Err("当前 shell 不支持系统通知".to_string())
    }
}

/// 平台无关输入事件 —— 桌面 shell 把原生事件翻译成此类型后再交给应用。
///
/// 坐标语义:全部为 **root layer 逻辑坐标**(已按 DPR 换算)。
#[derive(Clone, Debug, PartialEq)]
pub enum ShellEvent {
    CursorMoved {
        position: Point,
    },
    MouseInput {
        position: Point,
        button: MouseButton,
        pressed: bool,
        modifiers: KeyModifiers,
    },
    /// 光标离开窗口客户区(没有按键捕获时)
    CursorLeft,
    /// 滚轮/触控板:delta 已归一化为逻辑像素(约 16px/行)。
    Wheel {
        position: Point,
        delta: Point,
        modifiers: KeyModifiers,
    },
    ModifiersChanged(KeyModifiers),
    Keyboard {
        key: KeyCode,
        pressed: bool,
        repeat: bool,
        modifiers: KeyModifiers,
    },
    Focused(bool),
    Ime(ImeEvent),
    /// 文件被拖入窗口(每个文件一次)。
    FileHovered(PathBuf),
    /// 拖入的文件离开窗口。
    FileHoverCancelled,
    /// 文件在窗口内释放。
    FileDropped(PathBuf),
    /// 系统明暗主题变化。
    ThemeChanged(SystemTheme),
}

/// 平台无关 IME 事件。
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ImeEvent {
    Enabled,
    Disabled,
    Preedit(String, Option<(usize, usize)>),
    Commit(String),
}

/// 帧循环 / 动画使用的单调毫秒时钟。
pub trait Clock {
    fn now_ms(&self) -> u64;
}

/// 手动推进的确定性时钟 —— headless 测试 / 回放用。
#[derive(Clone, Debug)]
pub struct ManualClock {
    now_ms: Cell<u64>,
}

impl ManualClock {
    pub fn new(start_ms: u64) -> Self {
        Self { now_ms: Cell::new(start_ms) }
    }

    pub fn set(&self, now_ms: u64) {
        self.now_ms.set(now_ms);
    }

    pub fn advance(&self, delta_ms: u64) -> u64 {
        let next = self.now_ms.get().saturating_add(delta_ms);
        self.now_ms.set(next);
        next
    }
}

impl Default for ManualClock {
    fn default() -> Self {
        Self::new(0)
    }
}

impl Clock for ManualClock {
    fn now_ms(&self) -> u64 {
        self.now_ms.get()
    }
}

/// 真实系统时钟(桌面 / 集成环境用)。
#[derive(Debug)]
pub struct SystemClock {
    start: Instant,
}

impl SystemClock {
    pub fn new() -> Self {
        Self { start: Instant::now() }
    }
}

impl Default for SystemClock {
    fn default() -> Self {
        Self::new()
    }
}

impl Clock for SystemClock {
    fn now_ms(&self) -> u64 {
        self.start.elapsed().as_millis() as u64
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn manual_clock_is_deterministic() {
        let clock = ManualClock::new(100);
        assert_eq!(clock.now_ms(), 100);
        assert_eq!(clock.advance(16), 116);
        clock.set(500);
        assert_eq!(clock.now_ms(), 500);
    }

    #[test]
    fn metrics_clamp_invalid_values() {
        let m = ShellMetrics::new(Size::new(0.0, -5.0), 0.0);
        assert_eq!(m.logical_size, Size::new(1.0, 1.0));
        assert_eq!(m.scale_factor, 0.01);
    }

    #[test]
    fn metrics_from_physical_divides_by_dpr() {
        let m = ShellMetrics::from_physical(1920, 1080, 2.0);
        assert_eq!(m.logical_size, Size::new(960.0, 540.0));
        assert_eq!(m.scale_factor, 2.0);
    }

    #[test]
    fn window_state_roundtrip_and_validation() {
        let state = WindowState { size: Size::new(1024.0, 720.0), position: Some((120.0, 80.0)), maximized: true };
        let parsed = WindowState::parse(&state.encode()).expect("parse roundtrip");
        assert_eq!(parsed, state);

        // 无 position / 旧版本 / 非法尺寸
        let compact = WindowState::parse("mgui-window-state=1\nwidth=800\nheight=600\n").expect("compact");
        assert_eq!(compact.position, None);
        assert!(!compact.maximized);
        assert!(WindowState::parse("mgui-window-state=2\nwidth=800\nheight=600").is_none());
        assert!(WindowState::parse("mgui-window-state=1\nwidth=0\nheight=600").is_none());
    }

    #[test]
    fn window_state_file_roundtrip() {
        let path = std::env::temp_dir().join(format!(
            "mgui-window-state-{}-{}.txt",
            std::process::id(),
            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)
        ));
        let state = WindowState { size: Size::new(1280.0, 800.0), position: Some((10.0, 20.0)), maximized: false };
        state.save(&path).expect("save state");
        assert_eq!(WindowState::load(&path), Some(state));
        let _ = std::fs::remove_file(path);
    }

    #[test]
    fn file_dialog_options_builder() {
        let options = FileDialogOptions::new("Open")
            .with_directory("/tmp")
            .with_file_name("notes.txt")
            .with_filter("Text", ["txt", "md"])
            .with_filter("All", ["*"]);
        assert_eq!(options.title, "Open");
        assert_eq!(options.directory.as_deref(), Some(std::path::Path::new("/tmp")));
        assert_eq!(options.file_name.as_deref(), Some("notes.txt"));
        assert_eq!(options.filters.len(), 2);
        assert_eq!(options.filters[0].name, "Text");
        assert_eq!(options.filters[0].extensions, vec!["txt", "md"]);
    }

    #[test]
    fn notification_builder_defaults_and_overrides() {
        let n = Notification::new("Build finished");
        assert_eq!(n.title, "Build finished");
        assert!(n.body.is_empty());
        assert_eq!(n.level, NotificationLevel::Normal);
        assert_eq!(n.timeout, NotificationTimeout::Default);
        assert!(!n.silent);

        let n = n
            .with_body("all green")
            .with_app_id("studio.qianbai.mgui")
            .with_level(NotificationLevel::Critical)
            .with_timeout(NotificationTimeout::Never)
            .with_silent(true)
            .with_icon("dialog-information");
        assert_eq!(n.body, "all green");
        assert_eq!(n.app_id.as_deref(), Some("studio.qianbai.mgui"));
        assert_eq!(n.level, NotificationLevel::Critical);
        assert_eq!(n.timeout, NotificationTimeout::Never);
        assert!(n.silent);
        assert_eq!(n.icon.as_deref(), Some("dialog-information"));
    }

    #[test]
    fn tray_config_keeps_menu_order() {
        let icon = IconImage::from_rgba(2, 2, vec![255; 16]).expect("valid icon");
        let tray = TrayConfig::new("mgui")
            .with_icon(icon)
            .with_menu_item(TrayMenuItem::item(1, "Show"))
            .with_menu_item(TrayMenuItem::separator())
            .with_menu_item(TrayMenuItem::submenu("More", vec![TrayMenuItem::item_enabled(2, "Disabled", false)]))
            .with_open_menu_on_left_click(true);
        assert_eq!(tray.tooltip, "mgui");
        assert!(tray.icon.is_some());
        assert_eq!(tray.menu.len(), 3);
        assert!(matches!(tray.menu[0], TrayMenuItem::Item { id: 1, ref label, enabled: true } if label == "Show"));
        assert_eq!(tray.menu[1], TrayMenuItem::Separator);
        assert!(matches!(tray.menu[2], TrayMenuItem::Submenu { ref label, .. } if label == "More"));
        assert!(tray.open_menu_on_left_click);
    }

    #[test]
    fn tray_event_is_comparable() {
        assert_eq!(TrayEvent::Menu { id: 7 }, TrayEvent::Menu { id: 7 });
        assert_ne!(TrayEvent::Click { button: MouseButton::Left }, TrayEvent::Click { button: MouseButton::Right });
    }

    #[test]
    fn shortcut_helpers_set_expected_modifiers() {
        assert_eq!(Shortcut::command(ShortcutKey::Char('s')).modifiers, KeyModifiers::command_only());
        assert_eq!(Shortcut::ctrl(ShortcutKey::Char('s')).modifiers, KeyModifiers::ctrl_only());
        assert_eq!(
            Shortcut::ctrl_shift(ShortcutKey::F(5)).modifiers,
            KeyModifiers(KeyModifiers::CTRL | KeyModifiers::SHIFT)
        );
        assert_eq!(Shortcut::alt(ShortcutKey::Left).key, ShortcutKey::Left);
    }

    #[test]
    fn native_menu_builder_collects_nested_accelerators() {
        let menu = NativeMenuBar::new()
            .with_menu(
                NativeMenu::new("File")
                    .with_item(
                        NativeMenuCommand::new(1, "New").with_shortcut(Shortcut::command(ShortcutKey::Char('n'))),
                    )
                    .with_item(NativeMenuItem::separator())
                    .with_item(
                        NativeMenuCommand::new(2, "Exit").with_shortcut(Shortcut::command(ShortcutKey::Char('q'))),
                    )
                    .with_item(
                        NativeMenu::new("More").with_item(
                            NativeMenuCommand::new(3, "Deep")
                                .with_shortcut(Shortcut::ctrl_shift(ShortcutKey::F(7)))
                                .with_checked(true),
                        ),
                    ),
            )
            .with_menu(NativeMenu::new("Help"));
        let accelerators = menu.accelerators();
        assert_eq!(accelerators.len(), 3);
        assert_eq!(accelerators[0].0, 1);
        assert_eq!(accelerators[1].0, 2);
        assert_eq!(accelerators[2].0, 3);
        assert_eq!(accelerators[2].1.key, ShortcutKey::F(7));
        assert_eq!(menu.menus.len(), 2);
        assert_eq!(menu.command_ids(), vec![1, 2, 3]);
    }

    #[test]
    fn global_shortcut_keeps_id_and_combo() {
        let shortcut = Shortcut::ctrl_alt(ShortcutKey::Char('m'));
        let global = GlobalShortcut::new(42, shortcut);
        assert_eq!(global.id, 42);
        assert_eq!(global.shortcut, shortcut);
    }

    #[test]
    fn single_instance_config_defaults_to_forwarding() {
        let config = SingleInstanceConfig::new("studio.example.app");
        assert_eq!(config.id, "studio.example.app");
        assert!(config.forward_args);
        assert!(!config.with_forward_args(false).forward_args);
    }

    #[test]
    fn file_drag_options_default_to_copy() {
        let options = FileDragOptions::new().with_preview("/tmp/a.png").with_copy(false);
        assert_eq!(options.preview.as_deref(), Some(std::path::Path::new("/tmp/a.png")));
        assert!(!options.copy);
        assert!(FileDragOptions::default().copy);
    }

    #[test]
    fn resize_direction_hit_test_prioritizes_corners() {
        let size = Size::new(200.0, 100.0);
        assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 2.0), size, 6.0), Some(ResizeDirection::NorthWest));
        assert_eq!(ResizeDirection::hit_test(Point::new(198.0, 2.0), size, 6.0), Some(ResizeDirection::NorthEast));
        assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 98.0), size, 6.0), Some(ResizeDirection::SouthWest));
        assert_eq!(ResizeDirection::hit_test(Point::new(100.0, 98.0), size, 6.0), Some(ResizeDirection::South));
        assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 50.0), size, 6.0), Some(ResizeDirection::West));
        assert_eq!(ResizeDirection::hit_test(Point::new(100.0, 50.0), size, 6.0), None);
        assert_eq!(ResizeDirection::hit_test(Point::new(-1.0, 50.0), size, 6.0), None);
        assert_eq!(ResizeDirection::hit_test(Point::new(2.0, 2.0), size, 0.0), None);
    }
}