mitsuami-appkit 1.3.2

AppKit (macOS) backend for mitsuami
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
//! Objective-C classes bridging AppKit callbacks into mitsuami events.

use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::ffi::c_void;
use std::path::PathBuf;
use std::rc::Rc;

use mitsuami_core::services::Shortcut;
use mitsuami_core::{
    DisplayList, EventSink, EventValue, FileDrop, Insets, NodeId, Point, PointerEvent, PointerKind, Size, UiEvent,
    WidgetKind,
};
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject, Sel};
use objc2::{
    AnyThread, ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_class, msg_send, sel,
};
use objc2_app_kit::{
    NSButton, NSClickGestureRecognizer, NSColor, NSControl, NSControlStateValueOn, NSControlTextEditingDelegate,
    NSDragOperation, NSDraggingInfo, NSEvent, NSEventModifierFlags, NSEventType, NSPasteboardTypeFileURL,
    NSPopUpButton, NSRectFill, NSScreen, NSScrollView, NSSearchFieldDelegate, NSSlider, NSSwitch, NSText,
    NSTextDelegate, NSTextField, NSTextFieldDelegate, NSTextView, NSTextViewDelegate, NSTrackingArea,
    NSTrackingAreaOptions, NSView, NSViewFrameDidChangeNotification, NSWindow, NSWindowDelegate, NSWindowStyleMask,
};
use objc2_foundation::{
    NSArray, NSEdgeInsets, NSKeyValueObservingOptions, NSNotification, NSNotificationCenter,
    NSObjectNSKeyValueObserverRegistration, NSPoint, NSRect, NSSize, NSString, NSURL,
};

use crate::keys::Keys;

pub(crate) fn zero_rect() -> NSRect {
    NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(0.0, 0.0))
}

/// How far a scroll view is scrolled, from where its content starts: a
/// table's clip view is inset below its header, so its bounds start above.
pub(crate) fn scrolled(clip: &objc2_app_kit::NSClipView) -> NSPoint {
    let (origin, insets) = (clip.bounds().origin, clip.contentInsets());
    NSPoint::new(origin.x + insets.left, origin.y + insets.top)
}

/// Where a scroll view's clip view is in it: inside legacy scrollers
/// (overlay ones take no room) and its border.
pub(crate) fn viewport_insets(scroll: &objc2_app_kit::NSScrollView) -> Insets {
    let (outer, clip) = (scroll.bounds(), scroll.contentView().frame());
    let below = (clip.origin.y - outer.origin.y) as f32;
    let above = (outer.size.height - clip.size.height) as f32 - below;
    let (top, bottom) = if scroll.isFlipped() { (below, above) } else { (above, below) };
    let left = (clip.origin.x - outer.origin.x) as f32;
    Insets::new(top, (outer.size.width - clip.size.width) as f32 - left, bottom, left)
}

/// Where a scroll view's clip view goes for this offset from where its
/// content starts.
pub(crate) fn clip_origin(clip: &objc2_app_kit::NSClipView, offset: NSPoint) -> NSPoint {
    let insets = clip.contentInsets();
    NSPoint::new(offset.x - insets.left, offset.y - insets.top)
}

pub(crate) struct HostIvars {
    /// Paint the window background, while a window's capture draws: an
    /// offscreen capture has no window background behind the host. On
    /// screen the window draws its own, which on macOS 26 isn't this flat
    /// colour, so a host painting it there didn't match the title bar.
    fill: Cell<bool>,
    /// The files it takes when they're dropped on it, if any.
    drop: RefCell<Option<Drop>>,
    /// A table's cell: it keeps its host centred in its height.
    centers: Cell<bool>,
    /// The keys it takes, if the app gave any.
    keys: RefCell<Option<Keys>>,
}

/// A host's file drop: what it takes, where it reports, and whether
/// files it takes are over it.
pub(crate) struct Drop {
    pub(crate) id: NodeId,
    pub(crate) files: FileDrop,
    pub(crate) events: EventSink,
    pub(crate) hover: Cell<bool>,
}

define_class!(
    /// A layout host: a flipped view (origin top-left, like the core) that
    /// never lays out its children itself.
    #[unsafe(super(NSView))]
    #[thread_kind = MainThreadOnly]
    #[ivars = HostIvars]
    pub(crate) struct HostView;

    impl HostView {
        #[unsafe(method(isFlipped))]
        fn is_flipped(&self) -> bool {
            true
        }

        #[unsafe(method(resizeSubviewsWithOldSize:))]
        fn resize_subviews(&self, old: NSSize) {
            if self.ivars().centers.get() {
                self.center_subviews();
            } else {
                unsafe { msg_send![super(self), resizeSubviewsWithOldSize: old] }
            }
        }

        /// A key the focused view inside didn't use, passed up the
        /// responder chain: taken if it's one of the host's.
        #[unsafe(method(keyDown:))]
        fn key_down(&self, event: &NSEvent) {
            if !self.ivars().keys.borrow().as_ref().is_some_and(|keys| keys.take(event)) {
                unsafe { msg_send![super(self), keyDown: event] }
            }
        }

        #[unsafe(method(drawRect:))]
        fn draw_rect(&self, dirty: NSRect) {
            if self.ivars().fill.get() {
                NSColor::windowBackgroundColor().setFill();
                NSRectFill(dirty);
            }
        }

        // `NSDraggingDestination`: copy the files it takes, refuse others.
        #[unsafe(method(draggingEntered:))]
        fn dragging_entered(&self, info: &ProtocolObject<dyn NSDraggingInfo>) -> NSDragOperation {
            self.drag_files(&dragged_paths(info))
        }

        #[unsafe(method(draggingUpdated:))]
        fn dragging_updated(&self, info: &ProtocolObject<dyn NSDraggingInfo>) -> NSDragOperation {
            self.drag_files(&dragged_paths(info))
        }

        #[unsafe(method(draggingExited:))]
        fn dragging_exited(&self, _info: Option<&ProtocolObject<dyn NSDraggingInfo>>) {
            self.drag_leave();
        }

        #[unsafe(method(performDragOperation:))]
        fn perform_drag_operation(&self, info: &ProtocolObject<dyn NSDraggingInfo>) -> bool {
            self.drop_files(&dragged_paths(info))
        }
    }
);

define_class!(
    /// A scroll view that can run up under its window's title bar and
    /// toolbar, as Finder's does, so what scrolls under them shows through
    /// (macOS 26 blurs it at the bar's edge). The part under the bar is
    /// outside its alignment rect, which is where the core placed it, and
    /// its content starts below the bar (`contentInsets`).
    #[unsafe(super(NSScrollView, NSView))]
    #[thread_kind = MainThreadOnly]
    #[ivars = Cell<f64>]
    pub(crate) struct EdgeScrollView;

    impl EdgeScrollView {
        #[unsafe(method(alignmentRectInsets))]
        fn alignment_rect_insets(&self) -> NSEdgeInsets {
            NSEdgeInsets { top: self.ivars().get(), left: 0.0, bottom: 0.0, right: 0.0 }
        }
    }
);

impl EdgeScrollView {
    pub(crate) fn new(mtm: MainThreadMarker) -> Retained<EdgeScrollView> {
        let this = EdgeScrollView::alloc(mtm).set_ivars(Cell::new(0.0));
        unsafe { msg_send![super(this), initWithFrame: zero_rect()] }
    }

    /// How far it runs up under the bar.
    pub(crate) fn under_bar(&self) -> f64 {
        self.ivars().get()
    }

    /// Runs this far up under the bar (zero: not under it), keeping where
    /// the core placed it and how far it's scrolled. Whether it changed.
    pub(crate) fn set_under_bar(&self, height: f64) -> bool {
        if self.ivars().get() == height {
            return false;
        }
        let placed = self.alignmentRectForFrame(self.frame());
        let clip = self.contentView();
        let offset = scrolled(&clip);
        self.ivars().set(height);
        self.setContentInsets(NSEdgeInsets { top: height, left: 0.0, bottom: 0.0, right: 0.0 });
        self.setFrame(self.frameForAlignmentRect(placed));
        clip.scrollToPoint(clip_origin(&clip, offset));
        self.reflectScrolledClipView(&clip);
        true
    }
}

impl HostView {
    pub(crate) fn new(mtm: MainThreadMarker) -> Retained<HostView> {
        let this = HostView::alloc(mtm).set_ivars(HostIvars {
            fill: Cell::new(false),
            drop: RefCell::new(None),
            centers: Cell::new(false),
            keys: RefCell::new(None),
        });
        unsafe { msg_send![super(this), initWithFrame: zero_rect()] }
    }

    /// Paints the window background, for a window's capture.
    pub(crate) fn set_fill(&self, fill: bool) {
        self.ivars().fill.set(fill);
    }

    /// A table's cell: its host is centred in its height, now and as the
    /// row's height changes.
    pub(crate) fn new_cell(mtm: MainThreadMarker) -> Retained<HostView> {
        let cell = HostView::new(mtm);
        cell.ivars().centers.set(true);
        cell
    }

    /// Centres the host in a table's cell, at the left.
    pub(crate) fn center_subviews(&self) {
        let height = self.bounds().size.height;
        for view in self.subviews().iter() {
            let y = ((height - view.frame().size.height) / 2.0).round();
            view.setFrameOrigin(NSPoint::new(0.0, y));
        }
    }

    /// Takes these files when they're dropped on it, or none.
    pub(crate) fn set_file_drop(&self, drop: Option<Drop>) {
        match &drop {
            Some(_) => self.registerForDraggedTypes(&NSArray::from_slice(&[unsafe { NSPasteboardTypeFileURL }])),
            None => self.unregisterDraggedTypes(),
        }
        *self.ivars().drop.borrow_mut() = drop;
    }

    pub(crate) fn set_keys(&self, keys: Option<Keys>) {
        *self.ivars().keys.borrow_mut() = keys;
    }

    /// The keys it takes, if the app gave any.
    pub(crate) fn keys(&self) -> Option<Vec<Shortcut>> {
        self.ivars().keys.borrow().as_ref().map(|k| k.keys.clone())
    }

    pub(crate) fn takes(&self, shortcut: Shortcut) -> bool {
        self.ivars().keys.borrow().as_ref().is_some_and(|k| k.keys.contains(&shortcut))
    }

    pub(crate) fn file_drop(&self) -> Option<FileDrop> {
        self.ivars().drop.borrow().as_ref().map(|d| d.files.clone())
    }

    /// Files are over it: it copies them if it takes any, and says so
    /// once.
    pub(crate) fn drag_files(&self, paths: &[PathBuf]) -> NSDragOperation {
        let drop = self.ivars().drop.borrow();
        let Some(drop) = drop.as_ref() else { return NSDragOperation::None };
        if drop.files.accepted(paths).is_empty() {
            return NSDragOperation::None;
        }
        if !drop.hover.replace(true) {
            drop.events.emit(drop.id, UiEvent::DropHover(true));
        }
        NSDragOperation::Copy
    }

    pub(crate) fn drag_leave(&self) {
        let drop = self.ivars().drop.borrow();
        if let Some(drop) = drop.as_ref()
            && drop.hover.replace(false)
        {
            drop.events.emit(drop.id, UiEvent::DropHover(false));
        }
    }

    /// Files are dropped on it: it reports the ones it takes.
    pub(crate) fn drop_files(&self, paths: &[PathBuf]) -> bool {
        self.drag_files(paths);
        let accepted = self.ivars().drop.borrow().as_ref().map(|d| d.files.accepted(paths)).unwrap_or_default();
        if !accepted.is_empty()
            && let Some(drop) = self.ivars().drop.borrow().as_ref()
        {
            drop.events.emit(drop.id, UiEvent::FilesDropped(accepted.clone()));
        }
        self.drag_leave();
        !accepted.is_empty()
    }
}

/// The files and folders being dragged: the pasteboard's file URLs.
fn dragged_paths(info: &ProtocolObject<dyn NSDraggingInfo>) -> Vec<PathBuf> {
    let pasteboard = info.draggingPasteboard();
    let classes = NSArray::from_slice(&[NSURL::class()]);
    let Some(urls) = (unsafe { pasteboard.readObjectsForClasses_options(&classes, None) }) else {
        return Vec::new();
    };
    urls.iter()
        .filter_map(|url| url.downcast::<NSURL>().ok())
        .filter(|url| url.isFileURL())
        .filter_map(|url| url.path().map(|p| PathBuf::from(p.to_string())))
        .collect()
}

pub(crate) struct TargetIvars {
    id: NodeId,
    kind: WidgetKind,
    events: EventSink,
    /// Sliders whose step is too fine for tick marks: the step their
    /// action rounds to (see `set_ticks`).
    snap: Cell<Option<f64>>,
}

define_class!(
    /// Target of control actions and delegate of text fields and areas for one
    /// node.
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[ivars = TargetIvars]
    pub(crate) struct ActionTarget;

    impl ActionTarget {
        #[unsafe(method(fire:))]
        fn fire(&self, sender: &AnyObject) {
            let TargetIvars { id, kind, events, snap } = self.ivars();
            let event = match kind {
                WidgetKind::Button => UiEvent::Click,
                WidgetKind::Checkbox => match sender.downcast_ref::<NSButton>() {
                    Some(b) => {
                        // A click leaves the mixed state; later clicks
                        // mustn't cycle back into it.
                        b.setAllowsMixedState(false);
                        UiEvent::Changed(EventValue::Bool(b.state() == NSControlStateValueOn))
                    }
                    None => return,
                },
                WidgetKind::ToggleButton => match sender.downcast_ref::<NSButton>() {
                    Some(b) => UiEvent::Changed(EventValue::Bool(b.state() == NSControlStateValueOn)),
                    None => return,
                },
                WidgetKind::Switch => match sender.downcast_ref::<NSSwitch>() {
                    Some(s) => UiEvent::Changed(EventValue::Bool(s.state() == NSControlStateValueOn)),
                    None => return,
                },
                WidgetKind::Slider => match sender.downcast_ref::<NSSlider>() {
                    Some(s) => {
                        // Rounded to the step from the minimum, kept in
                        // range without `clamp` (a range may come upside
                        // down), and shown where it landed.
                        if let Some(step) = snap.get() {
                            let (min, max) = (s.minValue(), s.maxValue());
                            let value = min + ((s.doubleValue() - min) / step).round() * step;
                            s.setDoubleValue(value.min(max).max(min));
                        }
                        UiEvent::Changed(EventValue::Number(s.doubleValue()))
                    }
                    None => return,
                },
                WidgetKind::Select => match sender.downcast_ref::<NSPopUpButton>().map(|p| p.indexOfSelectedItem()) {
                    Some(index) if index >= 0 => UiEvent::Changed(EventValue::Index(index as usize)),
                    _ => return,
                },
                WidgetKind::SearchInput => match sender.downcast_ref::<NSTextField>() {
                    Some(f) => UiEvent::Search(f.stringValue().to_string()),
                    None => return,
                },
                _ => return,
            };
            events.emit(*id, event);
        }
    }

    impl ActionTarget {
        /// A scroll view's clip view moved (`NSViewBoundsDidChangeNotification`).
        #[unsafe(method(scrolled:))]
        fn scrolled(&self, notification: &NSNotification) {
            let Some(object) = notification.object() else { return };
            let Some(clip) = object.downcast_ref::<objc2_app_kit::NSClipView>() else { return };
            let origin = scrolled(clip);
            let offset = Point::new(origin.x as f32, origin.y as f32);
            self.ivars().events.emit(self.ivars().id, UiEvent::Scrolled(offset));
        }

        /// A scroll view's clip view was resized or moved
        /// (`NSViewFrameDidChangeNotification`): as it was, or as legacy
        /// scrollers came or went.
        #[unsafe(method(viewportChanged:))]
        fn viewport_changed(&self, notification: &NSNotification) {
            let Some(object) = notification.object() else { return };
            let Some(scroll) = object
                .downcast_ref::<objc2_app_kit::NSClipView>()
                // SAFETY: the clip view is in its scroll view, on the main thread.
                .and_then(|clip| unsafe { clip.superview() })
                .and_then(|s| s.downcast::<objc2_app_kit::NSScrollView>().ok())
            else {
                return;
            };
            self.ivars().events.emit(self.ivars().id, UiEvent::ViewportInsets(viewport_insets(&scroll)));
        }
    }

    unsafe impl NSObjectProtocol for ActionTarget {}

    unsafe impl NSControlTextEditingDelegate for ActionTarget {
        /// Return / Enter submits. Deliberately not the field's action: that
        /// also fires when editing ends by Tab or a click elsewhere. A search
        /// field's action is its search, Return's included.
        #[unsafe(method(control:textView:doCommandBySelector:))]
        fn control_text_view_do_command_by_selector(
            &self,
            _control: &NSControl,
            _text_view: &NSTextView,
            command: Sel,
        ) -> bool {
            if command == sel!(insertNewline:) && self.ivars().kind != WidgetKind::SearchInput {
                self.ivars().events.emit(self.ivars().id, UiEvent::Submit);
            }
            // Not handled: AppKit carries on with its default behaviour.
            false
        }

        #[unsafe(method(controlTextDidChange:))]
        fn control_text_did_change(&self, notification: &NSNotification) {
            let Some(object) = notification.object() else { return };
            if let Some(field) = object.downcast_ref::<NSTextField>() {
                let text = field.stringValue().to_string();
                self.ivars().events.emit(self.ivars().id, UiEvent::Changed(EventValue::Text(text)));
            }
        }
    }

    unsafe impl NSTextFieldDelegate for ActionTarget {}

    unsafe impl NSSearchFieldDelegate for ActionTarget {}

    unsafe impl NSTextDelegate for ActionTarget {
        /// A text area's text changed: by typing, pasting, undo. The text
        /// view doesn't post it when its string is set.
        #[unsafe(method(textDidChange:))]
        fn text_did_change(&self, notification: &NSNotification) {
            let Some(object) = notification.object() else { return };
            if let Some(text) = object.downcast_ref::<NSText>() {
                let text = text.string().to_string();
                self.ivars().events.emit(self.ivars().id, UiEvent::Changed(EventValue::Text(text)));
            }
        }
    }

    unsafe impl NSTextViewDelegate for ActionTarget {}
);

impl ActionTarget {
    pub(crate) fn new(
        mtm: MainThreadMarker,
        id: NodeId,
        kind: WidgetKind,
        events: EventSink,
    ) -> Retained<ActionTarget> {
        let this = ActionTarget::alloc(mtm).set_ivars(TargetIvars { id, kind, events, snap: Cell::new(None) });
        unsafe { msg_send![super(this), init] }
    }

    /// A slider's action rounds what it reports to this step.
    pub(crate) fn set_snap(&self, step: Option<f64>) {
        self.ivars().snap.set(step);
    }
}

/// Native view address → node, shared between the backend and delegates.
pub(crate) type ViewMap = Rc<RefCell<HashMap<usize, NodeId>>>;

pub(crate) struct WindowIvars {
    id: NodeId,
    events: EventSink,
    views: ViewMap,
    /// The node we last reported as focused.
    focused: Cell<Option<NodeId>>,
    /// A dialog: Escape asks it to close.
    modal: Cell<bool>,
    /// Full screen as AppKit has it, or is moving into.
    full_screen: Cell<bool>,
    /// Full screen as the app wants it (and the user, who changes it too).
    full_screen_wanted: Cell<bool>,
    /// A transition is under way: AppKit ignores a toggle until it ends.
    full_screen_moving: Cell<bool>,
    /// The transition starting is the app's own, so it isn't reported.
    full_screen_ours: Cell<bool>,
    /// Zoomed (AppKit's maximized) as last reported or set, to tell the
    /// user's zooms from the app's.
    zoomed: Cell<bool>,
    /// The app's minimum content size, if it set one.
    min_size: Cell<Option<Size>>,
    /// The content sets the height, not the user.
    height_locked: Cell<bool>,
    /// The window's content (its host), when it's beside a sidebar: the
    /// window's content area is larger by the sidebar and the title bar.
    detail: RefCell<Option<Retained<NSView>>>,
}

define_class!(
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[ivars = WindowIvars]
    pub(crate) struct WindowDelegate;

    impl WindowDelegate {
        /// KVO on the window's `firstResponder`: every focus change,
        /// whether it came from a click, Tab or code.
        #[unsafe(method(observeValueForKeyPath:ofObject:change:context:))]
        fn observe_value(
            &self,
            _key_path: Option<&NSString>,
            object: Option<&AnyObject>,
            _change: Option<&AnyObject>,
            _context: *mut c_void,
        ) {
            let Some(window) = object.and_then(|o| o.downcast_ref::<NSWindow>()) else { return };
            let now = self.focused_node(window);
            let WindowIvars { events, focused, .. } = self.ivars();
            let before = focused.replace(now);
            if before != now {
                if let Some(old) = before {
                    events.emit(old, UiEvent::FocusOut);
                }
                if let Some(new) = now {
                    events.emit(new, UiEvent::FocusIn);
                }
            }
        }
    }

    impl WindowDelegate {
        /// The content beside a sidebar changed size: the window's did, or
        /// the user moved the divider (`NSViewFrameDidChangeNotification`).
        #[unsafe(method(detailDidResize:))]
        fn detail_did_resize(&self, notification: &NSNotification) {
            let Some(view) = notification.object().and_then(|o| o.downcast::<NSView>().ok()) else { return };
            let size = view.frame().size;
            let size = Size::new(size.width as f32, size.height as f32);
            self.ivars().events.emit(self.ivars().id, UiEvent::WindowResized(size));
        }
    }

    impl WindowDelegate {
        /// Escape, from whatever has the focus and didn't use it: the
        /// window hands action messages nobody took to its delegate.
        #[unsafe(method(cancelOperation:))]
        fn cancel_operation(&self, _sender: Option<&AnyObject>) {
            if self.ivars().modal.get() {
                self.ivars().events.emit(self.ivars().id, UiEvent::WindowCloseRequested);
            }
        }
    }

    unsafe impl NSObjectProtocol for WindowDelegate {}

    unsafe impl NSWindowDelegate for WindowDelegate {
        /// The app decides whether a window closes (e.g. to ask about
        /// unsaved changes); the core destroys it if so.
        #[unsafe(method(windowShouldClose:))]
        fn window_should_close(&self, _sender: &NSWindow) -> bool {
            self.ivars().events.emit(self.ivars().id, UiEvent::WindowCloseRequested);
            false
        }

        #[unsafe(method(windowDidResize:))]
        fn window_did_resize(&self, notification: &NSNotification) {
            let Some(object) = notification.object() else { return };
            let Some(window) = object.downcast_ref::<NSWindow>() else { return };
            let content = window.contentRectForFrameRect(window.frame()).size;
            let size = Size::new(content.width as f32, content.height as f32);
            // A locked height is locked at the new one.
            if self.ivars().height_locked.get() && !window.styleMask().contains(NSWindowStyleMask::FullScreen) {
                self.apply_min_size(window);
            }
            // Beside a sidebar, the content's own size is reported, once
            // the split lays it out (`detailDidResize:`).
            if self.ivars().detail.borrow().is_none() {
                self.ivars().events.emit(self.ivars().id, UiEvent::WindowResized(size));
            }
            // A zoom by the user, or one a resize undid.
            let zoomed = self.zoomed(window);
            if self.ivars().zoomed.replace(zoomed) != zoomed {
                self.ivars().events.emit(self.ivars().id, UiEvent::MaximizedChanged(zoomed));
            }
        }

        /// Another screen, another cap on the minimum.
        #[unsafe(method(windowDidChangeScreen:))]
        fn window_did_change_screen(&self, notification: &NSNotification) {
            if let Some(window) = notification.object().and_then(|o| o.downcast::<NSWindow>().ok()) {
                self.apply_min_size(&window);
            }
        }

        #[unsafe(method(windowDidChangeBackingProperties:))]
        fn window_did_change_backing_properties(&self, _notification: &NSNotification) {
            self.ivars().events.emit(self.ivars().id, UiEvent::MetricsChanged);
        }

        // Full screen's transitions. `willEnter` and `willExit` come
        // inside `toggleFullScreen:`, from the app or from the title
        // bar's button; `did` ends the animation.

        #[unsafe(method(windowWillEnterFullScreen:))]
        fn window_will_enter_full_screen(&self, _notification: &NSNotification) {
            self.full_screen_starts(true);
        }

        #[unsafe(method(windowWillExitFullScreen:))]
        fn window_will_exit_full_screen(&self, _notification: &NSNotification) {
            self.full_screen_starts(false);
        }

        #[unsafe(method(windowDidEnterFullScreen:))]
        fn window_did_enter_full_screen(&self, notification: &NSNotification) {
            self.full_screen_ends(notification);
        }

        #[unsafe(method(windowDidExitFullScreen:))]
        fn window_did_exit_full_screen(&self, notification: &NSNotification) {
            self.full_screen_ends(notification);
        }

        #[unsafe(method(windowDidFailToEnterFullScreen:))]
        fn window_did_fail_to_enter_full_screen(&self, _window: &NSWindow) {
            self.full_screen_fails(false);
        }

        #[unsafe(method(windowDidFailToExitFullScreen:))]
        fn window_did_fail_to_exit_full_screen(&self, _window: &NSWindow) {
            self.full_screen_fails(true);
        }
    }
);

const FIRST_RESPONDER: &str = "firstResponder";

impl WindowDelegate {
    pub(crate) fn new(
        mtm: MainThreadMarker,
        id: NodeId,
        events: EventSink,
        views: ViewMap,
    ) -> Retained<WindowDelegate> {
        let this = WindowDelegate::alloc(mtm).set_ivars(WindowIvars {
            id,
            events,
            views,
            focused: Cell::new(None),
            modal: Cell::new(false),
            full_screen: Cell::new(false),
            full_screen_wanted: Cell::new(false),
            full_screen_moving: Cell::new(false),
            full_screen_ours: Cell::new(false),
            zoomed: Cell::new(false),
            min_size: Cell::new(None),
            height_locked: Cell::new(false),
            detail: RefCell::new(None),
        });
        unsafe { msg_send![super(this), init] }
    }

    pub(crate) fn set_modal(&self, modal: bool) {
        self.ivars().modal.set(modal);
    }

    /// The app's minimum content size. AppKit keeps the user from resizing
    /// below it, but a window already smaller stays so: it grows here, as
    /// on the other platforms.
    pub(crate) fn set_min_size(&self, window: &NSWindow, min: Size) {
        self.ivars().min_size.set(Some(min));
        self.apply_min_size(window);
    }

    /// The content sets the height: a minimum and a maximum at the height
    /// it has, so the user resizes only the width, and AppKit's resize
    /// cursors say so.
    pub(crate) fn set_height_locked(&self, window: &NSWindow, locked: bool) {
        self.ivars().height_locked.set(locked);
        self.apply_min_size(window);
    }

    pub(crate) fn height_locked(&self, window: &NSWindow) -> bool {
        window.contentMaxSize().height < f32::MAX as f64
    }

    /// Puts the window's content beside a sidebar (`Some`), or back as
    /// the window's whole content area. Its size is reported from then on.
    pub(crate) fn set_detail(&self, detail: Option<&NSView>) {
        let center = NSNotificationCenter::defaultCenter();
        if let Some(old) = self.ivars().detail.replace(detail.map(|d| d.retain())) {
            unsafe { center.removeObserver_name_object(self, Some(NSViewFrameDidChangeNotification), Some(&old)) };
        }
        if let Some(detail) = detail {
            detail.setPostsFrameChangedNotifications(true);
            unsafe {
                center.addObserver_selector_name_object(
                    self,
                    sel!(detailDidResize:),
                    Some(NSViewFrameDidChangeNotification),
                    Some(detail),
                )
            };
        }
    }

    /// How much larger the window's content area is than its content: by
    /// the sidebar and the title bar, beside a sidebar; else not at all.
    pub(crate) fn extra(&self, window: &NSWindow) -> NSSize {
        let Some(detail) = self.ivars().detail.borrow().clone() else { return NSSize::ZERO };
        window.layoutIfNeeded();
        let area = window.contentRectForFrameRect(window.frame()).size;
        let content = detail.frame().size;
        NSSize::new((area.width - content.width).max(0.0), (area.height - content.height).max(0.0))
    }

    /// The minimum, no larger than the content of a window filling its
    /// screen's visible area (a machine's mode can be larger than a laptop's
    /// screen; AppKit would make a window as large as asked), and a locked
    /// height.
    fn apply_min_size(&self, window: &NSWindow) {
        let extra = self.extra(window);
        let min = self.min_size_on_screen(window).map(|m| NSSize::new(m.width + extra.width, m.height + extra.height));
        let content = window.contentRectForFrameRect(window.frame()).size;
        let (mut least, mut most) = (min.unwrap_or(NSSize::ZERO), NSSize::new(f32::MAX as f64, f32::MAX as f64));
        if self.ivars().height_locked.get() {
            least.height = content.height;
            most.height = content.height;
        }
        window.setContentMinSize(least);
        window.setContentMaxSize(most);
        let Some(min) = min else { return };
        let grown = NSSize::new(content.width.max(min.width), content.height.max(min.height));
        if grown != content && !window.styleMask().contains(NSWindowStyleMask::FullScreen) {
            window.setContentSize(grown);
        }
    }

    /// The content area for a content size the app asks for, no smaller
    /// than its minimum: AppKit's `setContentSize:` would go below it.
    pub(crate) fn at_least_min(&self, window: &NSWindow, size: Size) -> NSSize {
        let min = self.min_size_on_screen(window).unwrap_or(NSSize::ZERO);
        let extra = self.extra(window);
        NSSize::new(
            (size.width as f64).max(min.width) + extra.width,
            (size.height as f64).max(min.height) + extra.height,
        )
    }

    /// The app's minimum content size, no larger than a window filling its
    /// screen could give its content.
    fn min_size_on_screen(&self, window: &NSWindow) -> Option<NSSize> {
        let min = self.ivars().min_size.get()?;
        let screen = window.screen().or_else(|| NSScreen::mainScreen(MainThreadMarker::from(self)));
        let extra = self.extra(window);
        let most = screen.map_or(NSSize::new(f64::MAX, f64::MAX), |s| {
            let area = window.contentRectForFrameRect(s.visibleFrame()).size;
            NSSize::new(area.width - extra.width, area.height - extra.height)
        });
        Some(NSSize::new((min.width as f64).min(most.width), (min.height as f64).min(most.height)))
    }

    /// The minimum as AppKit has it: the app's, if AppKit holds it as
    /// capped by the screen. A locked height hides the minimum's.
    pub(crate) fn min_size(&self, window: &NSWindow) -> Size {
        let extra = self.extra(window);
        let now = window.contentMinSize();
        let now = NSSize::new((now.width - extra.width).max(0.0), (now.height - extra.height).max(0.0));
        let locked = self.height_locked(window);
        match (self.ivars().min_size.get(), self.min_size_on_screen(window)) {
            (Some(min), Some(capped)) if capped.width == now.width && (locked || capped.height == now.height) => min,
            _ => Size::new(now.width as f32, now.height as f32),
        }
    }

    /// Zoomed, as AppKit maximizes a window: to its standard frame, the
    /// screen's visible area unless the window's delegate says otherwise.
    /// `zoom:` goes back to the frame it had before. In full screen, it
    /// isn't zoomed.
    pub(crate) fn set_zoomed(&self, window: &NSWindow, on: bool) {
        self.ivars().zoomed.set(on);
        if self.zoomed(window) != on {
            window.zoom(None);
        }
    }

    pub(crate) fn zoomed(&self, window: &NSWindow) -> bool {
        !window.styleMask().contains(NSWindowStyleMask::FullScreen) && window.isZoomed()
    }

    /// Full screen as the app wants it: applied once the window is shown
    /// (a hidden window would go into full screen unseen) and no
    /// transition is under way.
    pub(crate) fn set_full_screen(&self, window: &NSWindow, on: bool) {
        self.ivars().full_screen_wanted.set(on);
        self.apply_full_screen(window);
    }

    pub(crate) fn apply_full_screen(&self, window: &NSWindow) {
        let ivars = self.ivars();
        if ivars.full_screen_moving.get()
            || !window.isVisible()
            || ivars.full_screen.get() == ivars.full_screen_wanted.get()
        {
            return;
        }
        ivars.full_screen_ours.set(true);
        window.toggleFullScreen(None);
        // No transition started: AppKit refused (a sheet can't have full
        // screen). The window stays as it is, and the app hears so.
        if ivars.full_screen_ours.replace(false) {
            ivars.full_screen_wanted.set(ivars.full_screen.get());
            ivars.events.emit(ivars.id, UiEvent::FullScreenChanged(ivars.full_screen.get()));
        }
    }

    /// What the window shows: while it's hidden or moving, what it will.
    pub(crate) fn full_screen(&self, window: &NSWindow) -> bool {
        let ivars = self.ivars();
        if ivars.full_screen_moving.get() || !window.isVisible() {
            ivars.full_screen_wanted.get()
        } else {
            ivars.full_screen.get()
        }
    }

    fn full_screen_starts(&self, on: bool) {
        let ivars = self.ivars();
        ivars.full_screen.set(on);
        ivars.full_screen_moving.set(true);
        if !ivars.full_screen_ours.replace(false) {
            ivars.full_screen_wanted.set(on);
            ivars.events.emit(ivars.id, UiEvent::FullScreenChanged(on));
        }
    }

    /// The app may have changed its mind while it moved.
    fn full_screen_ends(&self, notification: &NSNotification) {
        self.ivars().full_screen_moving.set(false);
        if let Some(window) = notification.object().and_then(|o| o.downcast::<NSWindow>().ok()) {
            self.apply_full_screen(&window);
        }
    }

    /// The window is back as it was: the app hears so.
    fn full_screen_fails(&self, was: bool) {
        let ivars = self.ivars();
        ivars.full_screen.set(was);
        ivars.full_screen_moving.set(false);
        if ivars.full_screen_wanted.replace(was) != was {
            ivars.events.emit(ivars.id, UiEvent::FullScreenChanged(was));
        }
    }

    pub(crate) fn observe_focus(&self, window: &NSWindow) {
        unsafe {
            window.addObserver_forKeyPath_options_context(
                self,
                &NSString::from_str(FIRST_RESPONDER),
                NSKeyValueObservingOptions::New,
                std::ptr::null_mut(),
            );
        }
    }

    pub(crate) fn stop_observing_focus(&self, window: &NSWindow) {
        unsafe { window.removeObserver_forKeyPath(self, &NSString::from_str(FIRST_RESPONDER)) };
        self.set_detail(None);
    }

    /// The node owning the first responder: the nearest known view among
    /// the responder and its superviews. While a text field is edited, the
    /// first responder is the window's field editor, which AppKit places
    /// inside the field (its delegate isn't set yet when focus moves).
    fn focused_node(&self, window: &NSWindow) -> Option<NodeId> {
        let responder = window.firstResponder()?;
        let views = self.ivars().views.borrow();
        let mut view: Option<Retained<NSView>> = responder.downcast::<NSView>().ok();
        while let Some(current) = view {
            if let Some(id) = views.get(&(&*current as *const NSView as usize)) {
                return Some(*id);
            }
            view = unsafe { current.superview() };
        }
        None
    }
}

pub(crate) struct ClosureIvars {
    handler: Box<dyn Fn(&AnyObject)>,
}

define_class!(
    /// A control target that runs a closure: how native renders and native
    /// views hear about their controls' actions.
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[ivars = ClosureIvars]
    pub(crate) struct ClosureTarget;

    impl ClosureTarget {
        #[unsafe(method(fire:))]
        fn fire(&self, sender: &AnyObject) {
            (self.ivars().handler)(sender);
        }
    }

    unsafe impl NSObjectProtocol for ClosureTarget {}
);

impl ClosureTarget {
    pub(crate) fn new(mtm: MainThreadMarker, handler: impl Fn(&AnyObject) + 'static) -> Retained<ClosureTarget> {
        let this = ClosureTarget::alloc(mtm).set_ivars(ClosureIvars { handler: Box::new(handler) });
        unsafe { msg_send![super(this), init] }
    }
}

pub(crate) struct HoverIvars {
    id: NodeId,
    events: EventSink,
}

define_class!(
    /// The owner of a node's tracking area: reports the pointer coming
    /// over the view and leaving. Tracking areas cover their view's
    /// visible rect, its subviews' too, so moving onto a child doesn't
    /// leave.
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[ivars = HoverIvars]
    pub(crate) struct HoverTracker;

    impl HoverTracker {
        #[unsafe(method(mouseEntered:))]
        fn mouse_entered(&self, _event: &NSEvent) {
            self.ivars().events.emit(self.ivars().id, UiEvent::Hover(true));
        }

        #[unsafe(method(mouseExited:))]
        fn mouse_exited(&self, _event: &NSEvent) {
            self.ivars().events.emit(self.ivars().id, UiEvent::Hover(false));
        }
    }

    unsafe impl NSObjectProtocol for HoverTracker {}
);

impl HoverTracker {
    /// Tracks the pointer over `view` while the app is active, as AppKit's
    /// own controls track it for their hover looks.
    pub(crate) fn track(
        mtm: MainThreadMarker,
        view: &NSView,
        id: NodeId,
        events: EventSink,
    ) -> (Retained<HoverTracker>, Retained<NSTrackingArea>) {
        let this = HoverTracker::alloc(mtm).set_ivars(HoverIvars { id, events });
        let tracker: Retained<HoverTracker> = unsafe { msg_send![super(this), init] };
        let options = NSTrackingAreaOptions::MouseEnteredAndExited
            | NSTrackingAreaOptions::ActiveInActiveApp
            | NSTrackingAreaOptions::InVisibleRect;
        let area = unsafe {
            NSTrackingArea::initWithRect_options_owner_userInfo(
                NSTrackingArea::alloc(),
                zero_rect(),
                options,
                Some(&tracker),
                None,
            )
        };
        view.addTrackingArea(&area);
        (tracker, area)
    }

    /// What AppKit sends it when the pointer comes over its view
    /// (`entered`) or leaves.
    pub(crate) fn send(&self, view: &NSView, entered: bool) -> Option<()> {
        let window = view.window()?;
        let kind = if entered { NSEventType::MouseEntered } else { NSEventType::MouseExited };
        let event = unsafe {
            NSEvent::enterExitEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_trackingNumber_userData(
                kind,
                NSPoint::new(0.0, 0.0),
                NSEventModifierFlags::empty(),
                0.0,
                window.windowNumber(),
                None,
                0,
                0,
                std::ptr::null_mut(),
            )
        }?;
        let _: () = unsafe {
            if entered { msg_send![self, mouseEntered: &*event] } else { msg_send![self, mouseExited: &*event] }
        };
        Some(())
    }
}

pub(crate) struct DoubleClickIvars {
    id: NodeId,
    events: EventSink,
}

define_class!(
    /// The target of a node's double-click recognizer: reports a double
    /// click on the view, or on what's in it that isn't a control (a
    /// button or field keeps its own clicks).
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[ivars = DoubleClickIvars]
    pub(crate) struct DoubleClicker;

    impl DoubleClicker {
        #[unsafe(method(clicked:))]
        fn clicked(&self, recognizer: &NSClickGestureRecognizer) {
            let Some(view) = recognizer.view() else { return };
            let at = recognizer.locationInView(unsafe { view.superview() }.as_deref());
            let mut hit = view.hitTest(at);
            while let Some(v) = hit.filter(|v| **v != *view) {
                // A label is a text field too, one that takes no input.
                let label = v.downcast_ref::<NSTextField>().is_some_and(|f| !f.isEditable() && !f.isSelectable());
                if (v.isKindOfClass(NSControl::class()) && !label) || v.isKindOfClass(NSText::class()) {
                    return;
                }
                hit = unsafe { v.superview() };
            }
            self.fire();
        }
    }

    unsafe impl NSObjectProtocol for DoubleClicker {}
);

impl DoubleClicker {
    /// Recognizes double clicks on `view`, its subviews' too, without
    /// holding back the clicks its controls get.
    pub(crate) fn track(
        mtm: MainThreadMarker,
        view: &NSView,
        id: NodeId,
        events: EventSink,
    ) -> (Retained<DoubleClicker>, Retained<NSClickGestureRecognizer>) {
        let this = DoubleClicker::alloc(mtm).set_ivars(DoubleClickIvars { id, events });
        let target: Retained<DoubleClicker> = unsafe { msg_send![super(this), init] };
        let recognizer = unsafe {
            NSClickGestureRecognizer::initWithTarget_action(
                NSClickGestureRecognizer::alloc(mtm),
                Some(&target),
                Some(sel!(clicked:)),
            )
        };
        recognizer.setNumberOfClicksRequired(2);
        recognizer.setDelaysPrimaryMouseButtonEvents(false);
        view.addGestureRecognizer(&recognizer);
        (target, recognizer)
    }

    /// What a recognized double click reports, for `synthesize` too:
    /// AppKit can't be sent clicks without a window on screen.
    pub(crate) fn fire(&self) {
        self.ivars().events.emit(self.ivars().id, UiEvent::DoubleClick);
    }
}

pub(crate) struct DrawnIvars {
    id: NodeId,
    events: EventSink,
    drawing: RefCell<DisplayList>,
}

define_class!(
    /// A drawn custom widget: rasterizes the display list the core sends,
    /// and reports pointer events for the core to interpret.
    #[unsafe(super(NSView))]
    #[thread_kind = MainThreadOnly]
    #[ivars = DrawnIvars]
    pub(crate) struct DrawnView;

    impl DrawnView {
        #[unsafe(method(isFlipped))]
        fn is_flipped(&self) -> bool {
            true
        }

        #[unsafe(method(drawRect:))]
        fn draw_rect(&self, _dirty: NSRect) {
            crate::custom::rasterize(&self.ivars().drawing.borrow());
        }

        #[unsafe(method(acceptsFirstMouse:))]
        fn accepts_first_mouse(&self, _event: Option<&NSEvent>) -> bool {
            true
        }

        #[unsafe(method(mouseDown:))]
        fn mouse_down(&self, event: &NSEvent) {
            self.pointer(PointerKind::Down, event);
        }

        #[unsafe(method(mouseUp:))]
        fn mouse_up(&self, event: &NSEvent) {
            self.pointer(PointerKind::Up, event);
        }
    }
);

impl DrawnView {
    pub(crate) fn new(mtm: MainThreadMarker, id: NodeId, events: EventSink) -> Retained<DrawnView> {
        let this =
            DrawnView::alloc(mtm).set_ivars(DrawnIvars { id, events, drawing: RefCell::new(DisplayList::default()) });
        unsafe { msg_send![super(this), initWithFrame: zero_rect()] }
    }

    pub(crate) fn drawing(&self) -> DisplayList {
        self.ivars().drawing.borrow().clone()
    }

    pub(crate) fn set_drawing(&self, drawing: DisplayList) {
        *self.ivars().drawing.borrow_mut() = drawing;
        self.setNeedsDisplay(true);
    }

    fn pointer(&self, kind: PointerKind, event: &NSEvent) {
        let p = self.convertPoint_fromView(event.locationInWindow(), None);
        let position = Point::new(p.x as f32, p.y as f32);
        self.ivars().events.emit(self.ivars().id, UiEvent::Pointer(PointerEvent { kind, position }));
    }
}