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
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
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
//! `GpuSurface`: a view whose backing layer is a `CAMetalLayer`, which the
//! app presents to from its own thread (wgpu takes the view's layer as it
//! is).
//!
//! Taking input, it's a responder like a game's view: it takes the first
//! responder from a click and Tab, keys come to `keyDown:` and
//! `flagsChanged:` after the menus' key equivalents, and a local event
//! monitor catches their `keyUp:`s (AppKit sends none for keys released
//! while Command is held). Its pointer lock is what games do: the cursor
//! hidden and dissociated from the mouse, whose moves still come as
//! events with deltas, and GameController's `GCMouse` gives the same
//! moves before the system's acceleration. Its keyboard grab takes every key in that monitor
//! before AppKit dispatches it, menus' key equivalents too, and turns off
//! the system's shortcuts with the window server's hot key mode, or only
//! Command-Tab with the app's presentation options.
//!
//! Taking text, it's an `NSTextInputClient`, as a text view is: `keyDown:`
//! hands the key to `interpretKeyEvents:`, and what `insertText:` gives
//! during it is what the key typed. Input methods compose in its marked
//! text, reported as the preedit for the app to draw, and commit with
//! `insertText:`, which then is text on its own; their windows open by the app's caret
//! (`firstRectForCharacterRange:`). The keys they take for a composition
//! (any, while one goes on, but those they hand back as commands) aren't
//! the app's. Not knowing the app's text, it keeps what was typed since the
//! caret last moved otherwise as the text before the caret, which macOS's
//! accents (offered as a key is held) need, to replace the letter it typed.
//! Not taking text, it has no input context, so no input method takes a
//! game's keys.

use std::cell::{Cell, RefCell};
use std::collections::HashSet;
use std::ffi::{c_char, c_void};
use std::ptr::NonNull;

use block2::RcBlock;
use mitsuami_core::backend::SyntheticInput;
use mitsuami_core::raw_window_handle::{
    AppKitDisplayHandle, AppKitWindowHandle, HandleError, RawDisplayHandle, RawWindowHandle,
};
use mitsuami_core::{
    ActionError, Cursor, EventSink, ImageSource, KeyCode, Modifiers, MouseButton, NativeSurface, NodeId, Pixels, Point,
    Rect, ScrollDelta, SurfaceHandle, SurfaceInput, SurfaceSize, SystemCursor, UiEvent,
};
use objc2::rc::{Retained, Weak};
use objc2::runtime::{AnyClass, AnyObject, NSObjectProtocol, ProtocolObject, Sel};
use objc2::{
    AllocAnyThread, ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_class, msg_send, sel,
};
use objc2_app_kit::{
    NSAccessibility, NSAccessibilityImageRole, NSAllRomanInputSourcesLocaleIdentifier, NSApplication,
    NSApplicationPresentationOptions, NSCursor, NSEvent, NSEventMask, NSEventModifierFlags, NSEventType, NSResponder,
    NSScreen, NSTextInputClient, NSTextInputContext, NSTrackingArea, NSTrackingAreaOptions, NSView,
    NSViewLayerContentsPlacement, NSWindow, NSWindowDidResignKeyNotification,
};
use objc2_foundation::{
    NSArray, NSAttributedString, NSAttributedStringKey, NSNotFound, NSNotification, NSNotificationCenter,
    NSOperationQueue, NSPoint, NSRange, NSRangePointer, NSRect, NSSize, NSString, NSUInteger,
};

use objc2_game_controller::{GCMouse, GCMouseDidConnectNotification, GCMouseInput};

use crate::classes::zero_rect;

#[repr(C)]
struct CGPoint {
    x: f64,
    y: f64,
}

#[link(name = "CoreGraphics", kind = "framework")]
unsafe extern "C" {
    fn CGAssociateMouseAndMouseCursorPosition(connected: u32) -> i32;
    fn CGWarpMouseCursorPosition(point: CGPoint) -> i32;
}

unsafe extern "C" {
    fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
}

const RTLD_DEFAULT: *mut c_void = -2isize as *mut c_void;

/// What a grab turned off, to give back when it ends.
#[derive(Clone, Copy)]
enum Grab {
    /// The window server's hot key mode before the grab.
    HotKeys(i32),
    /// The app's presentation options before the grab.
    Presentation(NSApplicationPresentationOptions),
}

type GetHotKeyMode = unsafe extern "C" fn(conn: i32, mode: *mut i32) -> i32;
type SetHotKeyMode = unsafe extern "C" fn(conn: i32, mode: i32) -> i32;

/// The window server's hot key mode: its connection, and the getter and
/// setter. SkyLight's private interface, the one UTM and VirtualBox set
/// for their keyboard capture; looked up rather than linked, so an app
/// never imports it and gets the presentation options where it's gone.
fn hot_key_mode() -> Option<(i32, GetHotKeyMode, SetHotKeyMode)> {
    // SAFETY: the symbols, when there, have these signatures.
    unsafe {
        let conn = dlsym(RTLD_DEFAULT, c"CGSMainConnectionID".as_ptr());
        let get = dlsym(RTLD_DEFAULT, c"CGSGetGlobalHotKeyOperatingMode".as_ptr());
        let set = dlsym(RTLD_DEFAULT, c"CGSSetGlobalHotKeyOperatingMode".as_ptr());
        if conn.is_null() || get.is_null() || set.is_null() {
            return None;
        }
        let conn = std::mem::transmute::<*mut c_void, unsafe extern "C" fn() -> i32>(conn);
        let get = std::mem::transmute::<*mut c_void, GetHotKeyMode>(get);
        let set = std::mem::transmute::<*mut c_void, SetHotKeyMode>(set);
        Some((conn(), get, set))
    }
}

/// Every shortcut of the Keyboard settings pane off, the accessibility
/// ones kept.
const HOT_KEYS_OFF_BUT_UNIVERSAL_ACCESS: i32 = 2;

/// Turns the system's shortcuts off, returning the mode to give back, if
/// the window server took it.
fn hot_keys_off() -> Option<i32> {
    let (conn, get, set) = hot_key_mode()?;
    let mut before = -1;
    // SAFETY: plain calls on our own connection.
    unsafe {
        if get(conn, &mut before) != 0 || set(conn, HOT_KEYS_OFF_BUT_UNIVERSAL_ACCESS) != 0 {
            return None;
        }
        let mut now = -1;
        get(conn, &mut now);
        if now != HOT_KEYS_OFF_BUT_UNIVERSAL_ACCESS {
            set(conn, before);
            return None;
        }
    }
    Some(before)
}

fn hot_keys_back(before: i32) {
    if let Some((conn, _, set)) = hot_key_mode() {
        // SAFETY: as in `hot_keys_off`.
        unsafe { set(conn, before) };
    }
}

type Observer = Retained<ProtocolObject<dyn NSObjectProtocol>>;

pub(crate) struct SurfaceIvars {
    id: NodeId,
    events: EventSink,
    /// Taken when the node is destroyed: the app's handle may keep the view
    /// alive, but it no longer reports (and holds no handle to itself).
    handle: RefCell<Option<SurfaceHandle>>,
    takes_input: Cell<bool>,
    /// Keys down, by their virtual key codes: for modifier keys, which
    /// only report their flags, and so a release is never reported twice.
    down: RefCell<HashSet<u16>>,
    tracking: RefCell<Option<Retained<NSTrackingArea>>>,
    /// The monitor for key events, while it's the first responder.
    monitor: RefCell<Option<Retained<AnyObject>>>,
    /// What the app asked for, and what's in effect: a lock or a grab
    /// asked for before the view is in a window waits for one.
    lock_wanted: Cell<bool>,
    locked: Cell<bool>,
    grab_wanted: Cell<bool>,
    /// What the grab turned off, while it's in effect.
    grab: Cell<Option<Grab>>,
    /// Ends the lock and the grab when the window stops being the key one.
    resign_observer: RefCell<Option<Observer>>,
    /// While locked: mice that connect get the raw motion handler too.
    mouse_observer: RefCell<Option<Observer>>,
    /// Lets go of the keys down when the window stops being the key one,
    /// while it's the first responder.
    key_observer: RefCell<Option<Observer>>,
    /// The cursor over it (none: the arrow), and what the app asked for,
    /// which an `NSCursor` can't give back.
    cursor: RefCell<Option<Retained<NSCursor>>>,
    cursor_prop: RefCell<Cursor>,
    /// Whether it takes text, whether input methods compose in it, and the
    /// app's caret, in points from its top left (the view is flipped).
    text_input: Cell<bool>,
    input_method: Cell<bool>,
    text_cursor: Cell<Option<Rect>>,
    /// While `keyDown:` interprets a key: what `insertText:` gave.
    typing: RefCell<Option<String>>,
    /// While `keyDown:` interprets a key: whether an input method composed
    /// with it (marked text, or committed it), and whether it was handed
    /// back as a command.
    composed: Cell<bool>,
    commanded: Cell<bool>,
    /// What was typed since the caret last moved otherwise (an arrow, a
    /// click): the text before the app's caret, as far as it's known.
    typed: RefCell<String>,
    /// An input method's composition in progress.
    marked: RefCell<String>,
    /// The preedit last reported, so an unchanged one isn't again.
    preedit: RefCell<(String, Option<usize>)>,
}

define_class!(
    /// A flipped, layer-backed view whose backing layer is a
    /// `CAMetalLayer`, sized with the view by AppKit.
    #[unsafe(super(NSView))]
    #[thread_kind = MainThreadOnly]
    #[ivars = SurfaceIvars]
    pub(crate) struct SurfaceView;

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

        #[unsafe(method_id(makeBackingLayer))]
        fn make_backing_layer(&self) -> Retained<AnyObject> {
            let class = AnyClass::get(c"CAMetalLayer").expect("QuartzCore's CAMetalLayer");
            unsafe { msg_send![class, layer] }
        }

        /// The app draws the layer; AppKit never does.
        #[unsafe(method(wantsUpdateLayer))]
        fn wants_update_layer(&self) -> bool {
            true
        }

        #[unsafe(method(setFrameSize:))]
        fn set_frame_size(&self, size: NSSize) {
            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
            self.report();
        }

        #[unsafe(method(viewDidChangeBackingProperties))]
        fn did_change_backing_properties(&self) {
            let _: () = unsafe { msg_send![super(self), viewDidChangeBackingProperties] };
            if let Some(window) = self.window() {
                let layer: Option<Retained<AnyObject>> = unsafe { msg_send![self, layer] };
                if let Some(layer) = layer {
                    let _: () = unsafe { msg_send![&*layer, setContentsScale: window.backingScaleFactor()] };
                }
            }
            self.report();
        }

        /// A lock or grab asked for before it had a window.
        #[unsafe(method(viewDidMoveToWindow))]
        fn did_move_to_window(&self) {
            let _: () = unsafe { msg_send![super(self), viewDidMoveToWindow] };
            if self.window().is_some() {
                self.apply_lock();
                self.apply_grab();
            }
        }

        #[unsafe(method(acceptsFirstResponder))]
        fn accepts_first_responder(&self) -> bool {
            self.ivars().takes_input.get()
        }

        #[unsafe(method(becomeFirstResponder))]
        fn become_first_responder(&self) -> bool {
            let became: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
            if became {
                self.watch_keys();
            }
            became
        }

        #[unsafe(method(resignFirstResponder))]
        fn resign_first_responder(&self) -> bool {
            let resigned: bool = unsafe { msg_send![super(self), resignFirstResponder] };
            if resigned {
                self.forget_typed();
                self.stop_watching_keys();
                self.release_keys();
                // A grab lasts while the surface has focus.
                if self.ungrab() {
                    self.end_grab();
                }
            }
            resigned
        }

        #[unsafe(method(keyDown:))]
        fn key_down(&self, event: &NSEvent) {
            // Control-Tab leaves a view that takes Tab, as it leaves a
            // text view: the window moves focus on.
            let flags = event.modifierFlags();
            if !self.ivars().takes_input.get()
                || (event.keyCode() == TAB && flags.contains(NSEventModifierFlags::Control))
            {
                let _: () = unsafe { msg_send![super(self), keyDown: event] };
                return;
            }
            // With Command, a shortcut: the menus' key equivalents and the
            // app's own, never text.
            let text = if self.takes_text() && !flags.contains(NSEventModifierFlags::Command) {
                let ivars = self.ivars();
                ivars.composed.set(self.hasMarkedText());
                ivars.commanded.set(false);
                *ivars.typing.borrow_mut() = Some(String::new());
                self.interpretKeyEvents(&NSArray::from_retained_slice(&[event.retain()]));
                let text = ivars.typing.borrow_mut().take().filter(|t| !t.is_empty());
                // An input method's key, for its composition (to start,
                // convert or commit one): unless it handed it back.
                if ivars.composed.get() && !ivars.commanded.get() {
                    return;
                }
                text
            } else {
                self.forget_typed();
                None
            };
            self.key(event, true, text);
        }

        /// An input context only while it takes text: an input method
        /// would otherwise take a game's keys.
        #[unsafe(method_id(inputContext))]
        fn input_context(&self) -> Option<Retained<NSTextInputContext>> {
            let context: Option<Retained<NSTextInputContext>> =
                if self.takes_text() { unsafe { msg_send![super(self), inputContext] } } else { None };
            if let Some(context) = &context {
                self.allow_input_sources(context);
            }
            context
        }

        /// Only synthesized: the monitor takes real ones.
        #[unsafe(method(keyUp:))]
        fn key_up(&self, event: &NSEvent) {
            if self.ivars().takes_input.get() {
                self.key(event, false, None);
            } else {
                let _: () = unsafe { msg_send![super(self), keyUp: event] };
            }
        }

        #[unsafe(method(flagsChanged:))]
        fn flags_changed(&self, event: &NSEvent) {
            if self.ivars().takes_input.get() {
                self.modifier_key(event);
            } else {
                let _: () = unsafe { msg_send![super(self), flagsChanged: event] };
            }
        }

        #[unsafe(method(mouseDown:))]
        fn mouse_down(&self, event: &NSEvent) {
            if !self.pointer_event(event, Some(true)) {
                let _: () = unsafe { msg_send![super(self), mouseDown: event] };
            }
        }

        #[unsafe(method(mouseUp:))]
        fn mouse_up(&self, event: &NSEvent) {
            if !self.pointer_event(event, Some(false)) {
                let _: () = unsafe { msg_send![super(self), mouseUp: event] };
            }
        }

        /// A context menu, if the app gave it one, still opens.
        #[unsafe(method(rightMouseDown:))]
        fn right_mouse_down(&self, event: &NSEvent) {
            self.pointer_event(event, Some(true));
            let _: () = unsafe { msg_send![super(self), rightMouseDown: event] };
        }

        #[unsafe(method(rightMouseUp:))]
        fn right_mouse_up(&self, event: &NSEvent) {
            if !self.pointer_event(event, Some(false)) {
                let _: () = unsafe { msg_send![super(self), rightMouseUp: event] };
            }
        }

        #[unsafe(method(otherMouseDown:))]
        fn other_mouse_down(&self, event: &NSEvent) {
            if !self.pointer_event(event, Some(true)) {
                let _: () = unsafe { msg_send![super(self), otherMouseDown: event] };
            }
        }

        #[unsafe(method(otherMouseUp:))]
        fn other_mouse_up(&self, event: &NSEvent) {
            if !self.pointer_event(event, Some(false)) {
                let _: () = unsafe { msg_send![super(self), otherMouseUp: event] };
            }
        }

        #[unsafe(method(mouseMoved:))]
        fn mouse_moved(&self, event: &NSEvent) {
            if !self.pointer_event(event, None) {
                let _: () = unsafe { msg_send![super(self), mouseMoved: event] };
            }
        }

        #[unsafe(method(mouseDragged:))]
        fn mouse_dragged(&self, event: &NSEvent) {
            if !self.pointer_event(event, None) {
                let _: () = unsafe { msg_send![super(self), mouseDragged: event] };
            }
        }

        #[unsafe(method(rightMouseDragged:))]
        fn right_mouse_dragged(&self, event: &NSEvent) {
            if !self.pointer_event(event, None) {
                let _: () = unsafe { msg_send![super(self), rightMouseDragged: event] };
            }
        }

        #[unsafe(method(otherMouseDragged:))]
        fn other_mouse_dragged(&self, event: &NSEvent) {
            if !self.pointer_event(event, None) {
                let _: () = unsafe { msg_send![super(self), otherMouseDragged: event] };
            }
        }

        #[unsafe(method(mouseExited:))]
        fn mouse_exited(&self, event: &NSEvent) {
            if self.ivars().takes_input.get() && !self.ivars().locked.get() {
                self.emit(SurfaceInput::PointerLeft);
            } else {
                let _: () = unsafe { msg_send![super(self), mouseExited: event] };
            }
        }

        #[unsafe(method(scrollWheel:))]
        fn scroll_wheel(&self, event: &NSEvent) {
            if !self.ivars().takes_input.get() {
                let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
                return;
            }
            // AppKit's deltas are how far the content moves, with the
            // user's scrolling direction applied: towards the end is less.
            let (x, y) = (-event.scrollingDeltaX() as f32, -event.scrollingDeltaY() as f32);
            let delta =
                if event.hasPreciseScrollingDeltas() { ScrollDelta::Points { x, y } } else { ScrollDelta::Lines { x, y } };
            self.emit(SurfaceInput::Scroll { delta, modifiers: modifiers(event.modifierFlags()) });
        }

        /// The app's cursor, over the whole view; AppKit shows it while
        /// the window is the key one.
        #[unsafe(method(resetCursorRects))]
        fn reset_cursor_rects(&self) {
            if let Some(cursor) = &*self.ivars().cursor.borrow() {
                self.addCursorRect_cursor(self.bounds(), cursor);
            }
        }

        /// Moves, entering and leaving, while it takes input.
        #[unsafe(method(updateTrackingAreas))]
        fn update_tracking_areas(&self) {
            let _: () = unsafe { msg_send![super(self), updateTrackingAreas] };
            self.track();
        }
    }

    unsafe impl NSTextInputClient for SurfaceView {
        /// Typed by the key `keyDown:` is interpreting, or committed by an
        /// input method.
        #[unsafe(method(insertText:replacementRange:))]
        unsafe fn insert_text(&self, string: &AnyObject, replacement: NSRange) {
            let text: String = text_of(string).chars().filter(|c| !c.is_control()).collect();
            let composed = !std::mem::take(&mut *self.ivars().marked.borrow_mut()).is_empty();
            if composed {
                self.ivars().composed.set(true);
            }
            // The composition ends before what it committed comes, and what
            // it replaces goes.
            self.report_preedit(String::new(), None);
            self.replace_typed(replacement);
            self.remember_typed(&text);
            let mut typing = self.ivars().typing.borrow_mut();
            match typing.as_mut() {
                Some(typed) if !composed => typed.push_str(&text),
                _ => {
                    drop(typing);
                    if !text.is_empty() {
                        self.emit(SurfaceInput::Text(text));
                    }
                }
            }
        }

        /// Enter, arrows, Backspace: the keys report themselves, so all
        /// that's left is what they do to the text before the caret.
        /// Handling it here keeps AppKit from beeping.
        #[unsafe(method(doCommandBySelector:))]
        unsafe fn do_command_by_selector(&self, selector: Sel) {
            self.ivars().commanded.set(true);
            if selector == sel!(deleteBackward:) {
                self.ivars().typed.borrow_mut().pop();
            } else {
                self.forget_typed();
            }
        }

        #[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
        unsafe fn set_marked_text(&self, string: &AnyObject, selected: NSRange, replacement: NSRange) {
            let text = text_of(string);
            self.ivars().composed.set(true);
            self.replace_typed(replacement);
            // The composition's caret, in UTF-16 units, made bytes.
            let cursor = (!text.is_empty()).then(|| {
                char::decode_utf16(text.encode_utf16().take(selected.location))
                    .filter_map(Result::ok)
                    .map(char::len_utf8)
                    .sum()
            });
            *self.ivars().marked.borrow_mut() = text.clone();
            self.report_preedit(text, cursor);
        }

        #[unsafe(method(unmarkText))]
        fn unmark_text(&self) {
            self.ivars().composed.set(true);
            self.ivars().marked.borrow_mut().clear();
            self.report_preedit(String::new(), None);
        }

        /// The caret, after what was typed (and the composition): macOS's
        /// accents aren't offered without one.
        #[unsafe(method(selectedRange))]
        fn selected_range(&self) -> NSRange {
            NSRange::new(self.text_before_caret().encode_utf16().count(), 0)
        }

        /// The composition, after what was typed.
        #[unsafe(method(markedRange))]
        fn marked_range(&self) -> NSRange {
            match self.ivars().marked.borrow().encode_utf16().count() {
                0 => NSRange::new(NSNotFound as NSUInteger, 0),
                len => NSRange::new(self.ivars().typed.borrow().encode_utf16().count(), len),
            }
        }

        #[unsafe(method(hasMarkedText))]
        fn has_marked_text(&self) -> bool {
            !self.ivars().marked.borrow().is_empty()
        }

        #[unsafe(method_id(attributedSubstringForProposedRange:actualRange:))]
        unsafe fn attributed_substring(
            &self,
            range: NSRange,
            actual: NSRangePointer,
        ) -> Option<Retained<NSAttributedString>> {
            let text: Vec<u16> = self.text_before_caret().encode_utf16().collect();
            let start = range.location.min(text.len());
            let end = range.location.saturating_add(range.length).min(text.len());
            if !actual.is_null() {
                unsafe { *actual = NSRange::new(start, end - start) };
            }
            let text = String::from_utf16_lossy(&text[start..end]);
            Some(NSAttributedString::from_nsstring(&NSString::from_str(&text)))
        }

        #[unsafe(method_id(validAttributesForMarkedText))]
        fn valid_attributes_for_marked_text(&self) -> Retained<NSArray<NSAttributedStringKey>> {
            NSArray::new()
        }

        /// The app's caret on screen, where input methods open their
        /// windows; the view's top left without one.
        #[unsafe(method(firstRectForCharacterRange:actualRange:))]
        unsafe fn first_rect(&self, range: NSRange, actual: NSRangePointer) -> NSRect {
            if !actual.is_null() {
                unsafe { *actual = range };
            }
            let caret = self.ivars().text_cursor.get().unwrap_or_default();
            let rect = NSRect::new(
                NSPoint::new(caret.x() as f64, caret.y() as f64),
                NSSize::new(caret.width() as f64, caret.height() as f64),
            );
            let in_window = self.convertRect_toView(rect, None);
            self.window().map_or(in_window, |window| window.convertRectToScreen(in_window))
        }

        #[unsafe(method(characterIndexForPoint:))]
        fn character_index_for_point(&self, _point: NSPoint) -> NSUInteger {
            NSNotFound as NSUInteger
        }
    }
);

/// What `insertText:` or `setMarkedText:` were given: a string, or an
/// attributed one.
fn text_of(string: &AnyObject) -> String {
    if let Some(attributed) = string.downcast_ref::<NSAttributedString>() {
        attributed.string().to_string()
    } else if let Some(plain) = string.downcast_ref::<NSString>() {
        plain.to_string()
    } else {
        String::new()
    }
}

/// `kVK_Tab`.
const TAB: u16 = 0x30;

/// How many characters of what was typed it keeps as the text before the
/// caret.
const TYPED_KEPT: usize = 64;

impl SurfaceView {
    /// The view, and the handle the app gets, whose size it keeps.
    pub(crate) fn new(mtm: MainThreadMarker, id: NodeId, events: EventSink) -> (Retained<SurfaceView>, SurfaceHandle) {
        let this = SurfaceView::alloc(mtm).set_ivars(SurfaceIvars {
            id,
            events,
            handle: RefCell::new(None),
            takes_input: Cell::new(false),
            down: RefCell::default(),
            tracking: RefCell::new(None),
            monitor: RefCell::new(None),
            lock_wanted: Cell::new(false),
            locked: Cell::new(false),
            grab_wanted: Cell::new(false),
            grab: Cell::new(None),
            resign_observer: RefCell::new(None),
            mouse_observer: RefCell::new(None),
            key_observer: RefCell::new(None),
            cursor: RefCell::new(None),
            cursor_prop: RefCell::new(Cursor::Default),
            text_input: Cell::new(false),
            input_method: Cell::new(true),
            text_cursor: Cell::new(None),
            typing: RefCell::new(None),
            composed: Cell::new(false),
            commanded: Cell::new(false),
            typed: RefCell::new(String::new()),
            marked: RefCell::new(String::new()),
            preedit: RefCell::default(),
        });
        let view: Retained<SurfaceView> = unsafe { msg_send![super(this), initWithFrame: zero_rect()] };
        view.setWantsLayer(true);
        // Until the app presents at a new size, its last frame stays as it
        // was, at the top left, rather than stretched to the new bounds
        // (AppKit's default for layer-backed views).
        view.setLayerContentsPlacement(NSViewLayerContentsPlacement::TopLeft);
        view.setAccessibilityElement(true);
        view.setAccessibilityRole(Some(unsafe { NSAccessibilityImageRole }));
        let handle = SurfaceHandle::new(AppKitSurface(Some(Retained::into_super(view.clone()))));
        *view.ivars().handle.borrow_mut() = Some(handle.clone());
        (view, handle)
    }

    /// The node is gone; the app may still hold the view. It lets go of
    /// the pointer and keyboard without reporting it.
    pub(crate) fn detach(&self) {
        self.ivars().handle.borrow_mut().take();
        self.ivars().lock_wanted.set(false);
        self.ivars().grab_wanted.set(false);
        self.unlock();
        self.ungrab();
        self.stop_watching_keys();
        self.set_takes_input(false);
    }

    pub(crate) fn takes_input(&self) -> bool {
        self.ivars().takes_input.get()
    }

    pub(crate) fn pointer_locked(&self) -> bool {
        self.ivars().locked.get()
    }

    pub(crate) fn keyboard_grabbed(&self) -> bool {
        self.ivars().grab.get().is_some()
    }

    pub(crate) fn set_takes_input(&self, takes: bool) {
        if self.ivars().takes_input.replace(takes) == takes {
            return;
        }
        self.track();
        if !takes && let Some(window) = self.window() {
            let first: Option<Retained<NSResponder>> = window.firstResponder();
            if first.is_some_and(|r| std::ptr::eq(&*r, self.as_super().as_super())) {
                window.makeFirstResponder(None);
            }
        }
    }

    pub(crate) fn cursor(&self) -> Cursor {
        self.ivars().cursor_prop.borrow().clone()
    }

    /// An image, or a clear one for none: hiding the cursor with
    /// `NSCursor.hide` would hide it everywhere until it moved out.
    pub(crate) fn set_cursor(&self, cursor: &Cursor) {
        let ns_cursor = match cursor {
            Cursor::Default => None,
            Cursor::Hidden => cursor_image(&Pixels::new(1, 1, vec![0; 4]), Point::ZERO),
            Cursor::Image { pixels, hotspot } => cursor_image(pixels, *hotspot),
            Cursor::System(shape) => system_cursor(*shape),
        };
        *self.ivars().cursor.borrow_mut() = ns_cursor;
        *self.ivars().cursor_prop.borrow_mut() = cursor.clone();
        if let Some(window) = self.window() {
            window.invalidateCursorRectsForView(self);
        }
    }

    pub(crate) fn text_input(&self) -> bool {
        self.ivars().text_input.get()
    }

    pub(crate) fn input_method(&self) -> bool {
        self.ivars().input_method.get()
    }

    pub(crate) fn text_cursor(&self) -> Option<Rect> {
        self.ivars().text_cursor.get()
    }

    /// Input methods off, its context takes only Roman input sources:
    /// macOS switches to one while the view has focus, and back as it
    /// leaves. The keyboard layout still composes dead keys and Option.
    fn allow_input_sources(&self, context: &NSTextInputContext) {
        let roman = (!self.ivars().input_method.get())
            .then(|| NSArray::from_slice(&[unsafe { NSAllRomanInputSourcesLocaleIdentifier }]));
        if context.allowedInputSourceLocales().as_deref() != roman.as_deref() {
            context.setAllowedInputSourceLocales(roman.as_deref());
        }
    }

    /// Whether input methods compose in it while it takes text: the
    /// context's input sources follow it as it's asked for (above), so a
    /// view that has focus asks for it again, which switches the source now.
    pub(crate) fn set_input_method(&self, on: bool) {
        if self.ivars().input_method.replace(on) == on {
            return;
        }
        if self.is_first_responder()
            && let Some(context) = self.inputContext()
        {
            context.discardMarkedText();
            context.deactivate();
            context.activate();
        }
    }

    /// Takes text: its input context comes and goes with it. AppKit asks
    /// for the context as the view becomes the first responder, so a view
    /// that already is gets it (or loses it) here.
    pub(crate) fn set_text_input(&self, on: bool) {
        if self.ivars().text_input.replace(on) == on {
            return;
        }
        self.ivars().marked.borrow_mut().clear();
        self.forget_typed();
        *self.ivars().preedit.borrow_mut() = Default::default();
        if !self.is_first_responder() {
            return;
        }
        match self.inputContext() {
            Some(context) => context.activate(),
            None => {
                if let Some(current) = NSTextInputContext::currentInputContext(MainThreadMarker::from(self)) {
                    current.deactivate();
                }
            }
        }
    }

    /// The input method's windows move with the caret.
    pub(crate) fn set_text_cursor(&self, caret: Option<Rect>) {
        self.ivars().text_cursor.set(caret);
        if let Some(context) = self.inputContext() {
            context.invalidateCharacterCoordinates();
        }
    }

    fn takes_text(&self) -> bool {
        self.ivars().takes_input.get() && self.ivars().text_input.get()
    }

    fn is_first_responder(&self) -> bool {
        let first: Option<Retained<NSResponder>> = self.window().and_then(|w| w.firstResponder());
        first.is_some_and(|r| std::ptr::eq(&*r, self.as_super().as_super()))
    }

    pub(crate) fn set_pointer_lock(&self, on: bool) {
        self.ivars().lock_wanted.set(on);
        if on {
            self.apply_lock();
        } else {
            self.unlock();
        }
    }

    pub(crate) fn set_keyboard_grab(&self, on: bool) {
        self.ivars().grab_wanted.set(on);
        if on {
            self.apply_grab();
        } else {
            self.ungrab();
        }
    }

    /// What was typed and the composition: the text before the caret.
    fn text_before_caret(&self) -> String {
        format!("{}{}", self.ivars().typed.borrow(), self.ivars().marked.borrow())
    }

    /// Text typed, or committed, before the caret.
    fn remember_typed(&self, text: &str) {
        let mut typed = self.ivars().typed.borrow_mut();
        typed.push_str(text);
        // What an input method reaches back for is a letter or a few.
        if let Some((cut, _)) = typed.char_indices().rev().nth(TYPED_KEPT) {
            typed.drain(..=cut);
        }
    }

    /// The caret moved otherwise: what's before it isn't known.
    fn forget_typed(&self) {
        self.ivars().typed.borrow_mut().clear();
    }

    /// An input method replaces `range` of the text before the caret, in
    /// UTF-16 units: what of it was typed goes (it ends at the caret, as
    /// macOS's accents' does), and the app is told to delete it. Ranges in
    /// the composition are its own.
    fn replace_typed(&self, range: NSRange) {
        if range.location == NSNotFound as NSUInteger {
            return;
        }
        let before = {
            let mut typed = self.ivars().typed.borrow_mut();
            let mut units = 0;
            let Some(cut) = typed.char_indices().map(|(i, _)| i).find(|&i| {
                let at = units;
                units += typed[i..].chars().next().map_or(0, char::len_utf16);
                at >= range.location
            }) else {
                return;
            };
            let before = typed[cut..].chars().count();
            typed.truncate(cut);
            before
        };
        self.emit(SurfaceInput::DeleteSurrounding { before, after: 0 });
    }

    /// Reports an input method's composition, if it changed: the app draws
    /// it at its caret.
    fn report_preedit(&self, text: String, cursor: Option<usize>) {
        let preedit = (text, cursor);
        if *self.ivars().preedit.borrow() == preedit || !self.takes_text() {
            return;
        }
        *self.ivars().preedit.borrow_mut() = preedit.clone();
        let (text, cursor) = preedit;
        self.emit(SurfaceInput::Preedit { text, cursor });
    }

    fn emit(&self, input: SurfaceInput) {
        let ivars = self.ivars();
        if ivars.handle.borrow().is_some() {
            ivars.events.emit(ivars.id, UiEvent::SurfaceInput(input));
        }
    }

    /// Its size in pixels, as the layer's drawable should be, if it changed.
    fn report(&self) {
        let ivars = self.ivars();
        let Some(handle) = ivars.handle.borrow().clone() else { return };
        let pixels = self.convertSizeToBacking(self.bounds().size);
        let scale = self.window().map_or(1.0, |w| w.backingScaleFactor());
        let size = SurfaceSize {
            width: pixels.width.round() as u32,
            height: pixels.height.round() as u32,
            scale: scale as f32,
        };
        if handle.set_size(size) {
            ivars.events.emit(ivars.id, UiEvent::SurfaceResized(size));
        }
    }

    fn track(&self) {
        let ivars = self.ivars();
        if let Some(area) = ivars.tracking.borrow_mut().take() {
            self.removeTrackingArea(&area);
        }
        if !ivars.takes_input.get() {
            return;
        }
        let options = NSTrackingAreaOptions::MouseEnteredAndExited
            | NSTrackingAreaOptions::MouseMoved
            | NSTrackingAreaOptions::ActiveInActiveApp
            | NSTrackingAreaOptions::InVisibleRect;
        let area = unsafe {
            NSTrackingArea::initWithRect_options_owner_userInfo(
                NSTrackingArea::alloc(),
                zero_rect(),
                options,
                Some(self),
                None,
            )
        };
        self.addTrackingArea(&area);
        *ivars.tracking.borrow_mut() = Some(area);
    }

    // ------------------------------------------------------------- keys

    fn key(&self, event: &NSEvent, pressed: bool, text: Option<String>) {
        let code = event.keyCode();
        // Only key downs and ups know whether they repeat, or what they
        // type; asking a modifier key's `flagsChanged:` event raises an
        // exception.
        let key_event = matches!(event.r#type(), NSEventType::KeyDown | NSEventType::KeyUp);
        let repeat = pressed && event.r#type() == NSEventType::KeyDown && event.isARepeat();
        let was_down = if pressed {
            !self.ivars().down.borrow_mut().insert(code)
        } else {
            self.ivars().down.borrow_mut().remove(&code)
        };
        // A release for a key it never saw go down (it went down elsewhere).
        if !pressed && !was_down {
            return;
        }
        let modifiers = modifiers(event.modifierFlags());
        let unmodified = if key_event { unmodified(event) } else { None };
        let (code, native) = (KeyCode::from_mac(code), code as u32);
        self.emit(SurfaceInput::Key { code, native, pressed, repeat, modifiers, text, unmodified });
    }

    /// Modifier keys only change the flags: each side's device flag says
    /// whether it's down. Caps Lock's flag is the lock's, and it comes
    /// once for each press, so it's reported down and up.
    fn modifier_key(&self, event: &NSEvent) {
        let code = event.keyCode();
        let flags = event.modifierFlags().0;
        let side = match code {
            0x38 => 0x02,   // left Shift
            0x3C => 0x04,   // right Shift
            0x3B => 0x01,   // left Control
            0x3E => 0x2000, // right Control
            0x3A => 0x20,   // left Option
            0x3D => 0x40,   // right Option
            0x37 => 0x08,   // left Command
            0x36 => 0x10,   // right Command
            0x39 => {
                let modifiers = modifiers(event.modifierFlags());
                for pressed in [true, false] {
                    let (native, text, unmodified) = (code as u32, None, None);
                    let code = KeyCode::CapsLock;
                    self.emit(SurfaceInput::Key { code, native, pressed, repeat: false, modifiers, text, unmodified });
                }
                return;
            }
            _ => return,
        };
        let pressed = flags & side != 0;
        if pressed == self.ivars().down.borrow().contains(&code) {
            return;
        }
        self.key(event, pressed, None);
    }

    /// Releases every key it has down: focus left, or the window stopped
    /// being the key one, so their releases go elsewhere.
    fn release_keys(&self) {
        let down: Vec<u16> = self.ivars().down.borrow_mut().drain().collect();
        for code in down {
            let (native, modifiers) = (code as u32, Modifiers::default());
            let (code, text, unmodified) = (KeyCode::from_mac(code), None, None);
            self.emit(SurfaceInput::Key { code, native, pressed: false, repeat: false, modifiers, text, unmodified });
        }
    }

    /// While it's the first responder: every key release (AppKit sends
    /// none for keys let go while Command is held), and while the keyboard
    /// is grabbed, every key, before menus' key equivalents and the
    /// window see it.
    fn watch_keys(&self) {
        if self.ivars().monitor.borrow().is_some() {
            return;
        }
        let weak = Weak::from_retained(&self.retain());
        let handler = RcBlock::new(move |event: NonNull<NSEvent>| -> *mut NSEvent {
            let Some(view) = weak.load() else { return event.as_ptr() };
            // SAFETY: AppKit hands the monitor a live event.
            let e = unsafe { event.as_ref() };
            let mtm = MainThreadMarker::from(&*view);
            let ours = e.window(mtm).zip(view.window()).is_some_and(|(a, b)| std::ptr::eq(&*a, &*b));
            if !ours {
                return event.as_ptr();
            }
            match e.r#type() {
                NSEventType::KeyUp => view.key(e, false, None),
                // Taken before AppKit dispatches it: no input method sees it.
                NSEventType::KeyDown if view.keyboard_grabbed() => view.key(e, true, None),
                NSEventType::FlagsChanged if view.keyboard_grabbed() => view.modifier_key(e),
                _ => return event.as_ptr(),
            }
            std::ptr::null_mut()
        });
        let mask = NSEventMask::KeyDown | NSEventMask::KeyUp | NSEventMask::FlagsChanged;
        let monitor = unsafe { NSEvent::addLocalMonitorForEventsMatchingMask_handler(mask, &handler) };
        *self.ivars().monitor.borrow_mut() = monitor;
        // The window stays the first responder's when it stops being the
        // key one, but the keys' releases go to the new key window.
        let Some(window) = self.window() else { return };
        let weak = Weak::from_retained(&self.retain());
        let block = RcBlock::new(move |_: NonNull<NSNotification>| {
            if let Some(view) = weak.load() {
                view.release_keys();
            }
        });
        let observer = unsafe {
            NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(
                Some(NSWindowDidResignKeyNotification),
                Some(&window),
                None,
                &block,
            )
        };
        *self.ivars().key_observer.borrow_mut() = Some(observer);
    }

    fn stop_watching_keys(&self) {
        if let Some(monitor) = self.ivars().monitor.borrow_mut().take() {
            unsafe { NSEvent::removeMonitor(&monitor) };
        }
        if let Some(observer) = self.ivars().key_observer.borrow_mut().take() {
            unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
        }
    }

    // ---------------------------------------------------------- pointer

    /// A button (`Some(pressed)`) or a move; returns whether it took it.
    fn pointer_event(&self, event: &NSEvent, pressed: Option<bool>) -> bool {
        let ivars = self.ivars();
        if !ivars.takes_input.get() {
            return false;
        }
        let modifiers = modifiers(event.modifierFlags());
        let Some(pressed) = pressed else {
            if ivars.locked.get() {
                self.emit(SurfaceInput::Motion { dx: event.deltaX() as f32, dy: event.deltaY() as f32 });
            } else {
                self.emit(SurfaceInput::PointerMoved { position: self.position(event), modifiers });
            }
            return true;
        };
        if pressed {
            self.forget_typed();
            if let Some(window) = self.window() {
                window.makeFirstResponder(Some(self));
            }
        }
        let button = match event.r#type() {
            NSEventType::LeftMouseDown | NSEventType::LeftMouseUp => MouseButton::Primary,
            NSEventType::RightMouseDown | NSEventType::RightMouseUp => MouseButton::Secondary,
            _ => match event.buttonNumber() {
                2 => MouseButton::Middle,
                3 => MouseButton::Back,
                4 => MouseButton::Forward,
                n => MouseButton::Other(n as u16),
            },
        };
        let position = self.position(event);
        self.emit(SurfaceInput::Button { button, pressed, position, modifiers });
        true
    }

    fn position(&self, event: &NSEvent) -> Point {
        let at = self.convertPoint_fromView(event.locationInWindow(), None);
        Point::new(at.x as f32, at.y as f32)
    }

    /// Locks the pointer if the app asked and the window is the key one;
    /// in a window that isn't, it can't.
    fn apply_lock(&self) {
        let ivars = self.ivars();
        if !ivars.lock_wanted.get() || ivars.locked.get() {
            return;
        }
        let Some(window) = self.window() else { return };
        if !active(&window) {
            return self.end_lock();
        }
        // The cursor stays put, hidden, and the mouse's moves still come
        // as events, with their deltas.
        unsafe { CGAssociateMouseAndMouseCursorPosition(0) };
        NSCursor::hide();
        ivars.locked.set(true);
        self.warp_to_middle(&window);
        self.watch_window(&window);
        self.watch_mice();
    }

    /// Returns whether it was locked.
    fn unlock(&self) -> bool {
        if !self.ivars().locked.replace(false) {
            return false;
        }
        unsafe { CGAssociateMouseAndMouseCursorPosition(1) };
        NSCursor::unhide();
        self.stop_watching_window();
        self.stop_watching_mice();
        true
    }

    /// Raw motion while locked: `GCMouse`'s deltas are the device's, not
    /// affected by the pointer's speed setting (a small program showed the
    /// ratio to `NSEvent`'s changing with speed). Up is positive there.
    /// Its handlers run on the main queue, GameController's default. A
    /// mouse has one handler, so the last surface to lock has it.
    fn watch_mice(&self) {
        let mouse_handler = |view: &SurfaceView| {
            let weak = Weak::from_retained(&view.retain());
            RcBlock::new(move |_: NonNull<GCMouseInput>, dx: f32, dy: f32| {
                if MainThreadMarker::new().is_none() {
                    return;
                }
                if let Some(view) = weak.load()
                    && view.ivars().locked.get()
                {
                    view.emit(SurfaceInput::RawMotion { dx, dy: -dy });
                }
            })
        };
        let watch = move |mouse: &GCMouse, view: &SurfaceView| {
            if let Some(input) = unsafe { mouse.mouseInput() } {
                let handler = mouse_handler(view);
                unsafe { input.setMouseMovedHandler(RcBlock::as_ptr(&handler)) };
            }
        };
        for mouse in unsafe { GCMouse::mice() } {
            watch(&mouse, self);
        }
        let weak = Weak::from_retained(&self.retain());
        let block = RcBlock::new(move |notification: NonNull<NSNotification>| {
            let Some(view) = weak.load() else { return };
            // SAFETY: the notification center hands the block a live one.
            let object = unsafe { notification.as_ref() }.object();
            if let Some(mouse) = object.and_then(|o| o.downcast::<GCMouse>().ok()) {
                watch(&mouse, &view);
            }
        });
        let observer = unsafe {
            NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(
                Some(GCMouseDidConnectNotification),
                None,
                Some(&NSOperationQueue::mainQueue()),
                &block,
            )
        };
        *self.ivars().mouse_observer.borrow_mut() = Some(observer);
    }

    fn stop_watching_mice(&self) {
        if let Some(observer) = self.ivars().mouse_observer.borrow_mut().take() {
            unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
        }
        for mouse in unsafe { GCMouse::mice() } {
            if let Some(input) = unsafe { mouse.mouseInput() } {
                unsafe { input.setMouseMovedHandler(std::ptr::null_mut()) };
            }
        }
    }

    fn end_lock(&self) {
        self.unlock();
        self.ivars().lock_wanted.set(false);
        let ivars = self.ivars();
        if ivars.handle.borrow().is_some() {
            ivars.events.emit(ivars.id, UiEvent::PointerLockEnded);
        }
    }

    /// Puts the (hidden) cursor over the middle of the surface, so a
    /// click lands on it.
    fn warp_to_middle(&self, window: &NSWindow) {
        let bounds = self.bounds();
        let middle =
            NSPoint::new(bounds.origin.x + bounds.size.width / 2.0, bounds.origin.y + bounds.size.height / 2.0);
        let on_screen = window.convertPointToScreen(self.convertPoint_toView(middle, None));
        // Quartz's global coordinates start at the top left of the main
        // display; AppKit's at its bottom left.
        let mtm = MainThreadMarker::from(self);
        let Some(main) = NSScreen::screens(mtm).firstObject() else { return };
        let point = CGPoint { x: on_screen.x, y: main.frame().size.height - on_screen.y };
        unsafe { CGWarpMouseCursorPosition(point) };
    }

    // --------------------------------------------------------- keyboard

    /// Grabs the keyboard if the app asked and the window is the key one,
    /// focusing the surface.
    fn apply_grab(&self) {
        let ivars = self.ivars();
        if !ivars.grab_wanted.get() || ivars.grab.get().is_some() {
            return;
        }
        let Some(window) = self.window() else { return };
        if !active(&window) || !ivars.takes_input.get() || !window.makeFirstResponder(Some(self)) {
            return self.end_grab();
        }
        // With the window server's shortcuts off, their keys (Command-Tab,
        // Command-Space, Control-arrows) come as plain key downs. The
        // presentation options only stop the window server acting on
        // Command-Tab, Mission Control and the Spaces arrows: their keys
        // never come, and a key held for a game can't be pressed again
        // while Control is.
        let grab = match hot_keys_off() {
            Some(before) => Grab::HotKeys(before),
            None => {
                // Command-Tab and Command-H stay with the app; AppKit
                // allows turning off process switching only with the
                // Dock hidden or hiding itself.
                let app = NSApplication::sharedApplication(MainThreadMarker::from(self));
                let before = app.presentationOptions();
                let mut options = before
                    | NSApplicationPresentationOptions::DisableProcessSwitching
                    | NSApplicationPresentationOptions::DisableHideApplication;
                if !before.contains(NSApplicationPresentationOptions::HideDock) {
                    options |= NSApplicationPresentationOptions::AutoHideDock;
                }
                app.setPresentationOptions(options);
                Grab::Presentation(before)
            }
        };
        ivars.grab.set(Some(grab));
        self.watch_window(&window);
    }

    /// Returns whether it was grabbed. The hot key mode doesn't follow
    /// focus, so it's given back whenever the grab ends.
    fn ungrab(&self) -> bool {
        let Some(grab) = self.ivars().grab.take() else { return false };
        match grab {
            Grab::HotKeys(before) => hot_keys_back(before),
            Grab::Presentation(before) => {
                NSApplication::sharedApplication(MainThreadMarker::from(self)).setPresentationOptions(before)
            }
        }
        self.stop_watching_window();
        true
    }

    fn end_grab(&self) {
        self.ungrab();
        self.ivars().grab_wanted.set(false);
        let ivars = self.ivars();
        if ivars.handle.borrow().is_some() {
            ivars.events.emit(ivars.id, UiEvent::KeyboardGrabEnded);
        }
    }

    /// While locked or grabbed: the window stopping being the key one
    /// (another app, another window) ends both.
    fn watch_window(&self, window: &NSWindow) {
        if self.ivars().resign_observer.borrow().is_some() {
            return;
        }
        let weak = Weak::from_retained(&self.retain());
        let block = RcBlock::new(move |_: NonNull<NSNotification>| {
            let Some(view) = weak.load() else { return };
            if view.unlock() {
                view.end_lock();
            }
            if view.ungrab() {
                view.end_grab();
            }
        });
        let center = NSNotificationCenter::defaultCenter();
        let observer = unsafe {
            center.addObserverForName_object_queue_usingBlock(
                Some(NSWindowDidResignKeyNotification),
                Some(window),
                None,
                &block,
            )
        };
        *self.ivars().resign_observer.borrow_mut() = Some(observer);
    }

    fn stop_watching_window(&self) {
        let ivars = self.ivars();
        if ivars.locked.get() || ivars.grab.get().is_some() {
            return;
        }
        if let Some(observer) = ivars.resign_observer.borrow_mut().take() {
            unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
        }
    }
}

fn cursor_image(pixels: &Pixels, hotspot: Point) -> Option<Retained<NSCursor>> {
    let image = crate::backend::ns_image(&ImageSource::Pixels(pixels.clone()))?;
    let hotspot = NSPoint::new(hotspot.x as f64, hotspot.y as f64);
    Some(NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot))
}

/// Whether the window takes the keyboard: the key window of the active
/// app.
fn active(window: &NSWindow) -> bool {
    window.isKeyWindow() && NSApplication::sharedApplication(MainThreadMarker::from(window)).isActive()
}

/// The character the key types with no modifiers, in the keyboard's
/// layout. Function keys' characters are private use (U+F700 on).
fn unmodified(event: &NSEvent) -> Option<char> {
    let characters = event.charactersByApplyingModifiers(NSEventModifierFlags::empty())?;
    let c = characters.to_string().chars().next()?;
    (!c.is_control() && !('\u{F700}'..='\u{F8FF}').contains(&c)).then_some(c)
}

fn modifiers(flags: NSEventModifierFlags) -> Modifiers {
    Modifiers {
        shift: flags.contains(NSEventModifierFlags::Shift),
        control: flags.contains(NSEventModifierFlags::Control),
        alt: flags.contains(NSEventModifierFlags::Option),
        meta: flags.contains(NSEventModifierFlags::Command),
    }
}

/// Input for tests, through the view's own event methods: a click as
/// real mouse events (which focus it), keys as real key events to the
/// first responder, which interprets them as it does real ones, and an
/// input method's text through `insertText:` (and `setMarkedText:` as it
/// composes). Scrolls are reported as
/// they'd come: AppKit makes no scroll events but from Quartz ones.
pub(crate) fn synthesize(view: &SurfaceView, input: &SyntheticInput) -> Result<(), ActionError> {
    if !view.takes_input() {
        return Err(ActionError::Unsupported);
    }
    let window = view.window().ok_or(ActionError::Unsupported)?;
    match input {
        SyntheticInput::Click(point) => {
            let location = view.convertPoint_toView(NSPoint::new(point.x as f64, point.y as f64), None);
            for (kind, up) in [(NSEventType::LeftMouseDown, false), (NSEventType::LeftMouseUp, true)] {
                let event = NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
                    kind,
                    location,
                    NSEventModifierFlags::empty(),
                    0.0,
                    window.windowNumber(),
                    None,
                    0,
                    1,
                    if up { 0.0 } else { 1.0 },
                )
                .ok_or(ActionError::Unsupported)?;
                if up { view.mouseUp(&event) } else { view.mouseDown(&event) }
            }
        }
        SyntheticInput::Key(key) => {
            let first: Option<Retained<NSResponder>> = window.firstResponder();
            if !first.is_some_and(|r| std::ptr::eq(&*r, view.as_super().as_super())) {
                return Err(ActionError::Unsupported);
            }
            let (code, character) = (KeyCode::from_key(*key), crate::services::event_character(*key));
            let code = (0..0x7F).find(|c| KeyCode::from_mac(*c) == code).ok_or(ActionError::Unsupported)?;
            let characters = NSString::from_str(&character.to_string());
            for (kind, up) in [(NSEventType::KeyDown, false), (NSEventType::KeyUp, true)] {
                let event = NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
                    kind,
                    NSPoint::new(0.0, 0.0),
                    NSEventModifierFlags::empty(),
                    0.0,
                    window.windowNumber(),
                    None,
                    &characters,
                    &characters,
                    false,
                    code,
                )
                .ok_or(ActionError::Unsupported)?;
                if up { view.keyUp(&event) } else { view.keyDown(&event) }
            }
        }
        SyntheticInput::Scroll { dx, dy } => {
            let delta = ScrollDelta::Points { x: *dx, y: *dy };
            view.emit(SurfaceInput::Scroll { delta, modifiers: Modifiers::default() });
        }
        SyntheticInput::Text(text) => {
            if !view.takes_text() || !view.input_method() || !view.is_first_responder() {
                return Err(ActionError::Unsupported);
            }
            let string = NSString::from_str(text);
            let nowhere = NSRange::new(NSNotFound as NSUInteger, 0);
            unsafe { view.insertText_replacementRange(&string, nowhere) };
        }
        // As an input method composes: the view's marked text, its caret
        // at the end; empty ends it.
        SyntheticInput::Compose(text) => {
            if !view.takes_text() || !view.input_method() || !view.is_first_responder() {
                return Err(ActionError::Unsupported);
            }
            if text.is_empty() {
                view.unmarkText();
            } else {
                let string = NSString::from_str(text);
                let caret = NSRange::new(text.encode_utf16().count(), 0);
                let nowhere = NSRange::new(NSNotFound as NSUInteger, 0);
                unsafe { view.setMarkedText_selectedRange_replacementRange(&string, caret, nowhere) };
            }
        }
        // Keys with modifiers aren't simulated on a surface.
        SyntheticInput::Shortcut(_)
        | SyntheticInput::DragFiles(_)
        | SyntheticInput::DragLeave
        | SyntheticInput::DropFiles(_)
        | SyntheticInput::PointerEnter
        | SyntheticInput::PointerLeave
        | SyntheticInput::DoubleClick => {
            return Err(ActionError::Unsupported);
        }
    }
    Ok(())
}

/// The view, for `raw-window-handle`. Views belong to the main thread:
/// the last handle dropped elsewhere sends it there to be released.
struct AppKitSurface(Option<Retained<NSView>>);

// SAFETY: the view is only messaged on the main thread; other threads only
// read its address, and send it back to the main thread to be released.
unsafe impl Send for AppKitSurface {}
unsafe impl Sync for AppKitSurface {}

// SAFETY: it retains the view, released only when it's dropped.
unsafe impl NativeSurface for AppKitSurface {
    fn window_handle(&self) -> Result<RawWindowHandle, HandleError> {
        let view = self.0.as_ref().ok_or(HandleError::Unavailable)?;
        Ok(RawWindowHandle::AppKit(AppKitWindowHandle::new(NonNull::from(&**view).cast())))
    }

    fn display_handle(&self) -> Result<RawDisplayHandle, HandleError> {
        Ok(RawDisplayHandle::AppKit(AppKitDisplayHandle::new()))
    }
}

impl Drop for AppKitSurface {
    fn drop(&mut self) {
        if MainThreadMarker::new().is_some() {
            return;
        }
        struct Release(Retained<NSView>);
        // SAFETY: released on the main thread, never touched on the way.
        unsafe impl Send for Release {}
        if let Some(view) = self.0.take() {
            let release = Release(view);
            dispatch2::DispatchQueue::main().exec_async(move || {
                let release = release;
                drop(release.0);
            });
        }
    }
}

/// AppKit's cursor for a platform cursor, or `None` (the arrow) where it has
/// none: no busy cursor (the system shows its own spinner over an app that
/// doesn't answer), no help or move cursor. The resize cursors are macOS
/// 15's frame ones where it has them, looked up at run time; before, only
/// the straight ones, which 15 deprecated.
fn system_cursor(shape: SystemCursor) -> Option<Retained<NSCursor>> {
    use objc2_app_kit::{NSCursorFrameResizeDirections as Directions, NSCursorFrameResizePosition as Position};
    let frame = |position| {
        NSCursor::class()
            .class_method(sel!(frameResizeCursorFromPosition:inDirections:))
            .map(|_| NSCursor::frameResizeCursorFromPosition_inDirections(position, Directions::All))
    };
    match shape {
        SystemCursor::Text => Some(NSCursor::IBeamCursor()),
        SystemCursor::Pointer => Some(NSCursor::pointingHandCursor()),
        SystemCursor::Crosshair => Some(NSCursor::crosshairCursor()),
        SystemCursor::NotAllowed => Some(NSCursor::operationNotAllowedCursor()),
        #[allow(deprecated)]
        SystemCursor::ResizeNorthSouth => frame(Position::Top).or_else(|| Some(NSCursor::resizeUpDownCursor())),
        #[allow(deprecated)]
        SystemCursor::ResizeEastWest => frame(Position::Left).or_else(|| Some(NSCursor::resizeLeftRightCursor())),
        SystemCursor::ResizeNorthWestSouthEast => frame(Position::TopLeft),
        SystemCursor::ResizeNorthEastSouthWest => frame(Position::TopRight),
        SystemCursor::Wait | SystemCursor::Progress | SystemCursor::Help | SystemCursor::Move => None,
    }
}