ferrokit-core 0.7.1

The AppKit layer under ferrokit (use that): places real AppKit views in a window and keeps layout, focus and shortcuts in step
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
//! A real `NSTextView` (in its `NSScrollView`) as a text editor, plain or rich.
//!
//! What AppKit brings: IME with the candidate window at the caret, spell and
//! grammar checking with the suggestion menu, the find bar, undo, text
//! services (Look Up, Translate, Writing Tools), Dark Mode and VoiceOver.
//!
//! Offsets in this API are UTF-8 byte offsets into the text, as Rust strings
//! use; they're converted from AppKit's UTF-16 ranges at the boundary.
//! Like [`crate::table::TableModel`], user actions are queued on the model
//! and announced with [`crate::request_redraw`].
//!
//! Styled text: [`TextModel::set_highlighter`] colours and emphasises runs
//! of the text (syntax highlighting, search matches), re-run on every edit
//! before it's drawn. The text stays plain: styles aren't typed, pasted,
//! copied or undone.
//!
//! Rich text: [`TextModel::set_rich`] lets the user style the text
//! themselves (fonts, bold, colours, alignment, lists, pictures), with the
//! font panel, the ruler and the format bar; [`TextModel::rtf`] and
//! [`TextModel::html`] read it out, [`TextModel::set_rtf`] and
//! [`TextModel::set_html`] load it.

use objc2_foundation::NSArray;
use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::ops::Range;
use std::rc::{Rc, Weak};

use objc2::rc::Retained;
use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject};
use objc2::{AnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_class, msg_send};
use objc2_app_kit::{
    NSColor, NSFont, NSResponder, NSScrollView, NSText, NSTextDelegate, NSTextInputClient, NSTextStorage, NSTextStorageDelegate,
    NSTextStorageEditActions, NSTextView, NSTextViewDelegate, NSAutoresizingMaskOptions, NSView,
};
use objc2_foundation::{NSNotification, NSPoint, NSRange, NSRect, NSSize, NSString, NSUndoManager};

use crate::ViewId;
use crate::host::mtm;

/// Something the user did in the editor.
#[derive(Debug, Clone, PartialEq)]
pub enum TextEvent {
    /// The text changed (typing, paste, undo, a committed IME composition…).
    /// Read it with [`TextModel::text`]. Not sent while composing.
    Changed,
    /// The selection or caret moved (byte range).
    Selection(Range<usize>),
    /// An input method is composing (`Some(marked text)`), or stopped (`None`).
    Composition(Option<String>),
}

/// What a completer offers at the caret: the text it completes (a byte
/// range ending at the caret, such as the partial word) and the words that
/// would replace it, best first. See [`TextModel::set_completer`].
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Completion {
    /// The text the chosen word replaces (UTF-8 bytes, ending at the caret).
    pub range: Range<usize>,
    /// The words offered, in order.
    pub items: Vec<String>,
}

type Completer = dyn Fn(&str, usize) -> Option<Completion>;

// NSTextView's completion movements (NSText.h).
const RETURN_MOVEMENT: isize = 0x10;
const TAB_MOVEMENT: isize = 0x11;
const OTHER_MOVEMENT: isize = 0;

trait Data {
    fn push(&self, event: TextEvent);
    /// The completer's offer at the caret (UTF-16 range), if it has one.
    fn complete(&self) -> Option<(NSRange, Vec<String>)>;
    fn has_completer(&self) -> bool;
    fn quiet(&self) -> bool;
    fn composing(&self) -> bool;
    fn undo_manager(&self) -> Retained<NSUndoManager>;
    /// Records the words the completion list shows (for checks).
    fn offered(&self, items: &[String]);
    /// Restyles; inside an edit (`edited`), true when the rest of the
    /// region is left for [`Data::finish_highlight`] just after it.
    fn highlight(&self, edited: Option<NSRange>) -> bool;
    fn finish_highlight(&self);
}

struct ViewIvars {
    data: RefCell<Option<Weak<dyn Data>>>,
    composing: Cell<bool>,
}

define_class!(
    // NSTextView that reports input-method composition.
    #[unsafe(super(NSTextView, NSText, NSView, NSResponder, NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "FerrokitCoreTextView"]
    #[ivars = ViewIvars]
    struct HostTextView;

    impl HostTextView {
        #[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
        fn set_marked_text(&self, string: &AnyObject, selected: NSRange, replacement: NSRange) {
            crate::boundary::guarded("a text view (set_marked_text)", (), || {
                let () = unsafe { msg_send![super(self), setMarkedText: string, selectedRange: selected, replacementRange: replacement] };
                self.composition_changed();
            })
        }

        #[unsafe(method(unmarkText))]
        fn unmark_text(&self) {
            crate::boundary::guarded("a text view (unmark_text)", (), || {
                let () = unsafe { msg_send![super(self), unmarkText] };
                self.composition_changed();
            })
        }

        #[unsafe(method(insertText:replacementRange:))]
        fn insert_text(&self, string: &AnyObject, replacement: NSRange) {
            crate::boundary::guarded("a text view (insert_text)", (), || {
                let () = unsafe { msg_send![super(self), insertText: string, replacementRange: replacement] };
                self.composition_changed();
                // A typed word character (or a dot) opens the completer's list.
                let typed = string.downcast_ref::<NSString>().map(|s| s.to_string()).unwrap_or_default();
                let mut chars = typed.chars();
                if let (Some(c), None) = (chars.next(), chars.next())
                    && (c.is_alphanumeric() || c == '_' || c == '.')
                    && !self.hasMarkedText()
                    && self.data().is_some_and(|d| d.has_completer())
                {
                    self.complete_soon();
                }
            })
        }

        // complete_soon's timer: opens the completion list if there's
        // still something to offer.
        #[unsafe(method(ferrokitCompleteNow:))]
        fn complete_now(&self, _sender: Option<&AnyObject>) {
            crate::boundary::guarded("a text view (complete_now)", (), || {
                if self.hasMarkedText() || self.data().is_none_or(|d| d.complete().is_none_or(|(_, items)| items.is_empty())) {
                    return;
                }
                // SAFETY: AppKit's completion, on the main thread.
                objc2::rc::autoreleasepool(|_| unsafe { self.complete(None) });
            })
        }

        // The completer's partial word (after a dot, it may be empty).
        #[unsafe(method(rangeForUserCompletion))]
        fn range_for_user_completion(&self) -> NSRange {
            crate::boundary::guarded("a text view (range_for_user_completion)", NSRange::new(0, 0), || {
                if let Some((range, _)) = self.data().and_then(|d| d.complete()) {
                    return range;
                }
                unsafe { msg_send![super(self), rangeForUserCompletion] }
            })
        }

        // With a completer, a word goes in only when it's chosen (Return,
        // Tab, a click): not tentatively while moving through the list,
        // and not when typing goes on or Escape closes it.
        #[unsafe(method(insertCompletion:forPartialWordRange:movement:isFinal:))]
        fn insert_completion(&self, word: &NSString, range: NSRange, movement: isize, is_final: bool) {
            crate::boundary::guarded("a text view (insert_completion)", (), || {
                if self.data().is_some_and(|d| d.has_completer()) {
                    let clicked = || {
                        let mtm = MainThreadMarker::from(self);
                        objc2_app_kit::NSApplication::sharedApplication(mtm).currentEvent().is_some_and(|e| {
                            use objc2_app_kit::NSEventType as T;
                            matches!(e.r#type(), T::LeftMouseDown | T::LeftMouseUp)
                        })
                    };
                    let chosen = is_final && (movement == RETURN_MOVEMENT || movement == TAB_MOVEMENT || (movement == OTHER_MOVEMENT && clicked()));
                    if !chosen {
                        return;
                    }
                }
                let () = unsafe { msg_send![super(self), insertCompletion: word, forPartialWordRange: range, movement: movement, isFinal: is_final] };
            })
        }
    }
);

impl HostTextView {
    fn data(&self) -> Option<Rc<dyn Data>> {
        self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
    }

    /// Opens the completion list after this event (when there's something
    /// to offer), as AppKit's own complete: does: from a timer, once for
    /// the keys typed in one turn. Not from a run-loop block: the list runs
    /// its own event loop until an event ends it, and blocks queued in the
    /// same pass as that block (`later` work, the app's effects) would wait
    /// until then; on an idle Mac, forever.
    fn complete_soon(&self) {
        let sel = objc2::sel!(ferrokitCompleteNow:);
        // SAFETY: NSObject's perform requests, on the main thread; the
        // timer keeps the view alive until it fires.
        unsafe {
            let () = msg_send![objc2::class!(NSObject), cancelPreviousPerformRequestsWithTarget: self, selector: sel, object: Option::<&AnyObject>::None];
            let () = msg_send![self, performSelector: sel, withObject: Option::<&AnyObject>::None, afterDelay: 0.0f64];
        }
    }

    /// Emits `Composition` when marked text appears, changes or goes away.
    fn composition_changed(&self) {
        let composing = self.hasMarkedText();
        let was = self.ivars().composing.replace(composing);
        let Some(data) = self.data() else { return };
        if composing {
            let range = self.markedRange();
            let marked = self.string().to_string();
            let marked = utf16_slice(&marked, range.location, range.length);
            data.push(TextEvent::Composition(Some(marked)));
        } else if was {
            data.push(TextEvent::Composition(None));
        }
    }
}

struct DelegateIvars {
    data: RefCell<Option<Weak<dyn Data>>>,
}

define_class!(
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "FerrokitCoreTextDelegate"]
    #[ivars = DelegateIvars]
    struct Delegate;

    unsafe impl NSObjectProtocol for Delegate {}

    unsafe impl NSTextDelegate for Delegate {
        #[unsafe(method(textDidChange:))]
        fn text_did_change(&self, _notification: &NSNotification) {
            crate::boundary::guarded("a text view (text_did_change)", (), || {
                let Some(data) = self.data() else { return };
                // The edit is done and the caret placed: style the rest of what
                // it changed now (edits without this message, such as undo, get
                // it from the run loop).
                data.finish_highlight();
                if !data.quiet() {
                    data.push(TextEvent::Changed);
                }
            })
        }
    }

    // Every character edit, including undo and redo (for which AppKit sends
    // no textDidChange:), reaches the text storage.
    unsafe impl NSTextStorageDelegate for Delegate {
        // Restyling happens here, inside the edit, so new text never shows
        // in the previous run's style. Changing attributes after the edit
        // (in didProcessEditing, in an edit of its own) left TextKit 2's
        // layout behind the text: typed text didn't show, and the next
        // redraw read past the end of the string and aborted.
        #[unsafe(method(textStorage:willProcessEditing:range:changeInLength:))]
        fn will_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, range: NSRange, _delta: isize) {
            crate::boundary::guarded("a text view (will_process_editing)", (), || {
                if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
                    return;
                }
                let Some(data) = self.data().filter(|d| !d.composing()) else { return };
                if data.highlight(Some(range)) {
                    // Just after the edit, before the run loop draws, unless
                    // textDidChange: comes first.
                    let weak = self.ivars().data.borrow().clone();
                    let block = block2::RcBlock::new(move || {
                        if let Some(d) = weak.as_ref().and_then(Weak::upgrade) {
                            objc2::rc::autoreleasepool(|_| d.finish_highlight());
                        }
                    });
                    let main = objc2_core_foundation::CFRunLoop::main().expect("main run loop");
                    // SAFETY: the main run loop; the block touches main-thread state only.
                    unsafe { main.perform_block(objc2_core_foundation::kCFRunLoopCommonModes.map(|m| m.as_ref()), Some(&block)) };
                    main.wake_up();
                }
            })
        }

        #[unsafe(method(textStorage:didProcessEditing:range:changeInLength:))]
        fn did_process_editing(&self, _storage: &NSTextStorage, edited: NSTextStorageEditActions, _range: NSRange, _delta: isize) {
            crate::boundary::guarded("a text view (did_process_editing)", (), || {
                if !edited.contains(NSTextStorageEditActions::EditedCharacters) {
                    return;
                }
                let Some(data) = self.data().filter(|d| !d.composing() && !d.quiet()) else { return };
                data.push(TextEvent::Changed);
            })
        }
    }

    unsafe impl NSTextViewDelegate for Delegate {
        #[unsafe(method(textViewDidChangeSelection:))]
        fn selection_did_change(&self, notification: &NSNotification) {
            crate::boundary::guarded("a text view (selection_did_change)", (), || {
                let Some(data) = self.data().filter(|d| !d.quiet()) else { return };
                let Some(view) = notification.object().and_then(|o| o.downcast::<NSTextView>().ok()) else { return };
                let text = view.string().to_string();
                let r = view.selectedRange();
                data.push(TextEvent::Selection(utf16_to_bytes(&text, r.location, r.length)));
            })
        }

        // The completer's words (or AppKit's own, for an editor without one).
        #[unsafe(method_id(textView:completions:forPartialWordRange:indexOfSelectedItem:))]
        fn completions(&self, _view: &NSTextView, words: &NSArray<NSString>, _range: NSRange, index: *mut isize) -> Option<Retained<NSArray<NSString>>> {
            crate::boundary::guarded("a text view (completions)", None, || {
                Some(self.completion_words(words, index))
            })
        }

        // Each editor keeps its own undo history, instead of sharing the
        // window's (where ⌘Z in one view could undo another view's edit).
        #[unsafe(method_id(undoManagerForTextView:))]
        fn undo_manager_for(&self, _view: &NSTextView) -> Option<Retained<NSUndoManager>> {
            crate::boundary::guarded("a text view (undo_manager_for)", None, || {
                self.data().map(|d| d.undo_manager())
            })
        }
    }
);

impl Delegate {
    fn data(&self) -> Option<Rc<dyn Data>> {
        self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
    }

    fn completion_words(&self, words: &NSArray<NSString>, index: *mut isize) -> Retained<NSArray<NSString>> {
        let Some(data) = self.data().filter(|d| d.has_completer()) else { return words.retain() };
        let items = data.complete().map(|(_, items)| items).unwrap_or_default();
        if !index.is_null() {
            // SAFETY: AppKit's out-parameter.
            unsafe { *index = if items.is_empty() { -1 } else { 0 } };
        }
        data.offered(&items);
        let items: Vec<Retained<NSString>> = items.iter().map(|w| NSString::from_str(w)).collect();
        NSArray::from_retained_slice(&items)
    }
}

/// UTF-16 range → UTF-8 byte range in `text` (clamped).
pub(crate) fn utf16_to_bytes(text: &str, location: usize, length: usize) -> Range<usize> {
    let (mut units, mut start, mut end) = (0usize, None, None);
    for (byte, c) in text.char_indices() {
        if start.is_none() && units >= location {
            start = Some(byte);
        }
        if end.is_none() && units >= location + length {
            end = Some(byte);
        }
        units += c.len_utf16();
    }
    let start = start.unwrap_or(text.len());
    start..end.unwrap_or(text.len()).max(start)
}

/// UTF-8 byte range → UTF-16 range (location, length). Bytes inside a
/// character round down to its start.
pub(crate) fn bytes_to_utf16(text: &str, range: Range<usize>) -> (usize, usize) {
    let to_units = |byte: usize| -> usize {
        let byte = byte.min(text.len());
        let mut b = byte;
        while !text.is_char_boundary(b) {
            b -= 1;
        }
        text[..b].encode_utf16().count()
    };
    let (s, e) = (to_units(range.start), to_units(range.end.max(range.start)));
    (s, e - s)
}

fn utf16_slice(text: &str, location: usize, length: usize) -> String {
    text[utf16_to_bytes(text, location, length)].to_string()
}

struct Inner {
    id: ViewId,
    events: RefCell<VecDeque<TextEvent>>,
    quiet: Cell<bool>,
    mounted: Cell<bool>,
    undo: RefCell<Retained<NSUndoManager>>,
    /// Whether `undo` is someone else's (shared with other views).
    shared: Cell<bool>,
    scroll: Retained<NSScrollView>,
    view: Retained<HostTextView>,
    _delegate: Retained<Delegate>,
    /// The font unstyled text uses (`set_font`).
    font: RefCell<Retained<NSFont>>,
    highlighter: RefCell<Option<Rc<Highlighter>>>,
    completer: RefCell<Option<Rc<Completer>>>,
    /// The words the completion list last showed.
    offered: RefCell<Vec<String>>,
    /// Set while styles are applied (they re-enter the storage delegate).
    styling: Cell<bool>,
    /// The runs last applied and the text's length then, to restyle only
    /// what an edit changed.
    shown: RefCell<Option<(usize, Runs)>>,
    /// The UTF-16 span an edit left to restyle just after it.
    deferred: Cell<Option<(usize, usize)>>,
}

type Highlighter = dyn Fn(&str) -> Runs;
type Runs = Vec<(Range<usize>, TextStyle)>;

/// A colour: for text, backgrounds, borders, drawing. The named ones are the
/// system's colours: they follow Dark Mode, Increase Contrast and the user's
/// accent colour.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Color {
    /// The text colour (what unstyled text uses).
    Primary,
    /// Less prominent text.
    Secondary,
    /// Even less prominent text (comments, placeholders).
    Tertiary,
    /// The least prominent text and fills.
    Quaternary,
    /// The system's fill for thin shapes (a slider's track, a progress
    /// ring's track): the strongest of the fills, a translucent grey.
    Fill,
    /// A fill for medium shapes (a switch's background).
    SecondaryFill,
    /// A fill for large shapes (an input field, a search bar).
    TertiaryFill,
    /// A fill for large areas with content on them: grouped cards, as
    /// SwiftUI's `GroupBox` and grouped forms draw them.
    QuaternaryFill,
    /// The user's accent colour (System Settings › Appearance).
    Accent,
    /// Links.
    Link,
    /// System red.
    Red,
    /// System orange.
    Orange,
    /// System yellow.
    Yellow,
    /// System green.
    Green,
    /// System mint.
    Mint,
    /// System teal.
    Teal,
    /// System cyan.
    Cyan,
    /// System blue.
    Blue,
    /// System indigo.
    Indigo,
    /// System purple.
    Purple,
    /// System pink.
    Pink,
    /// System brown.
    Brown,
    /// System gray.
    Gray,
    /// The background of content (text, tables): white, or dark in Dark Mode.
    Background,
    /// The window's background (behind content).
    WindowBackground,
    /// The background of controls and grouped content: cards, panels.
    ControlBackground,
    /// Separator lines and grids.
    Separator,
    /// Fully transparent.
    Clear,
    /// A fixed sRGB colour (components 0–1; the same in light and dark).
    Rgb(f64, f64, f64),
    /// A fixed sRGB colour with opacity (components 0–1).
    Rgba(f64, f64, f64, f64),
}

impl Color {
    const NAMED: [Color; 28] = [
        Color::Primary,
        Color::Secondary,
        Color::Tertiary,
        Color::Quaternary,
        Color::Fill,
        Color::SecondaryFill,
        Color::TertiaryFill,
        Color::QuaternaryFill,
        Color::Accent,
        Color::Link,
        Color::Red,
        Color::Orange,
        Color::Yellow,
        Color::Green,
        Color::Mint,
        Color::Teal,
        Color::Cyan,
        Color::Blue,
        Color::Indigo,
        Color::Purple,
        Color::Pink,
        Color::Brown,
        Color::Gray,
        Color::Background,
        Color::WindowBackground,
        Color::ControlBackground,
        Color::Separator,
        Color::Clear,
    ];

    /// An opaque sRGB colour (components 0–1).
    pub const fn rgb(r: f64, g: f64, b: f64) -> Color {
        Color::Rgb(r, g, b)
    }

    /// An sRGB colour with opacity (components 0–1).
    pub const fn rgba(r: f64, g: f64, b: f64, a: f64) -> Color {
        Color::Rgba(r, g, b, a)
    }

    /// A colour from a hex string: `"#3a7bd5"`, `"3a7bd5"`, or with opacity
    /// `"#3a7bd580"`. Black for anything else.
    pub fn hex(hex: &str) -> Color {
        let h = hex.trim_start_matches('#');
        let byte = |i: usize| h.get(i..i + 2).and_then(|b| u8::from_str_radix(b, 16).ok()).map_or(0.0, |b| f64::from(b) / 255.0);
        match h.len() {
            8 => Color::Rgba(byte(0), byte(2), byte(4), byte(6)),
            6 => Color::Rgb(byte(0), byte(2), byte(4)),
            _ => Color::Rgb(0.0, 0.0, 0.0),
        }
    }

    /// The same colour at `opacity` (0–1), on top of its own.
    pub fn opacity(self, opacity: f64) -> Color {
        match self.components() {
            Some((r, g, b, a)) => Color::Rgba(r, g, b, a * opacity),
            None => self,
        }
    }

    /// Its sRGB components (red, green, blue, opacity), resolved for the
    /// current appearance for the named colours.
    pub fn components(self) -> Option<(f64, f64, f64, f64)> {
        match self {
            Color::Rgb(r, g, b) => Some((r, g, b, 1.0)),
            Color::Rgba(r, g, b, a) => Some((r, g, b, a)),
            _ => {
                let c = self.ns().colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
                Some((c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent()))
            }
        }
    }

    /// The `NSColor` (dynamic for the named colours).
    pub fn ns(self) -> Retained<NSColor> {
        match self {
            Color::Primary => NSColor::textColor(),
            Color::Secondary => NSColor::secondaryLabelColor(),
            Color::Tertiary => NSColor::tertiaryLabelColor(),
            Color::Quaternary => NSColor::quaternaryLabelColor(),
            Color::Fill => NSColor::systemFillColor(),
            Color::SecondaryFill => NSColor::secondarySystemFillColor(),
            Color::TertiaryFill => NSColor::tertiarySystemFillColor(),
            Color::QuaternaryFill => NSColor::quaternarySystemFillColor(),
            Color::Accent => NSColor::controlAccentColor(),
            Color::Link => NSColor::linkColor(),
            Color::Red => NSColor::systemRedColor(),
            Color::Orange => NSColor::systemOrangeColor(),
            Color::Yellow => NSColor::systemYellowColor(),
            Color::Green => NSColor::systemGreenColor(),
            Color::Mint => NSColor::systemMintColor(),
            Color::Teal => NSColor::systemTealColor(),
            Color::Cyan => NSColor::systemCyanColor(),
            Color::Blue => NSColor::systemBlueColor(),
            Color::Indigo => NSColor::systemIndigoColor(),
            Color::Purple => NSColor::systemPurpleColor(),
            Color::Pink => NSColor::systemPinkColor(),
            Color::Brown => NSColor::systemBrownColor(),
            Color::Gray => NSColor::systemGrayColor(),
            Color::Background => NSColor::textBackgroundColor(),
            Color::WindowBackground => NSColor::windowBackgroundColor(),
            Color::ControlBackground => NSColor::controlBackgroundColor(),
            Color::Separator => NSColor::separatorColor(),
            Color::Clear => NSColor::clearColor(),
            Color::Rgb(r, g, b) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, 1.0),
            Color::Rgba(r, g, b, a) => NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a),
        }
    }

    /// The colour an `NSColor` is: a named one if it's one of those, else
    /// its sRGB components.
    pub fn from_ns(color: &NSColor) -> Option<Color> {
        Self::NAMED.into_iter().find(|c| c.ns().isEqual(Some(color))).or_else(|| {
            let c = color.colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())?;
            let (r, g, b, a) = (c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent());
            Some(if a >= 1.0 { Color::Rgb(r, g, b) } else { Color::Rgba(r, g, b, a) })
        })
    }
}

/// How a run of text looks. What it leaves unset stays as the editor's own
/// (its font and text colour).
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct TextStyle {
    /// The text colour.
    pub color: Option<Color>,
    /// A background behind the run.
    pub background: Option<Color>,
    /// Bold (the font's bold face).
    pub bold: bool,
    /// Italic (the font's italic face, where it has one).
    pub italic: bool,
    /// Underlined.
    pub underline: bool,
}

impl TextStyle {
    /// A style that changes nothing.
    pub fn new() -> Self {
        Self::default()
    }

    /// With this text colour.
    pub fn color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    /// With this background.
    pub fn background(mut self, color: Color) -> Self {
        self.background = Some(color);
        self
    }

    /// Bold.
    pub fn bold(mut self) -> Self {
        self.bold = true;
        self
    }

    /// Italic.
    pub fn italic(mut self) -> Self {
        self.italic = true;
        self
    }

    /// Underlined.
    pub fn underline(mut self) -> Self {
        self.underline = true;
        self
    }
}

/// UTF-16 offsets of every byte offset of `text` (inside a character: that
/// character's start), plus the end.
fn utf16_map(text: &str) -> Vec<usize> {
    let mut map = Vec::with_capacity(text.len() + 1);
    let mut units = 0;
    for c in text.chars() {
        map.extend(std::iter::repeat_n(units, c.len_utf8()));
        units += c.len_utf16();
    }
    map.push(units);
    map
}

impl Inner {
    /// Styles the text with `runs`: what differs from the runs shown before
    /// (and the `edited` UTF-16 range) is reset to the editor's font and
    /// colour, then given its runs' styles. `None` restyles everything.
    /// With an `edited` range it runs inside the storage's own edit
    /// (willProcessEditing), so it opens no edit of its own; `only` limits
    /// a restyle outside an edit to a UTF-16 span. True when part of an
    /// edit's span was newly left for just after it.
    fn apply_styles(&self, runs: Vec<(Range<usize>, TextStyle)>, edited: Option<NSRange>, only: Option<(usize, usize)>) -> bool {
        // SAFETY: the text view's own storage, on the main thread.
        let Some(storage) = (unsafe { self.view.textStorage() }) else { return false };
        let text = storage.string().to_string();
        let map = utf16_map(&text);
        let len16 = *map.last().unwrap_or(&0);
        let shown = self.shown.borrow_mut().take();
        // The span whose runs changed: runs equal before it (a prefix) and,
        // shifted by the edit, after it (a suffix) keep their styles.
        let region = match (shown, edited) {
            (Some((old_len, old)), Some(edited)) => {
                let delta = text.len() as isize - old_len as isize;
                let shift = |r: &Range<usize>| (r.start as isize + delta) as usize..(r.end as isize + delta) as usize;
                let prefix = old.iter().zip(&runs).take_while(|(a, b)| a == b).count();
                let suffix = old[prefix..]
                    .iter()
                    .rev()
                    .zip(runs[prefix..].iter().rev())
                    .take_while(|(a, b)| a.1 == b.1 && a.0.start as isize + delta >= 0 && shift(&a.0) == b.0)
                    .count();
                let lo = if prefix > 0 { runs[prefix - 1].0.end.min(text.len()) } else { 0 };
                let hi = if suffix > 0 { runs[runs.len() - suffix].0.start.min(text.len()) } else { text.len() };
                // Runs may overlap or come unsorted (a search match over a
                // keyword): the span also covers every changed run itself,
                // old and new, wherever it sits among the others.
                let clamp = |i: isize| (i.max(0) as usize).min(text.len());
                let changed_new = runs[prefix..runs.len() - suffix].iter().map(|(r, _)| (r.start.min(text.len()), r.end.min(text.len())));
                let changed_old = old[prefix..old.len() - suffix].iter().flat_map(|(r, _)| [(clamp(r.start as isize), clamp(r.end as isize)), (clamp(r.start as isize + delta), clamp(r.end as isize + delta))]);
                let (lo, hi) = changed_new.chain(changed_old).fold((lo, hi.max(lo)), |(lo, hi), (a, b)| (lo.min(a), hi.max(b)));
                let (lo, hi) = (map[lo].min(edited.location), map[hi.max(lo)].max(edited.location + edited.length).min(len16));
                lo..hi
            }
            _ => only.map_or(0..len16, |(lo, hi)| lo.min(len16)..hi.min(len16)),
        };
        // Inside an edit only the edited characters are styled: attributes
        // changed past them widen the storage's edited range, and the text
        // view puts the caret at its end (typing mid-line jumped to the next
        // run). The rest of the span is restyled just after the edit (all
        // of the text if an earlier edit's span is still waiting).
        let mut deferred = false;
        let region = match edited {
            Some(e) => {
                let inside = region.start.max(e.location)..region.end.min(e.location + e.length);
                if inside != region {
                    deferred = self.deferred.get().is_none();
                    self.deferred.set(Some(if deferred { (region.start, region.end) } else { (0, usize::MAX) }));
                }
                inside.start..inside.end.max(inside.start)
            }
            None => region,
        };
        let font = self.font.borrow().clone();
        self.styling.set(true);
        // SAFETY: attribute keys and values of the documented types (fonts,
        // colours, an NSNumber for the underline style), in range.
        unsafe {
            use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
            if edited.is_none() {
                storage.beginEditing();
            }
            let base = objc2_foundation::NSDictionary::from_retained_objects(
                &[NSFontAttributeName, NSForegroundColorAttributeName],
                &[Retained::into_super(Retained::into_super(font.clone())), Retained::into_super(Retained::into_super(NSColor::textColor()))],
            );
            storage.setAttributes_range(Some(&base), NSRange::new(region.start, region.end - region.start));
            let fonts = objc2_app_kit::NSFontManager::sharedFontManager(mtm());
            for (range, style) in &runs {
                let (start, end) = (map[range.start.min(text.len())].max(region.start), map[range.end.min(text.len())].min(region.end));
                if start >= end {
                    continue;
                }
                let r = NSRange::new(start, end - start);
                if let Some(c) = style.color {
                    storage.addAttribute_value_range(NSForegroundColorAttributeName, &c.ns(), r);
                }
                if let Some(c) = style.background {
                    storage.addAttribute_value_range(NSBackgroundColorAttributeName, &c.ns(), r);
                }
                if style.bold || style.italic {
                    let mut f = font.clone();
                    if style.bold {
                        f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::BoldFontMask);
                    }
                    if style.italic {
                        f = fonts.convertFont_toHaveTrait(&f, objc2_app_kit::NSFontTraitMask::ItalicFontMask);
                    }
                    storage.addAttribute_value_range(NSFontAttributeName, &f, r);
                }
                if style.underline {
                    storage.addAttribute_value_range(NSUnderlineStyleAttributeName, &objc2_foundation::NSNumber::new_isize(1), r);
                }
            }
            if edited.is_none() {
                storage.endEditing();
            }
        }
        self.styling.set(false);
        *self.shown.borrow_mut() = Some((text.len(), runs));
        // What's typed next starts plain (the highlighter restyles it).
        // Not during an edit: the text view still has the selection from
        // before it, and setting typing attributes reads the attributes
        // there, past the end of shorter text (an NSRangeException that
        // stopped the edit halfway and left TextKit 2's layout behind the
        // text). After an edit the text view takes them from the text
        // around the caret, which is already styled.
        if edited.is_some() {
            return deferred;
        }
        // SAFETY: a dictionary of standard attributes.
        unsafe {
            use objc2_app_kit::{NSFontAttributeName, NSForegroundColorAttributeName};
            let typing = objc2_foundation::NSDictionary::from_retained_objects(
                &[NSFontAttributeName, NSForegroundColorAttributeName],
                &[Retained::into_super(Retained::into_super(font)), Retained::into_super(Retained::into_super(NSColor::textColor()))],
            );
            self.view.setTypingAttributes(&typing);
        }
        false
    }
}

impl Data for Inner {
    fn push(&self, event: TextEvent) {
        let mut events = self.events.borrow_mut();
        // `Changed` means "read the text again": one queued is enough (an
        // edit is reported by both the text storage and textDidChange:).
        if event == TextEvent::Changed && events.contains(&TextEvent::Changed) {
            return;
        }
        // Keep only the latest of a run of selection moves.
        if let (TextEvent::Selection(_), Some(TextEvent::Selection(_))) = (&event, events.back()) {
            events.pop_back();
        }
        events.push_back(event);
        drop(events);
        crate::request_redraw();
    }

    fn quiet(&self) -> bool {
        self.quiet.get()
    }

    fn complete(&self) -> Option<(NSRange, Vec<String>)> {
        let f = self.completer.borrow().clone()?;
        let text = self.view.string().to_string();
        let sel = self.view.selectedRange();
        let caret = utf16_to_bytes(&text, sel.location + sel.length, 0).start;
        let c = f(&text, caret)?;
        let start = c.range.start.min(caret);
        let (location, length) = bytes_to_utf16(&text, start..caret);
        Some((NSRange::new(location, length), c.items))
    }

    fn has_completer(&self) -> bool {
        self.completer.borrow().is_some()
    }

    fn offered(&self, items: &[String]) {
        *self.offered.borrow_mut() = items.to_vec();
    }

    fn composing(&self) -> bool {
        self.view.hasMarkedText()
    }

    fn undo_manager(&self) -> Retained<NSUndoManager> {
        self.undo.borrow().clone()
    }

    fn highlight(&self, edited: Option<NSRange>) -> bool {
        if self.styling.get() {
            return false;
        }
        let Some(f) = self.highlighter.borrow().clone() else { return false };
        let runs = f(&self.view.string().to_string());
        self.apply_styles(runs, edited, None)
    }

    fn finish_highlight(&self) {
        let Some(span) = self.deferred.take() else { return };
        if self.styling.get() || self.view.hasMarkedText() {
            return;
        }
        let Some(f) = self.highlighter.borrow().clone() else { return };
        let runs = f(&self.view.string().to_string());
        self.apply_styles(runs, None, Some(span));
    }
}

impl Drop for ViewIvars {
    fn drop(&mut self) {
        crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
    }
}

impl Drop for DelegateIvars {
    fn drop(&mut self) {
        crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
    }
}

impl Drop for Inner {
    fn drop(&mut self) {
        // The text view and its storage hold the delegate weakly: detach it first.
        self.view.setDelegate(None);
        if let Some(storage) = unsafe { self.view.textStorage() } {
            storage.setDelegate(None);
        }
        crate::testing::LIVE_MODELS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
        crate::keys::set_accepts_tab(self.id, false);
        if self.mounted.get() {
            crate::unmount(self.id);
        }
    }
}

/// A native plain-text editor. Cheap to clone (a handle); main thread only.
#[derive(Clone)]
pub struct TextModel {
    inner: Rc<Inner>,
}

impl std::fmt::Debug for TextModel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "TextModel({:?})", self.inner.id)
    }
}

impl TextModel {
    /// Creates the editor (added to the window the first time the host draws
    /// it). Defaults: plain text, system font 13 pt, continuous spell
    /// checking, find bar, undo, Tab inserts a tab (Ctrl-Tab moves focus on).
    pub fn new(id: ViewId, text: &str) -> Self {
        let mtm = mtm();
        let size = NSSize::new(400.0, 300.0);
        let scroll = NSScrollView::initWithFrame(NSScrollView::alloc(mtm), NSRect::new(NSPoint::ZERO, size));
        scroll.setHasVerticalScroller(true);
        scroll.setAutohidesScrollers(true);
        scroll.setBorderType(objc2_app_kit::NSBorderType::NoBorder);

        // The standard recipe for a text view in a scroll view: width tracks
        // the scroll view, height grows with the text.
        crate::testing::LIVE_OBJC.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
        crate::testing::LIVE_MODELS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let view = HostTextView::alloc(mtm).set_ivars(ViewIvars { data: RefCell::new(None), composing: Cell::new(false) });
        let view: Retained<HostTextView> = unsafe { msg_send![super(view), initWithFrame: NSRect::new(NSPoint::ZERO, size)] };
        view.setMinSize(NSSize::new(0.0, size.height));
        view.setMaxSize(NSSize::new(f64::MAX, f64::MAX));
        view.setVerticallyResizable(true);
        view.setHorizontallyResizable(false);
        view.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
        // SAFETY: the text view's own container.
        if let Some(container) = unsafe { view.textContainer() } {
            container.setContainerSize(NSSize::new(size.width, f64::MAX));
            container.setWidthTracksTextView(true);
        }
        view.setRichText(false);
        view.setImportsGraphics(false);
        view.setAllowsUndo(true);
        view.setUsesFindBar(true);
        view.setContinuousSpellCheckingEnabled(true);
        view.setFont(Some(&NSFont::systemFontOfSize(13.0)));
        view.setTextContainerInset(NSSize::new(4.0, 6.0));
        view.setString(&NSString::from_str(text));
        scroll.setDocumentView(Some(&view));

        let delegate = Delegate::alloc(mtm).set_ivars(DelegateIvars { data: RefCell::new(None) });
        let delegate: Retained<Delegate> = unsafe { msg_send![super(delegate), init] };

        let inner = Rc::new(Inner {
            id,
            events: RefCell::new(VecDeque::new()),
            quiet: Cell::new(false),
            mounted: Cell::new(false),
            undo: RefCell::new(NSUndoManager::new(mtm)),
            shared: Cell::new(false),
            scroll,
            view: view.clone(),
            _delegate: delegate.clone(),
            font: RefCell::new(NSFont::systemFontOfSize(13.0)),
            highlighter: RefCell::new(None),
            completer: RefCell::new(None),
            offered: RefCell::new(Vec::new()),
            styling: Cell::new(false),
            shown: RefCell::new(None),
            deferred: Cell::new(None),
        });
        let weak: Weak<dyn Data> = Rc::downgrade(&inner) as Weak<dyn Data>;
        *view.ivars().data.borrow_mut() = Some(weak.clone());
        *delegate.ivars().data.borrow_mut() = Some(weak);
        // SAFETY: the delegate lives as long as the model, which removes the view.
        view.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
        if let Some(storage) = unsafe { view.textStorage() } {
            // Weak in AppKit, like the view's delegate; detached in Drop.
            storage.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
        }
        crate::keys::set_accepts_tab(id, true);
        Self { inner }
    }

    /// The view id the editor was created with.
    pub fn id(&self) -> ViewId {
        self.inner.id
    }

    /// Adds the editor to the attached window if it isn't yet (the host
    /// widget calls this before placing it).
    pub fn ensure_mounted(&self) {
        if !self.inner.mounted.get() && crate::is_attached() {
            crate::mount(self.inner.id, Retained::into_super(self.inner.scroll.clone()));
            self.inner.mounted.set(true);
        }
    }

    /// The whole text.
    pub fn text(&self) -> String {
        self.inner.view.string().to_string()
    }

    /// Replaces the whole text (e.g. loading a document). Clears the undo
    /// history and emits no event.
    pub fn set_text(&self, text: &str) {
        self.inner.quiet.set(true);
        self.inner.view.setString(&NSString::from_str(text));
        self.inner.quiet.set(false);
        self.clear_undo();
    }

    /// Removes this editor's edits from its undo history (only this
    /// editor's, when the history is shared).
    fn clear_undo(&self) {
        let undo = self.inner.undo.borrow();
        if self.inner.shared.get() {
            // AppKit registers typing with the text storage as the target.
            unsafe {
                undo.removeAllActionsWithTarget(&self.inner.view);
                if let Some(storage) = self.inner.view.textStorage() {
                    undo.removeAllActionsWithTarget(&storage);
                }
            }
        } else {
            undo.removeAllActions();
        }
    }

    /// Records edits in `manager` (e.g. the window's, shared with other
    /// views and app-level changes) instead of the editor's own history, or
    /// in a fresh history of its own again with `None`. Edits recorded so
    /// far are dropped.
    pub fn share_undo(&self, manager: Option<&NSUndoManager>) {
        self.clear_undo();
        let mtm = MainThreadMarker::from(&*self.inner.view);
        let next = match manager {
            Some(m) => m.retain(),
            None => NSUndoManager::new(mtm),
        };
        *self.inner.undo.borrow_mut() = next;
        self.inner.shared.set(manager.is_some());
    }

    /// The undo history the editor records in.
    pub fn undo_manager(&self) -> Retained<NSUndoManager> {
        self.inner.undo.borrow().clone()
    }

    /// Replaces the selection as if typed: undoable, emits `Changed`.
    pub fn replace_selection(&self, text: &str) {
        let view = &self.inner.view;
        let range = view.selectedRange();
        let string = NSString::from_str(text);
        if view.shouldChangeTextInRange_replacementString(range, Some(&string)) {
            view.replaceCharactersInRange_withString(range, &string);
            view.didChangeText();
        }
    }

    /// Selected byte range (empty: the caret).
    pub fn selection(&self) -> Range<usize> {
        let r = self.inner.view.selectedRange();
        utf16_to_bytes(&self.text(), r.location, r.length)
    }

    /// Selects a byte range (emits no event).
    pub fn set_selection(&self, range: Range<usize>) {
        let (location, length) = bytes_to_utf16(&self.text(), range);
        self.inner.quiet.set(true);
        self.inner.view.setSelectedRange(NSRange::new(location, length));
        self.inner.view.scrollRangeToVisible(NSRange::new(location, length));
        self.inner.quiet.set(false);
    }

    /// Whether an input method is composing, and its marked text.
    pub fn composition(&self) -> Option<String> {
        let view = &self.inner.view;
        view.hasMarkedText().then(|| {
            let r = view.markedRange();
            utf16_slice(&view.string().to_string(), r.location, r.length)
        })
    }

    /// Read-only (`false`) or editable. Read-only text can still be selected and copied.
    pub fn set_editable(&self, editable: bool) {
        self.inner.view.setEditable(editable);
    }

    /// Whether the user can edit the text.
    pub fn is_editable(&self) -> bool {
        self.inner.view.isEditable()
    }

    /// Font: `None` for the system font, else a family or PostScript name.
    pub fn set_font(&self, name: Option<&str>, size: f64) {
        let font = match name {
            Some(name) => NSFont::fontWithName_size(&NSString::from_str(name), size),
            None => Some(NSFont::systemFontOfSize(size)),
        };
        if let Some(font) = font {
            self.inner.view.setFont(Some(&font));
            *self.inner.font.borrow_mut() = font;
            self.inner.highlight(None);
        }
    }

    /// Completes as the user types, in AppKit's completion list: `f` gets
    /// the text and the caret (a byte offset) and says what it completes
    /// there and with which words ([`Completion`]), or `None`. Typing a
    /// word character or a dot opens the list (⌥⎋ or F5 open it too);
    /// typing on filters it (`f` is asked again), ↑ and ↓ move, Return or
    /// Tab or a click puts the word in, and Escape closes it.
    pub fn set_completer(&self, f: Option<impl Fn(&str, usize) -> Option<Completion> + 'static>) {
        *self.inner.completer.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Completer>);
    }

    /// Opens the completion list at the caret now (as ⌥⎋ does).
    pub fn complete(&self) {
        // SAFETY: AppKit's completion, on the main thread.
        unsafe { self.inner.view.complete(None) };
    }

    /// The words the completion list showed last (for checks).
    pub fn offered_completions(&self) -> Vec<String> {
        self.inner.offered.borrow().clone()
    }

    /// Styles the text with `f`: given the text, it returns runs (UTF-8
    /// byte ranges) and their styles; the rest is plain. It runs now and
    /// after every edit (typing, paste, undo, `set_text`), before the edit
    /// is drawn, so keep it fast: it sees the whole text each time. `None`
    /// makes the text plain again.
    pub fn set_highlighter(&self, f: Option<impl Fn(&str) -> Vec<(Range<usize>, TextStyle)> + 'static>) {
        *self.inner.highlighter.borrow_mut() = f.map(|f| Rc::new(f) as Rc<Highlighter>);
        self.restyle();
    }

    /// Runs the highlighter again, for when what it depends on changed
    /// other than the text (a search term, a theme).
    pub fn restyle(&self) {
        if self.inner.highlighter.borrow().is_some() {
            self.inner.highlight(None);
        } else {
            self.inner.apply_styles(Vec::new(), None, None);
        }
    }

    /// The style of the character at byte `offset`, as shown (for checks).
    pub fn style_at(&self, offset: usize) -> TextStyle {
        // SAFETY: the text view's own storage, on the main thread.
        let Some(storage) = (unsafe { self.inner.view.textStorage() }) else { return TextStyle::default() };
        let text = storage.string().to_string();
        let Some(&index) = utf16_map(&text).get(offset).filter(|_| offset < text.len()) else { return TextStyle::default() };
        let mut style = TextStyle::default();
        // SAFETY: reading standard attributes at an index inside the text.
        unsafe {
            use objc2_app_kit::{NSBackgroundColorAttributeName, NSFontAttributeName, NSForegroundColorAttributeName, NSUnderlineStyleAttributeName};
            let at = |key| storage.attribute_atIndex_effectiveRange(key, index, std::ptr::null_mut());
            style.color = at(NSForegroundColorAttributeName)
                .and_then(|c| c.downcast::<NSColor>().ok())
                .and_then(|c| Color::from_ns(&c))
                .filter(|c| *c != Color::Primary);
            style.background = at(NSBackgroundColorAttributeName).and_then(|c| c.downcast::<NSColor>().ok()).and_then(|c| Color::from_ns(&c));
            if let Some(font) = at(NSFontAttributeName).and_then(|f| f.downcast::<NSFont>().ok()) {
                let traits = objc2_app_kit::NSFontManager::sharedFontManager(mtm()).traitsOfFont(&font);
                style.bold = traits.contains(objc2_app_kit::NSFontTraitMask::BoldFontMask);
                style.italic = traits.contains(objc2_app_kit::NSFontTraitMask::ItalicFontMask);
            }
            style.underline = at(NSUnderlineStyleAttributeName)
                .and_then(|n| n.downcast::<objc2_foundation::NSNumber>().ok())
                .is_some_and(|n| n.integerValue() != 0);
        }
        style
    }

    /// Rich text (`true`) or plain (`false`, the default). Rich, the user
    /// styles the text: fonts and sizes (the font panel, ⌘T), bold, italic
    /// and underline (⌘B, ⌘I, ⌘U), colours, alignment, spacing and lists
    /// (the ruler and the format bar); pasted text keeps its styles, and
    /// pictures can be pasted or dropped in. Don't combine it with a
    /// highlighter, which restyles the text itself.
    pub fn set_rich(&self, rich: bool) {
        let v = &self.inner.view;
        v.setRichText(rich);
        v.setImportsGraphics(rich);
        v.setUsesFontPanel(rich);
        v.setUsesRuler(rich);
        if !rich {
            v.setUsesInspectorBar(false);
            v.setRulerVisible(false);
        }
    }

    /// Whether the text is rich (see [`set_rich`](Self::set_rich)).
    pub fn is_rich(&self) -> bool {
        self.inner.view.isRichText()
    }

    /// TextEdit's format bar above the text (rich text): font, size,
    /// colours, bold, italic, underline, alignment, line spacing and lists.
    pub fn set_format_bar(&self, shown: bool) {
        self.inner.view.setUsesInspectorBar(shown);
    }

    /// Whether the format bar is shown.
    pub fn has_format_bar(&self) -> bool {
        self.inner.view.usesInspectorBar()
    }

    /// The ruler above the text (rich text): margins, tab stops,
    /// alignment, spacing and lists. Format ▸ Text ▸ Show Ruler (⌃⌘R)
    /// toggles it too.
    pub fn set_ruler_visible(&self, shown: bool) {
        self.inner.view.setRulerVisible(shown);
    }

    /// Whether the ruler is shown.
    pub fn is_ruler_visible(&self) -> bool {
        self.inner.view.isRulerVisible()
    }

    fn whole(&self) -> Option<(Retained<NSTextStorage>, NSRange)> {
        // SAFETY: the text view's own storage, on the main thread.
        let storage = unsafe { self.inner.view.textStorage() }?;
        let len = storage.length();
        Some((storage, NSRange::new(0, len)))
    }

    /// The text with its styles, as RTF (what TextEdit saves). Pictures
    /// aren't included.
    pub fn rtf(&self) -> Vec<u8> {
        let Some((storage, range)) = self.whole() else { return Vec::new() };
        let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::new();
        // SAFETY: NSAttributedString's AppKit addition, with no document attributes.
        let data: Option<Retained<objc2_foundation::NSData>> = unsafe { msg_send![&*storage, RTFFromRange: range, documentAttributes: &*attributes] };
        data.map(|d| d.to_vec()).unwrap_or_default()
    }

    /// Replaces the text with RTF's (from [`rtf`](Self::rtf), TextEdit or
    /// Word), styles and all. Clears the undo history and emits no event.
    /// False (and nothing changes) if `rtf` isn't RTF.
    pub fn set_rtf(&self, rtf: &[u8]) -> bool {
        let data = objc2_foundation::NSData::with_bytes(rtf);
        // SAFETY: NSAttributedString's AppKit initialiser; nil if it isn't RTF.
        let text: Option<Retained<objc2_foundation::NSAttributedString>> =
            unsafe { msg_send![objc2_foundation::NSAttributedString::alloc(), initWithRTF: &*data, documentAttributes: std::ptr::null_mut::<*mut AnyObject>()] };
        self.load(text)
    }

    fn load(&self, text: Option<Retained<objc2_foundation::NSAttributedString>>) -> bool {
        let (Some(text), Some((storage, _))) = (text, self.whole()) else { return false };
        self.inner.quiet.set(true);
        storage.setAttributedString(&text);
        self.inner.quiet.set(false);
        self.clear_undo();
        true
    }

    /// The text with its styles as an HTML document (for the web, mail or
    /// the clipboard).
    pub fn html(&self) -> String {
        let Some((storage, range)) = self.whole() else { return String::new() };
        // SAFETY: AppKit's document type constants and NSAttributedString's
        // AppKit addition; nil on failure.
        let data: Option<Retained<objc2_foundation::NSData>> = unsafe {
            let html: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
            let attributes = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(&[objc2_app_kit::NSDocumentTypeDocumentAttribute], &[html]);
            msg_send![&*storage, dataFromRange: range, documentAttributes: &*attributes, error: std::ptr::null_mut::<*mut AnyObject>()]
        };
        data.map(|d| String::from_utf8_lossy(&d.to_vec()).into_owned()).unwrap_or_default()
    }

    /// Replaces the text with HTML's, styles and all (headings, bold,
    /// links, lists). Clears the undo history and emits no event. False
    /// if AppKit can't read it.
    pub fn set_html(&self, html: &str) -> bool {
        let data = objc2_foundation::NSData::with_bytes(html.as_bytes());
        // SAFETY: as in `html`; the reader runs on the main thread, as it must.
        let text: Option<Retained<objc2_foundation::NSAttributedString>> = unsafe {
            let kind: &AnyObject = objc2_app_kit::NSHTMLTextDocumentType.as_ref();
            let utf8 = objc2_foundation::NSNumber::new_usize(4); // NSUTF8StringEncoding
            let options = objc2_foundation::NSDictionary::<NSString, AnyObject>::from_slices(
                &[objc2_app_kit::NSDocumentTypeDocumentOption, objc2_app_kit::NSCharacterEncodingDocumentOption],
                &[kind, utf8.as_ref()],
            );
            msg_send![objc2_foundation::NSAttributedString::alloc(), initWithData: &*data, options: &*options, documentAttributes: std::ptr::null_mut::<*mut AnyObject>(), error: std::ptr::null_mut::<*mut AnyObject>()]
        };
        self.load(text)
    }

    /// The current font size in points.
    pub fn font_size(&self) -> Option<f64> {
        self.inner.view.font().map(|f| f.pointSize())
    }

    /// Space between the text and the view's edges, in points.
    pub fn set_insets(&self, horizontal: f64, vertical: f64) {
        self.inner.view.setTextContainerInset(NSSize::new(horizontal, vertical));
    }

    /// Continuous spell checking (on by default).
    pub fn set_spell_checking(&self, on: bool) {
        self.inner.view.setContinuousSpellCheckingEnabled(on);
    }

    /// Grammar checking (off by default).
    pub fn set_grammar_checking(&self, on: bool) {
        self.inner.view.setGrammarCheckingEnabled(on);
    }

    /// Input for code (`true`) or prose (`false`, the default): code turns
    /// off what helps prose and breaks code: smart quotes and dashes (`"`
    /// becoming `“`), text replacement, spelling correction, spell checking
    /// and the spaces smart paste adds.
    pub fn set_code_input(&self, code: bool) {
        let view = &self.inner.view;
        view.setAutomaticQuoteSubstitutionEnabled(!code);
        view.setAutomaticDashSubstitutionEnabled(!code);
        view.setAutomaticTextReplacementEnabled(!code);
        view.setAutomaticSpellingCorrectionEnabled(!code);
        view.setContinuousSpellCheckingEnabled(!code);
        view.setSmartInsertDeleteEnabled(!code);
    }

    /// Whether plain Tab inserts a tab (default) or moves focus on.
    pub fn set_accepts_tab(&self, accepts: bool) {
        crate::keys::set_accepts_tab(self.inner.id, accepts);
    }

    /// Shows the find bar, as Edit ▸ Find ▸ Find… (⌘F) does in a Ferrokit
    /// app while the focus is in the editor.
    pub fn show_find(&self) {
        // NSTextFinderActionShowFindInterface = 1, passed as the sender's tag.
        let item = objc2_app_kit::NSMenuItem::new(mtm());
        item.setTag(1);
        let () = unsafe { msg_send![&*self.inner.view, performTextFinderAction: &*item] };
    }

    /// Whether long lines wrap at the editor's width (the default), or run
    /// on with a horizontal scroller (code, logs, tables of text).
    pub fn set_wraps(&self, wraps: bool) {
        let (view, scroll) = (&self.inner.view, &self.inner.scroll);
        // SAFETY: the text view's own container.
        let Some(container) = (unsafe { view.textContainer() }) else { return };
        if container.widthTracksTextView() == wraps {
            return;
        }
        let width = scroll.contentSize().width;
        scroll.setHasHorizontalScroller(!wraps);
        view.setHorizontallyResizable(!wraps);
        container.setWidthTracksTextView(wraps);
        if wraps {
            // Back to the scroll view's width, which the container follows.
            let mut frame = view.frame();
            frame.size.width = width;
            view.setFrame(frame);
            container.setContainerSize(NSSize::new(width, f64::MAX));
        } else {
            // (Wide enough for any line; the largest number breaks layout.)
            container.setContainerSize(NSSize::new(1.0e7, f64::MAX));
            view.setMaxSize(NSSize::new(1.0e7, f64::MAX));
        }
        view.sizeToFit();
        view.setNeedsDisplay(true);
    }

    /// Whether long lines wrap (see [`set_wraps`](Self::set_wraps)).
    pub fn wraps(&self) -> bool {
        // SAFETY: the text view's own container.
        unsafe { self.inner.view.textContainer() }.is_none_or(|c| c.widthTracksTextView())
    }

    /// Whether the find bar is showing.
    pub fn is_find_visible(&self) -> bool {
        unsafe { msg_send![&*self.inner.scroll, isFindBarVisible] }
    }

    /// Whether there is something to undo.
    pub fn can_undo(&self) -> bool {
        self.inner.undo.borrow().canUndo()
    }

    /// Undoes the last edit (as ⌘Z does).
    pub fn undo(&self) {
        let undo = self.undo_manager();
        if undo.canUndo() {
            undo.undo();
        }
    }

    /// Takes the queued user events (for the host widget).
    pub fn drain_events(&self) -> Vec<TextEvent> {
        self.inner.events.borrow_mut().drain(..).collect()
    }

    /// The `NSScrollView` holding the text view, for hosts that place it
    /// themselves (no [`crate::attach`]ed window).
    pub fn scroll_view(&self) -> Retained<NSScrollView> {
        self.inner.scroll.clone()
    }

    /// The underlying `NSTextView` (escape hatch).
    pub fn text_view(&self) -> Retained<NSTextView> {
        Retained::into_super(self.inner.view.clone())
    }
}

#[cfg(test)]
mod tests {
    use super::{bytes_to_utf16, utf16_to_bytes};

    #[test]
    fn offsets_round_trip() {
        let t = "a東京😀b";
        // a=1 unit/1 byte, 東,京=1 unit/3 bytes, 😀=2 units/4 bytes.
        assert_eq!(utf16_to_bytes(t, 1, 2), 1..7);
        assert_eq!(utf16_to_bytes(t, 3, 2), 7..11);
        assert_eq!(bytes_to_utf16(t, 7..11), (3, 2));
        assert_eq!(bytes_to_utf16(t, 0..t.len()), (0, 6));
        assert_eq!(utf16_to_bytes(t, 6, 0), 12..12);
        assert_eq!(utf16_to_bytes(t, 99, 1), 12..12);
    }
}