icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
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
//! The fonts every harness draws with.
//!
//! iced's font database is one per process and starts with the machine's own fonts, which
//! differ between machines. [`ensure_loaded`], called before the first harness boots, swaps it
//! for a database holding iced's built-in faces and the bundled set: Inter in regular, medium,
//! semibold and bold, and JetBrains Mono in regular and bold, all under the SIL Open Font
//! Licence 1.1 (the licence files sit beside the fonts in the crate). Sans-serif and serif
//! resolve to Inter and monospace to JetBrains Mono.
//!
//! A program's own fonts (`Settings::fonts`, `font::load`) load only in a process per test.
//! Under plain `cargo test` a font whose bytes are already bundled loads as a no-op and any
//! other fails with [`SnapshotError::FontsNeedProcessPerTest`], so layout never depends on
//! which test ran first.
//!
//! The bundled set is the default `bundled-fonts` feature. Without it, or with
//! `HarnessConfig::system_fonts(true)`, the machine's fonts stay loaded ([`FontMode::System`])
//! and every visual snapshot's report says it may differ between machines.

use std::borrow::Cow;
use std::collections::BTreeSet;
use std::sync::{Mutex, OnceLock, PoisonError};

use iced_graphics::text::cosmic_text::{self, fontdb};

use super::SnapshotError;
use super::env::Runner;

/// Inter Regular, 4.1.
#[cfg(feature = "bundled-fonts")]
pub const INTER_REGULAR: &[u8] = include_bytes!("../../fonts/Inter-Regular.ttf");
/// Inter Medium, 4.1.
#[cfg(feature = "bundled-fonts")]
pub const INTER_MEDIUM: &[u8] = include_bytes!("../../fonts/Inter-Medium.ttf");
/// Inter SemiBold, 4.1.
#[cfg(feature = "bundled-fonts")]
pub const INTER_SEMIBOLD: &[u8] = include_bytes!("../../fonts/Inter-SemiBold.ttf");
/// Inter Bold, 4.1.
#[cfg(feature = "bundled-fonts")]
pub const INTER_BOLD: &[u8] = include_bytes!("../../fonts/Inter-Bold.ttf");
/// JetBrains Mono Regular, 2.304.
#[cfg(feature = "bundled-fonts")]
pub const JETBRAINS_MONO_REGULAR: &[u8] = include_bytes!("../../fonts/JetBrainsMono-Regular.ttf");
/// JetBrains Mono Bold, 2.304.
#[cfg(feature = "bundled-fonts")]
pub const JETBRAINS_MONO_BOLD: &[u8] = include_bytes!("../../fonts/JetBrainsMono-Bold.ttf");

/// The bundled set, in load order.
#[cfg(feature = "bundled-fonts")]
pub const BUNDLED: &[&[u8]] = &[
    INTER_REGULAR,
    INTER_MEDIUM,
    INTER_SEMIBOLD,
    INTER_BOLD,
    JETBRAINS_MONO_REGULAR,
    JETBRAINS_MONO_BOLD,
];

/// The bundled set, empty without the `bundled-fonts` feature.
#[cfg(not(feature = "bundled-fonts"))]
pub const BUNDLED: &[&[u8]] = &[];

/// Which fonts the process draws with, chosen by its first harness.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FontMode {
    /// iced's built-in faces and the bundled set only, the same on every machine.
    Bundled,
    /// The machine's fonts as cosmic-text found them, plus the bundled set when the feature is
    /// on. Pixels can differ between machines.
    System,
}

impl FontMode {
    /// [`Bundled`](Self::Bundled) with the `bundled-fonts` feature, else
    /// [`System`](Self::System).
    #[must_use]
    pub const fn default_mode() -> Self {
        if cfg!(feature = "bundled-fonts") {
            Self::Bundled
        } else {
            Self::System
        }
    }

    /// Whether snapshots drawn in this mode can differ between machines.
    #[must_use]
    pub fn is_unreliable(self) -> bool {
        self == Self::System
    }
}

/// The mode a harness asking for `requested` gets, given the process's runner, the default
/// and the mode already loaded, if any.
pub(crate) fn decide(
    runner: Runner,
    default: FontMode,
    requested: FontMode,
    loaded: Option<FontMode>,
) -> Result<FontMode, SnapshotError> {
    if requested != default && runner == Runner::Shared {
        return Err(SnapshotError::SystemFontsNeedProcessPerTest);
    }
    match loaded {
        Some(loaded) if loaded != requested => Err(SnapshotError::FontModeChanged {
            before: loaded,
            now: requested,
        }),
        _ => Ok(requested),
    }
}

static MODE: OnceLock<FontMode> = OnceLock::new();

/// The mode the process draws with: the one its first harness chose, or the default before
/// any harness has booted.
#[must_use]
pub fn mode() -> FontMode {
    MODE.get().copied().unwrap_or(FontMode::default_mode())
}

/// Loads the fonts a harness asks for, `system_fonts` keeping the machine's, under the rules
/// above. The first harness of the process decides; a later one asking for the other mode
/// fails with [`SnapshotError::FontModeChanged`].
pub(crate) fn prepare(system_fonts: bool) -> Result<(), SnapshotError> {
    let requested = if system_fonts {
        FontMode::System
    } else {
        FontMode::default_mode()
    };
    let default = FontMode::default_mode();
    decide(Runner::current(), default, requested, MODE.get().copied())?;
    let loaded = *MODE.get_or_init(|| {
        install(requested);
        requested
    });
    decide(Runner::current(), default, requested, Some(loaded)).map(|_| ())
}

/// The family sans-serif and serif text resolves to.
pub const SANS: &str = "Inter";
/// The family monospace text resolves to.
pub const MONO: &str = "JetBrains Mono";

/// The locale cosmic-text picks script fallbacks for, the same on every machine.
const LOCALE: &str = "en-US";

/// Loads the process's fonts once, in the mode its first harness chose or the default one:
/// with the bundled set, the font database becomes iced's built-in faces and that set. Later
/// calls do nothing. Every harness calls it before it boots.
pub fn ensure_loaded() {
    MODE.get_or_init(|| {
        let mode = FontMode::default_mode();
        install(mode);
        mode
    });
}

fn install(mode: FontMode) {
    let mut system = iced_graphics::text::font_system()
        .write()
        .unwrap_or_else(PoisonError::into_inner);
    let raw = system.raw();
    if mode == FontMode::System {
        for font in BUNDLED {
            raw.db_mut().load_font_data(font.to_vec());
        }
        return;
    }
    let mut db = fontdb::Database::new();
    let built_in: Vec<fontdb::Source> = raw
        .db()
        .faces()
        .filter(|face| face.index == 0 && matches!(face.source, fontdb::Source::Binary(_)))
        .map(|face| face.source.clone())
        .collect();
    for source in built_in {
        let _ = db.load_font_source(source);
    }
    for font in BUNDLED {
        db.load_font_data(font.to_vec());
    }
    db.set_sans_serif_family(SANS);
    db.set_serif_family(SANS);
    db.set_cursive_family(SANS);
    db.set_fantasy_family(SANS);
    db.set_monospace_family(MONO);
    *raw = cosmic_text::FontSystem::new_with_locale_and_db(LOCALE.to_owned(), db);
}

/// The characters of `text` that no loaded face has a glyph for, which draw as the
/// missing-glyph box. Whitespace and control characters are left out.
#[must_use]
pub fn uncovered(text: &str) -> BTreeSet<char> {
    let mut wanted: BTreeSet<char> = text
        .chars()
        .filter(|c| !c.is_whitespace() && !c.is_control())
        .collect();
    if wanted.is_empty() {
        return wanted;
    }
    ensure_loaded();
    let mut system = iced_graphics::text::font_system()
        .write()
        .unwrap_or_else(PoisonError::into_inner);
    let db = system.raw().db();
    let ids: Vec<fontdb::ID> = db.faces().map(|face| face.id).collect();
    for id in ids {
        if wanted.is_empty() {
            break;
        }
        db.with_face_data(id, |data, index| {
            if let Ok(face) = ttf_parser::Face::parse(data, index) {
                wanted.retain(|c| face.glyph_index(*c).is_none());
            }
        });
    }
    wanted
}

/// A hash of every loaded face's bytes and index, in load order, which PNG baselines record
/// so a font change can be told apart from a change in the app.
#[must_use]
pub fn fingerprint() -> u64 {
    ensure_loaded();
    let mut system = iced_graphics::text::font_system()
        .write()
        .unwrap_or_else(PoisonError::into_inner);
    let db = system.raw().db();
    let mut hash = Fnv::new();
    let ids: Vec<fontdb::ID> = db.faces().map(|face| face.id).collect();
    for id in ids {
        db.with_face_data(id, |data, index| {
            hash.write(data);
            hash.write(&index.to_le_bytes());
        });
    }
    hash.finish()
}

/// The faces in the database, as (family, weight, monospaced), in load order.
#[must_use]
pub fn faces() -> Vec<(String, u16, bool)> {
    ensure_loaded();
    let mut system = iced_graphics::text::font_system()
        .write()
        .unwrap_or_else(PoisonError::into_inner);
    system
        .raw()
        .db()
        .faces()
        .map(|face| {
            let family = face
                .families
                .first()
                .map(|(name, _)| name.clone())
                .unwrap_or_default();
            (family, face.weight.0, face.monospaced)
        })
        .collect()
}

/// The family a generic family resolves to.
#[must_use]
pub fn generic_family(family: iced_core::font::Family) -> String {
    ensure_loaded();
    let mut system = iced_graphics::text::font_system()
        .write()
        .unwrap_or_else(PoisonError::into_inner);
    let db = system.raw().db();
    let family = match family {
        iced_core::font::Family::Name(name) => return name.to_owned(),
        iced_core::font::Family::Serif => fontdb::Family::Serif,
        iced_core::font::Family::SansSerif => fontdb::Family::SansSerif,
        iced_core::font::Family::Cursive => fontdb::Family::Cursive,
        iced_core::font::Family::Fantasy => fontdb::Family::Fantasy,
        iced_core::font::Family::Monospace => fontdb::Family::Monospace,
    };
    db.family_name(&family).to_owned()
}

/// 64-bit FNV-1a: small, with no dependency, and the same on every machine and release.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Fnv(u64);

impl Fnv {
    pub(crate) fn new() -> Self {
        Self(0xcbf2_9ce4_8422_2325)
    }

    pub(crate) fn write(&mut self, bytes: &[u8]) {
        for byte in bytes {
            self.0 = (self.0 ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3);
        }
    }

    pub(crate) fn finish(self) -> u64 {
        self.0
    }

    pub(crate) fn of(bytes: &[u8]) -> u64 {
        let mut hash = Self::new();
        hash.write(bytes);
        hash.finish()
    }
}

/// A font's identity for the rules below: its length and hash.
type FontKey = (usize, u64);

fn key(bytes: &[u8]) -> FontKey {
    (bytes.len(), Fnv::of(bytes))
}

/// Which program fonts this process has loaded, so a second harness in one test can be held
/// to the first one's set.
#[derive(Debug, Default)]
pub(crate) struct FontLedger {
    boot: Option<Vec<FontKey>>,
}

/// What to do with a harness's program fonts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FontPlan {
    /// Indices of the fonts to load; bundled ones are left out.
    pub load: Vec<usize>,
}

impl FontLedger {
    /// Decides what a harness's boot fonts do, under `runner`, with `bundled` the keys of
    /// the bundled set.
    pub(crate) fn boot(
        &mut self,
        runner: Runner,
        bundled: &[FontKey],
        fonts: &[FontKey],
    ) -> Result<FontPlan, SnapshotError> {
        let own: Vec<(usize, FontKey)> = fonts
            .iter()
            .copied()
            .enumerate()
            .filter(|(_, key)| !bundled.contains(key))
            .collect();
        if let (Runner::Shared, Some((_, (bytes, _)))) = (runner, own.first()) {
            return Err(SnapshotError::FontsNeedProcessPerTest { bytes: *bytes });
        }
        let set: Vec<FontKey> = own.iter().map(|(_, key)| *key).collect();
        match &self.boot {
            Some(before) if *before != set => {
                return Err(SnapshotError::FontSetChanged {
                    before: before.len(),
                    now: set.len(),
                });
            }
            Some(_) => {}
            None => self.boot = Some(set),
        }
        Ok(FontPlan {
            load: own.into_iter().map(|(index, _)| index).collect(),
        })
    }

    /// Decides whether one font from `font::load` loads.
    pub(crate) fn load(
        runner: Runner,
        bundled: &[FontKey],
        font: FontKey,
    ) -> Result<bool, SnapshotError> {
        if bundled.contains(&font) {
            return Ok(false);
        }
        match runner {
            Runner::ProcessPerTest => Ok(true),
            Runner::Shared => Err(SnapshotError::FontsNeedProcessPerTest { bytes: font.0 }),
        }
    }
}

fn bundled_keys() -> &'static [FontKey] {
    static KEYS: std::sync::OnceLock<Vec<FontKey>> = std::sync::OnceLock::new();
    KEYS.get_or_init(|| BUNDLED.iter().map(|font| key(font)).collect())
}

fn ledger() -> std::sync::MutexGuard<'static, FontLedger> {
    static LEDGER: Mutex<FontLedger> = Mutex::new(FontLedger { boot: None });
    LEDGER.lock().unwrap_or_else(PoisonError::into_inner)
}

fn load(font: Cow<'static, [u8]>) {
    iced_graphics::text::font_system()
        .write()
        .unwrap_or_else(PoisonError::into_inner)
        .load_font(font);
}

/// Loads a booting program's `Settings::fonts` under the process's rules.
pub(crate) fn load_program_fonts(fonts: &[Cow<'static, [u8]>]) -> Result<(), SnapshotError> {
    let keys: Vec<FontKey> = fonts.iter().map(|font| key(font)).collect();
    let plan = ledger().boot(Runner::current(), bundled_keys(), &keys)?;
    for index in plan.load {
        if let Some(font) = fonts.get(index) {
            load(font.clone());
        }
    }
    Ok(())
}

/// Loads one font from a `font::load` task under the process's rules.
pub(crate) fn load_program_font(font: Cow<'static, [u8]>) -> Result<(), SnapshotError> {
    if FontLedger::load(Runner::current(), bundled_keys(), key(&font))? {
        load(font);
    }
    Ok(())
}

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

    #[cfg(feature = "bundled-fonts")]
    const OWN: FontKey = (3, 7);

    #[cfg(feature = "bundled-fonts")]
    fn bundled() -> Vec<FontKey> {
        BUNDLED.iter().map(|font| key(font)).collect()
    }

    #[test]
    fn the_first_harness_decides_the_mode_and_a_shared_process_keeps_the_default() {
        use FontMode::{Bundled, System};
        assert_eq!(
            decide(Runner::Shared, Bundled, Bundled, None).unwrap(),
            Bundled
        );
        assert!(matches!(
            decide(Runner::Shared, Bundled, System, None),
            Err(SnapshotError::SystemFontsNeedProcessPerTest)
        ));
        assert_eq!(
            decide(Runner::ProcessPerTest, Bundled, System, None).unwrap(),
            System
        );
        assert!(matches!(
            decide(Runner::ProcessPerTest, Bundled, Bundled, Some(System)),
            Err(SnapshotError::FontModeChanged {
                before: System,
                now: Bundled
            })
        ));
        assert_eq!(
            decide(Runner::Shared, System, System, Some(System)).unwrap(),
            System,
            "without the bundled set every harness keeps the machine's fonts"
        );
        assert!(System.is_unreliable() && !Bundled.is_unreliable());
    }

    #[cfg(feature = "bundled-fonts")]
    #[test]
    fn characters_no_face_covers_are_listed() {
        assert!(uncovered("Leeks and beans 123").is_empty());
        let missing = uncovered("tea \u{1F375} \u{10FFFD}");
        assert_eq!(
            missing.into_iter().collect::<Vec<_>>(),
            vec!['\u{1F375}', '\u{10FFFD}']
        );
        assert!(uncovered(" \n\t").is_empty());
    }

    #[cfg(feature = "bundled-fonts")]
    #[test]
    fn after_loading_only_built_in_and_bundled_faces_remain() {
        ensure_loaded();
        let faces = faces();
        let families: Vec<&str> = faces.iter().map(|(family, _, _)| family.as_str()).collect();
        assert!(
            families
                .iter()
                .all(|f| matches!(*f, "Inter" | "JetBrains Mono" | "Iced-Icons")),
            "{families:?}"
        );
        assert_eq!(families.iter().filter(|f| **f == "Inter").count(), 4);
        assert_eq!(
            families.iter().filter(|f| **f == "JetBrains Mono").count(),
            2
        );
        let mut system = iced_graphics::text::font_system()
            .write()
            .unwrap_or_else(PoisonError::into_inner);
        assert!(
            system
                .raw()
                .db()
                .faces()
                .all(|face| matches!(face.source, fontdb::Source::Binary(_))),
            "no face comes from a file"
        );
    }

    #[cfg(feature = "bundled-fonts")]
    #[test]
    fn generic_families_resolve_to_the_bundled_faces() {
        assert_eq!(generic_family(iced_core::font::Family::SansSerif), "Inter");
        assert_eq!(generic_family(iced_core::font::Family::Serif), "Inter");
        assert_eq!(
            generic_family(iced_core::font::Family::Monospace),
            "JetBrains Mono"
        );
    }

    #[test]
    fn a_second_call_changes_nothing() {
        let before = fingerprint();
        ensure_loaded();
        assert_eq!(fingerprint(), before);
    }

    #[cfg(feature = "bundled-fonts")]
    #[test]
    fn a_shared_process_loads_bundled_bytes_as_a_no_op_and_refuses_others() {
        let bundled = bundled();
        let mut ledger = FontLedger::default();
        let plan = ledger
            .boot(Runner::Shared, &bundled, &[bundled[0], bundled[4]])
            .unwrap();
        assert!(plan.load.is_empty());
        assert!(matches!(
            ledger.boot(Runner::Shared, &bundled, &[bundled[0], OWN]),
            Err(SnapshotError::FontsNeedProcessPerTest { bytes: 3 })
        ));
        assert!(!FontLedger::load(Runner::Shared, &bundled, bundled[1]).unwrap());
        assert!(matches!(
            FontLedger::load(Runner::Shared, &bundled, OWN),
            Err(SnapshotError::FontsNeedProcessPerTest { .. })
        ));
    }

    #[cfg(feature = "bundled-fonts")]
    #[test]
    fn a_process_per_test_loads_program_fonts_and_holds_later_harnesses_to_them() {
        let bundled = bundled();
        let mut ledger = FontLedger::default();
        let plan = ledger
            .boot(Runner::ProcessPerTest, &bundled, &[bundled[0], OWN])
            .unwrap();
        assert_eq!(plan.load, vec![1]);
        assert!(
            ledger
                .boot(Runner::ProcessPerTest, &bundled, &[OWN])
                .is_ok(),
            "the same set again"
        );
        assert!(matches!(
            ledger.boot(Runner::ProcessPerTest, &bundled, &[]),
            Err(SnapshotError::FontSetChanged { before: 1, now: 0 })
        ));
        assert!(FontLedger::load(Runner::ProcessPerTest, &bundled, OWN).unwrap());
    }
}