guido 0.11.0

A reactive Rust GUI library using wgpu for Wayland layer shell widgets
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
use std::hash::{Hash, Hasher};

use glyphon::cosmic_text::{Align, Ellipsize, EllipsizeHeightLimit, Wrap};
use glyphon::{
    Attrs, Buffer, Cache, Color as GlyphonColor, ColorMode, FontSystem, Metrics, Resolution,
    Shaping, SwashCache, TextArea, TextAtlas, TextBounds, TextRenderer, Viewport,
};
use rustc_hash::FxHashMap;
use wgpu::{Device, MultisampleState, Queue};

use crate::app_state::with_app_state;
use crate::render_stats::{self, Pipeline};
use crate::widgets::font::{FontFamily, FontWeight, LineHeight};
use crate::widgets::{Rect, TextAlign, TextOverflow};

use super::text_measurer::LineFit;
use super::types::TextEntry;

/// Compute a cache key for a text buffer based on content and styling.
/// Two entries with the same key produce identical glyphon Buffers.
fn text_buffer_key(entry: &TextEntry, scale_factor: f32) -> u64 {
    let mut hasher = std::hash::DefaultHasher::new();
    entry.text.hash(&mut hasher);
    (entry.font_size * scale_factor).to_bits().hash(&mut hasher);
    entry.font_weight.hash(&mut hasher);
    entry.line_height.key().hash(&mut hasher);
    entry.font_family.hash(&mut hasher);
    entry.align.hash(&mut hasher);
    let (width, height) = shaping_buffer(entry.rect, scale_factor, entry.align);
    width.to_bits().hash(&mut hasher);
    height.to_bits().hash(&mut hasher);
    entry.fit.map(|fit| fit.key()).hash(&mut hasher);
    hasher.finish()
}

/// The buffer glyphon is given to shape a text of this layout box in, in
/// physical pixels.
///
/// The floors are glyphon's: a buffer narrower than the text it holds wraps it,
/// and a measured box can come back a hair narrower than the thing it measured.
///
/// An aligned text has no width floor: cosmic-text aligns each line across the
/// width it is shaped in, so a label narrower than the floor would be centred
/// in the floor rather than in its own box. A wrapped text's box is its widest
/// line as layout measured it, so that exact width breaks the lines where
/// layout did — `text_aligns_within_its_own_box_at_scale_1_5x` is the golden
/// that would see one break anywhere else.
///
/// It is a function and not four inline multiplications because a text's frost
/// is shaped separately from the text — see [`text_mask`](super::text_mask) —
/// and two shapings that disagree break their lines in different places, which
/// puts frost beside a letter that wrapped somewhere else. The sibling for the
/// transformed path is [`text_quad::shaping_buffer`](super::text_quad::shaping_buffer).
pub(super) fn shaping_buffer(rect: Rect, scale: f32, align: TextAlign) -> (f32, f32) {
    let width = match align {
        TextAlign::Start => rect.width.max(200.0),
        _ => rect.width,
    };
    (width * scale, rect.height.max(50.0) * scale)
}

/// Shape an untransformed text into a fresh buffer, as glyphon will draw it.
fn shape_entry(font_system: &mut FontSystem, entry: &TextEntry, scale_factor: f32) -> Buffer {
    shape(
        font_system,
        &entry.text,
        entry.font_size * scale_factor,
        entry.font_family,
        entry.font_weight,
        entry.line_height,
        entry.align,
        {
            let (width, height) = shaping_buffer(entry.rect, scale_factor, entry.align);
            (Some(width), Some(height))
        },
        entry.fit,
        scale_factor,
    )
}

/// Shape `text` at `font_size` physical pixels: into a buffer of `size`, or,
/// when the text is cut, to the lines `fit` allows at `scale` physical pixels
/// per logical one.
///
/// One function for every path that shapes — the measurer, glyphon's, the
/// transformed quad's and the frost's mask — because a frost has to break and
/// align its lines exactly where the letters over it do, a text has to be
/// drawn on the lines it was measured on, and four copies of this are four
/// places for an option to reach three of.
///
/// A cut text is shaped at the width it was laid out in, so the line the
/// ellipsis lands on is the line the measurer counted — unless it is aligned,
/// when it is shaped at its box's width like every aligned text, since that
/// is the width its lines are aligned across. The two cut it the same way: the
/// box is as wide as the widest line kept, every line that broke did not fit
/// the wider width and does not fit the box, and a marked line kept as many
/// glyphs as fit the wider width, which all fit the box.
///
/// The line height is resolved here and nowhere else, so the measurer and the
/// three draw paths cannot disagree about how tall a line is: `Normal` is the
/// primary face's own (see [`font_line_ratio`]), `Relative` a multiple of the
/// size, and `Absolute` logical pixels taken to physical ones by `scale`. A
/// number that is not a height — zero, negative, not finite — is `Normal`'s
/// answer, because `Metrics` handed one does not come back (#349).
///
/// A cut text is given the height of the lines it keeps, which is where every
/// reader of its lines stops and where shaping stops too. Half a line short of
/// the next one, so a line whose glyphs are taller than the line box neither
/// loses the last line kept nor lets the first one cut back in. That height is
/// the whole of an unmarked cut; a marked one is finished by [`cut_to_lines`].
#[allow(clippy::too_many_arguments)]
pub(super) fn shape(
    font_system: &mut FontSystem,
    text: &str,
    font_size: f32,
    font_family: FontFamily,
    font_weight: FontWeight,
    line_height: LineHeight,
    align: TextAlign,
    size: (Option<f32>, Option<f32>),
    fit: Option<LineFit>,
    scale: f32,
) -> Buffer {
    let px = crate::renderer::text_measurer::shapeable_size(font_size);
    let weight = if font_weight == FontWeight::default() {
        FontWeight::NORMAL
    } else {
        font_weight
    };
    let declared = match line_height {
        LineHeight::Normal => None,
        LineHeight::Relative(factor) => Some(factor * px),
        LineHeight::Absolute(height) => Some(height * scale),
    };
    let line_height = declared
        .filter(|h| h.is_finite() && *h > 0.0)
        .unwrap_or_else(|| font_line_ratio(font_system, font_family, weight) * px);
    let mut buffer = Buffer::new(font_system, Metrics::new(px, line_height));
    let lines = fit.map(|fit| fit.max_lines.max(1) as usize);
    match fit {
        None => buffer.set_size(size.0, size.1),
        Some(fit) => {
            let width = match align {
                TextAlign::Start => fit.width.map(|w| w * scale),
                _ => size.0,
            };
            let cut = lines.map(|n| (n as f32 - 0.5) * line_height);
            buffer.set_size(width, cut);
            if !fit.wrap {
                buffer.set_wrap(Wrap::None);
            }
        }
    }
    buffer.set_text(
        text,
        &Attrs::new()
            .family(font_family.to_cosmic())
            .weight(weight.to_cosmic()),
        Shaping::Advanced,
        cosmic_align(align),
    );
    buffer.shape_until_scroll(font_system, true);
    if let (Some(lines), Some(mark)) = (lines, fit.and_then(|fit| ellipsize(fit.overflow))) {
        cut_to_lines(font_system, &mut buffer, lines, mark);
    }
    buffer
}

/// The line height a family asks for at this weight, over its size, when nothing
/// else is declared.
///
/// Read from the *primary* face — the one that draws a space in this family and
/// weight — as CSS's `normal` reads it from the first available font: a fallback
/// glyph further along the line does not make the line taller. The face is
/// found by shaping, not by asking the font database for the family, because
/// that is how cosmic-text finds it: a generic family names one font
/// (sans-serif is Open Sans), and where that font is not installed the text is
/// drawn in a fallback a database query never returns.
///
/// Ascent, descent and line gap, as Chromium and Parley count them; Pango and
/// Flutter leave the gap out, but a font that declares one is asking for it.
///
/// Kept per family and weight in the application's state: the faces every font
/// system holds are the same ones, fixed once the first of them is built, and a
/// probe is a shaping.
fn font_line_ratio(font_system: &mut FontSystem, family: FontFamily, weight: FontWeight) -> f32 {
    let known = with_app_state(|app| app.line_ratios.borrow().get(&(family, weight)).copied());
    if let Some(ratio) = known {
        return ratio;
    }
    let mut probe = Buffer::new(font_system, Metrics::new(16.0, 16.0));
    probe.set_text(
        " ",
        &Attrs::new()
            .family(family.to_cosmic())
            .weight(weight.to_cosmic()),
        Shaping::Advanced,
        None,
    );
    probe.shape_until_scroll(font_system, false);
    let face = probe
        .layout_runs()
        .find_map(|run| run.glyphs.first().map(|glyph| glyph.font_id));
    let ratio = face
        .and_then(|id| font_system.get_font(id, weight.to_cosmic()))
        .and_then(|font| {
            let m = font.metrics();
            line_ratio(m.ascent, m.descent, m.leading, m.units_per_em)
        })
        .unwrap_or(RATIO_WITHOUT_A_FACE);
    with_app_state(|app| app.line_ratios.borrow_mut().insert((family, weight), ratio));
    ratio
}

/// A face's line height over its size, from its metrics in font units: ascent,
/// descent (negative, below the baseline), line gap and units per em. `None`
/// for metrics that do not make a height — a face that says nothing, or an em
/// of zero.
fn line_ratio(ascent: f32, descent: f32, line_gap: f32, units_per_em: u16) -> Option<f32> {
    let ratio = (ascent - descent + line_gap) / f32::from(units_per_em);
    (ratio.is_finite() && ratio > 0.0).then_some(ratio)
}

/// The line height over the size when no face draws even a space — a font
/// system with no faces at all, where nothing draws. CSS 2.1 suggests 1.0 to 1.2 for `normal`.
const RATIO_WITHOUT_A_FACE: f32 = 1.2;

/// cosmic-text's word for an alignment. `Start` is no word at all, so the
/// text's own direction decides where its lines begin.
fn cosmic_align(align: TextAlign) -> Option<Align> {
    match align {
        TextAlign::Start => None,
        TextAlign::Center => Some(Align::Center),
        TextAlign::End => Some(Align::End),
        TextAlign::Justified => Some(Align::Justified),
    }
}

/// What cosmic-text is asked to mark a one-line cut with. `None` for a cut
/// nothing marks.
fn ellipsize(overflow: TextOverflow) -> Option<Ellipsize> {
    let limit = EllipsizeHeightLimit::Lines(1);
    match overflow {
        TextOverflow::Clip => None,
        TextOverflow::Ellipsis => Some(Ellipsize::End(limit)),
        TextOverflow::EllipsisStart => Some(Ellipsize::Start(limit)),
        TextOverflow::EllipsisMiddle => Some(Ellipsize::Middle(limit)),
    }
}

/// Cut a shaped buffer to `max_lines` lines across all its paragraphs, and
/// mark the cut.
///
/// By hand around cosmic-text's own ellipsis rather than through it, for two
/// reasons. Its limit is per paragraph — a `\n` starts the count again, and a
/// cut that lands on a line break has no mark, because the paragraph before it
/// fit. And a mark it puts on any line but the first starts that line at the
/// blank the wrap broke on, so the last line sits a space to the right of the
/// ones above it — in 0.19 as in 0.18.
///
/// So the last line kept is made a paragraph of its own, split off where it
/// begins, and cosmic-text is asked to mark only that one line, which is the
/// case it gets right. When the cut fell after it rather than inside it, the
/// line is given a `…` of its own to end in. An unwrapped line wider than the
/// box is marked the same way wherever it is: it is one line already.
///
/// `mark` is what the cut line is marked with, as [`ellipsize`] gave it.
fn cut_to_lines(
    font_system: &mut FontSystem,
    buffer: &mut Buffer,
    max_lines: usize,
    mark: Ellipsize,
) {
    let width = buffer.size().0.unwrap_or(f32::INFINITY);
    let mut remaining = max_lines;
    let mut i = 0;
    while i < buffer.lines.len() {
        let layout = buffer.line_layout(font_system, i).unwrap_or_default();
        let count = layout.len();
        let kept = count.min(remaining);
        let last = kept.checked_sub(1).and_then(|at| layout.get(at));
        let too_wide = last.is_some_and(|line| line.w > width);
        let begins_at = last.map_or(0, |line| {
            line.glyphs.iter().map(|g| g.start).min().unwrap_or(0)
        });
        let ends_here = count >= remaining;
        let more_inside = count > remaining;
        let more_after = ends_here && i + 1 < buffer.lines.len();

        if !(more_inside || more_after || too_wide) {
            if ends_here {
                return;
            }
            remaining -= count;
            i += 1;
            continue;
        }

        if ends_here {
            buffer.lines.truncate(i + 1);
        }
        if kept > 1 {
            let rest = buffer.lines[i].split_off(begins_at);
            buffer.lines.insert(i + 1, rest);
            // The lines above the cut, laid out again as they were: a line
            // that has none is where every reader of the buffer stops.
            buffer.line_layout(font_system, i);
            i += 1;
        }
        let mark = if more_inside || too_wide {
            mark
        } else {
            let line = &mut buffer.lines[i];
            let marked = format!("{}\u{2026}", line.text());
            let (ending, attrs) = (line.ending(), line.attrs_list().clone());
            line.set_text(marked, ending, attrs);
            Ellipsize::End(EllipsizeHeightLimit::Lines(1))
        };
        let (fits_in, wrap, font_size) =
            (buffer.size().0, buffer.wrap(), buffer.metrics().font_size);
        let (mono, tab, hinting) = (
            buffer.monospace_width(),
            buffer.tab_width(),
            buffer.hinting(),
        );
        let line = &mut buffer.lines[i];
        line.reset_layout();
        line.layout(
            font_system,
            font_size,
            fits_in,
            wrap,
            mark,
            mono,
            tab,
            hinting,
        );
        if ends_here {
            return;
        }
        remaining -= kept;
        i += 1;
    }
}

pub struct TextRenderState {
    font_system: FontSystem,
    swash_cache: SwashCache,
    #[allow(dead_code)] // Used for viewport and atlas construction
    cache: Cache,
    atlas: TextAtlas,
    /// One renderer per draw group that contains text.
    ///
    /// glyphon draws everything a `TextRenderer` prepared in a single call,
    /// so text that must appear between two other groups needs a renderer of
    /// its own. Grown on demand and reused across frames; a UI with one group
    /// keeps exactly one, as before.
    text_renderers: Vec<TextRenderer>,
    buffers: Vec<Buffer>,
    viewport: Viewport,
    /// Cache of shaped text buffers from the previous frame, keyed by
    /// content+style hash. Avoids expensive Unicode analysis and glyph
    /// shaping for unchanged text. Multi-valued: the same label can appear
    /// several times in a frame (e.g. repeated list items) — with a
    /// single-entry cache the first occurrence consumed the only buffer and
    /// every duplicate re-shaped from scratch, every frame, forever.
    buffer_cache: FxHashMap<u64, Vec<Buffer>>,
    /// Keys for current frame's buffers (parallel to `self.buffers`), used to
    /// repopulate `buffer_cache` at the start of the next frame.
    frame_keys: Vec<u64>,
    /// Positions in the group's texts that the textured-quad path takes, and
    /// what [`prepare_layer`](Self::prepare_layer) hands back.
    ///
    /// A field for the same reason `buffers` is one: the group it describes
    /// lasts a frame, the container it needs does not have to.
    transformed_indices: Vec<usize>,
    /// Positions in the group's texts that glyphon draws, parallel to the
    /// buffers this group pushed.
    ///
    /// Written in the one place a buffer is pushed, so the two lists cannot
    /// come apart: a text area reads the entry and the buffer that was shaped
    /// for it, and an early-out added later drops both or neither. The two
    /// hash sets this replaces said the same thing by saying who was *left
    /// out*, which every skipping branch then had to remember.
    kept: Vec<usize>,
}

/// Whether a text lies entirely off one side of its clip, and so is not drawn
/// at all.
///
/// A whole side, not a corner: two boxes that overlap on neither axis are
/// still both here, and this only says yes when one interval is wholly past
/// the other. The tolerance is for the boundary, where a text ending exactly
/// where its clip does should be kept rather than lost to the last bit of a
/// float.
fn falls_outside(text: Rect, clip: Rect) -> bool {
    const EPSILON: f32 = 0.1;
    text.x + text.width < clip.x - EPSILON
        || text.x > clip.x + clip.width + EPSILON
        || text.y + text.height < clip.y - EPSILON
        || text.y > clip.y + clip.height + EPSILON
}

/// A text's layout box, in world pixels.
///
/// What the culling check has always compared against a clip, lifted out so
/// the routing question below can ask it too. Not outset: widening it here
/// would widen what gets culled, and the two questions want different
/// margins — see the call that adds one.
fn laid_out_in(entry: &TextEntry) -> Rect {
    let (p1x, p1y) = entry.transform.transform_point(entry.rect.x, entry.rect.y);
    let (p2x, p2y) = entry.transform.transform_point(
        entry.rect.x + entry.rect.width,
        entry.rect.y + entry.rect.height,
    );
    Rect::new(
        p1x.min(p2x),
        p1y.min(p2y),
        (p2x - p1x).abs(),
        (p2y - p1y).abs(),
    )
}

impl TextRenderState {
    pub fn new(device: &Device, queue: &Queue, format: wgpu::TextureFormat) -> Self {
        let mut font_system = FontSystem::new();
        for data in crate::get_registered_fonts() {
            font_system
                .db_mut()
                .load_font_source(glyphon::fontdb::Source::Binary(data));
        }
        let swash_cache = SwashCache::new();
        let cache = Cache::new(device);
        let mut atlas = TextAtlas::with_color_mode(device, queue, &cache, format, ColorMode::Web);
        let text_renderer =
            TextRenderer::new(&mut atlas, device, MultisampleState::default(), None);
        let viewport = Viewport::new(device, &cache);

        Self {
            font_system,
            swash_cache,
            cache,
            atlas,
            text_renderers: vec![text_renderer],
            buffers: Vec::new(),
            viewport,
            buffer_cache: FxHashMap::default(),
            frame_keys: Vec::new(),
            transformed_indices: Vec::new(),
            kept: Vec::new(),
        }
    }

    /// Start a frame: recycle last frame's shaped buffers into the cache.
    ///
    /// Split out of [`prepare_layer`](Self::prepare_layer) because a frame may
    /// prepare several groups and the recycling has to happen once for all.
    pub fn begin_frame(&mut self, queue: &Queue, screen: (u32, u32)) {
        for (key, buffer) in self.frame_keys.drain(..).zip(self.buffers.drain(..)) {
            self.buffer_cache.entry(key).or_default().push(buffer);
        }
        // Once per frame, not once per group: every group renders into the
        // same viewport.
        self.viewport.update(
            queue,
            Resolution {
                width: screen.0,
                height: screen.1,
            },
        );
    }

    /// Drop shaped buffers no group asked for. Call once every group has been
    /// prepared — whatever is still cached went unused this frame.
    pub fn end_frame(&mut self) {
        self.buffer_cache.clear();
    }

    /// Prepare one draw group's non-transformed text.
    ///
    /// `slot` selects the renderer, and with it when this text lands relative
    /// to the other groups; see [`render_slot`](Self::render_slot).
    /// Returns the indices, within `texts`, that need the textured-quad path —
    /// borrowed from the scratch they were sorted into, so the group's own
    /// prepare is the one that reads them.
    pub fn prepare_layer(
        &mut self,
        slot: usize,
        device: &Device,
        queue: &Queue,
        texts: &[TextEntry],
        screen: (u32, u32),
        scale_factor: f32,
    ) -> &[usize] {
        let (screen_width, screen_height) = screen;
        while self.text_renderers.len() <= slot {
            self.text_renderers.push(TextRenderer::new(
                &mut self.atlas,
                device,
                MultisampleState::default(),
                None,
            ));
        }
        // Buffers accumulate across the frame's groups; this is where this
        // group's own shaped buffers begin.
        let buffers_start = self.buffers.len();

        self.transformed_indices.clear();
        self.kept.clear();

        for (idx, entry) in texts.iter().enumerate() {
            // Text scaled to nothing is skipped before any work is done for
            // it. The scale comes from the row norms, not from the diagonal:
            // `a` and `d` are both `cos θ` for a rotation, so reading them as
            // the scale calls a quarter turn a collapse and throws the text
            // away at exactly 90° and 270° — and only there, which is why it
            // survived so long. `extract_scale_components` is what the rest of
            // the renderer already asks.
            if !entry.transform.is_identity() && !entry.transform.is_translation_only() {
                let (sx, sy) = entry.transform.extract_scale_components();
                if sx.abs() < 1e-3 || sy.abs() < 1e-3 {
                    continue;
                }
            }

            // Skip text that is completely outside its clip region (culling optimization)
            // Check this FIRST so culled texts don't get rendered via texture path either
            let laid_out = laid_out_in(entry);
            if entry
                .clip
                .is_some_and(|clip| falls_outside(laid_out, clip.world_aabb()))
            {
                // Text is completely outside clip - skip it entirely
                continue;
            }

            // Route all non-translation transforms (rotation, scale) to TextQuadRenderer.
            // This keeps the glyphon atlas stable — only identity/translation text goes through it.
            //
            // And anything glyphon cannot cut. `TextBounds` is four integers,
            // so the only clip it can honour is an upright rectangle: a turned
            // one, or a corner this text actually reaches into, has to be
            // tested in the clip's own space, and the quad is what does that
            // (#405). Asked of where the two answers *differ* rather than
            // whether they can, because a quad costs a rasterization and an
            // upload per text — a label in the middle of a rounded card is cut
            // the same by the box and stays with glyphon.
            let moved = !entry.transform.is_identity() && !entry.transform.is_translation_only();
            // Glyphs overshoot the box they were laid out in — descenders,
            // italics, accents — and ink that overshoots into a corner is ink
            // the box would not have cut. Half the font size is the slack
            // `command_to_text_backdrop` allows for the same reason, and it
            // errs the safe way here: too generous sends a text down the quad
            // path the box would have cut correctly, costing a rasterization;
            // too tight leaves ink outside its clip, which is the defect.
            let ink = laid_out.outset(entry.font_size * 0.5);
            let box_will_not_do = entry
                .clip
                .is_some_and(|clip| !clip.box_cuts_like_the_shape(ink));
            if moved || box_will_not_do {
                self.transformed_indices.push(idx);
                continue; // Skip transformed text in direct rendering
            }

            // Check buffer cache before expensive text shaping
            let key = text_buffer_key(entry, scale_factor);
            let cached = self
                .buffer_cache
                .get_mut(&key)
                .and_then(|buffers| buffers.pop());
            let buffer =
                cached.unwrap_or_else(|| shape_entry(&mut self.font_system, entry, scale_factor));
            self.kept.push(idx);
            self.frame_keys.push(key);
            self.buffers.push(buffer);
        }

        // Destructured so the text areas can borrow the buffers immutably
        // while `prepare` takes the font system and atlas mutably.
        let Self {
            font_system,
            swash_cache,
            atlas,
            viewport,
            buffers,
            text_renderers,
            kept,
            ..
        } = self;

        // Lazy rather than collected: glyphon takes an iterator, so the areas
        // are built as it reads them and the borrow of `buffers` each one
        // carries never has to outlive the call.
        let text_areas = kept
            .iter()
            .map(|&idx| &texts[idx])
            .zip(buffers[buffers_start..].iter())
            .map(|(entry, buffer)| {
                // Position text in world space using the full transform.
                // This is consistent with the clip rect (also in world space via
                // transform_clip_to_world), so TextBounds clipping works correctly.
                let (screen_x, screen_y) =
                    entry.transform.transform_point(entry.rect.x, entry.rect.y);

                // Scale positions for HiDPI rendering
                let scaled_left = screen_x * scale_factor;
                let scaled_top = screen_y * scale_factor;

                // Use clip rect if provided, otherwise use full screen
                // Clip bounds stay in screen space - don't apply transform translation
                // (text position is transformed, but clip region should remain fixed)
                // The box around the clip, because `TextBounds` is four
                // integers and glyphon has nowhere to put a shape. That is
                // exact here rather than approximate: a text this box would
                // cut differently from the shape never reaches this point —
                // `box_cuts_like_the_shape` sent it down the quad path
                // instead, which tests in the clip's own space (#405).
                let bounds = if let Some(clip_rect) = &entry.clip.map(|c| c.world_aabb()) {
                    TextBounds {
                        left: (clip_rect.x * scale_factor) as i32,
                        top: (clip_rect.y * scale_factor) as i32,
                        right: ((clip_rect.x + clip_rect.width) * scale_factor) as i32,
                        bottom: ((clip_rect.y + clip_rect.height) * scale_factor) as i32,
                    }
                } else {
                    TextBounds {
                        left: 0,
                        top: 0,
                        right: screen_width as i32,
                        bottom: screen_height as i32,
                    }
                };

                TextArea {
                    buffer,
                    left: scaled_left,
                    top: scaled_top,
                    scale: 1.0, // Buffer is already scaled, no additional scaling needed
                    bounds,
                    // The fade goes into the colour here: glyphon's atlas
                    // holds coverage and the colour rides each glyph's
                    // vertices, so a new alpha rasterises nothing.
                    default_color: {
                        let color = entry.color.scale_alpha(entry.opacity);
                        GlyphonColor::rgba(
                            (color.r * 255.0) as u8,
                            (color.g * 255.0) as u8,
                            (color.b * 255.0) as u8,
                            (color.a * 255.0) as u8,
                        )
                    },
                    custom_glyphs: &[],
                }
            });

        let result = text_renderers[slot].prepare(
            device,
            queue,
            font_system,
            atlas,
            viewport,
            text_areas,
            swash_cache,
        );

        if let Err(e) = result {
            log::error!("Text prepare failed: {:?}", e);
        }

        &self.transformed_indices
    }

    /// Draw the text prepared into `slot`.
    pub fn render_slot<'a>(&'a self, slot: usize, pass: &mut wgpu::RenderPass<'a>) {
        if let Some(renderer) = self.text_renderers.get(slot) {
            renderer
                .render(&self.atlas, &self.viewport, pass)
                .expect("Failed to render text");
            render_stats::record_draw_calls(Pipeline::Text, 1);
        }
    }
}

/// A text entry with nothing but its box and its placement said.
///
/// Shared by every test module that needs one — `text_quad`'s sets its own
/// `text` on top — rather than written out per module:
/// `TextEntry` has nine public fields and no constructor, so a builder per
/// module is a field list per module to keep in step.
#[cfg(test)]
pub(super) fn test_entry(rect: Rect, transform: crate::transform::Transform) -> TextEntry {
    TextEntry {
        text: "x".into(),
        rect,
        color: crate::widgets::Color::WHITE,
        font_size: 16.0,
        font_family: crate::widgets::FontFamily::default(),
        font_weight: FontWeight::default(),
        line_height: LineHeight::Normal,
        align: Default::default(),
        fit: None,
        opacity: 1.0,
        clip: None,
        transform,
    }
}

/// The per-group scratch is grown once and then kept.
///
/// Capacity and not an allocation count: counting allocations needs an
/// allocator this crate does not install (#461). What a capacity can say is
/// that the container outlived the frame boundary, which is the whole of this
/// change — and a local cannot be asked the question at all.
///
/// The second frame asks for *less* than the first, which is what makes the
/// answer mean something: only a container that was cleared rather than
/// dropped still has the first frame's room in it.
///
/// Five upright texts in that first frame, and not one or two, because a
/// `Vec<usize>` allocates room for four on its first push however few things
/// go into it. With fewer, `kept` reads 4 on a frame that keeps five and 4
/// again on a rebuilt frame that keeps one, and that half of the assertion
/// cannot fail. Five crosses the step to 8. `transformed_indices` needs no
/// such help — it goes from one entry to none, so a rebuilt one reads 0.
#[cfg(test)]
mod scratch_survives_the_frame {
    use super::{TextRenderState, test_entry};
    use crate::renderer::GpuContext;
    use crate::renderer::types::TextEntry;
    use crate::transform::Transform;
    use crate::widgets::Rect;

    #[test]
    fn a_smaller_second_frame_still_has_the_first_frame_s_room() {
        let Some(gpu) = crate::or_skip(GpuContext::try_new()) else {
            return;
        };
        let mut state =
            TextRenderState::new(&gpu.device, &gpu.queue, wgpu::TextureFormat::Rgba8UnormSrgb);

        /// What a `Vec<usize>` allocates for its first push.
        const MIN_CAP: usize = 4;
        /// Enough upright texts to take `kept` past that floor.
        const UPRIGHT: usize = 5;

        // Texts glyphon draws, and then one the quad path takes, so both
        // lists are filled: `kept` holds the first five, `transformed_indices`
        // the last.
        let box_ = Rect::new(0.0, 0.0, 80.0, 20.0);
        let mut texts: Vec<TextEntry> = (0..UPRIGHT)
            .map(|_| test_entry(box_, Transform::default()))
            .collect();
        texts.push(test_entry(box_, Transform::scale(2.0)));

        let frame = |state: &mut TextRenderState, texts: &[TextEntry]| {
            state.begin_frame(&gpu.queue, (200, 100));
            let transformed =
                state.prepare_layer(0, &gpu.device, &gpu.queue, texts, (200, 100), 1.0);
            let quads = transformed.to_vec();
            state.end_frame();
            quads
        };

        assert_eq!(
            frame(&mut state, &texts),
            [UPRIGHT],
            "the scaled text goes to the quad path, and only it"
        );
        let first = (state.transformed_indices.capacity(), state.kept.capacity());
        assert!(
            first.0 > 0 && first.1 > MIN_CAP,
            "five upright and one scaled should fill one list and grow the \
             other past a fresh `Vec`'s floor: {first:?}"
        );

        // One upright text now, and nothing at all for the quad path.
        assert_eq!(frame(&mut state, &texts[..1]), []);
        assert_eq!(
            (state.transformed_indices.capacity(), state.kept.capacity()),
            first,
            "the second frame reused the first frame's scratch"
        );
    }
}

/// What the scale-collapse cull decides, at the boundary and either side.
///
/// The one branch in `prepare_layer` that throws a text away before anything
/// is done for it, and it has been wrong once already: it read the diagonal
/// rather than the row norms, so a quarter turn — where `a` and `d` are both
/// `cos θ` — was called a collapse and the label vanished at exactly 90° and
/// 270°. `tests/text_at_angles.rs` counts the pixels that came back, which is
/// what caught *that*, but pixels cannot see this branch invert: a text the
/// cull lets through at zero scale draws a quad of zero width, so nothing
/// appears either way and the only difference is the work done to produce
/// nothing.
///
/// So this asks the decision rather than the picture. `||` read as `&&` keeps
/// a text flattened on one axis, and the threshold read as `<=` or `==`
/// changes the answer for a text sitting exactly on it — `1e-3` survives
/// `scale_xy` and the row norm unchanged, so the boundary is a real value and
/// not a hair either side of one.
#[cfg(test)]
mod a_text_is_culled_only_when_an_axis_has_collapsed {
    use super::{TextRenderState, test_entry};
    use crate::renderer::GpuContext;
    use crate::transform::Transform;
    use crate::widgets::Rect;

    /// The scale at which a text stops being drawn, as `prepare_layer` spells
    /// it.
    const COLLAPSED: f32 = 1e-3;

    #[test]
    fn one_flattened_axis_is_enough_and_the_threshold_itself_is_not() {
        let Some(gpu) = crate::or_skip(GpuContext::try_new()) else {
            return;
        };
        let mut state =
            TextRenderState::new(&gpu.device, &gpu.queue, wgpu::TextureFormat::Rgba8UnormSrgb);
        let box_ = Rect::new(0.0, 0.0, 80.0, 20.0);

        // `true` where the text should be thrown away. Anything kept is a
        // transformed text, so it leaves by the quad path rather than through
        // glyphon.
        let cases = [
            (Transform::scale_xy(0.0, 1.0), true, "flat in x, whole in y"),
            (Transform::scale_xy(1.0, 0.0), true, "whole in x, flat in y"),
            (Transform::scale_xy(0.0, 0.0), true, "flat in both"),
            (
                Transform::scale_xy(COLLAPSED, 1.0),
                false,
                "x exactly at the threshold, which is not below it",
            ),
            (
                Transform::scale_xy(1.0, COLLAPSED),
                false,
                "y exactly at the threshold",
            ),
            (
                Transform::rotate(std::f32::consts::FRAC_PI_2),
                false,
                "a quarter turn, where the diagonal is zero and the scale is not",
            ),
        ];

        for (transform, culled, what) in cases {
            let texts = [test_entry(box_, transform)];
            state.begin_frame(&gpu.queue, (200, 100));
            let transformed =
                state.prepare_layer(0, &gpu.device, &gpu.queue, &texts, (200, 100), 1.0);
            let quads = transformed.to_vec();
            let kept = state.kept.len();
            state.end_frame();

            assert_eq!(
                quads.is_empty(),
                culled,
                "{what}: {quads:?} went to the quad path"
            );
            assert_eq!(kept, 0, "{what}: a transformed text never reaches glyphon");
        }
    }
}

#[cfg(test)]
mod laid_out_tests {
    use super::{laid_out_in, test_entry as entry};
    use crate::transform::Transform;
    use crate::widgets::Rect;

    /// The box a text was laid out in, carried through its placement.
    ///
    /// Two callers read it — what gets culled against its clip, and what gets
    /// routed away from glyphon — so every term here decides whether a text is
    /// drawn at all or drawn through the wrong pipeline. It is four
    /// arithmetic operations and each of them can be written backwards without
    /// the picture obviously changing.
    /// A text is dropped only when it is wholly past one side of its clip.
    ///
    /// The cheapest thing the text path does and the easiest to get backwards:
    /// too eager and a visible text is never drawn, with nothing to say why.
    #[test]
    fn a_text_is_dropped_only_when_it_is_wholly_outside_its_clip() {
        use super::falls_outside;
        let clip = Rect::new(100.0, 100.0, 200.0, 100.0);

        assert!(
            !falls_outside(Rect::new(150.0, 120.0, 40.0, 20.0), clip),
            "inside"
        );
        assert!(
            !falls_outside(Rect::new(0.0, 0.0, 400.0, 400.0), clip),
            "over all of it"
        );

        // A whole side past, on each of the four.
        assert!(
            falls_outside(Rect::new(10.0, 120.0, 80.0, 20.0), clip),
            "left of it"
        );
        assert!(
            falls_outside(Rect::new(310.0, 120.0, 80.0, 20.0), clip),
            "right of it"
        );
        assert!(
            falls_outside(Rect::new(150.0, 10.0, 40.0, 80.0), clip),
            "above it"
        );
        assert!(
            falls_outside(Rect::new(150.0, 210.0, 40.0, 80.0), clip),
            "below it"
        );

        // Just reaching in on each side is not outside — the far edge is what
        // decides, and reading the near one instead keeps a text that has
        // gone and drops one that is still here.
        assert!(
            !falls_outside(Rect::new(20.0, 120.0, 81.0, 20.0), clip),
            "reaching in from the left"
        );
        assert!(
            !falls_outside(Rect::new(299.0, 120.0, 80.0, 20.0), clip),
            "reaching in from the right"
        );
        assert!(
            !falls_outside(Rect::new(150.0, 20.0, 40.0, 81.0), clip),
            "reaching in from above"
        );
        assert!(
            !falls_outside(Rect::new(150.0, 199.0, 40.0, 80.0), clip),
            "reaching in from below"
        );

        // Overlapping on neither axis is still two boxes in the same frame,
        // and a corner-to-corner pair is outside by both.
        assert!(
            falls_outside(Rect::new(0.0, 0.0, 50.0, 50.0), clip),
            "off the top-left corner"
        );

        // The tolerance, which is the whole reason there is one. A text
        // ending exactly where its clip begins is kept, and so is one a
        // hundredth of a pixel short of it — which is where a float lands
        // after a transform. Half a pixel past is gone. The margin runs
        // outward on every side; inward on any of them drops a text that is
        // still touching its clip.
        for (label, text) in [
            (
                "ending exactly at the left edge",
                Rect::new(20.0, 120.0, 80.0, 20.0),
            ),
            (
                "a hundredth short of the left edge",
                Rect::new(20.0, 120.0, 79.99, 20.0),
            ),
            (
                "starting exactly at the right edge",
                Rect::new(300.0, 120.0, 80.0, 20.0),
            ),
            (
                "a hundredth past the right edge",
                Rect::new(300.01, 120.0, 80.0, 20.0),
            ),
            (
                "ending exactly at the top edge",
                Rect::new(150.0, 20.0, 40.0, 80.0),
            ),
            (
                "starting exactly at the bottom edge",
                Rect::new(150.0, 200.0, 40.0, 80.0),
            ),
        ] {
            assert!(
                !falls_outside(text, clip),
                "{label}: a text touching its clip is still drawn"
            );
        }
        for (label, text) in [
            (
                "half a pixel short of the left edge",
                Rect::new(20.0, 120.0, 79.5, 20.0),
            ),
            (
                "half a pixel past the right edge",
                Rect::new(300.5, 120.0, 80.0, 20.0),
            ),
            (
                "half a pixel short of the top edge",
                Rect::new(150.0, 20.0, 40.0, 79.5),
            ),
            (
                "half a pixel past the bottom edge",
                Rect::new(150.0, 200.5, 40.0, 80.0),
            ),
        ] {
            assert!(
                falls_outside(text, clip),
                "{label}: past the tolerance is past the clip"
            );
        }
    }

    #[test]
    fn a_text_is_laid_out_where_its_placement_puts_it() {
        let r = Rect::new(10.0, 20.0, 100.0, 40.0);

        let plain = laid_out_in(&entry(r, Transform::IDENTITY));
        assert_eq!((plain.x, plain.y), (10.0, 20.0));
        assert_eq!((plain.width, plain.height), (100.0, 40.0));

        let moved = laid_out_in(&entry(r, Transform::translate(5.0, -7.0)));
        assert_eq!((moved.x, moved.y), (15.0, 13.0));
        assert_eq!((moved.width, moved.height), (100.0, 40.0));

        let scaled = laid_out_in(&entry(r, Transform::scale_xy(2.0, 3.0)));
        assert_eq!((scaled.x, scaled.y), (20.0, 60.0));
        assert_eq!((scaled.width, scaled.height), (200.0, 120.0));

        // A mirror puts the far corner first, and the box is still a box with
        // a positive extent — which is why the corners are taken as a min and
        // an absolute difference rather than as first and second.
        let mirrored = laid_out_in(&entry(r, Transform::scale_xy(-1.0, 1.0)));
        assert_eq!((mirrored.x, mirrored.y), (-110.0, 20.0));
        assert_eq!((mirrored.width, mirrored.height), (100.0, 40.0));
    }
}

#[cfg(test)]
mod shaping_buffer_tests {
    use super::shaping_buffer;
    use crate::widgets::{Rect, TextAlign};

    /// The floors are in logical pixels and the scale is applied after them, so
    /// a small box on a HiDPI screen gets the floor at that screen's density
    /// rather than a floor that shrinks as the screen gets finer.
    #[test]
    fn the_floor_is_logical_and_the_scale_comes_after_it() {
        assert_eq!(
            shaping_buffer(Rect::new(0.0, 0.0, 50.0, 10.0), 1.0, TextAlign::Start),
            (200.0, 50.0)
        );
        assert_eq!(
            shaping_buffer(Rect::new(0.0, 0.0, 50.0, 10.0), 2.0, TextAlign::Start),
            (400.0, 100.0)
        );
    }

    /// Above the floors the buffer is the box, scaled — and scaled, not offset,
    /// which is the whole of what makes it agree with a glyph drawn at that
    /// scale.
    #[test]
    fn a_box_above_the_floor_is_carried_by_the_scale_alone() {
        assert_eq!(
            shaping_buffer(Rect::new(0.0, 0.0, 300.0, 80.0), 1.0, TextAlign::Start),
            (300.0, 80.0)
        );
        assert_eq!(
            shaping_buffer(Rect::new(0.0, 0.0, 300.0, 80.0), 2.0, TextAlign::Start),
            (600.0, 160.0)
        );
        // The floor is logical, so a scale below 1 can carry the buffer under
        // it: 80 clears the floor of 50 and then halves to 40.
        assert_eq!(
            shaping_buffer(Rect::new(0.0, 0.0, 300.0, 80.0), 0.5, TextAlign::Start),
            (150.0, 40.0)
        );
    }

    /// The two rules are not the same rule, which is why a coverage mask has to
    /// pick one rather than assume. If this ever passes, `text_mask` no longer
    /// has a choice to get wrong — and the comment saying it does is stale.
    #[test]
    fn the_transformed_shaper_asks_for_something_else() {
        let rect = Rect::new(0.0, 0.0, 72.0, 80.0);
        assert_ne!(
            shaping_buffer(rect, 4.0, TextAlign::Start),
            super::super::text_quad::shaping_buffer(rect, 4.0, TextAlign::Start),
            "a 72-point box: 400 texels through this one and 317 through the other"
        );
    }
}

/// A line is aligned across the text's own box, whatever the renderer's floor.
///
/// Shaped with the vendored font alone, so the widths are the font's and not
/// the machine's. The box is 120 wide — under the 200 the shaper is otherwise
/// given — and the line is far shorter than that, so a line centred in the
/// floor instead of the box starts 40 pixels late, and one never aligned at
/// all starts at nought.
#[cfg(test)]
mod a_line_is_aligned_in_its_own_box {
    use super::{shape_entry, test_entry, text_buffer_key};
    use crate::transform::Transform;
    use crate::widgets::{FontFamily, Rect, TextAlign};
    use glyphon::FontSystem;

    const FONT: &[u8] = include_bytes!("../../tests/assets/DejaVuSansMono.ttf");
    const BOX: f32 = 120.0;

    fn entry(align: TextAlign) -> super::TextEntry {
        let mut entry = test_entry(Rect::new(0.0, 0.0, BOX, 20.0), Transform::default());
        entry.text = "hi".into();
        entry.font_family = FontFamily::name("DejaVu Sans Mono");
        entry.align = align;
        entry
    }

    /// Where the first line's glyphs begin and how wide the line is, in
    /// physical pixels.
    fn first_line(align: TextAlign, scale: f32) -> (f32, f32) {
        let mut db = glyphon::fontdb::Database::new();
        db.load_font_data(FONT.to_vec());
        let mut font_system = FontSystem::new_with_locale_and_db("en-US".into(), db);
        let buffer = shape_entry(&mut font_system, &entry(align), scale);
        let run = buffer.layout_runs().next().expect("a line");
        let start = run.glyphs.iter().map(|g| g.x).fold(f32::INFINITY, f32::min);
        (start, run.line_w)
    }

    #[test]
    fn a_centred_line_is_centred_in_its_box_and_not_in_the_floor() {
        for scale in [1.0, 2.0] {
            let (start, width) = first_line(TextAlign::Center, scale);
            let expected = (BOX * scale - width) / 2.0;
            assert!(
                (start - expected).abs() < 0.5,
                "at scale {scale} a {width}-pixel line in a {}-pixel box starts at \
                 {start}, not at {expected}",
                BOX * scale
            );
        }
    }

    #[test]
    fn an_end_aligned_line_ends_where_its_box_does() {
        let (start, width) = first_line(TextAlign::End, 1.0);
        assert!(
            (start + width - BOX).abs() < 0.5,
            "the line ends at {} in a box that ends at {BOX}",
            start + width
        );
    }

    #[test]
    fn a_start_aligned_line_starts_at_the_box() {
        let (start, _) = first_line(TextAlign::Start, 1.0);
        assert!(start.abs() < 0.5, "the line starts at {start}");
    }

    /// Two texts that differ only in alignment are two different buffers, so
    /// the cache must not hand one the other's.
    #[test]
    fn alignment_is_part_of_the_cache_key() {
        let keys: Vec<u64> = [
            TextAlign::Start,
            TextAlign::Center,
            TextAlign::End,
            TextAlign::Justified,
        ]
        .map(|align| text_buffer_key(&entry(align), 1.0))
        .into();
        for (i, a) in keys.iter().enumerate() {
            for b in &keys[i + 1..] {
                assert_ne!(a, b, "two alignments share a cached buffer");
            }
        }
    }
}

/// Two texts that differ only in line height are two buffers, so the glyphon
/// path's cache must not hand one the other's lines.
#[cfg(test)]
#[test]
fn line_height_is_part_of_the_buffer_key() {
    use crate::transform::Transform;
    let entry = |line_height| TextEntry {
        line_height,
        ..test_entry(Rect::new(0.0, 0.0, 120.0, 40.0), Transform::default())
    };
    assert_ne!(
        text_buffer_key(&entry(LineHeight::Normal), 1.0),
        text_buffer_key(&entry(LineHeight::Absolute(30.0)), 1.0),
    );
    assert_ne!(
        text_buffer_key(&entry(LineHeight::Relative(2.0)), 1.0),
        text_buffer_key(&entry(LineHeight::Absolute(2.0)), 1.0),
        "a factor and a height of the same number are not the same line",
    );
}

/// An aligned text that is cut is cut where it was measured, and its lines are
/// aligned across its own box.
///
/// The measurer shapes a cut text at the width it was laid out in; an aligned
/// one is drawn at its box's width, which is its widest kept line — the width
/// its lines are aligned across. The two must keep the same glyphs on the same
/// lines, the mark included, or a label is measured on one set of lines and
/// drawn on another. With the vendored font, so the widths are the font's.
#[cfg(test)]
mod an_aligned_cut_is_the_measured_cut {
    use super::shape;
    use crate::renderer::LineFit;
    use crate::widgets::{FontFamily, FontWeight, LineHeight, TextAlign, TextOverflow};
    use glyphon::FontSystem;

    const FONT: &[u8] = include_bytes!("../../tests/assets/DejaVuSansMono.ttf");
    const WORDS: &str = "one two three four five six seven eight nine ten eleven twelve";
    const OFFERED: f32 = 150.0;
    const SIZE: f32 = 16.0;

    fn font_system() -> FontSystem {
        let mut db = glyphon::fontdb::Database::new();
        db.load_font_data(FONT.to_vec());
        FontSystem::new_with_locale_and_db("en-US".into(), db)
    }

    fn fit(overflow: TextOverflow) -> LineFit {
        LineFit {
            width: Some(OFFERED),
            max_lines: 2,
            overflow,
            wrap: true,
        }
    }

    /// Each line as its glyph ids, where it starts and how wide it is.
    fn lines(
        align: TextAlign,
        width: Option<f32>,
        fit: LineFit,
        scale: f32,
    ) -> Vec<(Vec<u16>, f32, f32)> {
        let family = FontFamily::name("DejaVu Sans Mono");
        let buffer = shape(
            &mut font_system(),
            WORDS,
            SIZE * scale,
            family,
            FontWeight::NORMAL,
            LineHeight::Normal,
            align,
            (width, Some(1000.0)),
            Some(fit),
            scale,
        );
        buffer
            .layout_runs()
            .map(|run| {
                let start = run.glyphs.iter().map(|g| g.x).fold(f32::INFINITY, f32::min);
                (
                    run.glyphs.iter().map(|g| g.glyph_id).collect(),
                    start,
                    run.line_w,
                )
            })
            .collect()
    }

    fn ellipsis_glyph() -> u16 {
        let buffer = shape(
            &mut font_system(),
            "\u{2026}",
            SIZE,
            FontFamily::name("DejaVu Sans Mono"),
            FontWeight::NORMAL,
            LineHeight::Normal,
            TextAlign::Start,
            (None, None),
            None,
            1.0,
        );
        buffer.layout_runs().next().unwrap().glyphs[0].glyph_id
    }

    #[test]
    fn a_centred_ellipsis_keeps_the_measured_lines_and_centres_them_in_the_box() {
        for overflow in [TextOverflow::Ellipsis, TextOverflow::Clip] {
            // As the measurer shapes it: at the width layout offered.
            let measured = lines(TextAlign::Start, None, fit(overflow), 1.0);
            assert_eq!(measured.len(), 2, "{measured:?}");
            let widest = measured.iter().map(|l| l.2).fold(0.0, f32::max);

            for scale in [1.0, 2.0] {
                let drawn = lines(
                    TextAlign::Center,
                    Some(widest * scale),
                    fit(overflow),
                    scale,
                );
                let glyphs = |ls: &[(Vec<u16>, f32, f32)]| {
                    ls.iter().map(|l| l.0.clone()).collect::<Vec<_>>()
                };
                assert_eq!(
                    glyphs(&drawn),
                    glyphs(&measured),
                    "{overflow:?} at {scale}x cut somewhere else than it was measured"
                );
                for (_, start, width) in &drawn {
                    let expected = (widest * scale - width) / 2.0;
                    assert!(
                        (start - expected).abs() < 0.5,
                        "{overflow:?} at {scale}x: a {width}-pixel line starts at \
                         {start}, not centred at {expected}"
                    );
                }
            }
            if overflow == TextOverflow::Ellipsis {
                assert_eq!(measured[1].0.last(), Some(&ellipsis_glyph()));
            }
        }
    }
}

/// A generic family whose configured name is not installed still has a face
/// that draws it — cosmic-text falls back to one — and `Normal` is that face's
/// line height, not a guess. cosmic-text names Open Sans for sans-serif, which
/// most machines do not have; here the only face is DejaVu Sans Mono.
#[cfg(test)]
#[test]
fn normal_is_the_line_height_of_the_face_that_draws_the_text() {
    const FONT: &[u8] = include_bytes!("../../tests/assets/DejaVuSansMono.ttf");
    let mut db = glyphon::fontdb::Database::new();
    db.load_font_data(FONT.to_vec());
    let mut font_system = FontSystem::new_with_locale_and_db("en-US".into(), db);
    let ratio = font_line_ratio(&mut font_system, FontFamily::SansSerif, FontWeight::NORMAL);
    assert!(
        (ratio - 1.1640625).abs() < 1e-4,
        "{ratio} is not DejaVu Sans Mono's own 1.164"
    );
}

/// A face's own line is its ascent, its descent and its line gap, all three:
/// the vendored font declares no gap, so only a face that does can tell a gap
/// added from a gap taken away.
#[cfg(test)]
#[test]
fn a_face_s_line_counts_its_ascent_descent_and_gap() {
    assert_eq!(line_ratio(800.0, -200.0, 200.0, 1000), Some(1.2));
    assert_eq!(line_ratio(800.0, -200.0, 0.0, 2000), Some(0.5));
}

/// Metrics that make no height are not a ratio, so the caller falls back
/// rather than hand `Metrics` a line that does not come back (#349).
#[cfg(test)]
#[test]
fn metrics_that_make_no_height_are_no_ratio() {
    assert_eq!(line_ratio(800.0, -200.0, 0.0, 0), None, "an em of zero");
    assert_eq!(
        line_ratio(0.0, 0.0, 0.0, 1000),
        None,
        "a face that says nothing"
    );
    assert_eq!(line_ratio(f32::NAN, -200.0, 0.0, 1000), None);
}

/// An absolute line height is logical pixels, so a text shaped at twice the
/// scale has lines twice as tall — the step every draw path at HiDPI takes.
#[cfg(test)]
#[test]
fn an_absolute_line_height_is_scaled_with_the_text() {
    const FONT: &[u8] = include_bytes!("../../tests/assets/DejaVuSansMono.ttf");
    let mut db = glyphon::fontdb::Database::new();
    db.load_font_data(FONT.to_vec());
    let mut font_system = FontSystem::new_with_locale_and_db("en-US".into(), db);
    let line = |font_system: &mut FontSystem, scale: f32| {
        shape(
            font_system,
            "a",
            14.0 * scale,
            FontFamily::name("DejaVu Sans Mono"),
            FontWeight::NORMAL,
            LineHeight::Absolute(20.0),
            TextAlign::Start,
            (None, None),
            None,
            scale,
        )
        .metrics()
        .line_height
    };
    assert_eq!(line(&mut font_system, 1.0), 20.0);
    assert_eq!(line(&mut font_system, 2.0), 40.0);
}