lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
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
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
//! Text input on iOS: the view the keyboard types into, which is the focused text input as UIKit sees it.
//!
//! winit shows the keyboard through a view of its own that is told keys one at a time and tells nothing back,
//! so the keyboard knew nothing of the text: no autocorrection, no dictation, no composition, a delete key
//! that never speeds up, a password's keyboard recorded with the screen. [`TextInput`] is a view of the
//! shell's own that takes the keyboard instead and speaks `UITextInput`, the protocol of a text editor: UIKit
//! asks it what the text is, where the selection and the caret are, and tells it to replace a range, move the
//! selection or mark text that is being composed.
//!
//! UIKit asks in the middle of anything, while the shell may be using the tree, so the view does not reach
//! the tree. It answers from a copy of the input ([`Mirror`]) and applies UIKit's edits to that copy at once,
//! so that the next question finds them made; the edits are also queued, and the shell makes them in the tree
//! on its next turn ([`TextInput::sync`]). Then it compares: when the tree's input is not what the copy says
//! (a handler refused the edit, the app set the value, a mouse moved the caret, another input took the focus),
//! the copy takes the tree's and UIKit is told the text or the selection changed, which makes it drop what it
//! had worked out about the old one.
//!
//! UIKit counts text in UTF-16 units; the tree counts bytes of UTF-8. The copy keeps the text as a `String`
//! and every position UIKit is given or gives back is converted.
//!
//! Where characters are on the screen is in the copy too: every place a caret can be, as the tree last painted
//! the input. From it UIKit is told where a position is, which rectangles a range covers and which position is
//! nearest a point.
//!
//! With that, UIKit's text interaction is put on the view: the platform's own caret, selection with handles to
//! drag, the loupe, and the menu to copy, cut, paste and select all. The view lies over the focused input, so
//! that their touches land on it, and the tree paints no caret of its own
//! (`Tree::set_native_text_selection`). The selection's highlight stays the tree's, under the text, and the
//! platform's is not shown. A touch the interaction does not take goes on up to winit's view, as
//! any view passes on what it does not handle: scrolling from an input still scrolls.

use std::{
  ffi::c_void,
  ptr::NonNull,
  sync::{
    Mutex,
    atomic::{AtomicBool, AtomicPtr, Ordering},
  },
  time::{Duration, Instant},
};

use objc2::{
  class,
  encode::{Encode, Encoding},
  msg_send,
  rc::Retained,
  runtime::{AnyClass, AnyObject, AnyProtocol, Bool, ClassBuilder, Sel},
  sel,
};

use super::ios::{CGPoint, CGRect, CGSize};
use crate::{
  app::{
    Tree,
    events::ImeEvent,
    runtime::{AutofillPeer, KeyboardTraits, TextInputSnapshot},
  },
  node::{
    node_kind::{ContentKind, KeyboardKind, ReturnKey},
    text_selection::previous_delete_boundary,
  },
};

#[repr(C)]
#[derive(Clone, Copy)]
struct NSRange {
  location: usize,
  length: usize,
}

unsafe impl Encode for NSRange {
  const ENCODING: Encoding = Encoding::Struct("_NSRange", &[usize::ENCODING, usize::ENCODING]);
}

/// What UIKit did to the text, for the shell to do in the tree. Offsets are bytes of the copy's text as it was
/// when the edit was made.
enum Edit {
  /// Typed text, whole: a letter, a word of dictation, an emoji with all its parts, a line break for Return.
  Insert(String),
  DeleteBackward,
  /// A range replaced: an autocorrection, a suggestion taken, a paste.
  Replace {
    start: usize,
    end: usize,
    text: String,
  },
  Select {
    start: usize,
    end: usize,
  },
  /// Text being composed, and the selection inside it.
  Mark {
    text: String,
    selection: Option<(usize, usize)>,
  },
  /// The composition is confirmed as this text.
  Unmark(String),
  /// Undo or redo, of three fingers or of the system's bar of editing commands.
  Command(crate::app::events::EditCommand),
}

/// The focused text input as UIKit was last told it is.
#[derive(Default)]
struct Mirror {
  text: String,
  /// The selection, the start first, in bytes.
  selection: (usize, usize),
  /// The text being composed, in bytes.
  marked: Option<(usize, usize)>,
  /// Where the input and its characters are; `None` before its first frame.
  geometry: Option<Geometry>,
  traits: Option<KeyboardTraits>,
  edits: Vec<Edit>,
  /// When more than one character came at once into an input that hides what is typed: a saved password.
  filled_at: Option<Instant>,
  /// UIKit drew the caret where the view did not take it, or may have, as a saved password came: it is to be
  /// told where the caret is.
  caret_astray: bool,
  /// Whether the input has an edit to take back, and one to make again: what the system's undo asks.
  can_undo: bool,
  can_redo: bool,
}

/// How long after a saved password came UIKit's own moves of the caret are taken to be part of the filling.
const FILL_SETTLES: Duration = Duration::from_millis(700);

/// Whether a text input is typed into. winit's view takes no keyboard then: see [`quiet_window_view`].
static TYPES: AtomicBool = AtomicBool::new(false);

/// Where the focused input is on the screen, in points in the window.
#[derive(Clone, PartialEq)]
struct Geometry {
  /// The input's box, which is the view's frame: x, y, width, height.
  bounds: (f64, f64, f64, f64),
  /// Every place a caret can be: its byte in the text and its top-left corner.
  carets: Vec<(usize, f64, f64)>,
  line_height: f64,
}

/// How wide the caret is, in points.
const CARET_WIDTH: f64 = 2.0;

impl Geometry {
  /// Where a caret at the byte is: there, or at the last place before it.
  fn place(&self, byte: usize) -> (f64, f64) {
    self
      .carets
      .iter()
      .rev()
      .find(|(index, ..)| *index <= byte)
      .or(self.carets.first())
      .map_or((self.bounds.0, self.bounds.1), |(_, x, y)| (*x, *y))
  }

  /// A rectangle in the window as the view sees it: its frame is the input's box.
  fn in_view(&self, x: f64, y: f64, width: f64) -> CGRect {
    CGRect {
      origin: CGPoint {
        x: x - self.bounds.0,
        y: y - self.bounds.1,
      },
      size: CGSize {
        width,
        height: self.line_height,
      },
    }
  }

  /// The rectangles a range of bytes covers, one for each line it is on.
  fn rows(&self, start: usize, end: usize) -> Vec<(f64, f64, f64)> {
    let mut rows: Vec<(f64, f64, f64)> = Vec::new();
    for (_, x, y) in self.carets.iter().filter(|(index, ..)| (start..=end).contains(index)) {
      match rows.iter_mut().find(|(_, row, _)| (*row - *y).abs() < 0.5) {
        Some((left, _, right)) => {
          *left = left.min(*x);
          *right = right.max(*x);
        }
        None => rows.push((*x, *y, *x)),
      }
    }
    rows
  }

  /// The byte whose caret is nearest a point of the view: on the line the point is level with, the nearest
  /// across.
  fn nearest(&self, point: CGPoint) -> usize {
    let (x, y) = (point.x + self.bounds.0, point.y + self.bounds.1);
    let level = |row: f64| (row + self.line_height / 2.0 - y).abs();
    let Some(row) = self
      .carets
      .iter()
      .map(|(_, _, row)| *row)
      .min_by(|a, b| level(*a).total_cmp(&level(*b)))
    else {
      return 0;
    };
    self
      .carets
      .iter()
      .filter(|(_, _, caret)| (*caret - row).abs() < 0.5)
      .min_by(|a, b| (a.1 - x).abs().total_cmp(&(b.1 - x).abs()))
      .map_or(0, |(index, ..)| *index)
  }
}

static MIRROR: Mutex<Option<Mirror>> = Mutex::new(None);
/// The window's view, which the text input's view is in and outlives it. Asking it to draw wakes the shell.
static WINDOW_VIEW: AtomicPtr<AnyObject> = AtomicPtr::new(std::ptr::null_mut());
/// The rectangles UIKit last showed the selection as, in the window, as the tree was told them.
static HIGHLIGHT: Mutex<Vec<(f64, f64, f64, f64)>> = Mutex::new(Vec::new());

/// The view that types now. One that typed before it may still be told and asked by UIKit as it goes: what
/// UIKit keeps for a view is kept for this one alone.
static TYPING_VIEW: AtomicPtr<AnyObject> = AtomicPtr::new(std::ptr::null_mut());
/// UIKit's delegate, which is told of changes it did not make. UIKit owns it and clears it.
static INPUT_DELEGATE: AtomicPtr<AnyObject> = AtomicPtr::new(std::ptr::null_mut());
/// The tokenizer UIKit asks for word and line boundaries, made once for the view that types.
static TOKENIZER: AtomicPtr<AnyObject> = AtomicPtr::new(std::ptr::null_mut());

fn types_now(view: &AnyObject) -> bool {
  std::ptr::eq(TYPING_VIEW.load(Ordering::Acquire), view)
}

fn with_mirror<T>(default: T, read: impl FnOnce(&mut Mirror) -> T) -> T {
  MIRROR.lock().unwrap().as_mut().map_or(default, read)
}

impl Mirror {
  fn utf16_len(&self) -> isize {
    self.text.encode_utf16().count() as isize
  }

  /// The byte offset of a UTF-16 offset, which is brought into the text and onto a character.
  fn byte_of(&self, utf16: isize) -> usize {
    let mut units = 0isize;
    for (byte, character) in self.text.char_indices() {
      if units >= utf16 {
        return byte;
      }
      units += character.len_utf16() as isize;
    }
    self.text.len()
  }

  fn utf16_of(&self, byte: usize) -> isize {
    let byte = byte.min(self.text.len());
    self.text[..floor_char_boundary(&self.text, byte)]
      .encode_utf16()
      .count() as isize
  }

  /// Replaces bytes with text and puts the caret after it. Nothing is being composed afterwards.
  fn replace(&mut self, start: usize, end: usize, text: &str) {
    let start = floor_char_boundary(&self.text, start.min(self.text.len()));
    let end = floor_char_boundary(&self.text, end.clamp(start, self.text.len()));
    self.text.replace_range(start..end, text);
    self.selection = (start + text.len(), start + text.len());
    self.marked = None;
  }
}

fn floor_char_boundary(text: &str, mut index: usize) -> usize {
  index = index.min(text.len());
  while index > 0 && !text.is_char_boundary(index) {
    index -= 1;
  }
  index
}

fn string_of(text: *mut AnyObject) -> Option<String> {
  let text = unsafe { text.as_ref() }?;
  let utf8: *const std::ffi::c_char = unsafe { msg_send![text, UTF8String] };
  if utf8.is_null() {
    return None;
  }
  Some(unsafe { std::ffi::CStr::from_ptr(utf8) }.to_string_lossy().into_owned())
}

/// An autoreleased `NSString`.
fn ns_string(text: &str) -> *mut AnyObject {
  let units: Vec<u16> = text.encode_utf16().collect();
  let string: Retained<AnyObject> =
    unsafe { msg_send![class!(NSString), stringWithCharacters: units.as_ptr(), length: units.len()] };
  Retained::autorelease_ptr(string)
}

// Positions and ranges: UIKit's are opaque objects that the editor makes. These hold UTF-16 offsets.

fn position_class() -> &'static AnyClass {
  if let Some(class) = AnyClass::get(c"LurqTextPosition") {
    return class;
  }
  let mut builder = ClassBuilder::new(c"LurqTextPosition", class!(UITextPosition)).expect("a class name of its own");
  builder.add_ivar::<isize>(c"lurqOffset");
  builder.register()
}

fn range_class() -> &'static AnyClass {
  if let Some(class) = AnyClass::get(c"LurqTextRange") {
    return class;
  }
  extern "C-unwind" fn start(this: &AnyObject, _cmd: Sel) -> *mut AnyObject {
    position(range_ends(this).0)
  }
  extern "C-unwind" fn end(this: &AnyObject, _cmd: Sel) -> *mut AnyObject {
    position(range_ends(this).1)
  }
  extern "C-unwind" fn is_empty(this: &AnyObject, _cmd: Sel) -> Bool {
    let (start, end) = range_ends(this);
    Bool::new(start == end)
  }
  let mut builder = ClassBuilder::new(c"LurqTextRange", class!(UITextRange)).expect("a class name of its own");
  builder.add_ivar::<isize>(c"lurqStart");
  builder.add_ivar::<isize>(c"lurqEnd");
  unsafe {
    builder.add_method(sel!(start), start as extern "C-unwind" fn(_, _) -> _);
    builder.add_method(sel!(end), end as extern "C-unwind" fn(_, _) -> _);
    builder.add_method(sel!(isEmpty), is_empty as extern "C-unwind" fn(_, _) -> _);
  }
  builder.register()
}

fn set_ivar(object: &AnyObject, class: &AnyClass, name: &std::ffi::CStr, value: isize) {
  let ivar = class.instance_variable(name).expect("an ivar the class was made with");
  unsafe { *ivar.load_ptr::<isize>(object) = value };
}

fn ivar(object: &AnyObject, class: &AnyClass, name: &std::ffi::CStr) -> isize {
  let ivar = class.instance_variable(name).expect("an ivar the class was made with");
  unsafe { *ivar.load::<isize>(object) }
}

/// An autoreleased position at a UTF-16 offset.
fn position(offset: isize) -> *mut AnyObject {
  let class = position_class();
  let position: Retained<AnyObject> = unsafe { msg_send![class, new] };
  set_ivar(&position, class, c"lurqOffset", offset);
  Retained::autorelease_ptr(position)
}

/// An autoreleased range between UTF-16 offsets, the smaller first.
fn range(start: isize, end: isize) -> *mut AnyObject {
  let class = range_class();
  let range: Retained<AnyObject> = unsafe { msg_send![class, new] };
  set_ivar(&range, class, c"lurqStart", start.min(end));
  set_ivar(&range, class, c"lurqEnd", start.max(end));
  Retained::autorelease_ptr(range)
}

/// The offset of a position UIKit gives back, when it is one of ours.
fn offset_of(position: *mut AnyObject) -> Option<isize> {
  let position = unsafe { position.as_ref() }?;
  let class = position_class();
  let ours: bool = unsafe { msg_send![position, isKindOfClass: class] };
  ours.then(|| ivar(position, class, c"lurqOffset"))
}

fn range_ends(range: &AnyObject) -> (isize, isize) {
  let class = range_class();
  (ivar(range, class, c"lurqStart"), ivar(range, class, c"lurqEnd"))
}

fn ends_of(range: *mut AnyObject) -> Option<(isize, isize)> {
  let range = unsafe { range.as_ref() }?;
  let ours: bool = unsafe { msg_send![range, isKindOfClass: range_class()] };
  ours.then(|| range_ends(range))
}

// What UIKit asks and tells: `UIKeyInput` and `UITextInput`.

extern "C-unwind" fn can_become_first_responder(_this: &AnyObject, _cmd: Sel) -> Bool {
  Bool::YES
}

extern "C-unwind" fn has_text(_this: &AnyObject, _cmd: Sel) -> Bool {
  Bool::new(with_mirror(false, |mirror| !mirror.text.is_empty()))
}

extern "C-unwind" fn insert_text(_this: &AnyObject, _cmd: Sel, text: *mut AnyObject) {
  let Some(text) = string_of(text) else {
    return;
  };
  with_mirror((), |mirror| {
    // Over what is being composed, or over the selection. A line break is the Return key: what it does is
    // the input's to say, and the copy is put right when the tree has done it.
    let (start, end) = mirror.marked.unwrap_or(mirror.selection);
    if !text.contains('\n') {
      mirror.replace(start, end, &text);
    }
    if mirror.traits.is_some_and(|traits| traits.secure) && text.chars().nth(1).is_some() {
      mirror.filled_at = Some(Instant::now());
      mirror.caret_astray = true;
    }
    mirror.edits.push(Edit::Insert(text));
  });
}

extern "C-unwind" fn delete_backward(_this: &AnyObject, _cmd: Sel) {
  with_mirror((), |mirror| {
    let (start, end) = mirror.selection;
    if start != end {
      mirror.replace(start, end, "");
    } else if start > 0 {
      let from = previous_delete_boundary(&mirror.text, start);
      mirror.replace(from, start, "");
    }
    mirror.edits.push(Edit::DeleteBackward);
  });
}

extern "C-unwind" fn text_in_range(_this: &AnyObject, _cmd: Sel, range: *mut AnyObject) -> *mut AnyObject {
  let Some((start, end)) = ends_of(range) else {
    return std::ptr::null_mut();
  };
  let text = with_mirror(String::new(), |mirror| {
    mirror.text[mirror.byte_of(start)..mirror.byte_of(end)].to_owned()
  });
  ns_string(&text)
}

extern "C-unwind" fn replace_range(_this: &AnyObject, _cmd: Sel, range: *mut AnyObject, text: *mut AnyObject) {
  let (Some((start, end)), Some(text)) = (ends_of(range), string_of(text)) else {
    return;
  };
  with_mirror((), |mirror| {
    let (start, end) = (mirror.byte_of(start), mirror.byte_of(end));
    mirror.replace(start, end, &text);
    mirror.edits.push(Edit::Replace { start, end, text });
  });
}

extern "C-unwind" fn selected_text_range(_this: &AnyObject, _cmd: Sel) -> *mut AnyObject {
  match with_mirror(None, |mirror| {
    Some((mirror.utf16_of(mirror.selection.0), mirror.utf16_of(mirror.selection.1)))
  }) {
    Some((start, end)) => range(start, end),
    None => std::ptr::null_mut(),
  }
}

extern "C-unwind" fn set_selected_text_range(_this: &AnyObject, _cmd: Sel, selected: *mut AnyObject) {
  let Some((start, end)) = ends_of(selected) else {
    return;
  };
  let refused = with_mirror(false, |mirror| {
    let selection = (mirror.byte_of(start), mirror.byte_of(end));
    // After it fills a saved password in, UIKit puts the caret at the start and at the end by turns, and
    // leaves it at the start (seen on an iPhone 17: start, end, start, end, start). A text field of its own
    // ends with the caret after the password: the moves to the start that come with the filling are not
    // taken, and UIKit, which draws the caret where it put it, is told on the shell's next turn where it is.
    let filling = mirror.filled_at.is_some_and(|at| at.elapsed() < FILL_SETTLES);
    if filling && selection == (0, 0) && !mirror.text.is_empty() {
      mirror.caret_astray = true;
      return true;
    }
    if selection != mirror.selection {
      mirror.selection = selection;
      mirror.edits.push(Edit::Select {
        start: selection.0,
        end: selection.1,
      });
    }
    false
  });
  if refused {
    wake_shell();
  }
}

/// Has the shell take a turn, which nothing else may bring: asking the window's view to draw wakes it.
fn wake_shell() {
  let window_view = WINDOW_VIEW.load(Ordering::Acquire);
  if let Some(window_view) = unsafe { window_view.as_ref() } {
    let _: () = unsafe { msg_send![window_view, setNeedsDisplay] };
  }
}

extern "C-unwind" fn marked_text_range(_this: &AnyObject, _cmd: Sel) -> *mut AnyObject {
  match with_mirror(None, |mirror| {
    mirror
      .marked
      .map(|(start, end)| (mirror.utf16_of(start), mirror.utf16_of(end)))
  }) {
    Some((start, end)) => range(start, end),
    None => std::ptr::null_mut(),
  }
}

extern "C-unwind" fn marked_text_style(_this: &AnyObject, _cmd: Sel) -> *mut AnyObject {
  std::ptr::null_mut()
}

extern "C-unwind" fn set_marked_text_style(_this: &AnyObject, _cmd: Sel, _style: *mut AnyObject) {}

extern "C-unwind" fn set_marked_text(_this: &AnyObject, _cmd: Sel, text: *mut AnyObject, selected: NSRange) {
  let text = string_of(text).unwrap_or_default();
  with_mirror((), |mirror| {
    let (start, end) = mirror.marked.unwrap_or(mirror.selection);
    mirror.replace(start, end, &text);
    // The selection UIKit gives is inside the marked text, in UTF-16 units.
    let inside = |utf16: usize| {
      let mut units = 0;
      for (byte, character) in text.char_indices() {
        if units >= utf16 {
          return byte;
        }
        units += character.len_utf16();
      }
      text.len()
    };
    let selection = (inside(selected.location), inside(selected.location + selected.length));
    if text.is_empty() {
      mirror.marked = None;
      mirror.selection = (start, start);
    } else {
      mirror.marked = Some((start, start + text.len()));
      mirror.selection = (start + selection.0, start + selection.1);
    }
    mirror.edits.push(Edit::Mark {
      selection: (!text.is_empty()).then_some(selection),
      text,
    });
  });
}

extern "C-unwind" fn unmark_text(_this: &AnyObject, _cmd: Sel) {
  with_mirror((), |mirror| {
    if let Some((start, end)) = mirror.marked.take() {
      let text = mirror.text[start..end].to_owned();
      mirror.edits.push(Edit::Unmark(text));
    }
  });
}

extern "C-unwind" fn beginning_of_document(_this: &AnyObject, _cmd: Sel) -> *mut AnyObject {
  position(0)
}

extern "C-unwind" fn end_of_document(_this: &AnyObject, _cmd: Sel) -> *mut AnyObject {
  position(with_mirror(0, |mirror| mirror.utf16_len()))
}

extern "C-unwind" fn text_range_from_position(
  _this: &AnyObject,
  _cmd: Sel,
  from: *mut AnyObject,
  to: *mut AnyObject,
) -> *mut AnyObject {
  match (offset_of(from), offset_of(to)) {
    (Some(from), Some(to)) => range(from, to),
    _ => std::ptr::null_mut(),
  }
}

extern "C-unwind" fn position_from_position(
  _this: &AnyObject,
  _cmd: Sel,
  from: *mut AnyObject,
  offset: isize,
) -> *mut AnyObject {
  let Some(from) = offset_of(from) else {
    return std::ptr::null_mut();
  };
  let length = with_mirror(0, |mirror| mirror.utf16_len());
  let to = from + offset;
  // No position before the start or beyond the end.
  if to < 0 || to > length {
    return std::ptr::null_mut();
  }
  position(to)
}

/// `UITextLayoutDirection`: right 2, left 3, up 4, down 5. Up and down go by lines as they are painted; the
/// text is read left to right.
extern "C-unwind" fn position_in_direction(
  this: &AnyObject,
  cmd: Sel,
  from: *mut AnyObject,
  direction: isize,
  offset: isize,
) -> *mut AnyObject {
  if matches!(direction, 4 | 5) {
    let Some(from) = offset_of(from) else {
      return std::ptr::null_mut();
    };
    let lines = if direction == 4 { -offset } else { offset };
    let to = with_mirror(None, |mirror| {
      let geometry = mirror.geometry.as_ref()?;
      let (x, y) = geometry.place(mirror.byte_of(from));
      let point = CGPoint {
        x: x - geometry.bounds.0,
        y: y - geometry.bounds.1 + geometry.line_height * (lines as f64 + 0.5),
      };
      Some(mirror.utf16_of(geometry.nearest(point)))
    });
    return match to {
      Some(to) => position(to),
      None => std::ptr::null_mut(),
    };
  }
  let offset = if direction == 2 { offset } else { -offset };
  position_from_position(this, cmd, from, offset)
}

/// `NSComparisonResult`.
extern "C-unwind" fn compare_position(
  _this: &AnyObject,
  _cmd: Sel,
  one: *mut AnyObject,
  other: *mut AnyObject,
) -> isize {
  match (offset_of(one), offset_of(other)) {
    (Some(one), Some(other)) => (one - other).signum(),
    _ => 0,
  }
}

extern "C-unwind" fn offset_from_position(
  _this: &AnyObject,
  _cmd: Sel,
  from: *mut AnyObject,
  to: *mut AnyObject,
) -> isize {
  match (offset_of(from), offset_of(to)) {
    (Some(from), Some(to)) => to - from,
    _ => 0,
  }
}

extern "C-unwind" fn input_delegate(this: &AnyObject, _cmd: Sel) -> *mut AnyObject {
  if types_now(this) {
    INPUT_DELEGATE.load(Ordering::Acquire)
  } else {
    std::ptr::null_mut()
  }
}

extern "C-unwind" fn set_input_delegate(this: &AnyObject, _cmd: Sel, delegate: *mut AnyObject) {
  // A view that typed before is told it has no delegate after the one that types now was given its own.
  if types_now(this) {
    INPUT_DELEGATE.store(delegate, Ordering::Release);
  }
}

extern "C-unwind" fn tokenizer(this: &AnyObject, _cmd: Sel) -> *mut AnyObject {
  // UIKit's own, which reads words and lines out of the text through the view it is made for.
  let make = || -> Retained<AnyObject> {
    unsafe {
      let tokenizer: objc2::rc::Allocated<AnyObject> = msg_send![class!(UITextInputStringTokenizer), alloc];
      msg_send![tokenizer, initWithTextInput: this]
    }
  };
  if !types_now(this) {
    return Retained::autorelease_ptr(make());
  }
  let tokenizer = TOKENIZER.load(Ordering::Acquire);
  if !tokenizer.is_null() {
    return tokenizer;
  }
  let tokenizer = Retained::into_raw(make());
  TOKENIZER.store(tokenizer, Ordering::Release);
  tokenizer
}

extern "C-unwind" fn position_within_range(
  _this: &AnyObject,
  _cmd: Sel,
  within: *mut AnyObject,
  direction: isize,
) -> *mut AnyObject {
  match ends_of(within) {
    Some((_, end)) if matches!(direction, 2 | 5) => position(end),
    Some((start, _)) => position(start),
    None => std::ptr::null_mut(),
  }
}

extern "C-unwind" fn character_range_by_extending(
  _this: &AnyObject,
  _cmd: Sel,
  from: *mut AnyObject,
  direction: isize,
) -> *mut AnyObject {
  let Some(from) = offset_of(from) else {
    return std::ptr::null_mut();
  };
  if matches!(direction, 2 | 5) {
    range(from, with_mirror(from, |mirror| mirror.utf16_len()))
  } else {
    range(0, from)
  }
}

/// `NSWritingDirection`: left to right.
extern "C-unwind" fn base_writing_direction(
  _this: &AnyObject,
  _cmd: Sel,
  _position: *mut AnyObject,
  _direction: isize,
) -> isize {
  0
}

extern "C-unwind" fn set_base_writing_direction(
  _this: &AnyObject,
  _cmd: Sel,
  _direction: isize,
  _range: *mut AnyObject,
) {
}

fn no_rect() -> CGRect {
  CGRect {
    origin: CGPoint { x: 0.0, y: 0.0 },
    size: CGSize {
      width: 0.0,
      height: 0.0,
    },
  }
}

/// The first line of the range: where UIKit puts what belongs to the range, such as the menu.
extern "C-unwind" fn first_rect_for_range(_this: &AnyObject, _cmd: Sel, range: *mut AnyObject) -> CGRect {
  let Some((start, end)) = ends_of(range) else {
    return no_rect();
  };
  with_mirror(None, |mirror| {
    let geometry = mirror.geometry.as_ref()?;
    let (left, row, right) = *geometry.rows(mirror.byte_of(start), mirror.byte_of(end)).first()?;
    Some(geometry.in_view(left, row, (right - left).max(CARET_WIDTH)))
  })
  .unwrap_or_else(no_rect)
}

/// The view the rectangles above are measured in, and the one the system puts its caret and selection into.
extern "C-unwind" fn text_input_view(this: &AnyObject, _cmd: Sel) -> *const AnyObject {
  this
}

extern "C-unwind" fn caret_rect_for_position(_this: &AnyObject, _cmd: Sel, position: *mut AnyObject) -> CGRect {
  let Some(offset) = offset_of(position) else {
    return no_rect();
  };
  with_mirror(None, |mirror| {
    let geometry = mirror.geometry.as_ref()?;
    let (x, y) = geometry.place(mirror.byte_of(offset));
    Some(geometry.in_view(x, y, CARET_WIDTH))
  })
  .unwrap_or_else(no_rect)
}

/// A `UITextSelectionRect`: one line of a selection, and whether the selection starts and ends on it.
fn selection_rect_class() -> &'static AnyClass {
  if let Some(class) = AnyClass::get(c"LurqTextSelectionRect") {
    return class;
  }
  fn part(this: &AnyObject, name: &std::ffi::CStr) -> f64 {
    let ivar = selection_rect_class()
      .instance_variable(name)
      .expect("an ivar the class was made with");
    unsafe { *ivar.load::<f64>(this) }
  }
  extern "C-unwind" fn rect(this: &AnyObject, _cmd: Sel) -> CGRect {
    CGRect {
      origin: CGPoint {
        x: part(this, c"lurqX"),
        y: part(this, c"lurqY"),
      },
      size: CGSize {
        width: part(this, c"lurqWidth"),
        height: part(this, c"lurqHeight"),
      },
    }
  }
  /// `NSWritingDirection`: left to right.
  extern "C-unwind" fn writing_direction(_this: &AnyObject, _cmd: Sel) -> isize {
    0
  }
  extern "C-unwind" fn contains_start(this: &AnyObject, _cmd: Sel) -> Bool {
    Bool::new(part(this, c"lurqStart") != 0.0)
  }
  extern "C-unwind" fn contains_end(this: &AnyObject, _cmd: Sel) -> Bool {
    Bool::new(part(this, c"lurqEnd") != 0.0)
  }
  extern "C-unwind" fn is_vertical(_this: &AnyObject, _cmd: Sel) -> Bool {
    Bool::NO
  }
  let mut builder =
    ClassBuilder::new(c"LurqTextSelectionRect", class!(UITextSelectionRect)).expect("a class name of its own");
  for name in [
    c"lurqX",
    c"lurqY",
    c"lurqWidth",
    c"lurqHeight",
    c"lurqStart",
    c"lurqEnd",
  ] {
    builder.add_ivar::<f64>(name);
  }
  unsafe {
    builder.add_method(sel!(rect), rect as extern "C-unwind" fn(_, _) -> _);
    builder.add_method(
      sel!(writingDirection),
      writing_direction as extern "C-unwind" fn(_, _) -> _,
    );
    builder.add_method(sel!(containsStart), contains_start as extern "C-unwind" fn(_, _) -> _);
    builder.add_method(sel!(containsEnd), contains_end as extern "C-unwind" fn(_, _) -> _);
    builder.add_method(sel!(isVertical), is_vertical as extern "C-unwind" fn(_, _) -> _);
  }
  builder.register()
}

extern "C-unwind" fn selection_rects_for_range(_this: &AnyObject, _cmd: Sel, range: *mut AnyObject) -> *mut AnyObject {
  // UIKit is about to show a selection, a handle's as it is dragged too: the shell reads where on its next
  // turn, which nothing else may bring, a handle's touches being UIKit's.
  wake_shell();
  let rects: Retained<AnyObject> = unsafe { msg_send![class!(NSMutableArray), array] };
  let rows = ends_of(range).and_then(|(start, end)| {
    with_mirror(None, |mirror| {
      let geometry = mirror.geometry.as_ref()?;
      let rows = geometry.rows(mirror.byte_of(start), mirror.byte_of(end));
      Some(
        rows
          .into_iter()
          .map(|(left, row, right)| geometry.in_view(left, row, right - left))
          .collect::<Vec<_>>(),
      )
    })
  });
  let rows = rows.unwrap_or_default();
  let class = selection_rect_class();
  for (index, row) in rows.iter().enumerate() {
    let rect: Retained<AnyObject> = unsafe { msg_send![class, new] };
    let parts = [
      (c"lurqX", row.origin.x),
      (c"lurqY", row.origin.y),
      (c"lurqWidth", row.size.width),
      (c"lurqHeight", row.size.height),
      (c"lurqStart", f64::from(u8::from(index == 0))),
      (c"lurqEnd", f64::from(u8::from(index + 1 == rows.len()))),
    ];
    for (name, value) in parts {
      let ivar = class.instance_variable(name).expect("an ivar the class was made with");
      unsafe { *ivar.load_ptr::<f64>(&rect) = value };
    }
    let _: () = unsafe { msg_send![&*rects, addObject: &*rect] };
  }
  Retained::autorelease_ptr(rects)
}

/// The position nearest a point of the view, in UTF-16 units; the caret's when the input is not painted yet.
fn nearest_to(point: CGPoint) -> isize {
  with_mirror(0, |mirror| match &mirror.geometry {
    Some(geometry) => mirror.utf16_of(geometry.nearest(point)),
    None => mirror.utf16_of(mirror.selection.1),
  })
}

extern "C-unwind" fn closest_position_to_point(_this: &AnyObject, _cmd: Sel, point: CGPoint) -> *mut AnyObject {
  position(nearest_to(point))
}

extern "C-unwind" fn closest_position_within_range(
  _this: &AnyObject,
  _cmd: Sel,
  point: CGPoint,
  within: *mut AnyObject,
) -> *mut AnyObject {
  let nearest = nearest_to(point);
  match ends_of(within) {
    Some((start, end)) => position(nearest.clamp(start, end)),
    None => position(nearest),
  }
}

extern "C-unwind" fn character_range_at_point(_this: &AnyObject, _cmd: Sel, point: CGPoint) -> *mut AnyObject {
  let nearest = nearest_to(point);
  let length = with_mirror(0, |mirror| mirror.utf16_len());
  if nearest >= length {
    return std::ptr::null_mut();
  }
  range(nearest, nearest + 1)
}

// The menu over a selection: UIKit asks what can be done and tells the view to do it.

/// Tells UIKit the selection changed under it: the menu's actions change the copy from inside UIKit's call.
fn selection_changed_by(this: &AnyObject, change: impl FnOnce()) {
  let delegate = INPUT_DELEGATE.load(Ordering::Acquire);
  if let Some(delegate) = unsafe { delegate.as_ref() } {
    let _: () = unsafe { msg_send![delegate, selectionWillChange: this] };
  }
  change();
  if let Some(delegate) = unsafe { delegate.as_ref() } {
    let _: () = unsafe { msg_send![delegate, selectionDidChange: this] };
  }
}

fn selected_text() -> Option<String> {
  with_mirror(None, |mirror| {
    let (start, end) = mirror.selection;
    // A password is not copied out of its input.
    let secure = mirror.traits.is_some_and(|traits| traits.secure);
    (start != end && !secure).then(|| mirror.text[start..end].to_owned())
  })
}

fn pasteboard() -> Retained<AnyObject> {
  unsafe { msg_send![class!(UIPasteboard), generalPasteboard] }
}

extern "C-unwind" fn copy(_this: &AnyObject, _cmd: Sel, _sender: *mut AnyObject) {
  if let Some(text) = selected_text() {
    let _: () = unsafe { msg_send![&*pasteboard(), setString: ns_string(&text)] };
  }
}

extern "C-unwind" fn cut(this: &AnyObject, cmd: Sel, sender: *mut AnyObject) {
  if selected_text().is_none() {
    return;
  }
  copy(this, cmd, sender);
  delete_backward(this, cmd);
}

extern "C-unwind" fn paste(this: &AnyObject, cmd: Sel, _sender: *mut AnyObject) {
  let text: Option<Retained<AnyObject>> = unsafe { msg_send![&*pasteboard(), string] };
  if let Some(text) = text {
    insert_text(this, cmd, Retained::as_ptr(&text).cast_mut());
  }
}

extern "C-unwind" fn select_all(this: &AnyObject, _cmd: Sel, _sender: *mut AnyObject) {
  selection_changed_by(this, || {
    with_mirror((), |mirror| {
      mirror.selection = (0, mirror.text.len());
      mirror.edits.push(Edit::Select {
        start: 0,
        end: mirror.text.len(),
      });
    });
  });
}

extern "C-unwind" fn can_perform_action(_this: &AnyObject, _cmd: Sel, action: Sel, _sender: *mut AnyObject) -> Bool {
  let selected = selected_text().is_some();
  let allowed = if action == sel!(copy:) || action == sel!(cut:) {
    selected
  } else if action == sel!(paste:) {
    unsafe { msg_send![&*pasteboard(), hasStrings] }
  } else if action == sel!(selectAll:) {
    with_mirror(false, |mirror| {
      !mirror.text.is_empty() && mirror.selection != (0, mirror.text.len())
    })
  } else {
    false
  };
  Bool::new(allowed)
}

// Undo. UIKit's undo in a field (three fingers swiped, the bar of editing commands three fingers tap open, Cmd+Z
// of an attached keyboard, a shake) asks the field's `undoManager` whether it can and tells it to. The input's
// history is the tree's: the view's manager answers from what the tree last said of it, and has the tree take an
// edit back or make it again on the shell's next turn.

/// The view's undo manager, made once.
static UNDO_MANAGER: AtomicPtr<AnyObject> = AtomicPtr::new(std::ptr::null_mut());

extern "C-unwind" fn undo_manager(_this: &AnyObject, _cmd: Sel) -> *mut AnyObject {
  let manager = UNDO_MANAGER.load(Ordering::Acquire);
  if !manager.is_null() {
    return manager;
  }
  let manager: Retained<AnyObject> = unsafe { msg_send![undo_manager_class(), new] };
  let manager = Retained::into_raw(manager);
  UNDO_MANAGER.store(manager, Ordering::Release);
  manager
}

extern "C-unwind" fn can_undo(_this: &AnyObject, _cmd: Sel) -> Bool {
  Bool::new(with_mirror(false, |mirror| mirror.can_undo))
}

extern "C-unwind" fn can_redo(_this: &AnyObject, _cmd: Sel) -> Bool {
  Bool::new(with_mirror(false, |mirror| mirror.can_redo))
}

/// Has the tree run `command` on the input, and takes what it will be able to do then as UIKit's next questions
/// find it: an edit taken back is one to make again.
fn queue_history(command: crate::app::events::EditCommand) {
  use crate::app::events::EditCommand;
  let queued = with_mirror(false, |mirror| {
    let able = match command {
      EditCommand::Undo => &mut mirror.can_undo,
      _ => &mut mirror.can_redo,
    };
    if !*able {
      return false;
    }
    match command {
      EditCommand::Undo => mirror.can_redo = true,
      _ => mirror.can_undo = true,
    }
    mirror.edits.push(Edit::Command(command));
    true
  });
  if queued {
    wake_shell();
  }
}

extern "C-unwind" fn undo(_this: &AnyObject, _cmd: Sel) {
  queue_history(crate::app::events::EditCommand::Undo);
}

extern "C-unwind" fn redo(_this: &AnyObject, _cmd: Sel) {
  queue_history(crate::app::events::EditCommand::Redo);
}

/// An `NSUndoManager` whose history is the tree's input's.
fn undo_manager_class() -> &'static AnyClass {
  if let Some(class) = AnyClass::get(c"LurqTextUndoManager") {
    return class;
  }
  let mut builder = ClassBuilder::new(c"LurqTextUndoManager", class!(NSUndoManager)).expect("a class name of its own");
  // SAFETY: the methods have NSUndoManager's selectors' types.
  unsafe {
    builder.add_method(sel!(canUndo), can_undo as extern "C-unwind" fn(_, _) -> _);
    builder.add_method(sel!(canRedo), can_redo as extern "C-unwind" fn(_, _) -> _);
    builder.add_method(sel!(undo), undo as extern "C-unwind" fn(_, _));
    builder.add_method(sel!(redo), redo as extern "C-unwind" fn(_, _));
  }
  builder.register()
}

// A keyboard attached to the device. What it types, and its arrows and shortcuts, are the text system's, which
// has them from the view as it has the screen's keyboard. The keys that leave the input are the tree's.

/// The keys of an attached keyboard the tree takes while an input is typed into.
const TREE_KEYS: &[&str] = &["Tab", "Escape"];

extern "C-unwind" fn presses_began(this: &AnyObject, _cmd: Sel, presses: *mut AnyObject, event: *mut AnyObject) {
  if !super::ios::take_presses(presses, true, Some(TREE_KEYS)) {
    let _: () = unsafe { msg_send![super(this, class!(UIView)), pressesBegan: presses, withEvent: event] };
  }
}

extern "C-unwind" fn presses_ended(this: &AnyObject, _cmd: Sel, presses: *mut AnyObject, event: *mut AnyObject) {
  if !super::ios::take_presses(presses, false, Some(TREE_KEYS)) {
    let _: () = unsafe { msg_send![super(this, class!(UIView)), pressesEnded: presses, withEvent: event] };
  }
}

// The keyboard's traits: `UITextInputTraits`.

fn traits() -> Option<KeyboardTraits> {
  with_mirror(None, |mirror| mirror.traits)
}

extern "C-unwind" fn is_secure_text_entry(_this: &AnyObject, _cmd: Sel) -> Bool {
  Bool::new(traits().is_some_and(|traits| traits.secure))
}

/// `UIKeyboardType`.
extern "C-unwind" fn keyboard_type(_this: &AnyObject, _cmd: Sel) -> isize {
  match traits().map(|traits| traits.kind) {
    Some(KeyboardKind::Url) => 3,
    Some(KeyboardKind::Number) => 4,
    Some(KeyboardKind::Phone) => 5,
    Some(KeyboardKind::Email) => 7,
    Some(KeyboardKind::Decimal) => 8,
    Some(KeyboardKind::Search) => 10,
    Some(KeyboardKind::Text | KeyboardKind::None) | None => 0,
  }
}

/// `UIReturnKeyType`.
extern "C-unwind" fn return_key_type(_this: &AnyObject, _cmd: Sel) -> isize {
  match traits().map(|traits| traits.return_key) {
    Some(ReturnKey::Go) => 1,
    Some(ReturnKey::Next) => 4,
    Some(ReturnKey::Search) => 6,
    Some(ReturnKey::Send) => 7,
    Some(ReturnKey::Done) => 9,
    Some(ReturnKey::Default) | None => 0,
  }
}

#[link(name = "UIKit", kind = "framework")]
unsafe extern "C" {
  static UITextContentTypeName: *mut AnyObject;
  static UITextContentTypeEmailAddress: *mut AnyObject;
  static UITextContentTypeUsername: *mut AnyObject;
  static UITextContentTypePassword: *mut AnyObject;
  static UITextContentTypeNewPassword: *mut AnyObject;
  static UITextContentTypeOneTimeCode: *mut AnyObject;
  static UITextContentTypeTelephoneNumber: *mut AnyObject;
  static UITextContentTypeURL: *mut AnyObject;
}

/// `UITextContentType`: what the system offers to fill the input in with.
extern "C-unwind" fn text_content_type(_this: &AnyObject, _cmd: Sel) -> *mut AnyObject {
  unsafe {
    match traits().map(|traits| traits.content) {
      Some(ContentKind::Name) => UITextContentTypeName,
      Some(ContentKind::Email) => UITextContentTypeEmailAddress,
      Some(ContentKind::Username) => UITextContentTypeUsername,
      Some(ContentKind::Password) => UITextContentTypePassword,
      Some(ContentKind::NewPassword) => UITextContentTypeNewPassword,
      Some(ContentKind::OneTimeCode) => UITextContentTypeOneTimeCode,
      Some(ContentKind::Phone) => UITextContentTypeTelephoneNumber,
      Some(ContentKind::Url) => UITextContentTypeURL,
      Some(ContentKind::Auto | ContentKind::None) | None => std::ptr::null_mut(),
    }
  }
}

/// Whether the input holds prose: what is not a password, an address or a number is corrected and
/// capitalised as prose is.
fn is_prose() -> bool {
  traits().is_none_or(|traits| !traits.secure && matches!(traits.kind, KeyboardKind::Text | KeyboardKind::Search))
}

/// `UITextAutocapitalizationType`: sentences, or none.
extern "C-unwind" fn autocapitalization_type(_this: &AnyObject, _cmd: Sel) -> isize {
  if is_prose() { 2 } else { 0 }
}

/// `UITextAutocorrectionType` and `UITextSpellCheckingType`: the default, or no.
extern "C-unwind" fn correction_type(_this: &AnyObject, _cmd: Sel) -> isize {
  if is_prose() { 0 } else { 1 }
}

/// The class of the view that takes the keyboard, registered once.
fn text_input_class() -> &'static AnyClass {
  if let Some(class) = AnyClass::get(c"LurqTextInputView") {
    return class;
  }
  let mut builder = ClassBuilder::new(c"LurqTextInputView", class!(UIView)).expect("a class name of its own");
  for protocol in [c"UIKeyInput", c"UITextInputTraits", c"UITextInput"] {
    if let Some(protocol) = AnyProtocol::get(protocol) {
      builder.add_protocol(protocol);
    }
  }
  macro_rules! methods {
    ($($selector:expr => $function:expr),* $(,)?) => {
      unsafe {
        $(builder.add_method($selector, $function);)*
      }
    };
  }
  methods! {
    sel!(canBecomeFirstResponder) => can_become_first_responder as extern "C-unwind" fn(_, _) -> _,
    sel!(hasText) => has_text as extern "C-unwind" fn(_, _) -> _,
    sel!(insertText:) => insert_text as extern "C-unwind" fn(_, _, _),
    sel!(deleteBackward) => delete_backward as extern "C-unwind" fn(_, _),
    sel!(textInRange:) => text_in_range as extern "C-unwind" fn(_, _, _) -> _,
    sel!(replaceRange:withText:) => replace_range as extern "C-unwind" fn(_, _, _, _),
    sel!(selectedTextRange) => selected_text_range as extern "C-unwind" fn(_, _) -> _,
    sel!(setSelectedTextRange:) => set_selected_text_range as extern "C-unwind" fn(_, _, _),
    sel!(markedTextRange) => marked_text_range as extern "C-unwind" fn(_, _) -> _,
    sel!(markedTextStyle) => marked_text_style as extern "C-unwind" fn(_, _) -> _,
    sel!(setMarkedTextStyle:) => set_marked_text_style as extern "C-unwind" fn(_, _, _),
    sel!(setMarkedText:selectedRange:) => set_marked_text as extern "C-unwind" fn(_, _, _, _),
    sel!(unmarkText) => unmark_text as extern "C-unwind" fn(_, _),
    sel!(beginningOfDocument) => beginning_of_document as extern "C-unwind" fn(_, _) -> _,
    sel!(endOfDocument) => end_of_document as extern "C-unwind" fn(_, _) -> _,
    sel!(textRangeFromPosition:toPosition:) => text_range_from_position as extern "C-unwind" fn(_, _, _, _) -> _,
    sel!(positionFromPosition:offset:) => position_from_position as extern "C-unwind" fn(_, _, _, _) -> _,
    sel!(positionFromPosition:inDirection:offset:) =>
      position_in_direction as extern "C-unwind" fn(_, _, _, _, _) -> _,
    sel!(comparePosition:toPosition:) => compare_position as extern "C-unwind" fn(_, _, _, _) -> _,
    sel!(offsetFromPosition:toPosition:) => offset_from_position as extern "C-unwind" fn(_, _, _, _) -> _,
    sel!(inputDelegate) => input_delegate as extern "C-unwind" fn(_, _) -> _,
    sel!(setInputDelegate:) => set_input_delegate as extern "C-unwind" fn(_, _, _),
    sel!(tokenizer) => tokenizer as extern "C-unwind" fn(_, _) -> _,
    sel!(positionWithinRange:farthestInDirection:) =>
      position_within_range as extern "C-unwind" fn(_, _, _, _) -> _,
    sel!(characterRangeByExtendingPosition:inDirection:) =>
      character_range_by_extending as extern "C-unwind" fn(_, _, _, _) -> _,
    sel!(baseWritingDirectionForPosition:inDirection:) =>
      base_writing_direction as extern "C-unwind" fn(_, _, _, _) -> _,
    sel!(setBaseWritingDirection:forRange:) => set_base_writing_direction as extern "C-unwind" fn(_, _, _, _),
    sel!(textInputView) => text_input_view as extern "C-unwind" fn(_, _) -> _,
    sel!(firstRectForRange:) => first_rect_for_range as extern "C-unwind" fn(_, _, _) -> _,
    sel!(caretRectForPosition:) => caret_rect_for_position as extern "C-unwind" fn(_, _, _) -> _,
    sel!(selectionRectsForRange:) => selection_rects_for_range as extern "C-unwind" fn(_, _, _) -> _,
    sel!(closestPositionToPoint:) => closest_position_to_point as extern "C-unwind" fn(_, _, _) -> _,
    sel!(closestPositionToPoint:withinRange:) =>
      closest_position_within_range as extern "C-unwind" fn(_, _, _, _) -> _,
    sel!(characterRangeAtPoint:) => character_range_at_point as extern "C-unwind" fn(_, _, _) -> _,
    sel!(copy:) => copy as extern "C-unwind" fn(_, _, _),
    sel!(cut:) => cut as extern "C-unwind" fn(_, _, _),
    sel!(paste:) => paste as extern "C-unwind" fn(_, _, _),
    sel!(selectAll:) => select_all as extern "C-unwind" fn(_, _, _),
    sel!(canPerformAction:withSender:) => can_perform_action as extern "C-unwind" fn(_, _, _, _) -> _,
    sel!(undoManager) => undo_manager as extern "C-unwind" fn(_, _) -> _,
    sel!(pressesBegan:withEvent:) => presses_began as extern "C-unwind" fn(_, _, _, _),
    sel!(pressesEnded:withEvent:) => presses_ended as extern "C-unwind" fn(_, _, _, _),
    sel!(isSecureTextEntry) => is_secure_text_entry as extern "C-unwind" fn(_, _) -> _,
    sel!(keyboardType) => keyboard_type as extern "C-unwind" fn(_, _) -> _,
    sel!(returnKeyType) => return_key_type as extern "C-unwind" fn(_, _) -> _,
    sel!(autocapitalizationType) => autocapitalization_type as extern "C-unwind" fn(_, _) -> _,
    sel!(autocorrectionType) => correction_type as extern "C-unwind" fn(_, _) -> _,
    sel!(spellCheckingType) => correction_type as extern "C-unwind" fn(_, _) -> _,
    sel!(textContentType) => text_content_type as extern "C-unwind" fn(_, _) -> _,
    sel!(isKindOfClass:) => is_kind_of_class as extern "C-unwind" fn(_, _, _) -> _,
    sel!(forwardingTargetForSelector:) => forwarding_target as extern "C-unwind" fn(_, _, _) -> _,
  }
  builder.register()
}

// Saved passwords: UIKit offers them only to a `UITextField`, which it asks the focused view whether it
// is. While the input typed into hides what is typed, the view says it is one, and what UIKit then asks of
// a text field that this view has no answer to goes to a text field that is not seen. The filling itself comes
// through `UITextInput`, as typing does.

/// The text field that answers for the view; made when first asked for, and kept.
static FIELD_STAND_IN: AtomicPtr<AnyObject> = AtomicPtr::new(std::ptr::null_mut());

fn field_stand_in() -> *mut AnyObject {
  let field = FIELD_STAND_IN.load(Ordering::Acquire);
  if !field.is_null() {
    return field;
  }
  let field: Retained<AnyObject> = unsafe { msg_send![class!(UITextField), new] };
  let field = Retained::into_raw(field);
  FIELD_STAND_IN.store(field, Ordering::Release);
  field
}

fn is_secure() -> bool {
  traits().is_some_and(|traits| traits.secure)
}

extern "C-unwind" fn is_kind_of_class(this: &AnyObject, _cmd: Sel, class: *const AnyClass) -> Bool {
  let is: Bool = unsafe { msg_send![super(this, class!(UIView)), isKindOfClass: class] };
  Bool::new(is.as_bool() || (is_secure() && std::ptr::eq(class, class!(UITextField))))
}

extern "C-unwind" fn forwarding_target(_this: &AnyObject, _cmd: Sel, _selector: Sel) -> *mut AnyObject {
  if is_secure() {
    field_stand_in()
  } else {
    std::ptr::null_mut()
  }
}

/// What UIKit is told changed when the tree's input is not what the copy says.
enum Changed {
  Text,
  Selection,
  /// Neither: the same text and selection are painted elsewhere. UIKit's delegate is not told, which costs
  /// tens of milliseconds for it to read the text anew; only the caret and the selection are drawn anew.
  Place,
}

/// Has winit's view, which the text input's view is in, stand aside for it.
///
/// winit's view takes keys itself (`UIKeyInput`), for apps that have it show the keyboard, which the shell
/// never does: a view of the shell's own types. As it is, it gets in that view's way twice.
///
/// UIKit hands the keyboard to the next view up that will take it when a view gives it up
/// (`-[UIResponder resignFirstResponder]`), and winit's always will: the keyboard the person put away stayed,
/// winit's now and knowing nothing of the input. While an input is typed into it takes none.
///
/// And to fill a saved login in UIKit looks through the window for the fields of the form, the one for the
/// name beside the one for the password, and does not look inside a view that types itself
/// (`_requiresKeyboardWhenFirstResponder`): it saw winit's view and none of those in it, and filled the
/// password in alone. A view that says it is not to be edited is not one that types.
fn quiet_window_view(view: &AnyObject) {
  extern "C-unwind" fn is_editable(_this: &AnyObject, _cmd: Sel) -> Bool {
    Bool::NO
  }
  extern "C-unwind" fn can_become_first_responder(_this: &AnyObject, _cmd: Sel) -> Bool {
    Bool::new(!TYPES.load(Ordering::Acquire))
  }
  let class = view.class();
  let types = c"B@:";
  unsafe {
    let class = std::ptr::from_ref(class).cast_mut();
    // Both leave a class that already has them as it is: every view answers `isEditable`, with yes, and this
    // is winit's class's own answer.
    objc2::ffi::class_addMethod(
      class.cast(),
      sel!(isEditable),
      std::mem::transmute::<extern "C-unwind" fn(&AnyObject, Sel) -> Bool, unsafe extern "C-unwind" fn()>(is_editable),
      types.as_ptr(),
    );
    objc2::ffi::class_replaceMethod(
      class.cast(),
      sel!(canBecomeFirstResponder),
      std::mem::transmute::<extern "C-unwind" fn(&AnyObject, Sel) -> Bool, unsafe extern "C-unwind" fn()>(
        can_become_first_responder,
      ),
      types.as_ptr(),
    );
  }
}

/// The view the keyboard types into. Main thread only.
pub(super) struct TextInput {
  view: Retained<AnyObject>,
  /// Text fields that are not seen, one for each other input a saved login may fill: the platform looks for
  /// a field for the name beside the one for the password, and fills both.
  peers: Vec<Peer>,
}

struct Peer {
  id: crate::core::NodeId,
  field: Retained<AnyObject>,
  /// What the field and the tree's input both said at the last turn.
  value: String,
  /// Where the field was put in the window: see `sync_peers`.
  place: Option<(f64, f64)>,
}

impl TextInput {
  /// Adds the view, which shows nothing, to the window's view.
  pub(super) fn new(parent: NonNull<c_void>) -> Self {
    let parent: &AnyObject = unsafe { parent.cast::<AnyObject>().as_ref() };
    WINDOW_VIEW.store(std::ptr::from_ref(parent).cast_mut(), Ordering::Release);
    quiet_window_view(parent);
    Self {
      view: Self::view_in(parent),
      peers: Vec::new(),
    }
  }

  /// A view to type into, in the window's view, and the one that types from now on.
  fn view_in(parent: &AnyObject) -> Retained<AnyObject> {
    unsafe {
      let view: Retained<AnyObject> = msg_send![text_input_class(), new];
      // No size until an input has the focus, so nothing to see or touch; a hidden view could not take the
      // keyboard.
      let _: () = msg_send![&*view, setUserInteractionEnabled: false];
      let _: () = msg_send![parent, addSubview: &*view];
      Self::interact(&view);
      TYPING_VIEW.store(Retained::as_ptr(&view).cast_mut(), Ordering::Release);
      INPUT_DELEGATE.store(std::ptr::null_mut(), Ordering::Release);
      let tokenizer = TOKENIZER.swap(std::ptr::null_mut(), Ordering::AcqRel);
      drop(Retained::from_raw(tokenizer));
      view
    }
  }

  /// Gives a view the platform's caret, selection handles, loupe and menu: `UITextInteractionModeEditable`.
  fn interact(view: &AnyObject) {
    unsafe {
      let interaction: Retained<AnyObject> = msg_send![class!(UITextInteraction), textInteractionForMode: 0isize];
      let _: () = msg_send![&*interaction, setTextInput: view];
      let _: () = msg_send![view, addInteraction: &*interaction];
    }
  }

  /// Has UIKit read the view's selection anew. It keeps the selection it draws the caret and the handles from
  /// to itself, and reads the view's as it sets one itself, a key or a finger's, and as it makes the
  /// interaction: told by the view's input delegate that the selection changed, it tells the keyboard, and
  /// draws the caret where it was. So a selection UIKit did not set, the tree's own or a saved password's,
  /// which UIKit puts in without reading where the caret then is, has the view take a new interaction.
  fn reread_selection(&self) {
    unsafe {
      // The interaction, which takes the ones it made with it, and what those leave behind.
      let interactions: Retained<AnyObject> = msg_send![&*self.view, interactions];
      let count: usize = msg_send![&*interactions, count];
      for index in 0..count {
        let interaction: Retained<AnyObject> = msg_send![&*interactions, objectAtIndex: index];
        let _: () = msg_send![&*self.view, removeInteraction: &*interaction];
      }
    }
    Self::interact(&self.view);
    self.show_selection(true);
    self.update_selection();
  }

  /// Puts a new view in the place of the one that types, and gives back the old, which is still in the
  /// window. UIKit takes a view to be one field for as long as it lives: what it found out as the view first
  /// took the keyboard, the fields of a login around it among that, it keeps while the keyboard goes between
  /// that login's fields, and this view is all of them. So each input to type into has a view of its own, as
  /// each has a text field of its own in an app of UIKit's.
  fn renew(&mut self) -> Retained<AnyObject> {
    let parent: Option<Retained<AnyObject>> = unsafe { msg_send![&*self.view, superview] };
    match parent {
      Some(parent) => std::mem::replace(&mut self.view, Self::view_in(&parent)),
      None => self.view.clone(),
    }
  }

  /// One turn of the shell: makes UIKit's edits in the tree, then brings the keyboard and the copy to what the
  /// tree's focused text input now is.
  pub(super) fn sync(&mut self, tree: &mut Tree) {
    let edits = with_mirror(Vec::new(), |mirror| std::mem::take(&mut mirror.edits));
    for edit in edits {
      match edit {
        Edit::Insert(text) => tree.keyboard_insert(&text),
        Edit::DeleteBackward => tree.keyboard_delete_backward(),
        Edit::Replace { start, end, text } => tree.text_input_replace(start..end, &text),
        Edit::Select { start, end } => tree.text_input_select(start..end),
        Edit::Mark { text, selection } => tree.ime(ImeEvent::Preedit {
          text,
          cursor: selection,
        }),
        Edit::Unmark(text) => tree.ime(ImeEvent::Commit(text)),
        Edit::Command(command) => {
          tree.keyboard_edit(command);
        }
      }
    }
    let shown = self.shown_selection();
    let changed = {
      let mut highlight = HIGHLIGHT.lock().unwrap();
      let changed = *highlight != shown;
      if changed {
        highlight.clone_from(&shown);
      }
      changed
    };
    if changed {
      tree.set_native_selection_rects(
        shown
          .into_iter()
          .map(|(x, y, width, height)| (x as f32, y as f32, width as f32, height as f32))
          .collect(),
      );
    }
    let typing = MIRROR
      .lock()
      .unwrap()
      .as_ref()
      .is_some_and(|mirror| mirror.traits.is_some());
    let other_peers = self.sync_peers(tree);
    // While another app's or the system's view is over this one, the list of saved passwords among them, the
    // keyboard is neither the view's nor lost: UIKit gives it back with the screen.
    let active = unsafe {
      let app: Retained<AnyObject> = msg_send![class!(UIApplication), sharedApplication];
      let state: isize = msg_send![&*app, applicationState];
      state == 0
    };
    let first: bool = unsafe { msg_send![&*self.view, isFirstResponder] };
    if typing && active && !first {
      // The view is no longer the one that types, and the input is left: the person put the keyboard away, as
      // a finger that takes it down with it does, or UIKit did, as it does to a field of its own when a saved
      // login came from another app's list that had a keyboard up
      // (`-[UIKeyboardSceneDelegate _restoreInputViewsWithId:animated:]`).
      tree.keyboard_was_put_away();
    }
    let traits = tree.keyboard_traits();
    let snapshot = tree.text_input_snapshot();
    let (Some(traits), Some(snapshot)) = (traits, snapshot) else {
      self.dismiss();
      return;
    };
    let previous = with_mirror(None, |mirror| mirror.traits);
    // An input that hides what is typed where the one before did not, or is for something else of the
    // person's, or is of another login, is another field to UIKit: it decides what to offer over the keyboard,
    // a saved password among it, and which fields a saved login fills, as a view takes the keyboard.
    let another = match previous {
      None => true,
      Some(previous) => previous.secure != traits.secure || previous.content != traits.content || other_peers,
    };
    let before = another.then(|| self.renew());
    let geometry = snapshot.geometry.as_ref().map(|geometry| Geometry {
      bounds: (
        f64::from(geometry.bounds.0),
        f64::from(geometry.bounds.1),
        f64::from(geometry.bounds.2),
        f64::from(geometry.bounds.3),
      ),
      carets: geometry
        .carets
        .iter()
        .map(|(index, x, y)| (*index, f64::from(*x), f64::from(*y)))
        .collect(),
      line_height: f64::from(geometry.line_height),
    });
    let moved = with_mirror(true, |mirror| mirror.geometry != geometry);
    // Text that is the same but painted elsewhere, scrolled or laid out anew, is a caret to draw anew.
    let changed = Self::changed(&snapshot).or(moved.then_some(Changed::Place));
    if let Some(changed) = &changed {
      self.tell(changed, true);
    }
    {
      let mut mirror = MIRROR.lock().unwrap();
      let mirror = mirror.get_or_insert_with(Mirror::default);
      mirror.traits = Some(traits);
      mirror.geometry = geometry.clone();
      mirror.can_undo = snapshot.can_undo;
      mirror.can_redo = snapshot.can_redo;
      if matches!(changed, Some(Changed::Text | Changed::Selection)) {
        mirror.text = snapshot.text;
        mirror.selection = (snapshot.selection.start, snapshot.selection.end);
        mirror.marked = snapshot.composition.map(|marked| (marked.start, marked.end));
      }
    }
    // The view lies over the input, for the platform's caret and handles to be drawn and touched there.
    if (moved || another)
      && let Some(geometry) = &geometry
    {
      let frame = CGRect {
        origin: CGPoint {
          x: geometry.bounds.0,
          y: geometry.bounds.1,
        },
        size: CGSize {
          width: geometry.bounds.2,
          height: geometry.bounds.3,
        },
      };
      unsafe {
        let _: () = msg_send![&*self.view, setFrame: frame];
        let _: () = msg_send![&*self.view, setUserInteractionEnabled: true];
      }
    } else if another {
      // The input is not laid out yet. UIKit takes no view without a size for a field of a login, and reads
      // the fields in the order they lie in: under the first row, where the fields for a name are
      // (`sync_peers`), until the input's place is known.
      let frame = CGRect {
        origin: CGPoint { x: 0.0, y: 1.0 },
        size: CGSize {
          width: 1.0,
          height: 1.0,
        },
      };
      let _: () = unsafe { msg_send![&*self.view, setFrame: frame] };
    }
    if let Some(changed) = &changed {
      self.tell(changed, false);
      self.update_selection();
    }
    // The tree's text or selection is not what UIKit made it, or a saved password came, after which UIKit
    // may draw the caret where the view did not take it (`set_selected_text_range`): it reads the caret anew.
    // A new view's interaction is new.
    let astray = with_mirror(false, |mirror| std::mem::take(&mut mirror.caret_astray));
    if before.is_none() && (astray || matches!(changed, Some(Changed::Text | Changed::Selection))) {
      self.reread_selection();
    }
    TYPES.store(true, Ordering::Release);
    unsafe {
      match (before, previous) {
        // The keyboard goes from the view that typed to the new one, and stays up as it does between two
        // fields.
        (Some(before), _) => {
          // As the new view takes the keyboard UIKit looks for the fields of a login around it, and the old
          // view, still in the window, is not one of them: a view of no size is passed over.
          let _: () = msg_send![&*before, setFrame: no_rect()];
          let _: bool = msg_send![&*self.view, becomeFirstResponder];
          self.show_selection(true);
          let _: () = msg_send![&*before, removeFromSuperview];
        }
        // Another input took the focus: the keyboard stays up and becomes the one it asks for.
        (None, Some(previous)) if previous != traits => {
          let _: () = msg_send![&*self.view, reloadInputViews];
        }
        (None, _) => {}
      }
    }
  }

  /// Has the platform draw its caret and selection, or stop. The text interaction makes the interaction that
  /// draws them and leaves it off for a view that is not one of UIKit's own.
  fn show_selection(&self, shown: bool) {
    if shown {
      self.lower_surface();
    }
    if let Some(display) = self.selection_display() {
      unsafe {
        let _: () = msg_send![&*display, setActivated: shown];
        // The input paints the selection's highlight itself, under its text, where the platform's view says
        // it is (`shown_selection`); that view would lie over the text, and is not seen. It stays UIKit's
        // own: with a view of the shell's in its place UIKit showed no menu.
        let highlight: Option<Retained<AnyObject>> = msg_send![&*display, highlightView];
        if let Some(highlight) = highlight {
          let _: () = msg_send![&*highlight, setAlpha: 0.0f64];
        }
        let _: () = msg_send![&*display, setNeedsSelectionUpdate];
      }
    }
  }

  /// The rectangles UIKit shows the selection as, in the window: the selection's, and a handle's as it is
  /// dragged, when the selection itself is not yet set.
  fn shown_selection(&self) -> Vec<(f64, f64, f64, f64)> {
    let Some(display) = self.selection_display() else {
      return Vec::new();
    };
    unsafe {
      let highlight: Option<Retained<AnyObject>> = msg_send![&*display, highlightView];
      let Some(highlight) = highlight else {
        return Vec::new();
      };
      let rects: Option<Retained<AnyObject>> = msg_send![&*highlight, selectionRects];
      let Some(rects) = rects else {
        return Vec::new();
      };
      let count: usize = msg_send![&*rects, count];
      (0..count)
        .map(|index| {
          let rect: Retained<AnyObject> = msg_send![&*rects, objectAtIndex: index];
          let rect: CGRect = msg_send![&*rect, rect];
          let rect: CGRect = msg_send![&*highlight, convertRect: rect, toView: std::ptr::null::<AnyObject>()];
          (rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)
        })
        .collect()
    }
  }

  /// Puts the layer lurq renders into under the views of the window's view. wgpu adds it as a sublayer after
  /// them, which is over them: nothing a view draws, the caret and the selection here, would be seen.
  fn lower_surface(&self) {
    unsafe {
      let parent: Option<Retained<AnyObject>> = msg_send![&*self.view, superview];
      let Some(parent) = parent else {
        return;
      };
      let layer: Retained<AnyObject> = msg_send![&*parent, layer];
      let sublayers: Option<Retained<AnyObject>> = msg_send![&*layer, sublayers];
      let Some(sublayers) = sublayers else {
        return;
      };
      let count: usize = msg_send![&*sublayers, count];
      for index in 0..count {
        let sublayer: Retained<AnyObject> = msg_send![&*sublayers, objectAtIndex: index];
        let renders: bool = msg_send![&*sublayer, isKindOfClass: class!(CAMetalLayer)];
        if renders {
          let _: () = msg_send![&*sublayer, setZPosition: -1.0f64];
        }
      }
    }
  }

  /// Has the platform draw the caret and selection anew, where the view now says they are.
  fn update_selection(&self) {
    if let Some(display) = self.selection_display() {
      let _: () = unsafe { msg_send![&*display, setNeedsSelectionUpdate] };
      // Now, for the caret to move in the frame its character is drawn in and not a frame later.
      let _: () = unsafe { msg_send![&*display, layoutManagedSubviews] };
    }
  }

  /// The interaction of the view that draws the caret and the selection.
  fn selection_display(&self) -> Option<Retained<AnyObject>> {
    unsafe {
      let interactions: Retained<AnyObject> = msg_send![&*self.view, interactions];
      let count: usize = msg_send![&*interactions, count];
      (0..count)
        .map(|index| -> Retained<AnyObject> { msg_send![&*interactions, objectAtIndex: index] })
        .find(|interaction| msg_send![&**interaction, isKindOfClass: class!(UITextSelectionDisplayInteraction)])
    }
  }

  /// How the tree's input differs from the copy, if it does.
  fn changed(snapshot: &TextInputSnapshot) -> Option<Changed> {
    let mirror = MIRROR.lock().unwrap();
    let Some(mirror) = mirror.as_ref() else {
      return Some(Changed::Text);
    };
    if mirror.text != snapshot.text {
      Some(Changed::Text)
    } else if mirror.selection != (snapshot.selection.start, snapshot.selection.end)
      || mirror.marked != snapshot.composition.as_ref().map(|marked| (marked.start, marked.end))
    {
      Some(Changed::Selection)
    } else {
      None
    }
  }

  /// Tells UIKit the text or the selection is about to change, or has. It asks the view anew, which answers
  /// from the copy: the copy's lock is not held here.
  fn tell(&self, changed: &Changed, before: bool) {
    let delegate = INPUT_DELEGATE.load(Ordering::Acquire);
    let Some(delegate) = (unsafe { delegate.as_ref() }) else {
      return;
    };
    unsafe {
      let _: () = match (changed, before) {
        (Changed::Text, true) => msg_send![delegate, textWillChange: &*self.view],
        (Changed::Text, false) => msg_send![delegate, textDidChange: &*self.view],
        (Changed::Selection, true) => msg_send![delegate, selectionWillChange: &*self.view],
        (Changed::Selection, false) => msg_send![delegate, selectionDidChange: &*self.view],
        (Changed::Place, _) => return,
      };
    }
  }

  /// Keeps a text field for each other input of a login, and takes into the tree what the platform filled
  /// one in with. Says whether the fields are others than they were.
  fn sync_peers(&mut self, tree: &mut Tree) -> bool {
    let wanted = tree.autofill_peers();
    let mut other = false;
    self.peers.retain(|peer| {
      let kept = wanted.iter().any(|wanted| wanted.id == peer.id);
      if !kept {
        let _: () = unsafe { msg_send![&*peer.field, removeFromSuperview] };
        other = true;
      }
      kept
    });
    for wanted in &wanted {
      if self.peers.iter().any(|peer| peer.id == wanted.id) {
        continue;
      }
      other = true;
      unsafe {
        let field: Retained<AnyObject> = msg_send![class!(UITextField), new];
        // In the window, where the platform looks for it, and neither seen nor touched.
        let _: () = msg_send![&*field, setAlpha: 0.01f64];
        let _: () = msg_send![&*field, setUserInteractionEnabled: false];
        let content = match wanted.content {
          ContentKind::Email => UITextContentTypeEmailAddress,
          ContentKind::Username => UITextContentTypeUsername,
          ContentKind::Password => UITextContentTypePassword,
          ContentKind::NewPassword => UITextContentTypeNewPassword,
          _ if wanted.secure => UITextContentTypePassword,
          _ => std::ptr::null_mut(),
        };
        let _: () = msg_send![&*field, setTextContentType: content];
        let _: () = msg_send![&*field, setSecureTextEntry: wanted.secure];
        let superview: Option<Retained<AnyObject>> = msg_send![&*self.view, superview];
        if let Some(superview) = superview {
          // Under the view that types, as a form's fields are one after another.
          let _: () = msg_send![&*superview, insertSubview: &*field, belowSubview: &*self.view];
        }
        // The field starts as the input is: the first turn sets it.
        self.peers.push(Peer {
          id: wanted.id,
          field,
          value: String::from("\u{0}"),
          place: None,
        });
      }
    }
    // UIKit reads a form in the order its fields lie in, a row after another and each from its left, and takes
    // the field next before the password's to be the name's, whatever each says it is for. So the fields lie
    // around the view that types as a login's do: those for a name in the window's first row, the one that
    // says it is the name to log in with last of them, and those for a password in its last.
    let password =
      |peer: &AutofillPeer| peer.secure || matches!(peer.content, ContentKind::Password | ContentKind::NewPassword);
    let bottom = unsafe {
      let superview: Option<Retained<AnyObject>> = msg_send![&*self.view, superview];
      match superview {
        Some(superview) => {
          let bounds: CGRect = msg_send![&*superview, bounds];
          (bounds.size.height - 1.0).max(1.0)
        }
        None => 1.0,
      }
    };
    let (mut before, mut after) = (0.0, 0.0);
    let rows: [&dyn Fn(&AutofillPeer) -> bool; 3] = [
      &|peer| !password(peer) && peer.content != ContentKind::Username,
      &|peer| !password(peer) && peer.content == ContentKind::Username,
      &|peer| password(peer),
    ];
    for (row, belongs) in rows.iter().enumerate() {
      for wanted in wanted.iter().filter(|wanted| belongs(wanted)) {
        let Some(peer) = self.peers.iter_mut().find(|peer| peer.id == wanted.id) else {
          continue;
        };
        let place = if row == 2 {
          after += 1.0;
          (after - 1.0, bottom)
        } else {
          before += 1.0;
          (before - 1.0, 0.0)
        };
        if peer.place != Some(place) {
          let frame = CGRect {
            origin: CGPoint { x: place.0, y: place.1 },
            size: CGSize {
              width: 1.0,
              height: 1.0,
            },
          };
          let _: () = unsafe { msg_send![&*peer.field, setFrame: frame] };
          peer.place = Some(place);
        }
      }
    }
    for peer in &mut self.peers {
      let Some(wanted) = wanted.iter().find(|wanted| wanted.id == peer.id) else {
        continue;
      };
      let said = unsafe {
        let text: *mut AnyObject = msg_send![&*peer.field, text];
        string_of(text).unwrap_or_default()
      };
      if peer.value != "\u{0}" && said != peer.value {
        // The platform wrote in the field: a saved login's other half.
        tree.autofill(peer.id, &said);
        peer.value = said;
      } else if wanted.value != peer.value {
        let _: () = unsafe { msg_send![&*peer.field, setText: ns_string(&wanted.value)] };
        peer.value.clone_from(&wanted.value);
      }
    }
    other
  }

  /// No text input has focus: the keyboard goes away.
  fn dismiss(&mut self) {
    if MIRROR.lock().unwrap().take().is_none() {
      return;
    }
    unsafe {
      self.show_selection(false);
      // winit's view takes no keyboard yet, so none is handed to it as this view gives its own up: taking
      // interaction from a view that types has it give the keyboard up too.
      let _: () = msg_send![&*self.view, setUserInteractionEnabled: false];
      // Hidden where it is: moved away, its caret was at times seen on its way out, at the window's corner.
      let _: () = msg_send![&*self.view, setHidden: true];
      let _: bool = msg_send![&*self.view, resignFirstResponder];
    }
    TYPES.store(false, Ordering::Release);
  }
}