quadraui 0.6.0

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
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
//! Core Text infrastructure — font creation, metrics, text measurement
//! and rendering against a borrowed `CGContextRef`.
//!
//! ## Coordinate convention for `draw_text`
//!
//! Callers pass `(x, y)` in **view-local points with top-left origin**
//! — matching the rest of quadraui. `draw_text` flips the text matrix
//! internally so glyphs render right-side up inside our flipped
//! `QuadraView`, and offsets by ascent so `y` corresponds to the top
//! of the glyph cell rather than the baseline.
//!
//! ## Why direct CoreGraphics FFI for the draw call
//!
//! The high-level `CTLine::draw(context: &CGContext)` wrapper expects
//! an owned `core_graphics::context::CGContext`, which would release
//! the pointer when dropped — fatal for the borrowed pointer AppKit
//! hands us inside `drawRect:`. We use the wrapper for line / font
//! construction and drop to `extern "C"` for `CTLineDraw` +
//! `CGContextSetTextPosition` + matrix manipulation.

use core_foundation::array::{CFArray, CFArrayRef};
use core_foundation::attributed_string::{CFAttributedString, CFAttributedStringRef};
use core_foundation::base::{CFAllocatorRef, TCFType};
use core_foundation::boolean::CFBoolean;
use core_foundation::data::{CFData, CFDataRef};
use core_foundation::dictionary::{CFDictionary, CFDictionaryRef};
use core_foundation::error::CFErrorRef;
use core_foundation::string::{CFString, CFStringRef};
use core_graphics::base::CGFloat;
use core_graphics::data_provider::CGDataProvider;
use core_graphics::font::CGFont;
use core_graphics::geometry::CGAffineTransform;
use core_graphics::sys::{CGContextRef, CGFontRef};
use core_text::font::{self, CTFont, CTFontRef};
use core_text::font_descriptor::{
    self, kCTFontCascadeListAttribute, kCTFontFamilyNameAttribute, CTFontDescriptor,
};
use core_text::line::CTLine;
use core_text::string_attributes::{
    kCTFontAttributeName, kCTForegroundColorFromContextAttributeName,
};
use foreign_types::ForeignType;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};

use crate::testing::TextRun;
use crate::Rect;

/// Aggregate font measurements in points.
///
/// `line_height` follows the standard macOS convention
/// (`ascent + descent + leading`). `char_width` is the advance width
/// of the capital letter `M` — for monospace fonts every glyph shares
/// that advance; for proportional fonts it serves as a reasonable
/// "average glyph width" baseline used by primitives that lay out by
/// cell count (terminal, status bar, etc.).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FontMetrics {
    pub ascent: f64,
    pub descent: f64,
    pub leading: f64,
    pub line_height: f64,
    pub char_width: f64,
}

/// Create a [`CTFont`] for the named family at the given point size.
///
/// Returns `None` only when `CTFontCreateWithName` itself fails, which
/// in practice never happens for an unknown family: Core Text
/// **substitutes a default face (Helvetica) rather than failing**, so a
/// `Some` here does *not* mean "the system has this family". Callers
/// that need "this exact family or nothing" — a `Backend::set_ui_font`
/// / `set_editor_font` caller naming a family that may not be installed
/// — must use [`make_font_exact`] instead.
pub fn make_font(family: &str, size_pt: f64) -> Option<CTFont> {
    font::new_from_name(family, size_pt).ok()
}

/// [`make_font`], but `None` unless Core Text actually resolved the
/// family that was asked for.
///
/// `CTFontCreateWithName` has no "family not found" failure mode — hand
/// it `"Definitely Not A Real Font Family"` and it hands back Helvetica,
/// non-null and perfectly usable, with no indication that a substitution
/// happened. Every caller that means "install this family, or fall back
/// to *my* chosen default" (rather than "or fall back to whatever Core
/// Text feels like") therefore has to compare the resolved font's own
/// name against the request — that check is this function.
///
/// A request matches if it equals (ASCII-case-insensitively) either the
/// resolved font's family name (`"Menlo"`, `"Helvetica"`) or its
/// PostScript name (`"Menlo-Regular"`) — Core Text accepts both spellings
/// in `CTFontCreateWithName`, so both must count as a hit.
pub fn make_font_exact(family: &str, size_pt: f64) -> Option<CTFont> {
    let requested = family.trim();
    let font = make_font(requested, size_pt)?;
    let matched = font.family_name().eq_ignore_ascii_case(requested)
        || font.postscript_name().eq_ignore_ascii_case(requested);
    matched.then_some(font)
}

/// Build the CoreText system UI font (`kCTFontSystemFontType`) at
/// `size_pt` — the default `chrome_font` before any
/// [`crate::Backend::set_ui_font`] call overrides it. This is the CoreText
/// analogue of GTK's `"Sans 11"` / Win-GUI's `"Segoe UI"` chrome default:
/// a proportional face reserved for UI chrome, distinct from whatever
/// monospace family the app installs as the editor font.
///
/// Unlike [`make_font`], this can't fail to resolve a family — Core Text
/// always has *a* system font — so it returns a `CTFont` directly rather
/// than `Option`.
pub fn system_ui_font(size_pt: f64) -> CTFont {
    font::new_ui_font_for_language(font::kCTFontSystemFontType, size_pt, None)
}

/// Build the CoreText system *fixed-pitch* font
/// (`kCTFontUserFixedPitchFontType`) at `size_pt` — the CoreText analogue
/// of GTK/fontconfig's `Monospace` alias and Win-GUI's `Consolas`
/// default, and the resolution target for
/// [`crate::GenericFamily::Monospace`] on this backend.
/// Distinct from [`system_ui_font`], which resolves
/// [`crate::GenericFamily::SansSerif`]/[`crate::GenericFamily::SystemUi`]
/// instead — the two generic requests must land on different native
/// faces here the same way [`super::backend::MacBackend::set_editor_font`]
/// and [`crate::Backend::set_ui_font`] already keep the editor and chrome
/// fonts independent.
///
/// Like [`system_ui_font`], this can't fail to resolve a family — Core
/// Text always has *a* fixed-pitch system font — so it returns a
/// `CTFont` directly rather than `Option`.
pub fn system_monospace_font(size_pt: f64) -> CTFont {
    font::new_ui_font_for_language(font::kCTFontUserFixedPitchFontType, size_pt, None)
}

// ── Nerd-Font fallback ──────────────────────────────────────────────────
//
// macOS has no equivalent of GTK/Pango's implicit per-character font
// cascade (`crate::gtk::with_nerd_font_fallback`) — a `CTFont` built by
// [`make_font`] resolves every character against exactly one family, and
// a Private-Use-Area codepoint (where Nerd Font icon glyphs live) that
// family doesn't cover renders as the last-resort tofu box. Core Text
// *does* support an explicit per-font cascade list
// (`kCTFontCascadeListAttribute`, consulted only for characters the
// primary font can't cover — the same "later entry, uncovered characters
// only" contract Pango's cascade already has), it just has to be
// requested per font rather than applying automatically.

/// Copy `font` with `fallback_families` appended, in order, to its Core
/// Text cascade list — every metric (size, ascent/descent, any symbolic
/// traits `font` already carries) is preserved; only glyph resolution for
/// characters `font`'s own family can't cover changes, consulting each
/// fallback family in turn before Core Text's own system default cascade.
///
/// Reached through [`font_with_builtin_fallback`], which supplies the
/// family list every `MacBackend` font carries.
///
/// Drops to direct CoreText FFI for `CTFontCreateCopyWithAttributes` —
/// the same "the safe wrapper doesn't expose what we need" rationale
/// [`draw_text`]'s own module doc gives for `CTLineDraw`: `core-text`
/// 20.1 only calls this function from its own private
/// `clone_with_font_size`/`clone_with_symbolic_traits` methods (passing
/// `ptr::null()` for the attributes parameter both times), so a caller
/// that wants to pass real attributes — a cascade list, here — has no
/// public wrapper to reach for.
pub(crate) fn font_with_fallback(font: &CTFont, fallback_families: &[&str]) -> CTFont {
    let cascade_key = unsafe { CFString::wrap_under_get_rule(kCTFontCascadeListAttribute) };
    let entries: Vec<CTFontDescriptor> = fallback_families
        .iter()
        .map(|family| cascade_descriptor_for(family))
        .collect();
    let cascade_list = CFArray::from_CFTypes(&entries);
    let attrs = CFDictionary::from_CFType_pairs(&[(cascade_key, cascade_list.as_CFType())]);
    let desc = font_descriptor::new_from_attributes(&attrs);
    // SAFETY: `font.as_concrete_TypeRef()` is a valid, live `CTFontRef`;
    // `desc.as_concrete_TypeRef()` outlives the call (it's a local
    // binding dropped after this statement, and CTFontCreateCopyWithAttributes
    // reads it synchronously); `0.0` for `size` means "keep the
    // original font's point size" per Core Text's own documented
    // convention for this parameter, and a null `matrix` means "no
    // transform", matching what `core_text::font::CTFont::clone_with_font_size`
    // itself passes for the same two trailing-but-one parameters. The
    // returned ref is `+1`-retained per Core Foundation's create-rule,
    // which `wrap_under_create_rule` takes ownership of.
    let font_ref = unsafe {
        CTFontCreateCopyWithAttributes(
            font.as_concrete_TypeRef(),
            0.0,
            std::ptr::null(),
            desc.as_concrete_TypeRef(),
        )
    };
    unsafe { CTFont::wrap_under_create_rule(font_ref) }
}

/// Copy `font` with the cascade list every `MacBackend` font carries:
/// `app_fallback_family` first, when the app has configured one via
/// `Backend::set_nerd_font_fallback`, then [`crate::codicon::FONT_FAMILY`]
/// unconditionally.
///
/// `MacBackend::set_current_font`/`set_chrome_font`/
/// `set_nerd_font_fallback` all go through this, so every built-in chrome
/// glyph this crate paints through `current_font`/`chrome_font` (tab
/// dirty/close) resolves its codicon codepoint whether or not the app has
/// ever called `set_nerd_font_fallback`. `codicon::FONT_FAMILY`'s own doc
/// explains why appending it after `app_fallback_family` can never shadow
/// an app-supplied icon glyph: it is always the last entry in the
/// cascade, so an app-supplied font earlier in the list wins any
/// overlapping codepoint.
pub(crate) fn font_with_builtin_fallback(
    font: &CTFont,
    app_fallback_family: Option<&str>,
) -> CTFont {
    let mut families: Vec<&str> = Vec::with_capacity(2);
    if let Some(family) = app_fallback_family {
        families.push(family);
    }
    families.push(crate::codicon::FONT_FAMILY);
    font_with_fallback(font, &families)
}

/// Apple's system "no font anywhere covers this" placeholder carries only
/// a handful of generic category-box glyphs — one shared glyph per
/// Unicode block, rather than per character. Measured directly on a real
/// macOS host via `CTFont::glyph_count()`: the resolved placeholder font
/// (`.LastResort`, backed by `/System/Library/Fonts/LastResort.otf`) has
/// exactly 7 glyphs in total, while an installed Nerd Font covering actual
/// PUA icon ranges has over 12,000. [`resolved_fallback_for_char`] uses a
/// threshold far above the placeholder's count and far below any real
/// font's, so it needs no assumption about what name any macOS version
/// gives that placeholder (which varies: `CTFontGetGlyphsForCharacters`
/// called on the placeholder font directly still reports a nonzero glyph
/// for a covered block — it has a real cmap entry for its own box glyphs
/// — so a glyph-id lookup alone can't tell "real outline" apart from
/// "generic box" either; only the font's total repertoire size can).
#[cfg(test)]
const REAL_FONT_GLYPH_COUNT_FLOOR: core_foundation::base::CFIndex = 64;

/// Test/diagnostic hook: reports which font **family** Core Text's live
/// glyph substitution actually resolved `ch` to when painted through
/// `font`, and whether that resolved font is a real font covering `ch`
/// (`true`) rather than Apple's system-wide placeholder font (`false`) —
/// see [`REAL_FONT_GLYPH_COUNT_FLOOR`] for how that's told apart without
/// comparing any family-name string.
///
/// `FrameInventory::text_runs` (fed by [`draw_text`]'s recording hook
/// above) can only ever answer "this text was requested at this
/// position" — it has no way to say *which* font in the cascade
/// actually painted a given glyph. This answers that question for unit
/// tests inside this module: it builds the identical `CTLine`
/// [`draw_text`] would for a single character, then reads back the
/// resulting glyph run's resolved font via `CTRunGetAttributes` — the
/// actual substitution Core Text performed, not a guess from the font's
/// declared cascade-list descriptor (which only says what Core Text
/// *will consult*, not what it *found*).
///
/// `#[cfg(test)]`-gated rather than exposed via the unconditionally
/// compiled `pub mod testing` — reachable only from this file's own
/// unit tests, not from an integration test or a `MacDriver`-based
/// regression test.
#[cfg(test)]
pub(crate) fn resolved_fallback_for_char(font: &CTFont, ch: char) -> (String, bool) {
    let line = build_ctline(font, &ch.to_string());
    let runs = line.glyph_runs();
    let run = runs
        .get(0)
        .filter(|_| runs.len() == 1)
        .expect("a single non-empty character always lays out as exactly one glyph run");
    let attrs = run
        .attributes()
        .expect("a laid-out glyph run always carries attributes");
    let resolved_font = attrs
        .find(unsafe { CFString::wrap_under_get_rule(kCTFontAttributeName) })
        .expect("a laid-out glyph run always carries a resolved NSFont attribute")
        .downcast::<CTFont>()
        .expect("the NSFont attribute on a CTRun is always a CTFont");
    let family = resolved_font.family_name();
    let resolved_real_glyph = resolved_font.glyph_count() > REAL_FONT_GLYPH_COUNT_FLOOR;
    (family, resolved_real_glyph)
}

/// A bare [`core_text::font_descriptor::CTFontDescriptor`] carrying only
/// `family`'s [`kCTFontFamilyNameAttribute`] — resolved by Core Text's
/// ordinary name-matching the moment it's consulted. A family name on its
/// own is not a unique identity: any other font sharing the exact family
/// string — a stale copy left over in the user's font library, or an
/// unrelated public font release that happens to use the same name — is
/// just as valid a match, and Core Text's matcher is free to prefer it
/// over whichever font a caller actually meant. Only used as the fallback
/// path in [`cascade_descriptor_for`] when no exact registered descriptor
/// is on file for `family`.
fn descriptor_for_family(family: &str) -> CTFontDescriptor {
    let key = unsafe { CFString::wrap_under_get_rule(kCTFontFamilyNameAttribute) };
    let attrs = CFDictionary::from_CFType_pairs(&[(key, CFString::new(family).as_CFType())]);
    font_descriptor::new_from_attributes(&attrs)
}

// ── Pinning the cascade to the exact registered font ────────────────────
//
// Building `font_with_fallback`'s cascade-list entry purely from
// `descriptor_for_family`, i.e. by name, is ambiguous the moment more
// than one font on the host shares the fallback family's name: Core Text
// picks *a* match, not necessarily the one `register_font_from_memory`
// just handed back to the caller. A per-process table keyed by family
// name, populated with the precise descriptor
// `CTFontManagerCreateFontDescriptorsFromData` hands back for the exact
// bytes just registered, removes that ambiguity — the cascade entry then
// names a specific font resource rather than re-asking Core Text's name
// matcher to guess.
//
// A process-wide `Mutex`, not a thread-local: `CTFontManagerRegisterGraphicsFont`
// itself registers for the lifetime of the *process*, not the calling
// thread, so a table meant to mirror that registration's lifetime has to
// be visible to every thread, not just the one that happened to populate
// it. `CTFontDescriptor` is `Send` (core-text documents Core Text's font
// objects as safe to use from multiple threads), so a `Mutex`-guarded
// table is sufficient — no `unsafe impl Sync` needed on our side.
static REGISTERED_FONT_DESCRIPTORS: OnceLock<Mutex<HashMap<String, CTFontDescriptor>>> =
    OnceLock::new();

fn registered_font_descriptors() -> &'static Mutex<HashMap<String, CTFontDescriptor>> {
    REGISTERED_FONT_DESCRIPTORS.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Remember `descriptor` as the exact cascade entry to use for `family`,
/// so a later [`font_with_fallback`] call naming this family resolves to
/// *this* font resource rather than whatever Core Text's name matcher
/// finds first. Called by [`register_font_from_memory`] once per
/// successful registration.
fn remember_registered_descriptor(family: String, descriptor: &CTFontDescriptor) {
    // SAFETY: `descriptor.as_concrete_TypeRef()` is a valid, live
    // `CTFontDescriptorRef` for the duration of this call. We retain our
    // own reference (`wrap_under_get_rule`, not `wrap_under_create_rule`)
    // rather than borrowing the caller's: the table outlives the
    // registration call that populates it.
    let owned = unsafe { CTFontDescriptor::wrap_under_get_rule(descriptor.as_concrete_TypeRef()) };
    registered_font_descriptors()
        .lock()
        .expect("REGISTERED_FONT_DESCRIPTORS mutex should never be poisoned")
        .insert(family, owned);
}

/// The descriptor [`font_with_fallback`] should put in its cascade list
/// for `family`: the exact descriptor [`remember_registered_descriptor`]
/// stashed for it, if `family` was registered via a prior
/// [`register_font_from_memory`] call; otherwise [`descriptor_for_family`]'s
/// ordinary name lookup, for a caller naming a system font directly.
///
/// This keys purely on family name, so a caller that registers a blob
/// whose family string happens to collide with an installed *system*
/// family (e.g. a font claiming to be "Menlo") silently redirects every
/// later [`font_with_fallback`] call naming that family to the registered
/// blob instead of the system font. That is a new behaviour introduced by
/// this pin relative to the plain name lookup it replaces, not something
/// [`register_font_from_memory`]'s callers currently guard against.
fn cascade_descriptor_for(family: &str) -> CTFontDescriptor {
    let table = registered_font_descriptors()
        .lock()
        .expect("REGISTERED_FONT_DESCRIPTORS mutex should never be poisoned");
    // SAFETY: `descriptor` is a live `&CTFontDescriptor` borrowed from the
    // locked table for the duration of this closure; `wrap_under_get_rule`
    // retains its own reference, so the value returned from this function
    // stays valid once the lock (and the table's own reference) is
    // dropped at the end of this statement.
    let exact = table.get(family).map(|descriptor| unsafe {
        CTFontDescriptor::wrap_under_get_rule(descriptor.as_concrete_TypeRef())
    });
    drop(table);
    exact.unwrap_or_else(|| descriptor_for_family(family))
}

/// Register `bytes` (raw TTF/OTF font data) with Core Text for the
/// lifetime of this process via `CTFontManagerRegisterGraphicsFont` — no
/// filesystem write, no user font directory. Returns the family name Core
/// Text resolves the font to, or `None` if `bytes` isn't a font Core
/// Graphics can parse, or registration itself fails (e.g. a duplicate
/// PostScript name already registered in this process).
///
/// `CTFontManagerRegisterGraphicsFont` (unlike
/// `CTFontManagerRegisterFontsForURL`) has no registration-scope
/// argument — every font it registers is process-local for as long as
/// the process runs.
pub fn register_font_from_memory(bytes: &[u8]) -> Option<String> {
    let provider = CGDataProvider::from_buffer(Arc::new(bytes.to_vec()));
    let cgfont = CGFont::from_data_provider(provider).ok()?;

    let mut error: CFErrorRef = std::ptr::null_mut();
    // SAFETY: `cgfont.as_ptr()` is a valid, live `CGFontRef` for the
    // duration of this call; `error` is a valid out-param CoreText only
    // ever writes through. Its value is discarded on failure —
    // `register_font_from_memory`'s `None` already tells the caller
    // registration failed, and a `CFError` is a caller convenience this
    // method doesn't need to expose.
    let registered = unsafe { CTFontManagerRegisterGraphicsFont(cgfont.as_ptr(), &mut error) };
    if !registered {
        return None;
    }
    // A throwaway size is fine here — only `family_name()` is read, and
    // family membership doesn't depend on point size.
    let ctfont = font::new_from_CGFont(&cgfont, 12.0);
    let family = ctfont.family_name();

    // Stash the exact descriptor for these bytes, keyed by the family
    // name just resolved, so `font_with_fallback`'s cascade entry for
    // this family can bind to this specific font resource instead of
    // whatever Core Text's name matcher would otherwise pick — see
    // `cascade_descriptor_for`'s doc for why that distinction matters.
    // `CTFontManagerCreateFontDescriptorsFromData` describes the bytes
    // themselves, not a name to re-resolve, so a null result or an empty
    // array (bytes Core Graphics parsed but Core Text's font manager
    // can't describe) just means no exact descriptor is on file — the
    // family-name path remains available as a fallback, so registration
    // itself still succeeds. `cf_data` is dropped at the end of this
    // function, but Core Text retains the bytes it needs internally when
    // creating the descriptor array, so the descriptors — and the one we
    // stash — outlive `cf_data` safely.
    let cf_data = CFData::from_buffer(bytes);
    let descriptors_ref =
        unsafe { CTFontManagerCreateFontDescriptorsFromData(cf_data.as_concrete_TypeRef()) };
    if !descriptors_ref.is_null() {
        // SAFETY: a non-null return is a `+1`-retained `CFArrayRef` per
        // Core Foundation's create-rule, which `wrap_under_create_rule`
        // takes ownership of.
        let descriptors: CFArray<CTFontDescriptor> =
            unsafe { TCFType::wrap_under_create_rule(descriptors_ref) };
        // Only pin a descriptor whose own family matches the family we're
        // keying it under. A blob describing more than one face/family
        // (a `.ttc`, or a mismatch between `CGFont::from_data_provider`'s
        // face and this array's first entry) would otherwise silently
        // pin `family`'s cascade slot to a *different* family's font —
        // strictly worse than the name lookup it replaces, since the
        // cascade would then deliberately name the wrong resource rather
        // than ambiguously name the right one. Skipping the pin here
        // just leaves `cascade_descriptor_for` falling back to the name
        // path for `family`, matching this function's pre-existing
        // behaviour before the exact-descriptor pin existed.
        if let Some(descriptor) = descriptors.get(0) {
            if descriptor.family_name() == family {
                remember_registered_descriptor(family.clone(), &descriptor);
            }
        }
    }

    Some(family)
}

/// Register [`crate::codicon::FONT_BYTES`] exactly once per process via
/// [`register_font_from_memory`] — mirrors
/// `crate::gtk::app_font::ensure_codicon_registered`'s `OnceLock`
/// idempotency (a second `CTFontManagerRegisterGraphicsFont` call for
/// the same bytes fails on a duplicate PostScript name, so repeated
/// `MacBackend::new()` calls across e.g. a test binary must not re-run
/// the real registration). `MacBackend::new` calls this once per
/// instance.
///
/// Returns whether the font is available for painting in the current
/// process.
pub(crate) fn ensure_codicon_registered() -> bool {
    static REGISTERED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *REGISTERED.get_or_init(|| register_font_from_memory(crate::codicon::FONT_BYTES).is_some())
}

/// Sample a font's typographic metrics. The returned `char_width`
/// is computed via `measure_text(font, "M")` — measuring an empty
/// string is meaningless for char-width, and `M` is the conventional
/// fixed-width gauge.
pub fn font_metrics(font: &CTFont) -> FontMetrics {
    let ascent = font.ascent();
    let descent = font.descent();
    let leading = font.leading();
    let (char_width, _) = measure_text(font, "M");
    FontMetrics {
        ascent,
        descent,
        leading,
        line_height: ascent + descent + leading,
        char_width,
    }
}

/// Measure the rendered footprint of `text` in `font`. Returns
/// `(width, height)` in points — height is **always** `font`'s own
/// full line height (`ascent + descent + leading`), regardless of
/// string content (matches how primitives reserve vertical space).
///
/// Height must not come from `CTLine::get_typographic_bounds()` for
/// non-empty text: that aggregates metrics across every glyph *run* in
/// the line, and `font`'s cascade list (built by
/// [`font_with_fallback`] / [`font_with_builtin_fallback`] — every
/// `MacBackend` chrome/editor font carries one, always ending in
/// [`crate::codicon::FONT_FAMILY`]) means a character `font` itself
/// doesn't cover — a codicon PUA icon glyph being the common case —
/// resolves through a *different* font, whose ascent/descent/leading
/// then leak into the typographic bounds. [`draw_text_impl`] positions
/// every glyph using only `font`'s own `ascent()` (never a resolved
/// fallback run's), so letting height vary with the resolved run's
/// metrics would desynchronise the two: callers that centre text
/// vertically using this height (e.g.
/// `sidebar_panel::native_surface_paint::paint_toolbar_header`) would
/// then centre against a height [`draw_text_impl`] never positions
/// against, pushing the glyph low in its slot where a clip rect can cut
/// off its lower part. Pinning height to `font`'s own metrics, exactly
/// as the empty-string branch below also does, keeps this function's
/// contract true for every input and consistent with how glyphs are
/// actually drawn.
pub fn measure_text(font: &CTFont, text: &str) -> (f64, f64) {
    let height = font.ascent() + font.descent() + font.leading();
    if text.is_empty() {
        return (0.0, height);
    }
    let line = build_ctline(font, text);
    let bounds = line.get_typographic_bounds();
    (bounds.width, height)
}

/// Implements [`crate::primitives::layout_metrics::TextMeasure`] on `CTFont`
/// so every layout function that needs a `&dyn TextMeasure` can pass a
/// live `&CTFont` directly — no wrapper struct needed.
impl crate::primitives::layout_metrics::TextMeasure for CTFont {
    fn width_of(&self, text: &str) -> f32 {
        measure_text(self, text).0 as f32
    }
}

/// Paint `text` at `(x, y)` (view-local points, top-left origin) using
/// `font` and `color` (rgba 0.0–1.0 each). The CG context's clip
/// region is respected automatically by Core Text — callers that want
/// to clip to a rect call [`CGContextClipToRect`] before this.
///
/// # Safety
///
/// `ctx` must be a valid `CGContextRef` borrowed for the duration of
/// this call (typical: passed straight from `drawRect:`). Calling
/// with a freed or null pointer is UB.
pub unsafe fn draw_text(
    ctx: CGContextRef,
    font: &CTFont,
    text: &str,
    x: f64,
    y: f64,
    color: (f64, f64, f64, f64),
) {
    draw_text_impl(ctx, font, text, x, y, 1.0, color)
}

/// Like [`draw_text`], but additionally scales the glyph run horizontally
/// by `scale_x` around its own origin `(x, y)`.
///
/// Used by [`crate::macos::terminal::draw_terminal_cells`] to stretch or
/// shrink a double-width glyph (CJK / emoji) so it fills its two-column
/// cell box exactly — the scale factor comes from
/// [`crate::terminal_style::wide_glyph_x_scale`], the same decision GTK's
/// `cr.scale(scale_x, 1.0)` applies via Cairo's CTM. Core
/// Text has no per-draw scale parameter, but the text matrix's `a`
/// component scales every glyph outline in the run horizontally with no
/// extra CG calls — `scale_x == 1.0` renders identically to [`draw_text`].
///
/// # Safety
///
/// Same contract as [`draw_text`].
pub unsafe fn draw_text_scaled_x(
    ctx: CGContextRef,
    font: &CTFont,
    text: &str,
    x: f64,
    y: f64,
    scale_x: f64,
    color: (f64, f64, f64, f64),
) {
    draw_text_impl(ctx, font, text, x, y, scale_x, color)
}

unsafe fn draw_text_impl(
    ctx: CGContextRef,
    font: &CTFont,
    text: &str,
    x: f64,
    y: f64,
    scale_x: f64,
    color: (f64, f64, f64, f64),
) {
    if text.is_empty() {
        return;
    }

    record_if_active(font, text, x, y);

    CGContextSaveGState(ctx);

    // Set the *fill* colour rather than embedding a foreground-colour
    // attribute on the CFAttributedString — Core Text falls back to
    // the context's current fill colour for unattributed glyphs.
    CGContextSetRGBFillColor(ctx, color.0, color.1, color.2, color.3);

    // Flip the text matrix so glyphs render right-side up inside
    // QuadraView (which has `isFlipped = YES`). Without this the
    // glyphs would draw upside-down because CG's intrinsic text
    // origin is at the baseline with ascent rising in +y, but our
    // view's +y points downward. `a: scale_x` additionally stretches or
    // shrinks the glyph run horizontally for [`draw_text_scaled_x`];
    // [`draw_text`] always passes `scale_x == 1.0`, i.e. no change here.
    let flip = CGAffineTransform {
        a: scale_x,
        b: 0.0,
        c: 0.0,
        d: -1.0,
        tx: 0.0,
        ty: 0.0,
    };
    CGContextSetTextMatrix(ctx, flip);

    // `y` is the requested **top** of the glyph in view coords;
    // CT positions the baseline. Shift down by ascent so the glyph
    // cell's top edge lands at the requested `y`.
    let ascent = font.ascent();
    CGContextSetTextPosition(ctx, x, y + ascent);

    let line = build_ctline(font, text);
    CTLineDraw(line.as_concrete_TypeRef(), ctx);

    CGContextRestoreGState(ctx);
}

// ── Text-run recording ──────────────────────────────────────────────────
//
// `draw_text` is the single choke point every rasteriser paints text
// through, so recording here lets the frame inventory track text runs
// without threading a recorder through every call site. `draw_text` only
// ever has a borrowed `CGContextRef` in scope, so recording goes through
// the thread-local sink shared by every backend ([`crate::testing`]).

/// Start recording every subsequent [`draw_text`] call as a [`TextRun`]
/// until [`stop_recording_text`] is called.
/// [`super::backend::MacBackend::enter_frame_scope`] wraps its closure in
/// this pair when
/// [`super::backend::MacBackend::set_painted_text_recording`] is on.
pub(crate) fn start_recording_text() {
    // `MacBackend::enter_frame_scope` calls don't nest, so any previous
    // sink is discarded rather than threaded through.
    let _ = crate::testing::install_text_run_sink();
}

/// Stop recording and return everything captured since the matching
/// [`start_recording_text`]. Returns an empty `Vec` if recording was
/// never started — defensive; callers only invoke this when they know
/// they started it.
pub(crate) fn stop_recording_text() -> Vec<TextRun> {
    crate::testing::take_text_run_sink(None)
}

/// Push a [`TextRun`] for `text` at `(x, y)` — view-local points,
/// top-left origin, matching [`draw_text`]'s own coordinate convention —
/// if recording is active. A no-op (and no [`measure_text`] call, so no
/// extra `CTLine` layout cost) when it isn't.
fn record_if_active(font: &CTFont, text: &str, x: f64, y: f64) {
    if crate::testing::text_run_sink_active() {
        let (w, h) = measure_text(font, text);
        crate::testing::record_text_run(text, Rect::new(x as f32, y as f32, w as f32, h as f32));
    }
}

/// Build a `CTLine` carrying just the font attribute. Foreground
/// colour is left to the context's fill (see [`draw_text`]).
///
/// `core_foundation::CFAttributedString::new` doesn't take attributes,
/// so we call `CFAttributedStringCreate` directly via FFI and wrap
/// the resulting `+1`-retained ref in our own CFAttributedString.
fn build_ctline(font: &CTFont, text: &str) -> CTLine {
    let font_key = unsafe { CFString::wrap_under_get_rule(kCTFontAttributeName) };
    // Tell Core Text to honour the graphics context's current fill
    // colour for glyph rendering. Without this attribute CT defaults
    // to **black**, regardless of what `CGContextSetRGBFillColor`
    // was set to right before `CTLineDraw` — Core Text reads its
    // foreground from the attributed string, not the context state,
    // unless this flag is explicitly true.
    let from_ctx_key =
        unsafe { CFString::wrap_under_get_rule(kCTForegroundColorFromContextAttributeName) };
    let attributes = CFDictionary::from_CFType_pairs(&[
        (font_key, font.as_CFType()),
        (from_ctx_key, CFBoolean::true_value().as_CFType()),
    ]);
    let cf_text = CFString::new(text);
    // SAFETY: `cf_text` and `attributes` outlive the call. The create
    // function returns a `+1`-retained ref which `wrap_under_create_rule`
    // takes ownership of (matching CF's release-on-Drop semantics).
    let attr_ref: CFAttributedStringRef = unsafe {
        CFAttributedStringCreate(
            std::ptr::null(),
            cf_text.as_concrete_TypeRef(),
            attributes.as_concrete_TypeRef(),
        )
    };
    let attr_string = unsafe { CFAttributedString::wrap_under_create_rule(attr_ref) };
    CTLine::new_with_attributed_string(attr_string.as_concrete_TypeRef())
}

// ── Direct CoreGraphics / CoreText FFI ──────────────────────────────────────
//
// All these are linked transitively via core-graphics + core-text. The
// wrappers in those crates either take ownership of the `CGContextRef`
// (which we can't grant — AppKit owns it for the duration of
// `drawRect:`) or hide the text matrix / position calls behind types
// that don't compose with our smoke flow.

#[link(name = "CoreText", kind = "framework")]
extern "C" {
    fn CTLineDraw(line: core_text::line::CTLineRef, context: CGContextRef);
    // `core-text` 20.1 only calls this from its own private
    // `clone_with_font_size`/`clone_with_symbolic_traits` — see
    // `font_with_fallback`'s doc for why this crate needs its own
    // binding to pass a real `attributes` descriptor (a cascade list)
    // rather than the `ptr::null()` those two always pass.
    fn CTFontCreateCopyWithAttributes(
        font: CTFontRef,
        size: CGFloat,
        matrix: *const CGAffineTransform,
        attributes: core_text::font_descriptor::CTFontDescriptorRef,
    ) -> CTFontRef;
    // `core-text` 20.1 comments this one out entirely
    // (`font_manager.rs`: "//pub fn CTFontManagerRegisterGraphicsFont") —
    // see `register_font_from_memory`'s doc for why this method needs it.
    fn CTFontManagerRegisterGraphicsFont(font: CGFontRef, error: *mut CFErrorRef) -> bool;
    // Not bound by `core-text` 20.1 at all. Describes the exact font
    // resource `data` holds — distinct from `CTFontDescriptorCreateWithAttributes`'s
    // name-based matching, which only ever asks Core Text to go find
    // *something* answering to a given attribute dictionary. See
    // `register_font_from_memory`'s doc for why pinning to the described
    // resource rather than its name matters here.
    fn CTFontManagerCreateFontDescriptorsFromData(data: CFDataRef) -> CFArrayRef;
}

#[link(name = "CoreFoundation", kind = "framework")]
extern "C" {
    fn CFAttributedStringCreate(
        alloc: CFAllocatorRef,
        str: CFStringRef,
        attributes: CFDictionaryRef,
    ) -> CFAttributedStringRef;
}

extern "C" {
    fn CGContextSaveGState(c: CGContextRef);
    fn CGContextRestoreGState(c: CGContextRef);
    fn CGContextSetRGBFillColor(
        c: CGContextRef,
        red: CGFloat,
        green: CGFloat,
        blue: CGFloat,
        alpha: CGFloat,
    );
    fn CGContextSetTextMatrix(c: CGContextRef, t: CGAffineTransform);
    fn CGContextSetTextPosition(c: CGContextRef, x: CGFloat, y: CGFloat);
}

#[cfg(test)]
mod tests {
    use super::*;

    /// System-installed monospace font — present on every macOS install
    /// since 10.6. Picking a known-resident family makes the tests
    /// deterministic without reading the user's font preferences.
    const TEST_FONT: &str = "Menlo";
    const TEST_SIZE: f64 = 14.0;

    fn font() -> CTFont {
        make_font(TEST_FONT, TEST_SIZE).expect("Menlo should be installed on every macOS host")
    }

    #[test]
    fn make_font_existing_returns_some() {
        assert!(make_font("Menlo", 12.0).is_some());
    }

    /// Pins the Core Text substitution gotcha [`make_font_exact`] exists
    /// for: plain [`make_font`] answers an unknown family
    /// with a *usable font from a different family* rather than `None`,
    /// so only the checked variant can tell a caller "that family isn't
    /// here, use your own fallback".
    #[test]
    fn make_font_exact_rejects_an_unknown_family_that_make_font_substitutes() {
        // Documented as an `if let` rather than an `expect`: the point of
        // the test is `make_font_exact`'s answer. Should a future macOS
        // ever make `CTFontCreateWithName` fail honestly, `make_font`
        // returns `None`, the substitution assert is vacuous, and the
        // assert that matters below still holds.
        if let Some(substituted) = make_font("Definitely Not A Real Font Family", 12.0) {
            assert_ne!(
                substituted.family_name(),
                "Definitely Not A Real Font Family",
                "Core Text cannot have resolved a family that doesn't exist",
            );
        }
        assert!(
            make_font_exact("Definitely Not A Real Font Family", 12.0).is_none(),
            "make_font_exact must reject the family Core Text substituted",
        );
    }

    #[test]
    fn make_font_exact_accepts_family_and_postscript_spellings() {
        let by_family = make_font_exact("Menlo", TEST_SIZE).expect("Menlo by family name");
        assert_eq!(by_family.family_name(), "Menlo");
        assert_eq!(by_family.pt_size(), TEST_SIZE);

        // Core Text accepts a PostScript name in the same argument, so
        // the exactness check must not reject one.
        assert!(
            make_font_exact("Menlo-Regular", TEST_SIZE).is_some(),
            "PostScript spelling must count as an exact match",
        );

        // Surrounding whitespace is trimmed before the request, so a
        // padded family name still resolves.
        assert!(make_font_exact("  Menlo  ", TEST_SIZE).is_some());
    }

    #[test]
    fn font_metrics_structure_consistent() {
        let m = font_metrics(&font());
        assert!(
            m.ascent > 0.0,
            "ascent should be positive, got {}",
            m.ascent
        );
        assert!(
            m.descent >= 0.0,
            "descent should be non-negative, got {}",
            m.descent
        );
        assert!(
            m.leading >= 0.0,
            "leading should be non-negative, got {}",
            m.leading
        );
        // line_height ≡ ascent + descent + leading by definition
        let expected = m.ascent + m.descent + m.leading;
        assert!(
            (m.line_height - expected).abs() < 1e-9,
            "line_height {} should equal ascent + descent + leading = {}",
            m.line_height,
            expected,
        );
        // Plausibility: a 14pt font should produce a line height in
        // roughly the 14–28pt range (varies a bit by font).
        assert!(
            m.line_height > 12.0 && m.line_height < 30.0,
            "line_height {} out of plausible range for 14pt Menlo",
            m.line_height,
        );
    }

    #[test]
    fn font_metrics_char_width_positive() {
        let m = font_metrics(&font());
        assert!(
            m.char_width > 0.0 && m.char_width < TEST_SIZE * 2.0,
            "char_width {} out of expected range for 14pt Menlo",
            m.char_width,
        );
    }

    #[test]
    fn measure_text_empty_string() {
        let (w, h) = measure_text(&font(), "");
        assert_eq!(w, 0.0);
        assert!(
            h > 0.0,
            "empty-string height should still report line height"
        );
    }

    #[test]
    fn measure_text_single_char_matches_char_width_for_monospace() {
        let f = font();
        let m = font_metrics(&f);
        let (w, _) = measure_text(&f, "M");
        // Menlo is monospace — width of "M" should equal `char_width`
        // exactly (modulo floating-point round-trip).
        assert!(
            (w - m.char_width).abs() < 1e-6,
            "single-char width {} should equal char_width {}",
            w,
            m.char_width,
        );
    }

    #[test]
    fn measure_text_scales_linearly_for_monospace() {
        let f = font();
        let (w1, _) = measure_text(&f, "x");
        let (w10, _) = measure_text(&f, "xxxxxxxxxx");
        // Monospace: 10 chars should be 10× one char (within rounding).
        let ratio = w10 / w1;
        assert!(
            (ratio - 10.0).abs() < 0.05,
            "10× width ratio was {}, expected ~10 for monospace",
            ratio,
        );
    }

    // ── Text-run recording ───────────────────────────────────────────

    #[test]
    fn draw_text_records_nothing_when_not_recording() {
        let surface = super::super::headless::BitmapSurface::new(64, 32);
        // SAFETY: `surface`'s context is valid for the call's duration.
        unsafe {
            draw_text(
                surface.context_ptr(),
                &font(),
                "hello",
                2.0,
                3.0,
                (1.0, 1.0, 1.0, 1.0),
            );
        }
        // No matching `start_recording_text()` — proves `draw_text`
        // doesn't record unconditionally, only when a `MacDriver` (via
        // `MacBackend::enter_frame_scope`) has turned it on.
        assert!(stop_recording_text().is_empty());
    }

    #[test]
    fn draw_text_records_bounds_while_recording() {
        let surface = super::super::headless::BitmapSurface::new(64, 32);
        start_recording_text();
        // SAFETY: `surface`'s context is valid for the call's duration.
        unsafe {
            draw_text(
                surface.context_ptr(),
                &font(),
                "hi",
                2.0,
                3.0,
                (1.0, 1.0, 1.0, 1.0),
            );
        }
        let runs = stop_recording_text();
        assert_eq!(runs.len(), 1, "exactly one draw_text call should record");
        assert_eq!(runs[0].text, "hi");
        assert_eq!(runs[0].bounds.x, 2.0);
        assert_eq!(runs[0].bounds.y, 3.0);
        let (w, h) = measure_text(&font(), "hi");
        assert_eq!(runs[0].bounds.width, w as f32);
        assert_eq!(runs[0].bounds.height, h as f32);
    }

    #[test]
    fn draw_text_empty_string_records_nothing() {
        let surface = super::super::headless::BitmapSurface::new(4, 4);
        start_recording_text();
        // SAFETY: `surface`'s context is valid for the call's duration.
        // `draw_text` returns before touching `ctx` at all for an empty
        // string, so this also proves the early-return happens before
        // (not after) the recording hook.
        unsafe {
            draw_text(
                surface.context_ptr(),
                &font(),
                "",
                0.0,
                0.0,
                (1.0, 1.0, 1.0, 1.0),
            );
        }
        assert!(stop_recording_text().is_empty());
    }

    #[test]
    fn stop_recording_text_without_start_is_empty_not_panicking() {
        // Defensive default — a caller that forgets the matching
        // `start_recording_text()` gets an empty `Vec`, not a panic.
        assert!(stop_recording_text().is_empty());
    }

    // ── Nerd-Font fallback ───────────────────────────────────────────

    /// `font_with_fallback` must actually attach a
    /// `kCTFontCascadeListAttribute` to the returned font's descriptor —
    /// not just return a font that happens to still work. "Helvetica" is
    /// a plausible fallback family (present on every macOS install) and
    /// deliberately different from `TEST_FONT` so a copy-paste bug that
    /// silently no-ops (returning `font` unchanged) would still fail this
    /// assertion.
    #[test]
    fn font_with_fallback_attaches_a_cascade_list_attribute() {
        let base = font();
        let with_fallback = font_with_fallback(&base, &["Helvetica"]);
        // `contains_key` needs `ToVoid`, which core-foundation only
        // implements for `*const c_void` and `CFType` — not `CFString`
        // itself — so both the dictionary and the probed key are
        // dropped to their untyped/raw forms first.
        let attrs = with_fallback.copy_descriptor().attributes().to_untyped();
        let cascade_key = unsafe { CFString::wrap_under_get_rule(kCTFontCascadeListAttribute) };
        assert!(
            attrs.contains_key(&cascade_key.as_CFTypeRef()),
            "font_with_fallback's returned font must carry a cascade-list attribute"
        );
    }

    /// `font_with_fallback` must not otherwise change what the font
    /// resolves to for ordinary text: same family name and same point
    /// size as the font it was given, only the cascade extended.
    #[test]
    fn font_with_fallback_preserves_family_and_size() {
        let base = font();
        let with_fallback = font_with_fallback(&base, &["Helvetica"]);
        assert_eq!(with_fallback.family_name(), base.family_name());
        assert_eq!(with_fallback.pt_size(), base.pt_size());
    }

    /// `font_with_fallback` still measures ordinary (non-fallback-needing)
    /// text sanely — the cascade only matters for characters `base`
    /// itself can't cover, so painting/measuring plain ASCII must be
    /// unaffected.
    #[test]
    fn font_with_fallback_still_measures_ordinary_text() {
        let base = font();
        let with_fallback = font_with_fallback(&base, &["Helvetica"]);
        let (w, h) = measure_text(&with_fallback, "hello");
        assert!(
            w > 0.0 && h > 0.0,
            "measuring plain text through a font with a fallback attached must still work \
             (w={w}, h={h})"
        );
    }

    /// Does `font_with_fallback` + `clone_with_font_size` — the
    /// mechanism `MacBackend::set_current_font`/`set_chrome_font`
    /// install the fallback through, and the activity-bar icon-resize
    /// path then applies on top — correctly resolve real Nerd-Font
    /// Private-Use-Area codepoints *through the installed fallback
    /// family specifically*, both before and after that resize clone?
    ///
    /// Each codepoint carries a negative control: the bare base font,
    /// with no cascade attached, must fail to resolve it directly (if
    /// it didn't, the codepoint tells us nothing about the cascade).
    /// The cascade-equipped font must then resolve it *through
    /// `nerd_family` by name*, not merely through some family or
    /// other — PUA ranges are exactly where unrelated installed icon
    /// fonts can squat on the same codepoints, so "resolved to a real
    /// glyph" alone doesn't prove this cascade contributed anything.
    ///
    /// Skips (rather than failing) when no Nerd Font is installed on the
    /// host — there is nothing wrong to report, just nothing to test;
    /// CI hosts have none installed. Run on a dev machine with one
    /// installed for real coverage. [`resolved_fallback_for_char_reports_no_real_glyph_for_bare_menlo_on_pua`]
    /// below covers the same hook on every host, Nerd Font or not.
    #[test]
    fn nerd_font_fallback_resolves_pua_codepoints_before_and_after_icon_resize() {
        let families = core_text::font_manager::copy_available_font_family_names();
        let nerd_family = families
            .iter()
            .map(|f| f.to_string())
            .find(|name| name.to_ascii_lowercase().contains("nerd font"));
        let Some(nerd_family) = nerd_family else {
            eprintln!(
                "no installed font family contains \"Nerd Font\" — skipping \
                 (see this test's doc for why that's not a failure)"
            );
            return;
        };

        let base = font(); // Menlo — doesn't cover PUA itself
        let with_fallback = font_with_fallback(&base, &[nerd_family.as_str()]);
        // Mirrors `activity_bar::draw_activity_bar_with_style`'s
        // `font.clone_with_font_size(style.resolved_icon_size_px())`.
        let icon_size_px = crate::ActivityBarStyle::default().resolved_icon_size_px() as f64;
        let icon_sized = with_fallback.clone_with_font_size(icon_size_px);

        // Three codepoints reported broken, and three reported working,
        // against the same registered font in the same paint pass.
        let codepoints = [
            ('\u{EAF0}', "Explorer"),
            ('\u{EA68}', "SourceControl"),
            ('\u{EB91}', "RunDebug"),
            ('\u{F002}', "Search"),
            ('\u{EAE6}', "Extensions"),
            ('\u{F0E5}', "AiChat"),
        ];

        for (ch, label) in codepoints {
            let (base_family, base_ok) = resolved_fallback_for_char(&base, ch);
            assert!(
                !base_ok,
                "{label} (U+{:04X}) unexpectedly resolved a real glyph through bare \
                 {base_family:?} with no cascade attached — this negative control \
                 must fail, otherwise a pass below can't tell us the cascade did \
                 anything",
                ch as u32,
            );

            let (family_before, ok_before) = resolved_fallback_for_char(&with_fallback, ch);
            assert!(
                ok_before,
                "{label} (U+{:04X}) failed to resolve a real glyph *before* \
                 clone_with_font_size, through family {family_before:?} \
                 — the installed Nerd Font {nerd_family:?} should have \
                 covered it",
                ch as u32,
            );
            assert_eq!(
                family_before, nerd_family,
                "{label} (U+{:04X}) resolved through {family_before:?} instead of \
                 the cascade's own {nerd_family:?} — some other installed font is \
                 squatting on this PUA codepoint, so this pass doesn't show \
                 font_with_fallback's cascade contributed anything",
                ch as u32,
            );

            let (family_after, ok_after) = resolved_fallback_for_char(&icon_sized, ch);
            assert!(
                ok_after,
                "{label} (U+{:04X}) failed to resolve a real glyph *after* \
                 clone_with_font_size, through family {family_after:?} \
                 — the activity-bar icon resize must not drop fallback \
                 coverage that worked before the resize",
                ch as u32,
            );
            assert_eq!(
                family_after, nerd_family,
                "{label} (U+{:04X}) resolved through {family_after:?} instead of \
                 the cascade's own {nerd_family:?} after clone_with_font_size — the \
                 resize must preserve which family in the cascade covers this \
                 codepoint",
                ch as u32,
            );
        }
    }

    /// Host-independent counterpart to the Nerd-Font test above: bare
    /// Menlo, with no cascade attached, must not report a real glyph
    /// for a Private-Use-Area codepoint it was never built to cover.
    /// Needs no installed Nerd Font, so it runs on every CI host and
    /// proves [`resolved_fallback_for_char`] is wired up correctly
    /// even when the Nerd-Font-specific test above has nothing to do.
    #[test]
    fn resolved_fallback_for_char_reports_no_real_glyph_for_bare_menlo_on_pua() {
        let base = font();
        let (family, resolved_real_glyph) = resolved_fallback_for_char(&base, '\u{EAF0}');
        assert!(
            !resolved_real_glyph,
            "bare Menlo (no fallback cascade attached) unexpectedly resolved a \
             real glyph for U+EAF0 through family {family:?} — this codepoint is \
             outside Menlo's own coverage, so this must report no real glyph"
        );
    }

    /// Garbage bytes aren't a font Core Graphics can parse —
    /// `register_font_from_memory` must report that as `None` rather
    /// than panicking or fabricating a family name.
    #[test]
    fn register_font_from_memory_rejects_bytes_that_are_not_a_font() {
        let garbage = [0u8; 64];
        assert!(
            register_font_from_memory(&garbage).is_none(),
            "64 zero bytes are not a parseable font — must report None, not a fabricated family"
        );
    }

    // ── Shadowed-cascade regression (icon-font PUA codepoints) ───────

    /// The real icon font vimcode registers at startup — not a CI-only
    /// stand-in. Embedded rather than read from the user's font
    /// directory at test time, so this reproduces the exact bytes
    /// [`register_font_from_memory`] is handed in production regardless
    /// of what else happens to be installed on the host.
    ///
    /// Provenance: a subset of the upstream "Symbols Nerd Font" release
    /// (Nerd Fonts 3.5.1, OFL-licensed — see the sibling `LICENSE-NerdFonts`
    /// file), re-subset down to ~29 KB covering only the glyphs this
    /// module's tests reference. The `name` table entries still read
    /// "Symbols Nerd Font" / "Nerd Fonts 3.5.1" from the upstream release
    /// despite the file being named `vimcode-icons.ttf` here, matching
    /// what vimcode itself ships.
    const ICON_FONT_BYTES: &[u8] = include_bytes!("../../tests/fixtures/vimcode-icons.ttf");

    /// Register [`ICON_FONT_BYTES`] via [`register_font_from_memory`]
    /// exactly once for the whole test binary, and cache the family name
    /// Core Text resolved it to. `CTFontManagerRegisterGraphicsFont`
    /// registers for the lifetime of the *process*: a second call from a
    /// different test (cargo runs each `#[test]` across a thread pool, so
    /// "a different test" can mean "a different thread") would hand the
    /// same bytes to Core Text again and get back a duplicate-PostScript-name
    /// failure — seen here as [`register_font_from_memory`] returning
    /// `None` — rather than redoing a harmless no-op registration. Caching
    /// behind a single [`OnceLock`] sidesteps that: every test shares one
    /// real registration and one resolved family name.
    fn registered_icon_font_family() -> String {
        static FAMILY: OnceLock<String> = OnceLock::new();
        FAMILY
            .get_or_init(|| {
                register_font_from_memory(ICON_FONT_BYTES).expect(
                    "vimcode-icons.ttf is a well-formed font Core Graphics can parse — a \
                     `None` here would also fire if some other code path in this process \
                     already registered these same bytes under a duplicate PostScript name, \
                     but `registered_icon_font_family`'s whole point is to register them \
                     exactly once, so that isn't expected",
                )
            })
            .clone()
    }

    /// Builds the font the way [`super::super::backend::MacBackend`]
    /// does: register the icon font bytes (once, via
    /// [`registered_icon_font_family`]), then layer its family onto a
    /// base font's cascade via [`font_with_fallback`], exactly what
    /// `MacBackend::set_current_font`/`set_nerd_font_fallback` do to
    /// `current_font`. Returns the cascade-equipped font plus the family
    /// name Core Text resolved the registration to, so a test can assert
    /// against the *actual* registered family rather than assuming it
    /// matches the bytes' nominal name.
    fn icon_font_with_fallback() -> (CTFont, String) {
        let family = registered_icon_font_family();
        let base = font();
        (font_with_fallback(&base, &[family.as_str()]), family)
    }

    /// Host-independent guard for the cascade-pinning fix itself: proves
    /// [`cascade_descriptor_for`] actually consults the exact descriptor
    /// [`register_font_from_memory`] stashed, rather than falling straight
    /// through to [`descriptor_for_family`]'s bare name lookup — the
    /// regression the two tests below can only catch on a host that
    /// happens to have a second font sharing the icon font's family name.
    ///
    /// Without the fix, `cascade_descriptor_for` always returns
    /// `descriptor_for_family(family)`. Two independently-built
    /// family-name-only descriptors for the same family string are
    /// `CFEqual` — confirmed directly against this crate's real Core
    /// Text on real hardware, not assumed — so the assertion below fails
    /// deterministically on *every* host without the fix, not just one
    /// with a colliding font installed. With the fix, `cascade_descriptor_for`
    /// returns the descriptor pinned from `CTFontManagerCreateFontDescriptorsFromData`'s
    /// exact-bytes description, keyed by the font's own PostScript name
    /// rather than the family string, so `CFEqual` against the bare
    /// name-only descriptor is false everywhere.
    #[test]
    fn cascade_descriptor_for_pins_the_exact_registered_descriptor_not_a_name_lookup() {
        let family = registered_icon_font_family();

        let pinned = cascade_descriptor_for(&family);
        let name_only = descriptor_for_family(&family);
        assert_ne!(
            pinned.as_CFType(),
            name_only.as_CFType(),
            "cascade_descriptor_for({family:?}) returned a descriptor identical to a bare \
             family-name lookup — the exact descriptor register_font_from_memory stashed was \
             never consulted, so a test that only checks resolved glyphs would pass even \
             without the fix on a host with no competing font sharing this family name"
        );
    }

    /// Reproduces the exact split a real-screen capture of the native
    /// build showed: three codepoints from vimcode's registered icon
    /// font paint as Apple's placeholder glyph while three others from
    /// the same font, in the same frame, paint correctly. All six have
    /// real cmap entries and outlines in [`ICON_FONT_BYTES`] — see this
    /// module's `cascade_descriptor_for` doc for why a family-name-only
    /// cascade can still miss them when another font on the host shares
    /// the icon font's family name.
    #[test]
    fn icon_font_cascade_resolves_every_registered_pua_codepoint() {
        let (with_fallback, family) = icon_font_with_fallback();
        let bare = font();

        let codepoints = [
            ('\u{EAF0}', "Explorer"),
            ('\u{EA68}', "SourceControl"),
            ('\u{EB91}', "RunDebug"),
            ('\u{F002}', "Search"),
            ('\u{EAE6}', "Extensions"),
            ('\u{F0E5}', "AiChat"),
        ];

        for (ch, label) in codepoints {
            let (bare_family, bare_ok) = resolved_fallback_for_char(&bare, ch);
            assert!(
                !bare_ok,
                "{label} (U+{:04X}) unexpectedly resolved a real glyph through bare \
                 {bare_family:?} with no cascade attached, even after the icon font was \
                 registered process-wide — this negative control must fail, otherwise a \
                 pass below can't tell us the cascade did anything",
                ch as u32,
            );

            let (resolved_family, resolved_real_glyph) =
                resolved_fallback_for_char(&with_fallback, ch);
            assert!(
                resolved_real_glyph,
                "{label} (U+{:04X}) resolved to {resolved_family:?} with no real glyph — \
                 Core Text painted Apple's placeholder instead of a glyph from the \
                 registered icon font",
                ch as u32,
            );
            assert_eq!(
                resolved_family, family,
                "{label} (U+{:04X}) resolved through {resolved_family:?} instead of the \
                 registered icon font family {family:?} — some other font on this host \
                 shares that family name and is winning the cascade lookup",
                ch as u32,
            );
        }
    }

    /// Same cascade, after the activity-bar icon-resize clone — mirrors
    /// [`nerd_font_fallback_resolves_pua_codepoints_before_and_after_icon_resize`]'s
    /// before/after structure but against the real registered icon font
    /// rather than requiring a Nerd Font be separately installed, so it
    /// runs on every host this crate's test suite runs on.
    #[test]
    fn icon_font_cascade_survives_icon_resize_clone() {
        let (with_fallback, family) = icon_font_with_fallback();
        let icon_size_px = crate::ActivityBarStyle::default().resolved_icon_size_px() as f64;
        let icon_sized = with_fallback.clone_with_font_size(icon_size_px);

        let bare = font();
        let (bare_family, bare_ok) = resolved_fallback_for_char(&bare, '\u{EAF0}');
        assert!(
            !bare_ok,
            "Explorer (U+EAF0) unexpectedly resolved a real glyph through bare \
             {bare_family:?} with no cascade attached, even after the icon font was \
             registered process-wide — this negative control must fail, otherwise a pass \
             below can't tell us the cascade did anything",
        );

        let (resolved_family, resolved_real_glyph) =
            resolved_fallback_for_char(&icon_sized, '\u{EAF0}');
        assert!(
            resolved_real_glyph,
            "Explorer (U+EAF0) failed to resolve a real glyph after \
             clone_with_font_size, through family {resolved_family:?} — the \
             activity-bar icon resize must not drop cascade coverage that \
             worked before the resize",
        );
        assert_eq!(
            resolved_family, family,
            "Explorer (U+EAF0) resolved through {resolved_family:?} instead of the \
             registered icon font family {family:?} after clone_with_font_size",
        );
    }
}