lieui 0.1.0-alpha.3

A retained-tree GUI toolkit in pure Rust: retained view tree + reactive signals + pure-CPU rendering
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
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
//! 事件模型:类型 + 路由策略 + 两段式分发。
//!
//! 对齐 WinUI `UIElement` 的裁剪版(设计文档 §3.5 / §3.13):
//! - 一种事件种类表 + 三态路由(`Tunnel` / `Bubble` / `Direct`);
//! - 处理器统一是闭包 `Rc<dyn Fn(&mut Ctx)>`,**只拿 `&mut Ctx`**;
//! - `handled` + `handledEventsToo` 取代旧实现的 `.builtin()` 排序 hack;
//! - **`Ctx` 不提供对保留树的访问**:处理器只能改状态 / 攒 `Cmd` / 请求重绘,
//!   结构变化一律靠下一帧 `view()` 重跑(这就是"闭包不改结构"的落地约束)。
//!
//! 分发是**两段式**的(借用安全的唯一路径):
//! ① 只读遍历 → 收集 `HandlerSlot`(`Rc` clone);② 借用释放后逐个调用。

use std::rc::Rc;

use lieui_geom::Point;

use crate::cmd::{Cmd, CmdBuf};
use crate::reactive::{Dirty, Runtime};
use crate::track::{FocusState, NodeId, Track};
use crate::window::WindowId;

/// 指针身份(鼠标写死 0,触控留口)
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default)]
pub struct PointerId(pub u32);

/// 指针按键
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default)]
pub enum PointerButton {
    #[default]
    Left,
    Right,
    Middle,
    Other(u16),
}

/// 路由策略
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum Routing {
    /// 预览(隧道)阶段:外 → 内,先于 Bubble
    Tunnel,
    /// 冒泡阶段:内 → 外
    Bubble,
    /// 只发给目标节点,不传播
    Direct,
}

/// 命名键(M1 只列常用;`Other` 保留原始码)
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum NamedKey {
    Enter,
    Escape,
    Tab,
    Backspace,
    Delete,
    Insert,
    Space,
    Left,
    Right,
    Up,
    Down,
    Home,
    End,
    PageUp,
    PageDown,
    Shift,
    Control,
    Alt,
    Meta,
    Other(u32),
}

/// 键码
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum KeyCode {
    Named(NamedKey),
    Char(char),
}

/// 修饰键状态(手写位集;键盘编辑需要 Shift 扩选、Ctrl 全选/词跳)
#[derive(Copy, Clone, PartialEq, Eq, Default, Debug)]
pub struct Modifiers(u8);

impl Modifiers {
    pub const EMPTY: Self = Self(0);
    pub const SHIFT: Self = Self(1);
    pub const CTRL: Self = Self(1 << 1);
    pub const ALT: Self = Self(1 << 2);
    pub const META: Self = Self(1 << 3);

    pub const fn bits(self) -> u8 {
        self.0
    }

    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    pub const fn contains(self, other: Self) -> bool {
        self.0 & other.0 == other.0
    }

    pub const fn shift(self) -> bool {
        self.contains(Self::SHIFT)
    }

    pub const fn ctrl(self) -> bool {
        self.contains(Self::CTRL)
    }

    pub const fn alt(self) -> bool {
        self.contains(Self::ALT)
    }

    pub const fn meta(self) -> bool {
        self.contains(Self::META)
    }

    pub fn insert(&mut self, other: Self) {
        self.0 |= other.0;
    }
}

impl std::ops::BitOr for Modifiers {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

impl std::ops::BitOrAssign for Modifiers {
    fn bitor_assign(&mut self, rhs: Self) {
        self.insert(rhs);
    }
}

/// 事件种类(裁剪自 WinUI `UIElement` 的 32 个 `*Event` + `FrameworkElement` 的若干)
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum EventKind {
    // ── 指针 ──
    PointerEntered,
    PointerExited,
    PointerMoved,
    PointerPressed,
    PointerReleased,
    PointerWheelChanged,
    PointerCanceled,
    PointerCaptureLost,
    // ── 点击 / 手势 / 上下文 ──
    Tapped,
    DoubleTapped,
    RightTapped,
    Holding,
    ContextRequested,
    ContextCanceled,
    // ── 键盘 / 字符 ──
    KeyDown,
    KeyUp,
    PreviewKeyDown,
    PreviewKeyUp,
    CharacterReceived,
    // ── 焦点 ──
    GettingFocus,
    GotFocus,
    LosingFocus,
    LostFocus,
    NoFocusCandidateFound,
    // ── 文本 / IME ──
    TextCompositionStarted,
    TextCompositionChanged,
    TextCompositionEnded,
    // ── 生命周期 / 布局 ──
    Loaded,
    Unloaded,
    SizeChanged,
    EffectiveViewportChanged,
    ScrollChanged,
    BringIntoViewRequested,
    // ── 拖放 ──
    DragStarting,
    DragEnter,
    DragOver,
    DragLeave,
    Drop,
    DropCompleted,
    // ── 框架内 ──
    /// 浮层被"点击外部"关闭:发给该层根(由 `App` 在命中测试之外派发)
    Dismissed,
    /// 逐帧 tick(动画)——框架自有
    Tick,
}

impl EventKind {
    /// 路由策略(设计 §3.5:`Preview*` 走隧道,捕获丢失/生命周期类只发给目标)
    pub const fn routing(self) -> Routing {
        use EventKind::*;
        match self {
            PreviewKeyDown | PreviewKeyUp => Routing::Tunnel,
            PointerCaptureLost | Loaded | Unloaded | SizeChanged | EffectiveViewportChanged
            | ScrollChanged | BringIntoViewRequested | Dismissed | Tick | NoFocusCandidateFound => {
                Routing::Direct
            }
            _ => Routing::Bubble,
        }
    }

    /// 是否为指针类事件(分发时要按 `PointerId` 找捕获)
    pub const fn is_pointer(self) -> bool {
        use EventKind::*;
        matches!(
            self,
            PointerEntered
                | PointerExited
                | PointerMoved
                | PointerPressed
                | PointerReleased
                | PointerWheelChanged
                | PointerCanceled
                | PointerCaptureLost
                | Tapped
                | DoubleTapped
                | RightTapped
                | Holding
        )
    }

    /// 调试名
    pub const fn name(self) -> &'static str {
        use EventKind::*;
        match self {
            PointerEntered => "PointerEntered",
            PointerExited => "PointerExited",
            PointerMoved => "PointerMoved",
            PointerPressed => "PointerPressed",
            PointerReleased => "PointerReleased",
            PointerWheelChanged => "PointerWheelChanged",
            PointerCanceled => "PointerCanceled",
            PointerCaptureLost => "PointerCaptureLost",
            Tapped => "Tapped",
            DoubleTapped => "DoubleTapped",
            RightTapped => "RightTapped",
            Holding => "Holding",
            ContextRequested => "ContextRequested",
            ContextCanceled => "ContextCanceled",
            KeyDown => "KeyDown",
            KeyUp => "KeyUp",
            PreviewKeyDown => "PreviewKeyDown",
            PreviewKeyUp => "PreviewKeyUp",
            CharacterReceived => "CharacterReceived",
            GettingFocus => "GettingFocus",
            GotFocus => "GotFocus",
            LosingFocus => "LosingFocus",
            LostFocus => "LostFocus",
            NoFocusCandidateFound => "NoFocusCandidateFound",
            TextCompositionStarted => "TextCompositionStarted",
            TextCompositionChanged => "TextCompositionChanged",
            TextCompositionEnded => "TextCompositionEnded",
            Loaded => "Loaded",
            Unloaded => "Unloaded",
            SizeChanged => "SizeChanged",
            EffectiveViewportChanged => "EffectiveViewportChanged",
            ScrollChanged => "ScrollChanged",
            BringIntoViewRequested => "BringIntoViewRequested",
            DragStarting => "DragStarting",
            DragEnter => "DragEnter",
            DragOver => "DragOver",
            DragLeave => "DragLeave",
            Drop => "Drop",
            DropCompleted => "DropCompleted",
            Dismissed => "Dismissed",
            Tick => "Tick",
        }
    }
}

/// 事件(M1 的裁剪版;IME / 拖放 / 手势的 payload 随后续里程碑补)
#[derive(Clone, Debug, PartialEq)]
pub enum Event {
    Pointer {
        kind: EventKind,
        pointer: PointerId,
        pos: Point,
        button: PointerButton,
    },
    Wheel {
        pos: Point,
        delta: (f32, f32),
    },
    Key {
        kind: EventKind,
        code: KeyCode,
        /// 字符输入(`CharacterReceived` 的 payload;IME 提交也走这里)
        text: Option<String>,
        repeat: bool,
        modifiers: Modifiers,
    },
    /// 焦点 / 生命周期 / 框架内事件(无 payload)
    Simple {
        kind: EventKind,
    },
    /// IME 预编辑(输入法未提交的组合文本;`cursor` 是字节区间)
    ImePreedit {
        text: String,
        cursor: Option<(u32, u32)>,
    },
    /// 滚动变化(发给滚动容器自身;`offset` 是新偏移)
    Scroll {
        offset: (f32, f32),
    },
    Tick {
        now_ms: u64,
    },
}

/// 事件的**只读摘要**(`Copy`):处理器通过 `Ctx` 读它,避免每处理器 clone 整个 payload
#[derive(Clone, Copy, Debug)]
pub struct EventView {
    pub kind: EventKind,
    pub pos: Point,
    pub pointer: PointerId,
    pub button: PointerButton,
    pub wheel: (f32, f32),
    /// 滚动容器的新偏移(`ScrollChanged` 专用)
    pub scroll: (f32, f32),
    pub key: Option<KeyCode>,
    pub repeat: bool,
    pub modifiers: Modifiers,
    pub now_ms: u64,
}

impl Event {
    /// 指针类事件
    pub fn pointer(kind: EventKind, pointer: PointerId, pos: Point, button: PointerButton) -> Self {
        Event::Pointer {
            kind,
            pointer,
            pos,
            button,
        }
    }

    /// 滚轮(`delta` 正 = 向上:滚轮上推 / 触控板上滑 ⇒ offset 减小,见
    /// `input::default_wheel_scroll`)
    pub fn wheel(pos: Point, delta: (f32, f32)) -> Self {
        Event::Wheel { pos, delta }
    }

    /// 无 payload 事件(焦点 / 生命周期 / 框架内)
    pub fn simple(kind: EventKind) -> Self {
        Event::Simple { kind }
    }

    /// 键盘事件
    pub fn key(kind: EventKind, code: KeyCode) -> Self {
        Self::key_with(kind, code, Modifiers::EMPTY)
    }

    /// 键盘事件(带修饰键)
    pub fn key_with(kind: EventKind, code: KeyCode, modifiers: Modifiers) -> Self {
        Event::Key {
            kind,
            code,
            text: None,
            repeat: false,
            modifiers,
        }
    }

    /// 字符输入(`CharacterReceived`):IME 提交也走这条,一个字符一条
    pub fn char_received(ch: char) -> Self {
        Event::Key {
            kind: EventKind::CharacterReceived,
            code: KeyCode::Char(ch),
            text: Some(ch.to_string()),
            repeat: false,
            modifiers: Modifiers::EMPTY,
        }
    }

    pub fn kind(&self) -> EventKind {
        match self {
            Event::Pointer { kind, .. } | Event::Key { kind, .. } | Event::Simple { kind } => *kind,
            Event::Wheel { .. } => EventKind::PointerWheelChanged,
            Event::ImePreedit { .. } => EventKind::TextCompositionChanged,
            Event::Scroll { .. } => EventKind::ScrollChanged,
            Event::Tick { .. } => EventKind::Tick,
        }
    }

    pub fn summary(&self) -> EventView {
        match self {
            Event::Pointer {
                kind,
                pointer,
                pos,
                button,
            } => EventView {
                kind: *kind,
                pos: *pos,
                pointer: *pointer,
                button: *button,
                ..EventView::empty(*kind)
            },
            Event::Wheel { pos, delta } => EventView {
                kind: EventKind::PointerWheelChanged,
                pos: *pos,
                wheel: *delta,
                ..EventView::empty(EventKind::PointerWheelChanged)
            },
            Event::Key {
                kind,
                code,
                repeat,
                modifiers,
                ..
            } => EventView {
                kind: *kind,
                key: Some(*code),
                repeat: *repeat,
                modifiers: *modifiers,
                ..EventView::empty(*kind)
            },
            Event::Simple { kind } => EventView::empty(*kind),
            Event::ImePreedit { .. } => EventView::empty(EventKind::TextCompositionChanged),
            Event::Scroll { offset } => EventView {
                kind: EventKind::ScrollChanged,
                scroll: *offset,
                ..EventView::empty(EventKind::ScrollChanged)
            },
            Event::Tick { now_ms } => EventView {
                kind: EventKind::Tick,
                now_ms: *now_ms,
                ..EventView::empty(EventKind::Tick)
            },
        }
    }

    pub fn pointer_pos(&self) -> Option<Point> {
        match self {
            Event::Pointer { pos, .. } | Event::Wheel { pos, .. } => Some(*pos),
            _ => None,
        }
    }
}

impl EventView {
    fn empty(kind: EventKind) -> Self {
        Self {
            kind,
            pos: Point::zero(),
            pointer: PointerId(0),
            button: PointerButton::Left,
            wheel: (0.0, 0.0),
            scroll: (0.0, 0.0),
            key: None,
            repeat: false,
            modifiers: Modifiers::EMPTY,
            now_ms: 0,
        }
    }

    /// 无 payload 的事件(焦点 / 生命周期 / 框架内)
    pub fn simple(kind: EventKind) -> Self {
        Self::empty(kind)
    }

    /// 逐帧钩子的"伪事件"(`on_tick` 的 `Ctx` 也拿得到事件摘要,保持统一)
    pub fn tick() -> Self {
        Self::empty(EventKind::Tick)
    }

    /// 外部数据的"伪事件"
    pub fn external() -> Self {
        Self::empty(EventKind::Unloaded)
    }
}

/// 事件处理器:只拿 `&mut Ctx`(改状态 / 攒 `Cmd` / 请求重绘),**不拿保留树**
pub type Handler = Rc<dyn Fn(&mut Ctx)>;

/// 节点上的一个处理器槽位
#[derive(Clone)]
pub struct HandlerSlot {
    pub kind: EventKind,
    pub handler: Handler,
    /// `true` = 即便事件已被处理也要调用(≈ WinUI `handledEventsToo`);
    /// 框架内置行为用它,取代旧实现的 `.builtin()` 排序 hack。
    pub handled_events_too: bool,
}

impl std::fmt::Debug for HandlerSlot {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HandlerSlot")
            .field("kind", &self.kind)
            .field("handled_events_too", &self.handled_events_too)
            .finish()
    }
}

/// 处理器上下文。
///
/// 约束(§3.5):用户闭包**不能**直接改视图树,只能
/// ① 改 `Signal`(自动置 `VIEW`);② 用 `Cmd` 请求框架动作;③ 显式请求失效/重绘。
pub struct Ctx {
    rt: Runtime,
    window: WindowId,
    event: EventView,
    handled: bool,
    cmds: CmdBuf,
}

impl Ctx {
    pub fn new(rt: &Runtime, window: WindowId, event: EventView) -> Self {
        Self {
            rt: rt.clone(),
            window,
            event,
            handled: false,
            cmds: CmdBuf::new(),
        }
    }

    pub fn window(&self) -> WindowId {
        self.window
    }

    /// 运行时句柄(事件里要建新 signal / 新窗口时用)
    pub fn runtime(&self) -> Runtime {
        self.rt.clone()
    }

    /// 当前事件的只读摘要
    pub fn event(&self) -> EventView {
        self.event
    }

    /// 滚动容器的新偏移(`ScrollChanged` 事件专用;其它事件返回 `(0,0)`)
    pub fn scroll_offset(&self) -> (f32, f32) {
        self.event.scroll
    }

    // ── handled ──

    pub fn handled(&self) -> bool {
        self.handled
    }

    /// 标记"已处理":后续 `handled_events_too == false` 的处理器将被跳过
    pub fn mark_handled(&mut self) {
        self.handled = true;
    }

    pub fn set_handled(&mut self, v: bool) {
        self.handled = v;
    }

    // ── 失效 / 重绘 ──

    /// 非 `Signal` 路径的状态变更 → 下帧重跑 `view()` + `align`
    pub fn invalidate(&self) {
        self.rt.mark(self.window, Dirty::VIEW);
    }

    /// 请求重绘(不重跑 `view()`、不重排):**已有脏区**里那一块会被光栅化。
    ///
    /// 适合"状态在节点属性里、脏区已由树登记"的场景(光标闪烁、外部像素流)。
    /// 自绘节点改了内部状态(不经过树)时要用 [`Self::damage_all`] 或 [`Self::damage`],
    /// 否则没有脏区 ⇒ 什么都不画。
    pub fn request_repaint(&self) {
        self.rt.mark(self.window, Dirty::PAINT | Dirty::PRESENT);
    }

    /// **整窗标脏**(下一帧整窗重绘)。
    ///
    /// 动画帧里最常用:自绘节点(`CustomNode`)的相位不经过保留树,
    /// 没有脏矩形可登记 ⇒ 用整窗重绘保证画出来(精修脏区可用 [`Self::damage`])。
    pub fn damage_all(&mut self) {
        self.cmds.damage_all();
    }

    // ── 定时器 / 动画帧(见 `crate::timer`)──

    /// 延迟 `dur` 后回调一次(在 **UI 线程**执行,可拿 `&mut Ctx`)
    pub fn set_timeout<F: FnMut(&mut Ctx) + 'static>(
        &self,
        dur: std::time::Duration,
        f: F,
    ) -> crate::timer::TimerHandle {
        self.rt.set_timeout(self.window, dur, f)
    }

    /// 每 `dur` 回调一次(直到 `TimerHandle::cancel` 或窗口关闭)
    pub fn set_interval<F: FnMut(&mut Ctx) + 'static>(
        &self,
        dur: std::time::Duration,
        f: F,
    ) -> crate::timer::TimerHandle {
        self.rt.set_interval(self.window, dur, f)
    }

    /// 请求下一帧回调 `ViewModel::on_animation`(想继续动画就在回调里再请求一次)
    pub fn request_animation(&self) {
        self.rt.request_animation(self.window);
    }

    // ── 后台任务 / loading 遮罩(见 `crate::task`)──

    /// 起一个后台任务(**在当前窗口**):返回值由框架投递给 `on_external`(包在
    /// [`crate::task::TaskEvent`] 里)。多数情况用带遮罩的
    /// [`Self::spawn_task_busy`](Self::spawn_task_busy)。
    pub fn spawn_task<T, F>(&self, work: F) -> crate::task::TaskHandle
    where
        T: Send + 'static,
        F: FnOnce(crate::task::TaskCtx) -> T + Send + 'static,
    {
        self.rt.spawn_task(self.window, work)
    }

    /// 起一个后台任务 + loading 遮罩(文案 `label`):完成时遮罩自动收起。
    pub fn spawn_task_busy<T, F>(&self, label: impl Into<String>, work: F) -> crate::task::TaskHandle
    where
        T: Send + 'static,
        F: FnOnce(crate::task::TaskCtx) -> T + Send + 'static,
    {
        self.rt.spawn_task_busy(self.window, label, work)
    }

    /// 手动开一个「忙碌」段(遮罩随 `BusyToken` 的 drop 结束)
    pub fn begin_busy(&self, label: impl Into<String>) -> crate::task::BusyToken {
        self.rt.begin_busy(self.window, label)
    }

    /// 平台唤醒器(`None` = 无头 / 事件循环未起)。想自己管线程时用它带出去。
    pub fn waker(&self) -> Option<std::sync::Arc<dyn crate::task::Waker>> {
        self.rt.waker()
    }

    // ── 命令(延迟写入通道)──

    /// 提交一个待处理请求(**框架控制消息**:开窗/关窗等;载荷类型由 `app` 层解释)。
    ///
    /// 用法见 [`crate::app::open_window`] / [`crate::app::close_self`]。
    /// 业务事件请用 [`Self::emit`](走 `on_external`,跨线程一致)。
    pub fn request<T: 'static>(&self, v: T) {
        self.rt.requests().push(v);
    }

    /// 投递一条**自定义事件**给本窗口(下一个 tick 由 `ViewModel::on_external` 收到)。
    ///
    /// 这是 `Signal` 之外的"消息"通道:适合枚举型业务事件(`MyEvent::SaveFinished`)、
    /// 或者"不想为它建 Signal"的一次性通知。同一个 `T` 也可以跨线程投递
    /// ([`crate::task::TaskCtx::post`] 与 [`Emitter`] 是同一条管道)。
    pub fn emit<T: Send + 'static>(&self, msg: T) -> bool {
        self.rt.emit(self.window, msg)
    }

    pub fn cmd(&mut self, c: Cmd) {
        self.cmds.push(c);
    }

    pub fn cmds(&self) -> &[Cmd] {
        self.cmds.as_slice()
    }

    pub fn take_cmds(&mut self) -> Vec<Cmd> {
        self.cmds.take()
    }

    pub fn damage(&mut self, id: NodeId) {
        self.cmds.damage(id);
    }

    pub fn focus(&mut self, id: NodeId) {
        self.cmds.focus(id, FocusState::Programmatic);
    }

    pub fn capture_pointer(&mut self, pointer: PointerId, id: NodeId) {
        self.cmds.capture(pointer, id);
    }

    pub fn release_pointer(&mut self, pointer: PointerId) {
        self.cmds.release(pointer);
    }

    pub fn scroll_to(&mut self, id: NodeId, offset: (f32, f32)) {
        self.cmds.scroll_to(id, offset);
    }
}

// ───────────────────────── 自定义事件(`emit` / `Emitter`)─────────────────────────

impl Runtime {
    /// 投递一条自定义事件到某个窗口:UI 线程在下一个 tick 的
    /// `ViewModel::on_external` 里收到(`data.downcast::<T>()`)。
    ///
    /// 与 [`crate::task::TaskCtx::post`] 是同一条管道(`Waker`):有平台时走
    /// `EventLoopProxy`,无头时进本地队列(`App::frame_all` 消费)。返回 `false`
    /// 表示事件循环已退出。
    pub fn emit<T: Send + 'static>(&self, window: WindowId, msg: T) -> bool {
        self.inner
            .waker
            .borrow()
            .post(window, crate::app::ExternalData::new(msg))
    }

    /// **广播**一条自定义事件给所有已注册窗口(载荷用 `Arc` 共享,免得逐个克隆)。
    ///
    /// ```ignore
    /// rt.emit_global(Arc::new(AppEvent::ThemePackChanged));
    /// // 窗口侧:data.downcast::<Arc<AppEvent>>()
    /// ```
    pub fn emit_global<T: Send + Sync + 'static>(&self, msg: std::sync::Arc<T>) -> bool {
        let windows = self.windows();
        let mut ok = false;
        for w in windows {
            ok |= self.emit(w, std::sync::Arc::clone(&msg));
        }
        ok
    }
}

/// 类型化的**事件发射器**:`Clone + Send`,可以挂在业务层里、也可以 move 进工作线程。
///
/// 与 [`crate::task::TaskCtx`] 的区别:发射器只关心"发事件",不带任务语义
/// (没有进度 / 取消 / 完成);适合把 UI 无关的业务模块(网络层、文件监听、设备)接进来。
///
/// ```ignore
/// struct Net { tx: Emitter<NetEvent> }               // 业务层持有
/// impl Net {
///     fn on_bytes(&self, b: Vec<u8>) { self.tx.emit(NetEvent::Bytes(b)); }
/// }
/// // UI 侧:ViewModel::on_external 里 downcast::<NetEvent>()
/// ```
///
/// 内部只存 [`WakerSlot`](crate::task::WakerSlot)(`Send + Sync`)而**不是** `Runtime`
/// —— 这正是它天然能跨线程、无需 unsafe 的原因。
pub struct Emitter<T> {
    window: WindowId,
    waker: crate::task::WakerSlot,
    _marker: std::marker::PhantomData<fn() -> T>,
}

impl<T> Clone for Emitter<T> {
    fn clone(&self) -> Self {
        Self {
            window: self.window,
            waker: self.waker.clone(),
            _marker: std::marker::PhantomData,
        }
    }
}

impl<T: Send + 'static> Emitter<T> {
    /// 造一个发射器
    pub fn new(rt: &Runtime, window: WindowId) -> Self {
        Self {
            window,
            waker: rt.inner.waker.borrow().clone(),
            _marker: std::marker::PhantomData,
        }
    }

    pub fn window(&self) -> WindowId {
        self.window
    }

    /// 发一条事件(UI 线程在 `on_external` 里收到)
    pub fn emit(&self, msg: T) -> bool {
        self.waker
            .post(self.window, crate::app::ExternalData::new(msg))
    }
}

impl<T> std::fmt::Debug for Emitter<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Emitter")
            .field("window", &self.window)
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod emit_tests {
    use super::*;
    use crate::app::ExternalData;
    use crate::reactive::Runtime;
    use crate::window::WindowId;

    fn win() -> WindowId {
        WindowId::new(1)
    }

    #[test]
    fn emit_targets_one_window_and_lands_in_the_local_queue() {
        let rt = Runtime::new();
        rt.register_window(win());
        assert!(rt.emit(win(), 7u32));

        let queued = rt.take_pending_external();
        assert_eq!(queued.len(), 1);
        assert_eq!(queued[0].0, win());
        assert_eq!(queued[0].1.downcast_ref::<u32>(), Some(&7));
    }

    #[test]
    fn emit_global_broadcasts_to_every_window() {
        let rt = Runtime::new();
        let a = WindowId::new(1);
        let b = WindowId::new(2);
        rt.register_window(a);
        rt.register_window(b);

        assert!(rt.emit_global(std::sync::Arc::new("refresh".to_string())));
        let queued = rt.take_pending_external();
        assert_eq!(queued.len(), 2, "每个窗口一条");
        for (w, data) in queued {
            assert!(w == a || w == b);
            let payload = data.downcast::<std::sync::Arc<String>>().expect("是 Arc<String>");
            assert_eq!(payload.as_str(), "refresh");
        }
    }

    #[test]
    fn emitter_is_send_sync_and_carries_its_own_channel() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Emitter<u32>>();

        let rt = Runtime::new();
        rt.register_window(win());
        let tx = Emitter::<&'static str>::new(&rt, win());
        let tx2 = tx.clone();
        assert_eq!(tx2.window(), win());

        // 模拟"业务层在别的线程发事件":并发发两条,都能落到队列
        let handles: Vec<_> = ["a", "b"]
            .into_iter()
            .map(|msg| {
                let tx = tx.clone();
                std::thread::spawn(move || tx.emit(msg))
            })
            .collect();
        for h in handles {
            assert!(h.join().unwrap());
        }
        let queued = rt.take_pending_external();
        assert_eq!(queued.len(), 2, "跨线程投递同样进队列");
        let mut got: Vec<&'static str> = queued
            .into_iter()
            .map(|(_, d)| d.downcast::<&'static str>().unwrap())
            .collect();
        got.sort_unstable();
        assert_eq!(got, vec!["a", "b"]);
    }

    #[test]
    fn request_stays_the_framework_control_channel() {
        // `request` 走 RequestQueue(开窗/关窗),`emit` 走 Waker 管道 —— 互不干扰
        let rt = Runtime::new();
        rt.register_window(win());
        let cx = Ctx::new(&rt, win(), EventView::tick());
        cx.request(42u8);
        cx.emit("event");
        assert_eq!(rt.requests().len(), 1, "控制消息在 RequestQueue");
        assert_eq!(rt.take_pending_external().len(), 1, "业务事件在 Waker 管道");
    }

    #[test]
    fn external_data_is_the_single_payload_type() {
        // 说明性断言:两条管道共用 `ExternalData` 作为载荷载体
        let d = ExternalData::new(String::from("x"));
        assert_eq!(d.downcast::<String>().as_deref(), Some("x"));
    }
}

/// 一次分发收集到的任务清单
#[derive(Default, Debug)]
pub struct RoutePlan {
    pub target: NodeId,
    pub items: Vec<HandlerSlot>,
}

fn collect_from(track: &Track, id: NodeId, kind: EventKind, items: &mut Vec<HandlerSlot>) {
    if let Some(n) = track.get(id) {
        for slot in &n.handlers {
            if slot.kind == kind {
                items.push(slot.clone());
            }
        }
    }
}

/// ① 只读阶段:按路由策略沿命中链收集处理器。
///
/// `path` 约定:`path[0]` = 最外层,`path.last()` = 命中目标(由 M2 的命中测试产出)。
pub fn collect_route(track: &Track, path: &[NodeId], kind: EventKind) -> RoutePlan {
    let Some(target) = path.last().copied() else {
        return RoutePlan::default();
    };

    let mut items = Vec::new();
    match kind.routing() {
        // 隧道:外 → 内
        Routing::Tunnel => {
            for id in path {
                collect_from(track, *id, kind, &mut items);
            }
        }
        // 冒泡:内 → 外
        Routing::Bubble => {
            for id in path.iter().rev() {
                collect_from(track, *id, kind, &mut items);
            }
        }
        Routing::Direct => collect_from(track, target, kind, &mut items),
    }

    RoutePlan { target, items }
}

/// 分发结果
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DispatchOutcome {
    pub handled: bool,
    pub invoked: usize,
    pub skipped: usize,
}

/// ② 可写阶段:按序调用处理器。
///
/// 借用说明:`track` 只在这一阶段**只读**用来收集;收集完成后就不再借用它,
/// 处理器只拿到 `&mut Ctx`(内部只有 `Runtime` / `CmdBuf`),所以不会与树冲突。
/// 处理器攒下的 `Cmd` 由调用方在**分发结束后**统一 `apply_cmds` 落树。
pub fn dispatch(
    rt: &Runtime,
    window: WindowId,
    track: &Track,
    path: &[NodeId],
    ev: &Event,
    extra_cmds: &mut CmdBuf,
) -> DispatchOutcome {
    let kind = ev.kind();
    let plan = collect_route(track, path, kind);
    if plan.items.is_empty() {
        return DispatchOutcome::default();
    }

    let mut cx = Ctx::new(rt, window, ev.summary());
    let mut out = DispatchOutcome::default();

    for slot in &plan.items {
        if cx.handled && !slot.handled_events_too {
            out.skipped += 1;
            continue;
        }
        (slot.handler)(&mut cx);
        out.invoked += 1;
    }

    out.handled = cx.handled();
    extra_cmds.extend(cx.take_cmds());
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cmd::apply_cmds;
    use crate::track::Kind;

    fn slot(kind: EventKind, too: bool, f: impl Fn(&mut Ctx) + 'static) -> HandlerSlot {
        HandlerSlot {
            kind,
            handler: Rc::new(f),
            handled_events_too: too,
        }
    }

    fn chain(depth: usize) -> (Track, Vec<NodeId>) {
        let mut t = Track::new();
        let mut path = Vec::new();
        let root = t.create(Kind::Box, None);
        path.push(root);
        let mut cur = root;
        for _ in 1..depth {
            let c = t.create(Kind::Box, None);
            t.append_child(cur, c);
            cur = c;
            path.push(c);
        }
        (t, path)
    }

    #[test]
    fn routing_is_grouped_as_designed() {
        assert_eq!(EventKind::PreviewKeyDown.routing(), Routing::Tunnel);
        assert_eq!(EventKind::KeyDown.routing(), Routing::Bubble);
        assert_eq!(EventKind::Tapped.routing(), Routing::Bubble);
        assert_eq!(EventKind::PointerCaptureLost.routing(), Routing::Direct);
        assert_eq!(EventKind::Loaded.routing(), Routing::Direct);
        assert_eq!(EventKind::Dismissed.routing(), Routing::Direct);
        assert_eq!(EventKind::Tapped.name(), "Tapped");
    }

    #[test]
    fn pointer_kinds_are_flagged() {
        assert!(EventKind::PointerMoved.is_pointer());
        assert!(EventKind::Tapped.is_pointer());
        assert!(!EventKind::KeyDown.is_pointer());
        assert!(!EventKind::Loaded.is_pointer());
    }

    #[test]
    fn ctx_marks_the_own_window_only() {
        let rt = Runtime::new();
        let a = WindowId::new(1);
        let b = WindowId::new(2);
        rt.register_window(a);
        rt.register_window(b);

        let ctx = Ctx::new(&rt, a, EventView::empty(EventKind::Tapped));
        ctx.invalidate();
        assert!(rt.take_dirty(a).contains(Dirty::VIEW));
        assert!(rt.take_dirty(b).is_empty(), "不应影响其他窗口");

        ctx.request_repaint();
        let d = rt.take_dirty(a);
        assert!(d.contains(Dirty::PAINT) && d.contains(Dirty::PRESENT));
        assert!(!d.contains(Dirty::VIEW), "只重绘不应触发 view()");
    }

    #[test]
    fn bubble_goes_inner_to_outer() {
        let (mut t, path) = chain(3);
        let log = Rc::new(std::cell::RefCell::new(Vec::new()));
        for (i, id) in path.iter().enumerate() {
            let log = Rc::clone(&log);
            t.get_mut(*id).unwrap().handlers.push(slot(
                EventKind::Tapped,
                false,
                move |_| log.borrow_mut().push(i),
            ));
        }

        let rt = Runtime::new();
        let w = WindowId::new(1);
        rt.register_window(w);
        let mut cmds = CmdBuf::new();
        let out = dispatch(
            &rt,
            w,
            &t,
            &path,
            &Event::Simple {
                kind: EventKind::Tapped,
            },
            &mut cmds,
        );

        assert_eq!(out.invoked, 3);
        // 内 → 外:2, 1, 0
        assert_eq!(*log.borrow(), vec![2, 1, 0]);
    }

    #[test]
    fn tunnel_goes_outer_to_inner() {
        let (mut t, path) = chain(3);
        let log = Rc::new(std::cell::RefCell::new(Vec::new()));
        for (i, id) in path.iter().enumerate() {
            let log = Rc::clone(&log);
            t.get_mut(*id).unwrap().handlers.push(slot(
                EventKind::PreviewKeyDown,
                false,
                move |_| log.borrow_mut().push(i),
            ));
        }

        let rt = Runtime::new();
        let w = WindowId::new(1);
        rt.register_window(w);
        let mut cmds = CmdBuf::new();
        dispatch(
            &rt,
            w,
            &t,
            &path,
            &Event::Simple {
                kind: EventKind::PreviewKeyDown,
            },
            &mut cmds,
        );

        assert_eq!(*log.borrow(), vec![0, 1, 2], "隧道:外 → 内");
    }

    #[test]
    fn direct_only_reaches_the_target() {
        let (mut t, path) = chain(3);
        let log = Rc::new(std::cell::RefCell::new(Vec::new()));
        for (i, id) in path.iter().enumerate() {
            let log = Rc::clone(&log);
            t.get_mut(*id).unwrap().handlers.push(slot(
                EventKind::Loaded,
                false,
                move |_| log.borrow_mut().push(i),
            ));
        }

        let rt = Runtime::new();
        let w = WindowId::new(1);
        rt.register_window(w);
        let mut cmds = CmdBuf::new();
        dispatch(
            &rt,
            w,
            &t,
            &path,
            &Event::Simple {
                kind: EventKind::Loaded,
            },
            &mut cmds,
        );

        assert_eq!(*log.borrow(), vec![2], "只有目标");
    }

    #[test]
    fn handled_stops_the_bubble_but_not_handled_events_too() {
        let (mut t, path) = chain(3);
        let log = Rc::new(std::cell::RefCell::new(Vec::new()));

        // 目标(最内层):标记 handled
        {
            let log = Rc::clone(&log);
            t.get_mut(path[2]).unwrap().handlers.push(slot(
                EventKind::Tapped,
                false,
                move |cx| {
                    log.borrow_mut().push("target");
                    cx.mark_handled();
                },
            ));
        }
        // 中间层:普通(应被跳过)
        {
            let log = Rc::clone(&log);
            t.get_mut(path[1]).unwrap().handlers.push(slot(
                EventKind::Tapped,
                false,
                move |_| log.borrow_mut().push("mid"),
            ));
        }
        // 最外层:handledEventsToo(应仍然执行 —— 内置行为的语义)
        {
            let log = Rc::clone(&log);
            t.get_mut(path[0]).unwrap().handlers.push(slot(
                EventKind::Tapped,
                true,
                move |_| log.borrow_mut().push("root-builtin"),
            ));
        }

        let rt = Runtime::new();
        let w = WindowId::new(1);
        rt.register_window(w);
        let mut cmds = CmdBuf::new();
        let out = dispatch(
            &rt,
            w,
            &t,
            &path,
            &Event::Simple {
                kind: EventKind::Tapped,
            },
            &mut cmds,
        );

        assert!(out.handled);
        assert_eq!(out.invoked, 2);
        assert_eq!(out.skipped, 1);
        assert_eq!(*log.borrow(), vec!["target", "root-builtin"]);
    }

    #[test]
    fn handlers_can_queue_commands_that_apply_after_dispatch() {
        let (mut t, path) = chain(2);
        let root = path[0];

        t.get_mut(path[1]).unwrap().handlers.push(slot(
            EventKind::Tapped,
            false,
            move |cx| {
                cx.damage(root);
                cx.focus(root);
            },
        ));

        let rt = Runtime::new();
        let w = WindowId::new(1);
        rt.register_window(w);
        let mut cmds = CmdBuf::new();
        dispatch(
            &rt,
            w,
            &t,
            &path,
            &Event::Simple {
                kind: EventKind::Tapped,
            },
            &mut cmds,
        );

        assert_eq!(cmds.len(), 2);
        // 分发结束、借用释放后才落树
        let d = apply_cmds(&mut t, cmds.as_slice());
        assert!(d.contains(Dirty::PAINT));
        assert_eq!(t.focused, Some(root));
    }

    #[test]
    fn empty_path_is_a_no_op() {
        let rt = Runtime::new();
        let w = WindowId::new(1);
        rt.register_window(w);
        let t = Track::new();
        let mut cmds = CmdBuf::new();
        let out = dispatch(
            &rt,
            w,
            &t,
            &[],
            &Event::Simple {
                kind: EventKind::Tapped,
            },
            &mut cmds,
        );
        assert_eq!(out, DispatchOutcome::default());
    }

    #[test]
    fn event_summary_exposes_payload() {
        let ev = Event::Pointer {
            kind: EventKind::PointerPressed,
            pointer: PointerId(3),
            pos: Point::new(10.0, 20.0),
            button: PointerButton::Right,
        };
        let s = ev.summary();
        assert_eq!(s.kind, EventKind::PointerPressed);
        assert_eq!(s.pointer, PointerId(3));
        assert_eq!(s.pos, Point::new(10.0, 20.0));
        assert_eq!(s.button, PointerButton::Right);
        assert_eq!(ev.pointer_pos(), Some(Point::new(10.0, 20.0)));

        let k = Event::Key {
            kind: EventKind::KeyDown,
            code: KeyCode::Named(NamedKey::Enter),
            text: None,
            repeat: false,
            modifiers: Modifiers::SHIFT,
        };
        assert_eq!(k.summary().key, Some(KeyCode::Named(NamedKey::Enter)));
        assert!(k.summary().modifiers.shift());
        assert!(!k.summary().modifiers.ctrl());
        assert!(!Modifiers::CTRL.shift());
        assert!((Modifiers::CTRL | Modifiers::SHIFT).ctrl());
        assert_eq!((Modifiers::CTRL | Modifiers::SHIFT).bits(), 0b011);
        assert!(Modifiers::EMPTY.is_empty());
    }
}