mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
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
// The fixture drives a glyph store as the tile store's update does: it keeps
// the waits of its tiles, takes in what arrives in its inbox, and asks the
// store again whenever the store wakes it.

#![expect(clippy::disallowed_types, reason = "single-threaded test harness")]

use std::cell::{RefCell, RefMut};
use std::collections::VecDeque;
use std::num::NonZeroU16;
use std::rc::{Rc, Weak};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
use std::thread::ThreadId;

use mln_style::bitmap::AlphaImage;
use mln_style::collections::{VecMap, VecSet};
use mln_style::i18n;
use mln_style::size::Size;
use parking_lot::Mutex;

use super::{GlyphStore, GlyphWait, ResolvedGlyphs};
use crate::exec::pool::{Pool, TaskGroup};
use crate::exec::queue::Queue;
use crate::render::events::RendererEvent;
use crate::storage::response::{Reason, ResourceError};
use crate::storage::stub_file_source::{ResponseType, StubFileSource};
use crate::storage::{FileSource, Kind, Resource, Response};
use crate::text::font_face_engine::{FontFaceEngine, FontFaceShaper};
use crate::text::font_stack::FontStack;
use crate::text::glyph::{
    FontData, FontFace, Glyph, GlyphDependencies, GlyphFont, GlyphID, GlyphIDs, GlyphMetrics, GlyphRange,
    ShapeRequests, glyph_range,
};
use crate::text::glyph_cache::GlyphCache;
use crate::text::local_fonts::{FontChooser, LocalGlyphRasterizer, LocalGlyphs};
use crate::text::tagged_string::font_stack_hash;
use crate::text::tiny_sdf::transform_raster_to_sdf;
use crate::text::{GlyphAdjust, ShapedText};
use crate::tile_store::inbox::{Inbox, TileEvent};

/// A glyph PBF of range 0–255, with 'a', 'å', ' ', 'E' and others.
const GLYPHS: &str = "test/fixtures/resources/glyphs.pbf";
/// A glyph PBF of range 0–255 with 'E' and without 'A'.
const FAKE_GLYPHS: &str = "test/fixtures/resources/fake_glyphs-0-255.pbf";
/// A glyph PBF of the range of '々' and 'テ'.
const CJK_GLYPHS: &str = "test/fixtures/resources/glyphs-12244-12543.pbf";

/// The local fonts' glyph, whatever glyph they are asked for: a 24×24
/// square of coverage on a 30×30 raster.
fn stub_glyph(glyph_id: GlyphID) -> Glyph {
    let coverage: Vec<u8> = (0..30 * 30)
        .map(|i| if (3..27).contains(&(i % 30)) && (3..27).contains(&(i / 30)) { 255 } else { 0 })
        .collect();
    Glyph {
        id: glyph_id,
        metrics: GlyphMetrics { width: 24, height: 24, left: 0.0, top: -8.0, advance: 24, ..Default::default() },
        bitmap: AlphaImage::from_slice(Size::new(30, 30), &coverage).unwrap(),
    }
}

/// Local fonts with the glyphs of CJK characters
/// (`i18n::allows_fixed_width_glyph_generation`).
struct CjkRasterizer;

impl LocalGlyphRasterizer for CjkRasterizer {
    fn rasterize_glyph(&self, _font_stack: &FontStack, glyph_id: GlyphID) -> Option<Glyph> {
        glyph_id.char().is_some_and(i18n::allows_fixed_width_glyph_generation).then(|| stub_glyph(glyph_id))
    }
}

/// Local fonts with one glyph, katakana テ.
struct KatakanaRasterizer;

impl LocalGlyphRasterizer for KatakanaRasterizer {
    fn rasterize_glyph(&self, _font_stack: &FontStack, glyph_id: GlyphID) -> Option<Glyph> {
        (glyph_id.code == 'テ' as u16).then(|| stub_glyph(glyph_id))
    }
}

/// Local fonts with every glyph, with an advance of `advance`, drawn at
/// twice the resolution if `double_resolution`.
struct EveryRasterizer {
    advance: u32,
    double_resolution: bool,
}

impl LocalGlyphRasterizer for EveryRasterizer {
    fn rasterize_glyph(&self, _font_stack: &FontStack, glyph_id: GlyphID) -> Option<Glyph> {
        let glyph = stub_glyph(glyph_id);
        let metrics =
            GlyphMetrics { advance: self.advance, is_double_resolution: self.double_resolution, ..glyph.metrics };
        Some(Glyph { metrics, ..glyph })
    }
}

/// Local fonts that draw every glyph as the stub's.
fn every_glyph() -> EveryRasterizer {
    EveryRasterizer { advance: 24, double_resolution: false }
}

/// Local fonts that draw every glyph wider than any other source's, so that
/// a test tells their glyphs apart.
fn wide_glyphs() -> EveryRasterizer {
    EveryRasterizer { advance: 99, double_resolution: false }
}

/// Local glyphs from `rasterizer`, CJK first, without device fonts, as in
/// the browser.
fn local(rasterizer: impl LocalGlyphRasterizer + 'static) -> LocalGlyphs {
    LocalGlyphs { ideographs: true, chooser: None, rasterizer: Some(Arc::new(rasterizer)) }
}

/// The device's fonts as faces whose files hold their names: `fonts` names
/// the font of each character, if one draws it, and a cluster takes its first
/// character's unless `clusters` names one for the whole cluster. Records the
/// first character of each cluster it is asked about, and the thread that
/// asked.
struct DeviceFonts {
    fonts: fn(char) -> Option<&'static str>,
    clusters: fn(&[char]) -> Option<&'static str>,
    weight: u16,
    asked: Mutex<Vec<(char, ThreadId)>>,
}

impl DeviceFonts {
    fn new(fonts: fn(char) -> Option<&'static str>) -> Arc<DeviceFonts> {
        Arc::new(DeviceFonts { fonts, clusters: |_| None, weight: 400, asked: Mutex::default() })
    }

    /// The characters asked about, in order.
    fn asked(&self) -> Vec<char> {
        self.asked.lock().iter().map(|(c, _)| *c).collect()
    }
}

impl FontChooser for DeviceFonts {
    fn choose(&self, _font_stack: &FontStack, cluster: &[char]) -> Option<FontFace> {
        self.asked.lock().push((cluster[0], std::thread::current().id()));
        let font = (self.clusters)(cluster).or_else(|| (self.fonts)(cluster[0]))?;
        Some(FontFace::device(font, self.weight, FontData::from(font.as_bytes().to_vec())))
    }
}

/// Local glyphs from `fonts`, CJK first.
fn device(fonts: &Arc<DeviceFonts>) -> LocalGlyphs {
    LocalGlyphs { ideographs: true, chooser: Some(Arc::<DeviceFonts>::clone(fonts)), rasterizer: None }
}

/// A glyph store, the waits it hasn't answered, and what it reported and
/// answered.
struct Store {
    glyphs: RefCell<GlyphStore>,
    /// Where the responses arrive.
    inbox: Inbox,
    /// Where it requests from: `None` once a test takes it away.
    file_source: RefCell<Option<Arc<dyn FileSource>>>,
    waits: RefCell<Vec<(GlyphDependencies, GlyphWait)>>,
    events: RefCell<Vec<RendererEvent>>,
    answers: RefCell<VecDeque<ResolvedGlyphs>>,
}

impl Store {
    /// Keeps what the store reported since the last call.
    fn report(&self) {
        let events = self.glyphs.borrow_mut().take_events();
        self.events.borrow_mut().extend(events);
    }

    /// Takes in the responses and device fonts that arrived.
    fn take_responses(&self) {
        while let Some(event) = self.inbox.next() {
            match event {
                TileEvent::Glyphs { font_stack, range, id, result } => {
                    self.glyphs.borrow_mut().take_response(&font_stack, range, id, result);
                }
                TileEvent::DeviceFonts { font_stack, faces } => {
                    self.glyphs.borrow_mut().take_device_fonts(&font_stack, faces);
                }
                _ => {}
            }
        }
        self.report();
    }

    /// Answers the waits the store can answer now.
    fn answer(&self) {
        let waits = std::mem::take(&mut *self.waits.borrow_mut());
        let file_source = self.file_source.borrow().clone();
        for (dependencies, mut wait) in waits {
            let resolved =
                self.glyphs.borrow_mut().resolve(&dependencies, &mut wait, file_source.as_ref(), self.inbox.sender());
            match resolved {
                Some(resolved) => self.answers.borrow_mut().push_back(resolved),
                None => self.waits.borrow_mut().push((dependencies, wait)),
            }
        }
        self.report();
    }
}

struct Fixture {
    /// Runs the store's wakes and the asynchronous file source's responses.
    run_loop: Queue<Weak<Store>>,
    file_source: Arc<StubFileSource>,
    store: Rc<Store>,
}

impl Fixture {
    fn new(local: LocalGlyphs, response_type: ResponseType) -> Self {
        Self::with_all(local, response_type, Arc::default(), crate::text::font_face_engine::default_engine())
    }

    fn with_all(
        local: LocalGlyphs,
        response_type: ResponseType,
        glyph_cache: Arc<GlyphCache>,
        engine: Arc<dyn FontFaceEngine>,
    ) -> Self {
        let run_loop = Queue::new();
        let file_source = StubFileSource::on_queue(&run_loop, response_type);
        // The wakes before the task runs share it.
        let (woken, queue) = (Arc::new(AtomicBool::new(false)), run_loop.downgrade());
        let wake: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
            if woken.swap(true, Ordering::SeqCst) {
                return;
            }
            let woken = Arc::clone(&woken);
            if let Some(queue) = queue.upgrade() {
                queue.post(move |store: &mut Weak<Store>| {
                    woken.store(false, Ordering::SeqCst);
                    if let Some(store) = store.upgrade() {
                        store.take_responses();
                        store.glyphs.borrow_mut().update();
                        store.report();
                        store.answer();
                    }
                });
            }
        });
        let pool = TaskGroup::new(&Pool::new(4));
        let glyphs = GlyphStore::new(local, glyph_cache, pool, engine, Arc::clone(&wake));
        let source: Arc<dyn FileSource> = Arc::<StubFileSource>::clone(&file_source);
        let store = Rc::new(Store {
            glyphs: RefCell::new(glyphs),
            inbox: Inbox::new(wake),
            file_source: RefCell::new(Some(source)),
            waits: RefCell::default(),
            events: RefCell::default(),
            answers: RefCell::default(),
        });
        Fixture { run_loop, file_source, store }
    }

    fn glyphs(&self) -> RefMut<'_, GlyphStore> {
        self.store.glyphs.borrow_mut()
    }

    /// Serves every glyph request with `responder`.
    fn respond(&self, responder: impl Fn(&Resource) -> Option<Response> + Send + Sync + 'static) {
        self.file_source.set_response(Kind::Glyphs, responder);
    }

    /// A tile's wait for `dependencies`, answered at once if the store can.
    fn request(&self, dependencies: GlyphDependencies) {
        self.store.waits.borrow_mut().push((dependencies, GlyphWait::default()));
        self.store.answer();
    }

    /// Runs one task of the test's queue, if one is there.
    fn turn(&self) {
        self.run_loop.run_once(&mut Rc::downgrade(&self.store));
    }

    /// Runs the test's queue until `done`, as answers arrive from the pool.
    fn run_until(&self, done: impl Fn(&Self) -> bool) {
        let mut store = Rc::downgrade(&self.store);
        while !done(self) {
            if !self.run_loop.run_once(&mut store) {
                self.run_loop.park();
            }
        }
    }

    fn has_answer(&self) -> bool {
        !self.store.answers.borrow().is_empty()
    }

    /// The oldest answer not taken yet, once there is one.
    fn next_answer(&self) -> ResolvedGlyphs {
        self.run_until(Self::has_answer);
        self.store.answers.borrow_mut().pop_front().unwrap()
    }

    /// Requests `dependencies` and runs until the oldest wait is answered:
    /// its answer.
    fn answered(&self, dependencies: GlyphDependencies) -> ResolvedGlyphs {
        self.request(dependencies);
        self.next_answer()
    }

    /// Loads `c` of `font_stack` from the `GLYPHS` fixture: the store's glyph.
    fn load(&self, font_stack: &FontStack, c: char) -> Arc<Glyph> {
        self.respond(serve(GLYPHS));
        self.glyphs().set_url(GLYPHS);
        let ids: GlyphIDs = [gid(c)].into_iter().collect();
        self.answered(GlyphDependencies {
            glyphs: VecMap::from([(font_stack.clone(), ids)]),
            shapes: ShapeRequests::default(),
        });
        self.glyphs().glyph(font_stack, gid(c))
    }

    /// The glyph events the store reported, in order, with their font
    /// stacks and ranges.
    fn glyph_events(&self) -> Vec<(&'static str, FontStack, GlyphRange)> {
        let events = self.store.events.borrow();
        events
            .iter()
            .filter_map(|event| match event {
                RendererEvent::GlyphsRequested { font_stack, range } => Some(("requested", font_stack.clone(), *range)),
                RendererEvent::GlyphsLoaded { font_stack, range } => Some(("loaded", font_stack.clone(), *range)),
                RendererEvent::GlyphsError { font_stack, range, .. } => Some(("error", font_stack.clone(), *range)),
                _ => None,
            })
            .collect()
    }

    /// The font stacks and ranges of the glyph events named `name`.
    fn ranges(&self, name: &str) -> Vec<(FontStack, GlyphRange)> {
        self.glyph_events()
            .into_iter()
            .filter(|(event, ..)| *event == name)
            .map(|(_, font_stack, range)| (font_stack, range))
            .collect()
    }

    fn requests(&self) -> usize {
        self.ranges("requested").len()
    }

    /// The messages of the store's glyph errors.
    fn errors(&self) -> Vec<String> {
        let events = self.store.events.borrow();
        events
            .iter()
            .filter_map(|event| match event {
                RendererEvent::GlyphsError { error, .. } => Some(error.to_string()),
                _ => None,
            })
            .collect()
    }
}

fn test_stack() -> FontStack {
    vec!["Test Stack".to_owned()]
}

fn gid(c: char) -> GlyphID {
    GlyphID::from_char(c).unwrap()
}

fn dependencies(chars: &[char]) -> GlyphDependencies {
    let ids: GlyphIDs = chars.iter().map(|c| gid(*c)).collect();
    GlyphDependencies { glyphs: VecMap::from([(test_stack(), ids)]), shapes: ShapeRequests::default() }
}

/// The dependencies of `text`, shaped with the device's fonts.
fn system_text(text: &str) -> GlyphDependencies {
    let text: Vec<char> = text.chars().collect();
    let shapes = VecMap::from([(test_stack(), VecMap::from([(GlyphFont::SYSTEM, [text].into())]))]);
    GlyphDependencies { glyphs: VecMap::new(), shapes }
}

/// The test stack's glyph `id` in `answer`, which names it.
fn glyph_of(answer: &ResolvedGlyphs, id: GlyphID) -> Option<Arc<Glyph>> {
    answer.glyphs[&font_stack_hash(&test_stack())].get(&id).expect("the answer names the glyph").clone()
}

/// The test stack's glyph of `c` in `answer`, which names it.
fn glyph(answer: &ResolvedGlyphs, c: char) -> Option<Arc<Glyph>> {
    glyph_of(answer, gid(c))
}

/// The glyphs `text` was shaped as with fonts of `font` in `answer`.
fn shaped(answer: &ResolvedGlyphs, font: GlyphFont, text: &[char]) -> Vec<GlyphID> {
    answer.shaping[&test_stack()][&font][&text.to_vec()].glyphs.clone()
}

/// The range of the fixtures' 0–255 glyph PBFs.
fn pbf_range() -> GlyphRange {
    GlyphRange::new(0, 255, GlyphFont::FontPBF)
}

fn data(bytes: Arc<Vec<u8>>) -> Response {
    let mut response = Response::new();
    response.data = Some(bytes);
    response
}

fn failure(reason: Reason) -> Response {
    let mut response = Response::new();
    response.error = Some(Box::new(ResourceError::new(reason, "Failed by the test case")));
    response
}

/// Answers every request with the fixture at `path`.
fn serve(path: &str) -> impl Fn(&Resource) -> Option<Response> + Send + Sync + 'static {
    let bytes = Arc::new(crate::tests::testdata(path));
    move |_: &Resource| Some(data(Arc::clone(&bytes)))
}

/// Fails the first request, and answers the others with `bytes`.
fn fails_first_then(bytes: Vec<u8>) -> impl Fn(&Resource) -> Option<Response> + Send + Sync + 'static {
    let (loads, bytes) = (AtomicU32::new(0), Arc::new(bytes));
    move |_: &Resource| {
        Some(if loads.fetch_add(1, Ordering::SeqCst) == 0 {
            failure(Reason::NotFound)
        } else {
            data(Arc::clone(&bytes))
        })
    }
}

/// A glyph PBF's answer has the glyphs it has and the others missing, and
/// the store reports the range loaded, whether the file source answers at
/// once or later.
#[test]
fn a_glyph_pbf_answers_with_the_glyphs_it_has() {
    let cases: [(&str, &[char], &[char]); 2] = [(GLYPHS, &['a', 'å', ' '], &[]), (FAKE_GLYPHS, &['E'], &['A'])];
    for response_type in [ResponseType::Asynchronous, ResponseType::Synchronous] {
        for (pbf, present, missing) in cases {
            let fixture = Fixture::new(LocalGlyphs::default(), response_type);
            fixture.respond(serve(pbf));
            fixture.glyphs().set_url(pbf);
            let chars = [present, missing].concat();

            let answer = fixture.answered(dependencies(&chars));

            assert_eq!(answer.glyphs[&font_stack_hash(&test_stack())].len(), chars.len(), "{pbf}");
            assert!(present.iter().all(|c| glyph(&answer, *c).is_some()), "{pbf}");
            assert!(missing.iter().all(|c| glyph(&answer, *c).is_none()), "{pbf}");
            assert_eq!(fixture.ranges("loaded"), [(test_stack(), pbf_range())], "{pbf}");
            assert_eq!(fixture.errors(), Vec::<String>::new(), "{pbf}");
        }
    }
}

/// A range whose request fails, or whose PBF is corrupt, is reported as an
/// error, and its glyphs are answered missing. A failed request's error
/// carries the file source's message.
#[test]
fn a_range_that_fails_to_load_answers_its_glyphs_as_missing() {
    // A failed request, or the bytes of a corrupt PBF.
    for bytes in [None, Some(Arc::new(b"CORRUPTED".to_vec()))] {
        let corrupt = bytes.is_some();
        let fixture = Fixture::new(local(CjkRasterizer), ResponseType::Asynchronous);
        fixture.respond(move |_| Some(bytes.clone().map_or_else(|| failure(Reason::Other), data)));
        fixture.glyphs().set_url(GLYPHS);

        let answer = fixture.answered(dependencies(&['a', 'å']));

        assert!(glyph(&answer, 'a').is_none() && glyph(&answer, 'å').is_none());
        assert_eq!(fixture.ranges("error"), [(test_stack(), pbf_range())], "corrupt: {corrupt}");
        let errors = fixture.errors();
        assert_eq!(errors.len(), 1, "corrupt: {corrupt}");
        assert!(corrupt || errors[0] == "Failed by the test case", "{errors:?}");
    }
}

/// A wait answered without the glyphs of a range that failed while it
/// waited names the range, so that a still image lays its tile out again. A
/// later wait requests the range again, and once it loads, the store reports
/// it recovered once, so that the tiles laid out without it lay out again.
#[test]
fn a_failed_range_is_requested_again_by_a_later_wait() {
    for response_type in [ResponseType::Asynchronous, ResponseType::Synchronous] {
        let fixture = Fixture::new(local(CjkRasterizer), response_type);
        fixture.respond(fails_first_then(crate::tests::testdata(GLYPHS)));
        fixture.glyphs().set_url(GLYPHS);
        let range = (test_stack(), pbf_range());

        let answer = fixture.answered(dependencies(&['a']));
        assert!(glyph(&answer, 'a').is_none());
        assert_eq!(answer.failed, VecSet::from([range.clone()]), "the answer names the range");
        assert_eq!(fixture.requests(), 1);
        assert!(fixture.glyphs().take_recovered().is_empty(), "nothing loaded yet");

        let answer = fixture.answered(dependencies(&['a']));
        assert!(glyph(&answer, 'a').is_some());
        assert!(answer.failed.is_empty());
        assert_eq!(fixture.requests(), 2);
        assert_eq!(fixture.glyphs().take_recovered(), VecSet::from([range]));
        assert!(fixture.glyphs().take_recovered().is_empty(), "reported once");
    }
}

/// A wait for a range that fails while it waits gets the range's glyphs as
/// missing however often it asks again: a failure can't leave it waiting.
#[test]
fn a_wait_resolves_a_range_that_failed_during_it_as_missing() {
    let fixture = Fixture::new(local(CjkRasterizer), ResponseType::Asynchronous);
    fixture.respond(|_| Some(failure(Reason::Other)));
    fixture.glyphs().set_url(GLYPHS);

    let file_source = fixture.store.file_source.borrow().clone().unwrap();
    let inbox = fixture.store.inbox.sender().clone();
    let mut wait = GlyphWait::default();
    assert!(fixture.glyphs().resolve(&dependencies(&['a']), &mut wait, Some(&file_source), &inbox).is_none());
    fixture.turn();
    fixture.store.take_responses();
    fixture.glyphs().update();
    for _ in 0..2 {
        let resolved =
            fixture.glyphs().resolve(&dependencies(&['a']), &mut wait, Some(&file_source), &inbox).expect("answered");
        assert!(!resolved.failed.is_empty());
        assert!(glyph(&resolved, 'a').is_none());
    }
    fixture.store.report();
    assert_eq!(fixture.requests(), 1);
}

#[test]
fn a_failed_range_leaves_the_other_ranges_glyphs_in_the_answer() {
    let fixture = Fixture::new(local(CjkRasterizer), ResponseType::Asynchronous);
    let bytes = Arc::new(crate::tests::testdata(GLYPHS));
    fixture.respond(move |resource| {
        Some(if resource.url == "glyphs-0-255.pbf" { data(Arc::clone(&bytes)) } else { failure(Reason::NotFound) })
    });
    fixture.glyphs().set_url("glyphs-{range}.pbf");

    let answer = fixture.answered(dependencies(&['a', 'ở']));

    assert_eq!(answer.glyphs[&font_stack_hash(&test_stack())].len(), 2);
    assert!(glyph(&answer, 'a').is_some());
    assert!(glyph(&answer, 'ở').is_none());
}

/// Stores that share a glyph cache share the glyphs they parse, across font
/// stacks.
#[test]
fn stores_that_share_a_glyph_cache_share_the_glyphs_they_parse() {
    let cache = Arc::new(GlyphCache::new());
    let load = |font_stack: &str| {
        let engine = crate::text::font_face_engine::default_engine();
        let fixture = Fixture::with_all(local(CjkRasterizer), ResponseType::Asynchronous, Arc::clone(&cache), engine);
        fixture.load(&vec![font_stack.to_owned()], 'a')
    };

    assert!(Arc::ptr_eq(&load("Test Stack"), &load("Other Stack")));
}

#[test]
fn evicting_a_font_stack_releases_its_glyphs() {
    let cache = Arc::new(GlyphCache::new());
    let engine = crate::text::font_face_engine::default_engine();
    let fixture = Fixture::with_all(local(CjkRasterizer), ResponseType::Asynchronous, Arc::clone(&cache), engine);
    drop(fixture.load(&test_stack(), 'a'));
    assert_ne!(0, cache.live_glyphs());

    fixture.glyphs().evict(&VecSet::new());

    assert_eq!(0, cache.live_glyphs());
}

/// A wait whose font stacks are evicted, the one still loading and the one it
/// already has, requests them again and is answered with both.
#[test]
fn a_wait_requests_the_font_stacks_evicted_while_it_waits_again() {
    let fixture = Fixture::new(local(CjkRasterizer), ResponseType::Asynchronous);
    let loaded_stack = vec!["Loaded Stack".to_owned()];
    fixture.load(&loaded_stack, 'a');

    let ids: GlyphIDs = [gid('a')].into_iter().collect();
    fixture.request(GlyphDependencies {
        glyphs: VecMap::from([(loaded_stack.clone(), ids.clone()), (test_stack(), ids)]),
        shapes: ShapeRequests::default(),
    });
    fixture.glyphs().evict(&VecSet::new());
    // The renderer's update asks the waiting tiles again after an eviction.
    fixture.store.answer();

    let answer = fixture.next_answer();
    for font_stack in [loaded_stack, test_stack()] {
        assert!(answer.glyphs[&font_stack_hash(&font_stack)][&gid('a')].is_some(), "{font_stack:?}");
    }
}

/// A response that arrived for a range evicted since is stale: the range
/// isn't loaded by it, and a later wait requests it again, from the glyph
/// URL the store has then.
#[test]
fn a_response_to_an_evicted_range_is_dropped() {
    let fixture = Fixture::new(local(CjkRasterizer), ResponseType::Synchronous);
    let urls = Arc::new(Mutex::new(Vec::new()));
    let (u, serve) = (Arc::clone(&urls), serve(GLYPHS));
    fixture.respond(move |resource| {
        u.lock().push(resource.url.clone());
        serve(resource)
    });

    fixture.glyphs().set_url("old/{fontstack}/{range}.pbf");
    fixture.request(dependencies(&['a']));
    fixture.glyphs().evict(&VecSet::new());
    fixture.store.take_responses();

    fixture.glyphs().set_url("new/{fontstack}/{range}.pbf");
    fixture.request(dependencies(&['a']));
    let urls = urls.lock();
    assert_eq!(urls.len(), 2, "requested again: {urls:?}");
    assert!(urls[1].starts_with("new/"));
}

/// The glyphs local fonts draw, CJK ideographs and symbols, need no request,
/// and are stored with the local font's metrics as SDFs of the radius a
/// PBF's glyphs have, twice that for a glyph drawn at twice the resolution.
#[test]
fn local_cjk_glyphs_are_drawn_as_sdfs_without_a_request() {
    for (double_resolution, radius) in [(false, 8.0), (true, 16.0)] {
        let rasterizer = EveryRasterizer { advance: 24, double_resolution };
        let raster = rasterizer.rasterize_glyph(&test_stack(), gid('中')).unwrap();
        let fixture = Fixture::new(local(rasterizer), ResponseType::Asynchronous);
        fixture.respond(|resource| panic!("requested {}", resource.url));
        fixture.glyphs().set_url(GLYPHS);

        let answer = fixture.answered(dependencies(&['中', '〒', '!']));

        assert_eq!(fixture.requests(), 0);
        assert!(glyph(&answer, '〒').is_some() && glyph(&answer, '!').is_some());
        let glyph = glyph(&answer, '中').expect("the local glyph");
        assert_eq!(glyph.id, gid('中'));
        assert_eq!(glyph.metrics, raster.metrics);
        assert_eq!(glyph.bitmap, transform_raster_to_sdf(&raster.bitmap, radius, 0.25), "radius {radius}");
    }
}

/// A glyph the local fonts draw comes from them though a loaded PBF range
/// has it.
#[test]
fn a_local_glyph_is_drawn_locally_though_a_loaded_range_has_it() {
    let fixture = Fixture::new(local(KatakanaRasterizer), ResponseType::Asynchronous);
    fixture.respond(serve(CJK_GLYPHS));
    fixture.glyphs().set_url(CJK_GLYPHS);

    // '々' (U+3005) isn't the local fonts', so it loads its range.
    let answer = fixture.answered(dependencies(&['々']));
    assert!(glyph(&answer, '々').is_some());

    // 'テ' (U+30C6), of the same range, is.
    let answer = fixture.answered(dependencies(&['テ']));
    let glyph = glyph(&answer, 'テ').expect("the local glyph");
    assert_eq!(glyph.metrics, stub_glyph(gid('テ')).metrics);
    assert_eq!(fixture.requests(), 1);
}

/// A font-face engine that is ready once the test calls back the `ready`s it
/// holds, as the browser's is once it loads its shaper's module.
type Ready = Box<dyn FnOnce(Result<(), String>) + Send>;

#[derive(Default)]
struct DeferredEngine {
    ready: Mutex<Vec<Ready>>,
    prepares: AtomicUsize,
    loads: AtomicUsize,
}

impl DeferredEngine {
    fn report(&self, result: &Result<(), String>) {
        let ready = std::mem::take(&mut *self.ready.lock());
        for ready in ready {
            ready(result.clone());
        }
    }

    fn loads(&self) -> usize {
        self.loads.load(Ordering::SeqCst)
    }
}

impl FontFaceEngine for DeferredEngine {
    fn prepare(&self, ready: Ready) {
        self.prepares.fetch_add(1, Ordering::SeqCst);
        self.ready.lock().push(ready);
    }

    fn load(&self, font: GlyphFont, data: FontData, _weight: u16) -> Option<Box<dyn FontFaceShaper>> {
        self.loads.fetch_add(1, Ordering::SeqCst);
        (data.as_bytes() == b"font")
            .then(|| -> Box<dyn FontFaceShaper> { Box::new(LetterShaper { font, splits: false }) })
    }
}

const FONT_FACE: GlyphFont = GlyphFont::face(NonZeroU16::new(7).unwrap());

/// The text the font-face tests shape.
const FACE_TEXT: [char; 2] = ['\u{5}', '\u{6}'];

/// A store on `engine` with one font face of the test stack, and a
/// synchronous file source that answers its file with "font".
fn font_face_fixture(engine: &Arc<DeferredEngine>) -> Fixture {
    let fixture = Fixture::with_all(
        local(CjkRasterizer),
        ResponseType::Synchronous,
        Arc::default(),
        Arc::<DeferredEngine>::clone(engine),
    );
    let font = Arc::new(b"font".to_vec());
    fixture.respond(move |resource| {
        assert_eq!(resource.url, "test://face.ttf");
        Some(data(Arc::clone(&font)))
    });
    let face = FontFace { font: FONT_FACE, ..FontFace::new("Test Stack", "test://face.ttf", vec![]) };
    fixture.glyphs().set_font_faces(Some(Arc::new(vec![face])));
    fixture
}

/// The font face's file and the shaping of `FACE_TEXT` with it.
fn font_face_dependencies() -> GlyphDependencies {
    let ids: GlyphIDs = [GlyphID::with_type(0, FONT_FACE)].into_iter().collect();
    let shapes =
        VecMap::from([(test_stack(), VecMap::from([(FONT_FACE, [FACE_TEXT.to_vec()].into_iter().collect())]))]);
    GlyphDependencies { glyphs: VecMap::from([(test_stack(), ids)]), shapes }
}

fn face_codes(answer: &ResolvedGlyphs) -> Vec<u16> {
    shaped(answer, FONT_FACE, &FACE_TEXT).iter().map(|glyph| glyph.code).collect()
}

#[test]
fn a_font_face_waits_for_the_engine() {
    let engine = Arc::new(DeferredEngine::default());
    let fixture = font_face_fixture(&engine);
    // Asked to get ready by the font faces, before any file arrives.
    assert_eq!(engine.prepares.load(Ordering::SeqCst), 1);

    // The file arrived (synchronously), but the engine isn't ready: the
    // wait waits, and the file isn't parsed.
    fixture.request(font_face_dependencies());
    fixture.turn();
    assert!(!fixture.has_answer());
    assert_eq!(engine.loads(), 0);

    // Once it is, the store wakes the renderer, which parses the file and
    // answers the wait.
    engine.report(&Ok(()));
    assert!(!fixture.has_answer());
    let answer = fixture.next_answer();
    assert_eq!((engine.loads(), engine.prepares.load(Ordering::SeqCst)), (1, 1));
    // The file's glyph 0 only marks it as a dependency; the shaped glyphs
    // are drawn.
    assert!(glyph_of(&answer, GlyphID::with_type(0, FONT_FACE)).is_none());
    assert_eq!(face_codes(&answer), [5, 6]);
    let glyph = glyph_of(&answer, GlyphID::with_type(5, FONT_FACE)).expect("the shaped glyph");
    assert_eq!(glyph.metrics, stub_glyph(glyph.id).metrics);

    // A later wait is answered at once.
    fixture.request(font_face_dependencies());
    assert!(fixture.has_answer());
}

/// An engine that fails to get ready leaves the face out, as a file that
/// isn't a font does: the wait is answered without its shaping.
#[test]
fn a_font_face_engine_failure_leaves_the_face_out() {
    let engine = Arc::new(DeferredEngine::default());
    let fixture = font_face_fixture(&engine);
    fixture.request(font_face_dependencies());
    engine.report(&Err("no shaper".to_owned()));
    let answer = fixture.next_answer();
    assert_eq!(engine.loads(), 0);
    assert_eq!(face_codes(&answer), Vec::<u16>::new());
}

/// A face whose file fails to load while a wait shapes text with it leaves
/// the wait answered without its shaping, naming the face's range failed.
#[test]
fn a_font_face_whose_file_fails_is_answered_without_its_shaping() {
    let engine = Arc::new(DeferredEngine::default());
    let fixture = font_face_fixture(&engine);
    fixture.respond(|_| Some(failure(Reason::Other)));
    engine.report(&Ok(()));

    let answer = fixture.answered(font_face_dependencies());

    assert_eq!(face_codes(&answer), Vec::<u16>::new());
    let range = glyph_range(GlyphID::with_type(0, FONT_FACE));
    assert_eq!(answer.failed, VecSet::from([(test_stack(), range)]));
    assert_eq!(fixture.ranges("error"), [(test_stack(), range)]);
}

/// A face that holds its font file, as an app's fallback faces can, loads it
/// without a request.
#[test]
fn a_font_face_with_its_data_needs_no_request() {
    let engine = Arc::new(DeferredEngine::default());
    let fixture = font_face_fixture(&engine);
    fixture.respond(|resource| panic!("requested {}", resource.url));
    let face = FontFace { font: FONT_FACE, ..FontFace::new("", "app://face.ttf", vec![(0, 0xFFFF)]) }
        .with_data(FontData::new(Arc::new(b"font".to_vec())));
    fixture.glyphs().set_font_faces(Some(Arc::new(vec![face])));
    engine.report(&Ok(()));
    fixture.turn();

    fixture.request(font_face_dependencies());
    assert!(fixture.has_answer(), "answered at once");
    assert_eq!(engine.loads(), 1);
    assert_eq!(face_codes(&fixture.next_answer()), [5, 6]);
}

/// A style without a glyph URL draws its text from local fonts, and requests
/// no glyph PBF.
#[test]
fn without_a_glyph_url_glyphs_come_from_local_fonts() {
    for (local, drawn) in [(local(every_glyph()), true), (LocalGlyphs::default(), false)] {
        let fixture = Fixture::new(local, ResponseType::Asynchronous);
        fixture.glyphs().set_url("");

        fixture.request(dependencies(&['a', '中']));
        assert!(fixture.has_answer(), "answered at once");

        let answer = fixture.next_answer();
        assert_eq!(glyph(&answer, 'a').is_some(), drawn);
        assert_eq!(glyph(&answer, '中').is_some(), drawn);
        assert_eq!(fixture.requests(), 0);
    }
}

/// A glyph that the stack's PBF lacks comes from local fonts, and the PBF's
/// glyphs stay the PBF's.
#[test]
fn a_glyph_the_pbf_lacks_comes_from_local_fonts() {
    let fixture = Fixture::new(local(every_glyph()), ResponseType::Asynchronous);
    fixture.respond(serve(FAKE_GLYPHS));
    fixture.glyphs().set_url(GLYPHS);

    let answer = fixture.answered(dependencies(&['A', 'E']));

    assert_eq!(glyph(&answer, 'A').expect("a local 'A'").metrics, stub_glyph(gid('A')).metrics);
    assert_ne!(glyph(&answer, 'E').expect("the PBF's 'E'").metrics, stub_glyph(gid('E')).metrics);
}

/// Without local ideographs, a CJK glyph comes from the PBF first.
#[test]
fn ideographs_come_from_pbfs_first_unless_local_ideographs_are_set() {
    let local = LocalGlyphs { ideographs: false, ..local(CjkRasterizer) };
    let fixture = Fixture::new(local, ResponseType::Asynchronous);
    fixture.respond(serve(CJK_GLYPHS));
    fixture.glyphs().set_url(CJK_GLYPHS);

    let answer = fixture.answered(dependencies(&['々']));

    assert_ne!(glyph(&answer, '々').expect("the PBF's glyph").metrics, stub_glyph(gid('々')).metrics);
    assert_eq!(fixture.requests(), 1);
}

/// A local glyph comes from the fallback font faces that cover it before the
/// device's fonts, one glyph at a time, and the device's are asked only about
/// what the faces lack.
#[test]
fn a_fallback_face_draws_local_glyphs_before_the_device() {
    let engine = Arc::new(DeferredEngine::default());
    let katakana = DeviceFonts::new(|c| (c == 'テ').then_some("font"));
    let fixture = Fixture::with_all(
        device(&katakana),
        ResponseType::Synchronous,
        Arc::default(),
        Arc::<DeferredEngine>::clone(&engine),
    );
    fixture.respond(|resource| panic!("requested {}", resource.url));
    let face = FontFace { font: FONT_FACE, ..FontFace::new("", "app://face.ttf", vec![(0x4E2D, 0x4E2D)]) }
        .with_data(FontData::new(Arc::new(b"font".to_vec())));
    fixture.glyphs().set_font_faces(Some(Arc::new(vec![face])));
    engine.report(&Ok(()));
    fixture.turn();
    fixture.glyphs().set_url(GLYPHS);

    // The device's fonts have only テ.
    let answer = fixture.answered(dependencies(&['中', 'テ']));
    assert_eq!(glyph(&answer, '中').expect("the face's glyph").id, gid('中'));
    assert_eq!(glyph(&answer, 'テ').expect("the device's glyph").id, gid('テ'));
    assert_eq!(katakana.asked(), ['テ']);
    // The fallback face and the device's font.
    assert_eq!(engine.loads(), 2);
}

/// The device's fonts as three: one for Hebrew, one for Arabic and one for
/// everything else but marks, which none has on its own.
fn script_fonts(c: char) -> Option<&'static str> {
    match c {
        '\u{0300}'..='\u{036F}' => None,
        '\u{0590}'..='\u{05FF}' => Some("hebrew"),
        '\u{0600}'..='\u{06FF}' => Some("arabic"),
        _ => Some("latin"),
    }
}

/// Loads each font as a shaper that maps each character to the glyph of
/// that index, in its font's type, and shapes it as that glyph, reversed for
/// right-to-left text.
#[derive(Default)]
struct LetterEngine {
    /// The type and weight of each font loaded.
    loads: Mutex<Vec<(GlyphFont, u16)>>,
    /// Whether its fonts fail to load, as files that aren't fonts do.
    invalid: bool,
    /// Whether shaping splits each character into its glyph and glyph 1, as
    /// `ccmp` splits a dotted Arabic letter into its dotless form and dots.
    splits: bool,
}

impl FontFaceEngine for LetterEngine {
    fn prepare(&self, ready: Box<dyn FnOnce(Result<(), String>) + Send>) {
        ready(Ok(()));
    }

    fn load(&self, font: GlyphFont, _data: FontData, weight: u16) -> Option<Box<dyn FontFaceShaper>> {
        self.loads.lock().push((font, weight));
        (!self.invalid).then(|| -> Box<dyn FontFaceShaper> { Box::new(LetterShaper { font, splits: self.splits }) })
    }
}

struct LetterShaper {
    font: GlyphFont,
    splits: bool,
}

impl FontFaceShaper for LetterShaper {
    fn shape(&self, text: &[char], rtl: bool, shaped: &mut ShapedText) {
        let mut glyphs: Vec<GlyphID> = Vec::new();
        for &c in text {
            glyphs.push(GlyphID::with_type(c as u16, self.font));
            if self.splits {
                glyphs.push(GlyphID::with_type(1, self.font));
            }
        }
        if rtl {
            glyphs.reverse();
        }
        shaped.adjusts.extend(glyphs.iter().map(|_| GlyphAdjust::new(0.0, 0.0, 10.0)));
        shaped.glyphs.extend(glyphs);
    }

    fn glyph_of(&self, c: char) -> Option<GlyphID> {
        Some(GlyphID::with_type(c as u16, self.font))
    }

    fn rasterize(&self, glyph: GlyphID) -> Glyph {
        stub_glyph(glyph)
    }
}

/// A store on `engine` that draws from `fonts`, with a synchronous file
/// source.
fn letter_fixture(fonts: &Arc<DeviceFonts>, engine: LetterEngine) -> (Fixture, Arc<LetterEngine>) {
    let engine = Arc::new(engine);
    let fixture = Fixture::with_all(
        device(fonts),
        ResponseType::Synchronous,
        Arc::default(),
        Arc::<LetterEngine>::clone(&engine),
    );
    (fixture, engine)
}

/// The glyph type of the device's `font` at regular weight.
fn device_type(font: &str) -> GlyphFont {
    FontFace::device(font, 400, FontData::default()).font
}

/// The glyphs that the device's `fonts` shape `text` as, by character and
/// font.
fn shape_with_device_fonts(fonts: &Arc<DeviceFonts>, text: &str) -> Vec<(char, GlyphFont)> {
    let (fixture, _) = letter_fixture(fonts, LetterEngine::default());
    let answer = fixture.answered(system_text(text));
    let text: Vec<char> = text.chars().collect();
    let shaped = shaped(&answer, GlyphFont::SYSTEM, &text);
    shaped.iter().map(|glyph| (char::from_u32(u32::from(glyph.code)).unwrap(), glyph.font)).collect()
}

#[test]
fn the_devices_fonts_shape_each_piece_with_its_font() {
    let glyphs = shape_with_device_fonts(&DeviceFonts::new(script_fonts), "ab \u{05D0}\u{05D1}\u{062C} c\u{0301}");
    let chars: String = glyphs.iter().map(|(c, _)| *c).collect();
    // The right-to-left run's pieces in visual order: the Arabic after the
    // Hebrew comes first; the mark stays with the letter before it.
    assert_eq!(chars, "ab \u{062C}\u{05D1}\u{05D0} c\u{0301}");
    let type_of = |c: char| glyphs.iter().find(|(glyph, _)| *glyph == c).unwrap().1;
    assert_eq!(type_of('a'), type_of('c'));
    assert_eq!(type_of('\u{0301}'), type_of('c'));
    assert_ne!(type_of('\u{05D0}'), type_of('a'));
    assert_ne!(type_of('\u{062C}'), type_of('\u{05D0}'));
    assert!(glyphs.iter().all(|(_, font)| ![GlyphFont::FontPBF, GlyphFont::SYSTEM].contains(font)));
}

/// A mark that its character's font lacks takes the cluster to a font that
/// draws both, rather than splitting it across two.
#[test]
fn a_cluster_takes_a_font_that_draws_all_of_it() {
    let fonts = Arc::new(DeviceFonts {
        fonts: |_| Some("latin"),
        clusters: |cluster| (cluster == ['c', '\u{20E3}']).then_some("symbols"),
        weight: 400,
        asked: Mutex::default(),
    });
    let glyphs = shape_with_device_fonts(&fonts, "bc\u{20E3}");
    assert_eq!(glyphs.iter().map(|(c, _)| *c).collect::<String>(), "bc\u{20E3}");
    assert_eq!(glyphs[0].1, device_type("latin"));
    assert_eq!(glyphs[1].1, device_type("symbols"));
    assert_eq!(glyphs[2].1, device_type("symbols"));
}

#[test]
fn a_character_that_no_device_font_draws_is_left_out() {
    let glyphs = shape_with_device_fonts(&DeviceFonts::new(|c| (c != 'b').then_some("latin")), "abc");
    assert_eq!(glyphs.iter().map(|(c, _)| *c).collect::<String>(), "ac");
}

#[test]
fn the_devices_fonts_wait_for_the_engine() {
    let engine = Arc::new(DeferredEngine::default());
    let fixture = Fixture::with_all(
        device(&DeviceFonts::new(|_| Some("font"))),
        ResponseType::Synchronous,
        Arc::default(),
        Arc::<DeferredEngine>::clone(&engine),
    );
    fixture.request(system_text("\u{5}\u{6}"));
    // Chosen, and the chosen face's file parked for the engine.
    fixture.run_until(|fixture| fixture.requests() > 0);
    assert!(!fixture.has_answer());
    assert_eq!(engine.loads(), 0);

    engine.report(&Ok(()));
    let answer = fixture.next_answer();
    assert_eq!(engine.loads(), 1);
    let codes: Vec<u16> = shaped(&answer, GlyphFont::SYSTEM, &FACE_TEXT).iter().map(|glyph| glyph.code).collect();
    assert_eq!(codes, [5, 6]);
}

#[test]
fn a_chooser_never_runs_on_the_render_thread() {
    let fonts = DeviceFonts::new(|_| Some("latin"));
    let (fixture, _) = letter_fixture(&fonts, LetterEngine::default());
    fixture.glyphs().set_url("");
    let mut dependencies = system_text("ab");
    dependencies.glyphs = VecMap::from([(test_stack(), [gid('中')].into_iter().collect())]);
    fixture.answered(dependencies);
    let asked = fonts.asked.lock();
    assert!(!asked.is_empty());
    assert!(asked.iter().all(|(_, thread)| *thread != std::thread::current().id()));
}

/// A glyph of the device's fonts waits for the choice of its font, which the
/// store reports requested and loaded as a range of the font's.
#[test]
fn a_glyph_waits_for_its_device_font_then_draws_from_it() {
    let (fixture, _) = letter_fixture(&DeviceFonts::new(|_| Some("font")), LetterEngine::default());
    fixture.glyphs().set_url("");

    fixture.request(dependencies(&['a']));
    assert!(!fixture.has_answer(), "waits for the choice");
    assert_eq!(fixture.glyph_events(), []);

    let glyph = glyph(&fixture.next_answer(), 'a').expect("the device's glyph");
    assert_eq!(glyph.id, gid('a'));
    assert_eq!(glyph.metrics, stub_glyph(gid('a')).metrics);
    let range = glyph_range(GlyphID::with_type(0, device_type("font")));
    assert_eq!(fixture.glyph_events(), [("requested", test_stack(), range), ("loaded", test_stack(), range)]);
}

#[test]
fn a_device_face_loads_at_its_weight() {
    let bold =
        Arc::new(DeviceFonts { fonts: |_| Some("bold"), clusters: |_| None, weight: 700, asked: Mutex::default() });
    let (fixture, engine) = letter_fixture(&bold, LetterEngine::default());
    let face = FontFace { font: FONT_FACE, ..FontFace::new("Test Stack", "app://face.ttf", vec![(0, 0xFFFF)]) }
        .with_data(FontData::from(b"font".to_vec()));
    fixture.glyphs().set_font_faces(Some(Arc::new(vec![face])));
    let mut dependencies = system_text("a");
    dependencies.glyphs = VecMap::from([(test_stack(), [GlyphID::with_type(0, FONT_FACE)].into_iter().collect())]);
    fixture.answered(dependencies);
    let device = FontFace::device("bold", 700, FontData::default()).font;
    let mut loads = engine.loads.lock().clone();
    loads.sort();
    let mut expected = vec![(FONT_FACE, 400), (device, 700)];
    expected.sort();
    assert_eq!(loads, expected);
}

/// Without a file source, the faces that hold their font files, an app's
/// fallback faces and the device's, still load; a glyph PBF never does, and
/// a wait for it waits.
#[test]
fn without_a_file_source_only_faces_that_hold_their_files_load() {
    let katakana = DeviceFonts::new(|c| (c == 'テ').then_some("font"));
    let (fixture, engine) = letter_fixture(&katakana, LetterEngine::default());
    *fixture.store.file_source.borrow_mut() = None;
    let face = FontFace { font: FONT_FACE, ..FontFace::new("", "app://face.ttf", vec![(0x4E2D, 0x4E2D)]) }
        .with_data(FontData::from(b"font".to_vec()));
    fixture.glyphs().set_font_faces(Some(Arc::new(vec![face])));
    fixture.glyphs().set_url(GLYPHS);

    let answer = fixture.answered(dependencies(&['中', 'テ']));
    assert!(glyph(&answer, '中').is_some(), "the fallback face's glyph");
    assert!(glyph(&answer, 'テ').is_some(), "the device's glyph");
    assert_eq!(engine.loads.lock().len(), 2);

    fixture.request(dependencies(&['a']));
    assert!(!fixture.has_answer());
    assert!(fixture.ranges("requested").iter().all(|(_, range)| *range != pbf_range()));
}

/// A later wait requests a fallback face's file that failed to load again,
/// and draws the face's glyphs once it loads. Until then, a local glyph, if
/// the local fonts have one, stands in for the face's.
#[test]
fn a_fallback_face_that_failed_to_load_is_requested_again() {
    for (local, stand_in) in [(device(&DeviceFonts::new(|_| None)), false), (local(wide_glyphs()), true)] {
        let fixture =
            Fixture::with_all(local, ResponseType::Synchronous, Arc::default(), Arc::new(LetterEngine::default()));
        fixture.respond(fails_first_then(b"font".to_vec()));
        let face = FontFace { font: FONT_FACE, ..FontFace::new("", "app://face.ttf", vec![(0x4E2D, 0x4E2D)]) };
        fixture.glyphs().set_font_faces(Some(Arc::new(vec![face])));
        fixture.glyphs().set_url("");
        let range = (test_stack(), glyph_range(GlyphID::with_type(0, FONT_FACE)));

        let answer = fixture.answered(dependencies(&['中']));
        let first = glyph(&answer, '中');
        assert_eq!(first.map(|glyph| glyph.metrics.advance), stand_in.then_some(99), "the rasterizer's glyph or none");
        assert_eq!(answer.failed, VecSet::from([range.clone()]), "the answer names the face");

        let answer = fixture.answered(dependencies(&['中']));
        let face_glyph = glyph(&answer, '中').expect("the face's glyph");
        assert_ne!(face_glyph.metrics.advance, 99);
        assert_eq!(fixture.requests(), 2);
        assert_eq!(fixture.glyphs().take_recovered(), VecSet::from([range]));
    }
}

/// A local glyph stands in for a glyph PBF that failed to load, until a
/// later wait loads the PBF and draws its glyph.
#[test]
fn a_local_glyph_stands_in_for_a_range_that_failed_to_load() {
    let fixture = Fixture::new(local(wide_glyphs()), ResponseType::Synchronous);
    fixture.respond(fails_first_then(crate::tests::testdata(GLYPHS)));
    fixture.glyphs().set_url(GLYPHS);
    let range = (test_stack(), pbf_range());

    let answer = fixture.answered(dependencies(&['a']));
    assert_eq!(glyph(&answer, 'a').expect("a glyph").metrics.advance, 99, "the rasterizer's glyph");
    assert_eq!(answer.failed, VecSet::from([range.clone()]), "the answer names the range");

    let answer = fixture.answered(dependencies(&['a']));
    assert_ne!(glyph(&answer, 'a').expect("a glyph").metrics.advance, 99, "the PBF's glyph");
    assert_eq!(fixture.glyphs().take_recovered(), VecSet::from([range]));
}

/// A device glyph is the glyph its font maps the character to, as a PBF's
/// is, even where shaping the character alone splits it.
#[test]
fn a_device_glyph_is_its_fonts_glyph_of_the_character() {
    let engine = LetterEngine { splits: true, ..LetterEngine::default() };
    let (fixture, _) = letter_fixture(&DeviceFonts::new(|_| Some("arabic")), engine);
    fixture.glyphs().set_url("");
    let answer = fixture.answered(dependencies(&['\u{0628}']));
    let glyph = glyph(&answer, '\u{0628}').expect("the device's glyph");
    assert_eq!(glyph.metrics, stub_glyph(gid('\u{0628}')).metrics);
}

#[test]
fn a_cjk_glyph_without_a_device_font_comes_from_the_pbf() {
    let (fixture, _) = letter_fixture(&DeviceFonts::new(|_| None), LetterEngine::default());
    fixture.respond(serve(GLYPHS));
    fixture.glyphs().set_url(GLYPHS);
    fixture.answered(dependencies(&['中']));
    assert_eq!(fixture.ranges("requested"), [(test_stack(), glyph_range(gid('中')))]);
}

#[test]
fn a_device_face_that_fails_to_load_draws_nothing() {
    let engine = LetterEngine { invalid: true, ..LetterEngine::default() };
    let (fixture, _) = letter_fixture(&DeviceFonts::new(|_| Some("font")), engine);
    fixture.glyphs().set_url("");
    let mut dependencies = system_text("b");
    dependencies.glyphs = VecMap::from([(test_stack(), [gid('a')].into_iter().collect())]);

    let answer = fixture.answered(dependencies);
    assert!(glyph(&answer, 'a').is_none());
    assert_eq!(shaped(&answer, GlyphFont::SYSTEM, &['b']), []);
    assert_eq!(fixture.ranges("loaded"), [(test_stack(), glyph_range(GlyphID::with_type(0, device_type("font"))))]);
}

/// The device's fonts chosen for a font stack evicted since don't change
/// the store; a wait that asks again has them chosen again.
#[test]
fn an_answer_for_an_evicted_stack_is_dropped() {
    let fonts = DeviceFonts::new(|_| Some("latin"));
    let (fixture, _) = letter_fixture(&fonts, LetterEngine::default());
    fixture.request(system_text("a"));
    fixture.glyphs().evict(&VecSet::new());

    let revision = fixture.glyphs().revision();
    let face = FontFace::device("latin", 400, FontData::from(b"latin".to_vec()));
    fixture.glyphs().take_device_fonts(&test_stack(), vec![(vec!['a'], Some(face))]);
    assert_eq!(fixture.glyphs().revision(), revision);

    // The wait resolves again, asks again, and is answered.
    fixture.store.answer();
    fixture.next_answer();
    assert_eq!(fonts.asked().last(), Some(&'a'));
}

#[test]
fn characters_are_asked_once_per_stack() {
    let fonts = DeviceFonts::new(|_| Some("latin"));
    let (fixture, _) = letter_fixture(&fonts, LetterEngine::default());
    fixture.request(system_text("ab"));
    fixture.answered(system_text("ab"));
    let mut asked = fonts.asked();
    asked.sort_unstable();
    assert_eq!(asked, ['a', 'b']);
}